(*
 * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
 *
 * SPDX-License-Identifier: BSD-2-Clause
 *)

section "Lemmas for Word Length 64"

theory Word_Lemmas_64
imports
  Word_Lemmas
  Word_Setup_64
begin

lemma ucast_8_64_inj:
  "inj (ucast ::  8 word \<Rightarrow> 64 word)"
  by (rule down_ucast_inj) (clarsimp simp: is_down_def target_size source_size)

lemma upto_2_helper:
  "{0..<2 :: 64 word} = {0, 1}"
  by (safe; simp) unat_arith

lemmas upper_bits_unset_is_l2p_64 = upper_bits_unset_is_l2p [where 'a=64, folded word_bits_def]
lemmas le_2p_upper_bits_64 = le_2p_upper_bits [where 'a=64, folded word_bits_def]
lemmas le2p_bits_unset_64 = le2p_bits_unset[where 'a=64, folded word_bits_def]

lemma word_bits_len_of:
  "len_of TYPE (64) = word_bits"
  by (simp add: word_bits_conv)

lemmas unat_power_lower64' = unat_power_lower[where 'a=64]
lemmas unat_power_lower64 [simp] = unat_power_lower64'[unfolded word_bits_len_of]

lemmas word64_less_sub_le' = word_less_sub_le[where 'a = 64]
lemmas word64_less_sub_le[simp] = word64_less_sub_le' [folded word_bits_def]

lemma word_bits_size:
  "size (w::word64) = word_bits"
  by (simp add: word_bits_def word_size)

lemmas word64_power_less_1' = word_power_less_1[where 'a = 64]
lemmas word64_power_less_1[simp] = word64_power_less_1'[folded word_bits_def]

lemma of_nat64_0:
  "\<lbrakk>of_nat n = (0::word64); n < 2 ^ word_bits\<rbrakk> \<Longrightarrow> n = 0"
  by (erule of_nat_0, simp add: word_bits_def)

lemma unat_mask_2_less_4:
  "unat (p && mask 2 :: word64) < 4"
  apply (rule unat_less_helper)
  apply (rule order_le_less_trans, rule word_and_le1)
  apply (simp add: mask_def)
  done

lemmas unat_of_nat64' = unat_of_nat_eq[where 'a=64]
lemmas unat_of_nat64 = unat_of_nat64'[unfolded word_bits_len_of]

lemmas word_power_nonzero_64 = word_power_nonzero [where 'a=64, folded word_bits_def]

lemmas unat_mult_simple = iffD1 [OF unat_mult_lem [where 'a = 64, unfolded word_bits_len_of]]

lemmas div_power_helper_64 = div_power_helper [where 'a=64, folded word_bits_def]

lemma n_less_word_bits:
  "(n < word_bits) = (n < 64)"
  by (simp add: word_bits_def)

lemmas of_nat_less_pow_64 = of_nat_power [where 'a=64, folded word_bits_def]

lemma lt_word_bits_lt_pow:
  "sz < word_bits \<Longrightarrow> sz < 2 ^ word_bits"
  by (simp add: word_bits_conv)

lemma unat_less_word_bits:
  fixes y :: word64
  shows "x < unat y \<Longrightarrow> x < 2 ^ word_bits"
  unfolding word_bits_def
  by (rule order_less_trans [OF _ unat_lt2p])

lemmas unat_mask_word64' = unat_mask[where 'a=64]
lemmas unat_mask_word64 = unat_mask_word64'[folded word_bits_def]

lemma unat_less_2p_word_bits:
  "unat (x :: 64 word) < 2 ^ word_bits"
  apply (simp only: word_bits_def)
  apply (rule unat_lt2p)
  done

lemma Suc_unat_mask_div:
  "Suc (unat (mask sz div word_size::word64)) = 2 ^ (min sz word_bits - 3)"
  apply (case_tac "sz < word_bits")
   apply (case_tac "3\<le>sz")
    apply (clarsimp simp: word_size_def word_bits_def min_def mask_def)
    apply (drule (2) Suc_div_unat_helper
           [where 'a=64 and sz=sz and us=3, simplified, symmetric])
   apply (simp add: not_le word_size_def word_bits_def)
   apply (case_tac sz, simp add: unat_word_ariths)
   apply (case_tac nat, simp add: unat_word_ariths
                                  unat_mask_word64 min_def word_bits_def)
   apply (case_tac nata, simp add: unat_word_ariths unat_mask_word64 word_bits_def)
   apply simp
  apply (simp add: unat_word_ariths
                   unat_mask_word64 min_def word_bits_def word_size_def)
  done

lemmas word64_minus_one_le' = word_minus_one_le[where 'a=64]
lemmas word64_minus_one_le = word64_minus_one_le'[simplified]

lemma ucast_not_helper:
  fixes a::word8
  assumes a: "a \<noteq> 0xFF"
  shows "ucast a \<noteq> (0xFF::word64)"
proof
  assume "ucast a = (0xFF::word64)"
  also
  have "(0xFF::word64) = ucast (0xFF::word8)" by simp
  finally
  show False using a
    apply -
    apply (drule up_ucast_inj, simp)
    apply simp
    done
qed

lemma less_4_cases:
  "(x::word64) < 4 \<Longrightarrow> x=0 \<or> x=1 \<or> x=2 \<or> x=3"
  apply clarsimp
  apply (drule word_less_cases, erule disjE, simp, simp)+
  done

lemma if_then_1_else_0:
  "((if P then 1 else 0) = (0 :: word64)) = (\<not> P)"
  by simp

lemma if_then_0_else_1:
  "((if P then 0 else 1) = (0 :: word64)) = (P)"
  by simp

lemmas if_then_simps = if_then_0_else_1 if_then_1_else_0

lemma ucast_le_ucast_8_64:
  "(ucast x \<le> (ucast y :: word64)) = (x \<le> (y :: word8))"
  by (simp add: ucast_le_ucast)

lemma in_16_range:
  "0 \<in> S \<Longrightarrow> r \<in> (\<lambda>x. r + x * (16 :: word64)) ` S"
  "n - 1 \<in> S \<Longrightarrow> (r + (16 * n - 16)) \<in> (\<lambda>x :: word64. r + x * 16) ` S"
  by (clarsimp simp: image_def elim!: bexI[rotated])+

lemma eq_2_64_0:
  "(2 ^ 64 :: word64) = 0"
  by simp

lemma x_less_2_0_1:
  fixes x :: word64 shows
  "x < 2 \<Longrightarrow> x = 0 \<or> x = 1"
  by (rule x_less_2_0_1') auto

lemmas mask_64_max_word  = max_word_mask [symmetric, where 'a=64, simplified]

lemma of_nat64_n_less_equal_power_2:
 "n < 64 \<Longrightarrow> ((of_nat n)::64 word) < 2 ^ n"
  by (rule of_nat_n_less_equal_power_2, clarsimp simp: word_size)

lemma word_rsplit_0:
  "word_rsplit (0 :: word64) = [0, 0, 0, 0, 0, 0, 0, 0 :: word8]"
  apply (simp add: word_rsplit_def bin_rsplit_def Let_def)
  done

lemma unat_ucast_10_64 :
  fixes x :: "10 word"
  shows "unat (ucast x :: word64) = unat x"
  unfolding ucast_def unat_def
  apply (subst int_word_uint)
  apply (subst mod_pos_pos_trivial)
    apply simp
   apply (rule lt2p_lem)
   apply simp
  apply simp
  done

lemma bool_mask [simp]:
  fixes x :: word64
  shows "(0 < x && 1) = (x && 1 = 1)"
  by (rule bool_mask') auto

lemma word64_bounds:
  "- (2 ^ (size (x :: word64) - 1)) = (-9223372036854775808 :: int)"
  "((2 ^ (size (x :: word64) - 1)) - 1) = (9223372036854775807 :: int)"
  "- (2 ^ (size (y :: 64 signed word) - 1)) = (-9223372036854775808 :: int)"
  "((2 ^ (size (y :: 64 signed word) - 1)) - 1) = (9223372036854775807 :: int)"
  by (simp_all add: word_size)

lemma word_ge_min:"sint (x::64 word) \<ge> -9223372036854775808"
  by (metis sint_ge word64_bounds(1) word_size)

lemmas signed_arith_ineq_checks_to_eq_word64'
    = signed_arith_ineq_checks_to_eq[where 'a=64]
      signed_arith_ineq_checks_to_eq[where 'a="64 signed"]

lemmas signed_arith_ineq_checks_to_eq_word64
    = signed_arith_ineq_checks_to_eq_word64' [unfolded word64_bounds]

lemmas signed_mult_eq_checks64_to_64'
    = signed_mult_eq_checks_double_size[where 'a=64 and 'b=64]
      signed_mult_eq_checks_double_size[where 'a="64 signed" and 'b=64]

lemmas signed_mult_eq_checks64_to_64 = signed_mult_eq_checks64_to_64'[simplified]

lemmas sdiv_word64_max' = sdiv_word_max [where 'a=64] sdiv_word_max [where 'a="64 signed"]
lemmas sdiv_word64_max = sdiv_word64_max'[simplified word_size, simplified]

lemmas sdiv_word64_min' = sdiv_word_min [where 'a=64] sdiv_word_min [where 'a="64 signed"]
lemmas sdiv_word64_min = sdiv_word64_min' [simplified word_size, simplified]

lemmas sint64_of_int_eq' = sint_of_int_eq [where 'a=64]
lemmas sint64_of_int_eq = sint64_of_int_eq' [simplified]

lemma ucast_of_nats [simp]:
  "(ucast (of_nat x :: word64) :: sword64) = (of_nat x)"
  "(ucast (of_nat x :: word64) :: sword16) = (of_nat x)"
  "(ucast (of_nat x :: word64) :: sword8) = (of_nat x)"
  "(ucast (of_nat x :: word16) :: sword16) = (of_nat x)"
  "(ucast (of_nat x :: word16) :: sword8) = (of_nat x)"
  "(ucast (of_nat x :: word8) :: sword8) = (of_nat x)"
  by (auto simp: ucast_of_nat is_down)

lemmas signed_shift_guard_simpler_64'
    = power_strict_increasing_iff[where b="2 :: nat" and y=31]
lemmas signed_shift_guard_simpler_64 = signed_shift_guard_simpler_64'[simplified]

lemma word64_31_less:
  "31 < len_of TYPE (64 signed)" "31 > (0 :: nat)"
  "31 < len_of TYPE (64)" "31 > (0 :: nat)"
  by auto

lemmas signed_shift_guard_to_word_64
    = signed_shift_guard_to_word[OF word64_31_less(1-2)]
    signed_shift_guard_to_word[OF word64_31_less(3-4)]

lemma le_step_down_word_3:
  fixes x :: "64 word"
  shows "\<lbrakk>x \<le>  y; x \<noteq> y; y < 2 ^ 64 - 1\<rbrakk> \<Longrightarrow> x \<le> y - 1"
  by (rule le_step_down_word_2, assumption+)

lemma shiftr_1:
  "(x::word64) >> 1 = 0 \<Longrightarrow> x < 2"
  by word_bitwise clarsimp

lemma mask_step_down_64:
  "(b::64word) && 0x1 = (1::64word) \<Longrightarrow> (\<exists>x. x < 64 \<and> mask x = b >> 1) \<Longrightarrow> (\<exists>x. mask x = b)"
  apply clarsimp
  apply (rule_tac x="x + 1" in exI)
  apply (subgoal_tac "x \<le> 63")
   apply (erule le_step_down_nat, clarsimp simp:mask_def, word_bitwise, clarsimp+)+
   apply (clarsimp simp:mask_def, word_bitwise, clarsimp)
  apply clarsimp
  done

lemma unat_of_int_64:
  "\<lbrakk>i \<ge> 0; i \<le> 2 ^ 63\<rbrakk> \<Longrightarrow> (unat ((of_int i)::sword64)) = nat i"
  unfolding unat_def
  apply (subst eq_nat_nat_iff, clarsimp+)
  apply (simp add: word_of_int uint_word_of_int)
  done

lemmas word_ctz_not_minus_1_64 = word_ctz_not_minus_1[where 'a=64, simplified]

(* Helper for packing then unpacking a 64-bit variable. *)
lemma cast_chunk_assemble_id_64[simp]:
  "(((ucast ((ucast (x::64 word))::32 word))::64 word) || (((ucast ((ucast (x >> 32))::32 word))::64 word) << 32)) = x"
  by (simp add:cast_chunk_assemble_id)

(* Another variant of packing and unpacking a 64-bit variable. *)
lemma cast_chunk_assemble_id_64'[simp]:
  "(((ucast ((scast (x::64 word))::32 word))::64 word) || (((ucast ((scast (x >> 32))::32 word))::64 word) << 32)) = x"
  by (simp add:cast_chunk_scast_assemble_id)

(* Specialisations of down_cast_same for adding to local simpsets. *)
lemma cast_down_u64: "(scast::64 word \<Rightarrow> 32 word) = (ucast::64 word \<Rightarrow> 32 word)"
  apply (subst down_cast_same[symmetric])
   apply (simp add:is_down)+
  done

lemma cast_down_s64: "(scast::64 sword \<Rightarrow> 32 word) = (ucast::64 sword \<Rightarrow> 32 word)"
  apply (subst down_cast_same[symmetric])
   apply (simp add:is_down)+
  done

end


(*  Title:      HOL/HOLCF/Lift.thy
    Author:     Olaf Mueller
*)

section {* Lifting types of class type to flat pcpo's *}

theory Lift
imports Discrete Up
begin

default_sort type

pcpodef 'a lift = "UNIV :: 'a discr u set"
by simp_all

lemmas inst_lift_pcpo = Abs_lift_strict [symmetric]

definition
  Def :: "'a \<Rightarrow> 'a lift" where
  "Def x = Abs_lift (up\<cdot>(Discr x))"

subsection {* Lift as a datatype *}

lemma lift_induct: "\<lbrakk>P \<bottom>; \<And>x. P (Def x)\<rbrakk> \<Longrightarrow> P y"
apply (induct y)
apply (rule_tac p=y in upE)
apply (simp add: Abs_lift_strict)
apply (case_tac x)
apply (simp add: Def_def)
done

old_rep_datatype "\<bottom>\<Colon>'a lift" Def
  by (erule lift_induct) (simp_all add: Def_def Abs_lift_inject inst_lift_pcpo)

text {* @{term bottom} and @{term Def} *}

lemma not_Undef_is_Def: "(x \<noteq> \<bottom>) = (\<exists>y. x = Def y)"
  by (cases x) simp_all

lemma lift_definedE: "\<lbrakk>x \<noteq> \<bottom>; \<And>a. x = Def a \<Longrightarrow> R\<rbrakk> \<Longrightarrow> R"
  by (cases x) simp_all

text {*
  For @{term "x ~= \<bottom>"} in assumptions @{text defined} replaces @{text
  x} by @{text "Def a"} in conclusion. *}

method_setup defined = {*
  Scan.succeed (fn ctxt => SIMPLE_METHOD'
    (etac @{thm lift_definedE} THEN' asm_simp_tac ctxt))
*}

lemma DefE: "Def x = \<bottom> \<Longrightarrow> R"
  by simp

lemma DefE2: "\<lbrakk>x = Def s; x = \<bottom>\<rbrakk> \<Longrightarrow> R"
  by simp

lemma Def_below_Def: "Def x \<sqsubseteq> Def y \<longleftrightarrow> x = y"
by (simp add: below_lift_def Def_def Abs_lift_inverse)

lemma Def_below_iff [simp]: "Def x \<sqsubseteq> y \<longleftrightarrow> Def x = y"
by (induct y, simp, simp add: Def_below_Def)

subsection {* Lift is flat *}

instance lift :: (type) flat
proof
  fix x y :: "'a lift"
  assume "x \<sqsubseteq> y" thus "x = \<bottom> \<or> x = y"
    by (induct x) auto
qed

subsection {* Continuity of @{const case_lift} *}

lemma case_lift_eq: "case_lift \<bottom> f x = fup\<cdot>(\<Lambda> y. f (undiscr y))\<cdot>(Rep_lift x)"
apply (induct x, unfold lift.case)
apply (simp add: Rep_lift_strict)
apply (simp add: Def_def Abs_lift_inverse)
done

lemma cont2cont_case_lift [simp]:
  "\<lbrakk>\<And>y. cont (\<lambda>x. f x y); cont g\<rbrakk> \<Longrightarrow> cont (\<lambda>x. case_lift \<bottom> (f x) (g x))"
unfolding case_lift_eq by (simp add: cont_Rep_lift)

subsection {* Further operations *}

definition
  flift1 :: "('a \<Rightarrow> 'b::pcpo) \<Rightarrow> ('a lift \<rightarrow> 'b)"  (binder "FLIFT " 10)  where
  "flift1 = (\<lambda>f. (\<Lambda> x. case_lift \<bottom> f x))"

translations
  "\<Lambda>(XCONST Def x). t" => "CONST flift1 (\<lambda>x. t)"
  "\<Lambda>(CONST Def x). FLIFT y. t" <= "FLIFT x y. t"
  "\<Lambda>(CONST Def x). t" <= "FLIFT x. t"

definition
  flift2 :: "('a \<Rightarrow> 'b) \<Rightarrow> ('a lift \<rightarrow> 'b lift)" where
  "flift2 f = (FLIFT x. Def (f x))"

lemma flift1_Def [simp]: "flift1 f\<cdot>(Def x) = (f x)"
by (simp add: flift1_def)

lemma flift2_Def [simp]: "flift2 f\<cdot>(Def x) = Def (f x)"
by (simp add: flift2_def)

lemma flift1_strict [simp]: "flift1 f\<cdot>\<bottom> = \<bottom>"
by (simp add: flift1_def)

lemma flift2_strict [simp]: "flift2 f\<cdot>\<bottom> = \<bottom>"
by (simp add: flift2_def)

lemma flift2_defined [simp]: "x \<noteq> \<bottom> \<Longrightarrow> (flift2 f)\<cdot>x \<noteq> \<bottom>"
by (erule lift_definedE, simp)

lemma flift2_bottom_iff [simp]: "(flift2 f\<cdot>x = \<bottom>) = (x = \<bottom>)"
by (cases x, simp_all)

lemma FLIFT_mono:
  "(\<And>x. f x \<sqsubseteq> g x) \<Longrightarrow> (FLIFT x. f x) \<sqsubseteq> (FLIFT x. g x)"
by (rule cfun_belowI, case_tac x, simp_all)

lemma cont2cont_flift1 [simp, cont2cont]:
  "\<lbrakk>\<And>y. cont (\<lambda>x. f x y)\<rbrakk> \<Longrightarrow> cont (\<lambda>x. FLIFT y. f x y)"
by (simp add: flift1_def cont2cont_LAM)

end


section \<open>Traces\<close>

text \<open>Traces extend transitions to finitely many intermediate events.\<close>

theory Trace
  imports
    "HOL-Library.Sublist"
    Distributed_System

begin

context distributed_system

begin

text \<open>We can think of a trace as the transitive closure of the next
relation. A trace consists of initial and final configurations $c$ and
$c'$, with an ordered list of events $t$ occurring sequentially on $c$,
yielding $c'$.\<close>

inductive (in distributed_system) trace where
    tr_init: "trace c [] c"
  | tr_step: "\<lbrakk> c \<turnstile> ev \<mapsto> c'; trace c' t c'' \<rbrakk>
              \<Longrightarrow> trace c (ev # t) c''"

subsection \<open>Properties of traces\<close>

lemma trace_trans:
  shows
    "\<lbrakk> trace c t c';
       trace c' t' c''
     \<rbrakk> \<Longrightarrow> trace c (t @ t') c''"
proof (induct c t c' rule:trace.induct)
  case tr_init
  then show ?case by simp
next
  case tr_step
  then show ?case using trace.tr_step by auto
qed

lemma trace_decomp_head:
  assumes
    "trace c (ev # t) c'"
  shows
    "\<exists>c''. c \<turnstile> ev \<mapsto> c'' \<and> trace c'' t c'"
  using assms trace.simps by blast

lemma trace_decomp_tail:
  shows
    "trace c (t @ [ev]) c' \<Longrightarrow> \<exists>c''. trace c t c'' \<and> c'' \<turnstile> ev \<mapsto> c'"
proof (induct t arbitrary: c)
  case Nil
  then show ?case
    by (metis (mono_tags, lifting) append_Nil distributed_system.trace.simps distributed_system_axioms list.discI list.sel(1) list.sel(3))
next
  case (Cons ev' t)
  then obtain d where step: "c \<turnstile> ev' \<mapsto> d" and "trace d (t @ [ev]) c'" using trace_decomp_head by force
  then obtain d' where tr: "trace d t d'" and "d' \<turnstile> ev \<mapsto> c'" using Cons.hyps by blast
  moreover have "trace c (ev' # t) d'" using step tr trace.tr_step by simp
  ultimately show ?case by auto
qed

lemma trace_snoc:
  assumes
    "trace c t c'" and
    "c' \<turnstile> ev \<mapsto> c''"
  shows
    "trace c (t @ [ev]) c''"
  using assms(1) assms(2) tr_init tr_step trace_trans by auto

lemma trace_rev_induct [consumes 1, case_names tr_rev_init tr_rev_step]:
  "\<lbrakk> trace c t c';
     (\<And>c. P c [] c);
     (\<And>c t c' ev c''. trace c t c' \<Longrightarrow> P c t c' \<Longrightarrow> c' \<turnstile> ev \<mapsto> c'' \<Longrightarrow> P c (t @ [ev]) c'')
   \<rbrakk> \<Longrightarrow> P c t c'"
proof (induct t arbitrary: c' rule:rev_induct)
  case Nil
  then show ?case
    using distributed_system.trace.cases distributed_system_axioms by blast
next
  case (snoc ev t)
  then obtain c'' where "trace c t c''" "c'' \<turnstile> ev \<mapsto> c'" using trace_decomp_tail by blast
  then show ?case using snoc by simp
qed

lemma trace_and_start_determines_end:
  shows
    "trace c t c' \<Longrightarrow> trace c t d' \<Longrightarrow> c' = d'"
proof (induct c t c' arbitrary: d' rule:trace_rev_induct)
  case tr_rev_init
  then show ?case using trace.cases by fastforce
next
  case (tr_rev_step c t c' ev c'')
  then obtain d'' where "trace c t d''" "d'' \<turnstile> ev \<mapsto> d'" using trace_decomp_tail by blast
  then show ?case using tr_rev_step state_and_event_determine_next by simp
qed

lemma suffix_split_trace:
  shows
    "\<lbrakk> trace c t c';
       suffix t' t
     \<rbrakk> \<Longrightarrow> \<exists>c''. trace c'' t' c'"
proof (induct t arbitrary: c)
  case Nil
  then have "t' = []" by simp
  then have "trace c' t' c'" using tr_init by simp
  then show ?case by blast
next
  case (Cons ev t'')
  from Cons.prems have q: "suffix t' t'' \<or> t' = ev # t''" by (meson suffix_Cons)
  thus ?case
  proof (cases "suffix t' t''")
    case True
    then show ?thesis using Cons.hyps Cons.prems(1) trace.simps by blast
  next
    case False
    hence "t' = ev # t''" using q by simp
    thus ?thesis using Cons.hyps Cons.prems by blast
  qed
qed

lemma prefix_split_trace:
  fixes
    c :: "('p, 's, 'm) configuration" and
    t :: "('p, 's, 'm) trace"
  shows
    "\<lbrakk> \<exists>c'. trace c t c';
       prefix t' t
     \<rbrakk> \<Longrightarrow> \<exists>c''. trace c t' c''"
proof (induct t rule:rev_induct)
  case Nil
  then show ?case by simp
next
  case (snoc ev t'')
  from snoc.prems have q: "prefix t' t'' \<or> t' = t'' @ [ev]" by auto
  thus ?case
  proof (cases "prefix t' t''")
    case True
    thus ?thesis using trace_decomp_tail using snoc.hyps snoc.prems(1) trace.simps by blast
  next
    case False
    thus ?thesis using q snoc.prems by fast
  qed
qed

lemma split_trace:
  shows
    "\<lbrakk> trace c t c';
       t = t' @ t''
     \<rbrakk> \<Longrightarrow> \<exists>c''. trace c t' c'' \<and> trace c'' t'' c'"
proof (induct t'' arbitrary: t')
  case Nil
  then show ?case using tr_init by auto
next
  case (Cons ev t'')
  obtain c'' where p: "trace c (t' @ [ev]) c''"
    using Cons.prems prefix_split_trace rotate1.simps(2) by force
  then have "trace c'' t'' c'"
    using Cons.hyps Cons.prems trace_and_start_determines_end by force
  then show ?case
    by (meson distributed_system.tr_step distributed_system.trace_decomp_tail distributed_system_axioms p)
qed

subsection \<open>Describing intermediate configurations\<close>

definition construct_fun_from_rel :: "('a * 'b) set \<Rightarrow> 'a \<Rightarrow> 'b" where
  "construct_fun_from_rel R x = (THE y. (x,y) \<in> R)"

definition trace_rel where
  "trace_rel \<equiv> {((x, t'), y). trace x t' y}"

lemma fun_must_admit_trace:
  shows
    "single_valued R \<Longrightarrow> x \<in> Domain R
     \<Longrightarrow> (x, construct_fun_from_rel R x) \<in> R"
  unfolding construct_fun_from_rel_def
  by (rule theI') (auto simp add: single_valued_def)

lemma single_valued_trace_rel:
  shows
    "single_valued trace_rel"
proof (rule single_valuedI)
  fix x y y'
  assume asm: "(x, y) \<in> trace_rel" "(x, y') \<in> trace_rel"
  then obtain x' t where "x = (x', t)"
    by (meson surj_pair)
  then have "trace x' t y" "trace x' t y'"
    using asm trace_rel_def by auto
  then show "y = y'"
    using trace_and_start_determines_end by blast
qed

definition run_trace where
  "run_trace \<equiv> construct_fun_from_rel trace_rel"

text \<open>In order to describe intermediate configurations
of a trace we introduce the $s$ function definition, which,
given an initial configuration $c$, a trace $t$ and an index $i \in \mathbb{N}$,
determines the unique state after the first $i$ events of $t$.\<close>

definition s where
  "s c t i = (THE c'. trace c (take i t) c')"

lemma s_is_partial_execution:
  shows
    "s c t i = run_trace (c, take i t)"
  unfolding s_def run_trace_def
            construct_fun_from_rel_def trace_rel_def
  by auto

lemma exists_trace_for_any_i:
  assumes
    "\<exists>c'. trace c t c'"
  shows
    "trace c (take i t) (s c t i)"
proof -
  have "prefix (take i t) t" using take_is_prefix by auto
  then obtain c'' where tr: "trace c (take i t) c''" using assms prefix_split_trace by blast
  then show ?thesis
  proof -
    have "((c, take i t), s c t i) \<in> trace_rel"
      unfolding s_def trace_rel_def construct_fun_from_rel_def
      by (metis case_prod_conv distributed_system.trace_and_start_determines_end distributed_system_axioms mem_Collect_eq the_equality tr)
    then show ?thesis by (simp add: trace_rel_def)
  qed
qed

lemma exists_trace_for_any_i_j:
  assumes
    "\<exists>c'. trace c t c'" and
    "i \<le> j"
  shows
    "trace (s c t i) (take (j - i) (drop i t)) (s c t j)"
proof -
  have "trace c (take j t) (s c t j)" using exists_trace_for_any_i assms by simp
  from \<open>j \<ge> i\<close> have "take j t = take i t @ (take (j - i) (drop i t))"
    by (metis le_add_diff_inverse take_add)
  then have "trace c (take i t) (s c t i) \<and> trace (s c t i) (take (j - i) (drop i t)) (s c t j)"
    by (metis (no_types, lifting) assms(1) exists_trace_for_any_i split_trace trace_and_start_determines_end)
  then show ?thesis by simp
qed

lemma step_Suc:
  assumes
    "i < length t" and
    valid: "trace c t c'"
  shows "(s c t i) \<turnstile> (t ! i) \<mapsto> (s c t (Suc i))"
proof -
  have ex_trace: "trace (s c t i) (take (Suc i - i) (drop i t)) (s c t (Suc i))"
    using exists_trace_for_any_i_j le_less valid by blast
  moreover have "Suc i - i = 1" by auto
  moreover have "take 1 (drop i t) = [t ! i]"
    by (metis \<open>Suc i - i = 1\<close> assms(1) hd_drop_conv_nth le_add_diff_inverse lessI nat_less_le same_append_eq take_add take_hd_drop)
  ultimately show ?thesis
    by (metis list.discI trace.simps trace_decomp_head)
qed

subsection \<open>Trace-related lemmas\<close>

lemma snapshot_state_unchanged_trace:
  assumes
    "trace c t c'" and
    "ps c p = Some u"
  shows
    "ps c' p = Some u"
  using assms snapshot_state_unchanged by (induct c t c', auto)

lemma no_state_change_if_only_nonregular_events:
  shows
    "\<lbrakk> trace c t c';
       \<nexists>ev. ev \<in> set t \<and> regular_event ev \<and> occurs_on ev = p;
       states c p = st
     \<rbrakk> \<Longrightarrow> states c' p = st"
proof (induct c t c' rule:trace_rev_induct)
  case (tr_rev_init c)
  then show ?case by simp
next
  case (tr_rev_step c t c' ev c'')
  then have "states c' p = st"
  proof -
    have "\<nexists>ev. ev : set t \<and> regular_event ev \<and> occurs_on ev = p"
      using tr_rev_step by auto
    then show ?thesis using tr_rev_step by blast
  qed
  then show ?case
    using tr_rev_step no_state_change_if_no_event no_state_change_if_nonregular_event
    by auto
qed

lemma message_must_be_delivered_2_trace:
  assumes
    "trace c t c'" and
    "m : set (msgs c i)" and
    "m \<notin> set (msgs c' i)" and
    "channel i = Some (q, p)"
  shows
    "\<exists>ev \<in> set t. (\<exists>p q. ev = RecvMarker i p q \<and> m = Marker) \<or> (\<exists>p q s s' m'. ev = Recv i q p s s' m' \<and> m = Msg m')"
proof (rule ccontr)
  assume "~ (\<exists>ev \<in> set t. (\<exists>p q. ev = RecvMarker i p q \<and> m = Marker) \<or> (\<exists>p q s s' m'. ev = Recv i q p s s' m' \<and> m = Msg m'))" (is ?P)
  have "\<lbrakk> trace c t c'; m : set (msgs c i); ?P \<rbrakk> \<Longrightarrow> m : set (msgs c' i)"
  proof (induct c t c' rule:trace_rev_induct)
    case (tr_rev_init c)
    then show ?case by simp
  next
    case (tr_rev_step c t d ev c')
    then have m_in_set: "m : set (msgs d i)"
      using tr_rev_step by auto
    then show ?case
    proof (cases ev)
      case (Snapshot r)
      then show ?thesis
        using distributed_system.message_must_be_delivered_2 distributed_system_axioms m_in_set tr_rev_step.hyps(3) by blast
    next
      case (RecvMarker i' r s)
      then show ?thesis
      proof (cases "m = Marker")
        case True
        then have "i' \<noteq> i" using tr_rev_step RecvMarker by simp
        then show ?thesis
          using RecvMarker m_in_set message_must_be_delivered_2 tr_rev_step.hyps(3) by blast
      next
        case False
        then show ?thesis
          using RecvMarker tr_rev_step.hyps(3) m_in_set message_must_be_delivered_2 by blast
      qed
    next
      case (Trans r u u')
      then show ?thesis
        using tr_rev_step.hyps(3) m_in_set by auto
    next
      case (Send i' r s u u' m')
      then show ?thesis
        using distributed_system.message_must_be_delivered_2 distributed_system_axioms m_in_set tr_rev_step.hyps(3) by blast
    next
      case (Recv i' r s u u' m')
      then show ?thesis
      proof (cases "Msg m' = m")
        case True
        then have "i' \<noteq> i" using Recv tr_rev_step by auto
        then show ?thesis
          using Recv m_in_set tr_rev_step(3) by auto
      next
        case False
        then show ?thesis
          by (metis Recv event.distinct(17) event.inject(3) m_in_set message_must_be_delivered_2 tr_rev_step.hyps(3))
      qed
    qed
  qed
  then have "m : set (msgs c' i)" using assms \<open>?P\<close> by auto
  then show False using assms by simp
qed

lemma marker_must_be_delivered_2_trace:
  assumes
    "trace c t c'" and
    "Marker : set (msgs c i)" and
    "Marker \<notin> set (msgs c' i)" and
    "channel i = Some (p, q)"
  shows
    "\<exists>ev \<in> set t. (\<exists>p q. ev = RecvMarker i p q)"
proof -
  show "\<exists>ev \<in> set t. (\<exists>p q. ev = RecvMarker i p q)"
    using assms message_must_be_delivered_2_trace by fast
qed

lemma snapshot_stable:
  shows
    "\<lbrakk> trace c t c';
       has_snapshotted c p
     \<rbrakk> \<Longrightarrow> has_snapshotted c' p"
proof (induct c t c' rule:trace_rev_induct)
  case (tr_rev_init c)
  then show ?case by blast
next
  case (tr_rev_step c t c' ev c'')
  then show ?case
  proof (cases ev)
    case (Snapshot q)
    then have "p \<noteq> q" using tr_rev_step next_snapshot can_occur_def by auto
    then show ?thesis using Snapshot tr_rev_step by auto
  next
    case (RecvMarker i q r)
    with tr_rev_step show ?thesis
      by (cases "p = q"; auto)
  qed simp_all
qed

lemma snapshot_stable_2:
  shows
    "trace c t c' \<Longrightarrow> ~ has_snapshotted c' p \<Longrightarrow> ~ has_snapshotted c p"
  using snapshot_stable by blast

lemma no_markers_if_all_snapshotted:
  shows
    "\<lbrakk> trace c t c';
      \<forall>p. has_snapshotted c p;
      Marker \<notin> set (msgs c i)
     \<rbrakk> \<Longrightarrow> Marker \<notin> set (msgs c' i)"
proof (induct c t c' rule:trace_rev_induct)
  case (tr_rev_init c)
  then show ?case by simp
next
  case (tr_rev_step c t c' ev c'')
  have all_snapshotted: "\<forall>p. has_snapshotted c' p" using snapshot_stable tr_rev_step by auto
  have no_marker: "Marker \<notin> set (msgs c' i)" using tr_rev_step by blast
  then show ?case
  proof (cases ev)
    case (Snapshot r)
    then show ?thesis using can_occur_def tr_rev_step all_snapshotted by auto
  next
    case (RecvMarker i' r s)
    have "i' \<noteq> i"
    proof (rule ccontr)
      assume "~ i' \<noteq> i"
      then have "Marker : set (msgs c i)"
        using can_occur_def RecvMarker tr_rev_step  RecvMarker_implies_Marker_in_set by blast
      then show False using tr_rev_step by simp
    qed
    then show ?thesis using tr_rev_step all_snapshotted no_marker RecvMarker by auto
  next
    case (Trans p s s')
    then show ?thesis using tr_rev_step no_marker by auto
  next
   case (Send i' r s u u' m)
   then show ?thesis
   proof (cases "i' = i")
     case True
     then have "msgs c'' i = msgs c' i @ [Msg m]" using tr_rev_step Send by auto
     then show ?thesis using no_marker by auto
   next
     case False
     then show ?thesis using Send tr_rev_step no_marker by auto
   qed
  next
    case (Recv i' r s u u' m)
    then show ?thesis
    proof (cases "i = i'")
      case True
      then have "msgs c'' i = tl (msgs c' i)" using tr_rev_step Recv by auto
      then show ?thesis using no_marker by (metis list.sel(2) list.set_sel(2))
    next
      case False
      then show ?thesis using Recv tr_rev_step no_marker by auto
    qed
  qed
qed

lemma event_stays_valid_if_no_occurrence_trace:
  shows
    "\<lbrakk> trace c t c';
       list_all (\<lambda>ev. occurs_on ev \<noteq> occurs_on ev') t;
       can_occur ev' c
     \<rbrakk> \<Longrightarrow> can_occur ev' c'"
proof (induct c t c' rule:trace_rev_induct)
  case tr_rev_init
  then show ?case by blast
next
  case tr_rev_step
  then show ?case using event_stays_valid_if_no_occurrence by auto
qed

lemma event_can_go_back_if_no_sender_trace:
  shows
    "\<lbrakk> trace c t c';
       list_all (\<lambda>ev. occurs_on ev \<noteq> occurs_on ev') t;
       can_occur ev' c';
       ~ isRecvMarker ev';
       list_all (\<lambda>ev. ~ isSend ev) t
     \<rbrakk> \<Longrightarrow> can_occur ev' c"
proof (induct c t c' rule:trace_rev_induct)
  case tr_rev_init
  then show ?case by blast
next
  case tr_rev_step
  then show ?case using event_can_go_back_if_no_sender by auto
qed

lemma done_only_from_recv_marker_trace:
  assumes
    "trace c t c'" and
    "t \<noteq> []" and
    "snd (cs c cid) \<noteq> Done" and
    "snd (cs c' cid) = Done" and
    "channel cid = Some (p, q)"
  shows
    "RecvMarker cid q p \<in> set t"
proof (rule ccontr)
  assume "~ RecvMarker cid q p \<in> set t"
  moreover have "\<lbrakk> trace c t c'; ~ RecvMarker cid q p \<in> set t; snd (cs c cid) \<noteq> Done; channel cid = Some (p, q) \<rbrakk>
                 \<Longrightarrow> snd (cs c' cid) \<noteq> Done"
  proof (induct t arbitrary: c' rule:rev_induct)
    case Nil
    then show ?case
      by (metis list.discI trace.simps)
  next
    case (snoc ev t)
    then obtain d where ind: "trace c t d" and step: "d \<turnstile> ev \<mapsto> c'"
      using trace_decomp_tail by blast
    then have "snd (cs d cid) \<noteq> Done"
    proof -
      have "~ RecvMarker cid q p \<in> set t"
        using snoc.prems(2) by auto
      then show ?thesis using snoc ind by blast
    qed
    then show ?case
      using done_only_from_recv_marker local.step snoc.prems(2) snoc.prems(4) by auto
  qed
  ultimately have "snd (cs c' cid) \<noteq> Done" using assms by blast
  then show False using assms by simp
qed

lemma cs_not_not_started_stable_trace:
  shows
    "\<lbrakk> trace c t c'; snd (cs c cid) \<noteq> NotStarted; channel cid = Some (p, q) \<rbrakk> \<Longrightarrow> snd (cs c' cid) \<noteq> NotStarted"
proof (induct t arbitrary:c' rule:rev_induct)
  case Nil
  then show ?case
    by (metis list.discI trace.simps)
next
  case (snoc ev t)
  then obtain d where tr: "trace c t d" and step: "d \<turnstile> ev \<mapsto> c'"
    using trace_decomp_tail by blast
  then have "snd (cs d cid) \<noteq> NotStarted" using snoc by blast
  then show ?case using cs_not_not_started_stable snoc step by blast
qed

lemma no_messages_introduced_if_no_channel:
  assumes
    trace: "trace init t final" and
    no_msgs_if_no_channel: "\<forall>i. channel i = None \<longrightarrow> msgs init i = []"
  shows
    "channel cid = None \<Longrightarrow> msgs (s init t i) cid = []"
proof (induct i)
  case 0
  then show ?case
    by (metis assms exists_trace_for_any_i no_msgs_if_no_channel take0 tr_init trace_and_start_determines_end)
next
  case (Suc n)
  have f: "trace (s init t n) (take ((Suc n) - n) (drop n t)) (s init t (Suc n))"
    using exists_trace_for_any_i_j order_le_less trace assms by blast
  then show ?case
  proof (cases "drop n t = Nil")
    case True
    then show ?thesis using Suc.hyps Suc.prems
      by (metis f tr_init trace_and_start_determines_end take_Nil)
  next
    case False
    have suc_n_minus_n: "Suc n - n = 1" by auto
    then have "length (take ((Suc n) - n) (drop n t)) = 1" using False by auto
    then obtain ev where "ev # Nil = take ((Suc n) - n) (drop n t)"
      by (metis False One_nat_def suc_n_minus_n length_greater_0_conv self_append_conv2 take_eq_Nil take_hd_drop)
    then have g: "(s init t n) \<turnstile> ev \<mapsto> (s init t (Suc n))"
      by (metis f tr_init trace_and_start_determines_end trace_decomp_head)
    then show ?thesis
    proof (cases ev)
      case (Snapshot r)
      then show ?thesis
        using Suc.hyps Suc.prems g by auto
    next
      case (RecvMarker cid' sr r)
      have "cid' \<noteq> cid" using RecvMarker can_occur_def g Suc by auto
      with RecvMarker Suc g show ?thesis by (cases "has_snapshotted (s init t n) sr", auto)
    next
      case (Trans r u u')
      then show ?thesis
        by (metis Suc.hyps Suc.prems g next_trans)
    next
      case (Send cid' r s u u' m)
      have "cid' \<noteq> cid" using Send can_occur_def g Suc by auto
      then show ?thesis using Suc g Send by simp
    next
      case (Recv cid' s r u u' m)
      have "cid' \<noteq> cid" using Recv can_occur_def g Suc by auto
      then show ?thesis using Suc g Recv by simp
    qed
  qed
qed

end (* context distributed_system *)

end (* theory Trace *)


theory Trivial_Pursuit
  imports ZIOS
begin

lit_vars

typedecl Player
typedecl Colour

alphabet LocalScore =
  s :: "Colour set"

alphabet GlobalScore =
  score :: "Player \<Zpfun> LocalScore"

definition AnswerLocal :: "Colour \<Rightarrow> LocalScore rel" where
"AnswerLocal c = (s\<^sup>> = s\<^sup>< \<union> {c})\<^sub>u"

definition AnswerGlobal :: "Player \<Rightarrow> Colour \<Rightarrow> GlobalScore rel" where
"AnswerGlobal p c =
  (p \<in> dom ($score\<^sup><)
  \<and> {p} \<Zndres> $score\<^sup>> = {p} \<Zndres> $score\<^sup><
  \<and> (($score\<^sup>>) p):s = (($score\<^sup><) p):s \<union> {c})\<^sub>u"

text \<open> We can prove that promoting @{term AnswerLocal} yields @{term AnswerGlobal}. \<close>

lemma promote_AnswerLocal:
  "AnswerLocal c \<Up> score[p] = AnswerGlobal p c"
  apply (rel_simp add: AnswerLocal_def AnswerGlobal_def)
  apply (auto simp add: scene_equiv_outside_pfun unrest)
     apply (simp_all add: scene_equiv_def scene_override_commute unrest)
     apply (expr_auto)+
  done

end


(*  Title:      HOL/HOLCF/ex/Pattern_Match.thy
    Author:     Brian Huffman
*)

section \<open>An experimental pattern-matching notation\<close>

theory Pattern_Match
imports HOLCF
begin

default_sort pcpo

text \<open>FIXME: Find a proper way to un-hide constants.\<close>

abbreviation fail :: "'a match"
where "fail \<equiv> Fixrec.fail"

abbreviation succeed :: "'a \<rightarrow> 'a match"
where "succeed \<equiv> Fixrec.succeed"

abbreviation run :: "'a match \<rightarrow> 'a"
where "run \<equiv> Fixrec.run"

subsection \<open>Fatbar combinator\<close>

definition
  fatbar :: "('a \<rightarrow> 'b match) \<rightarrow> ('a \<rightarrow> 'b match) \<rightarrow> ('a \<rightarrow> 'b match)" where
  "fatbar = (\<Lambda> a b x. a\<cdot>x +++ b\<cdot>x)"

abbreviation
  fatbar_syn :: "['a \<rightarrow> 'b match, 'a \<rightarrow> 'b match] \<Rightarrow> 'a \<rightarrow> 'b match" (infixr "\<parallel>" 60)  where
  "m1 \<parallel> m2 == fatbar\<cdot>m1\<cdot>m2"

lemma fatbar1: "m\<cdot>x = \<bottom> \<Longrightarrow> (m \<parallel> ms)\<cdot>x = \<bottom>"
by (simp add: fatbar_def)

lemma fatbar2: "m\<cdot>x = fail \<Longrightarrow> (m \<parallel> ms)\<cdot>x = ms\<cdot>x"
by (simp add: fatbar_def)

lemma fatbar3: "m\<cdot>x = succeed\<cdot>y \<Longrightarrow> (m \<parallel> ms)\<cdot>x = succeed\<cdot>y"
by (simp add: fatbar_def)

lemmas fatbar_simps = fatbar1 fatbar2 fatbar3

lemma run_fatbar1: "m\<cdot>x = \<bottom> \<Longrightarrow> run\<cdot>((m \<parallel> ms)\<cdot>x) = \<bottom>"
by (simp add: fatbar_def)

lemma run_fatbar2: "m\<cdot>x = fail \<Longrightarrow> run\<cdot>((m \<parallel> ms)\<cdot>x) = run\<cdot>(ms\<cdot>x)"
by (simp add: fatbar_def)

lemma run_fatbar3: "m\<cdot>x = succeed\<cdot>y \<Longrightarrow> run\<cdot>((m \<parallel> ms)\<cdot>x) = y"
by (simp add: fatbar_def)

lemmas run_fatbar_simps [simp] = run_fatbar1 run_fatbar2 run_fatbar3

subsection \<open>Bind operator for match monad\<close>

definition match_bind :: "'a match \<rightarrow> ('a \<rightarrow> 'b match) \<rightarrow> 'b match" where
  "match_bind = (\<Lambda> m k. sscase\<cdot>(\<Lambda> _. fail)\<cdot>(fup\<cdot>k)\<cdot>(Rep_match m))"

lemma match_bind_simps [simp]:
  "match_bind\<cdot>\<bottom>\<cdot>k = \<bottom>"
  "match_bind\<cdot>fail\<cdot>k = fail"
  "match_bind\<cdot>(succeed\<cdot>x)\<cdot>k = k\<cdot>x"
unfolding match_bind_def fail_def succeed_def
by (simp_all add: cont_Rep_match cont_Abs_match
  Rep_match_strict Abs_match_inverse)

subsection \<open>Case branch combinator\<close>

definition
  branch :: "('a \<rightarrow> 'b match) \<Rightarrow> ('b \<rightarrow> 'c) \<rightarrow> ('a \<rightarrow> 'c match)" where
  "branch p \<equiv> \<Lambda> r x. match_bind\<cdot>(p\<cdot>x)\<cdot>(\<Lambda> y. succeed\<cdot>(r\<cdot>y))"

lemma branch_simps:
  "p\<cdot>x = \<bottom> \<Longrightarrow> branch p\<cdot>r\<cdot>x = \<bottom>"
  "p\<cdot>x = fail \<Longrightarrow> branch p\<cdot>r\<cdot>x = fail"
  "p\<cdot>x = succeed\<cdot>y \<Longrightarrow> branch p\<cdot>r\<cdot>x = succeed\<cdot>(r\<cdot>y)"
by (simp_all add: branch_def)

lemma branch_succeed [simp]: "branch succeed\<cdot>r\<cdot>x = succeed\<cdot>(r\<cdot>x)"
by (simp add: branch_def)

subsection \<open>Cases operator\<close>

definition
  cases :: "'a match \<rightarrow> 'a::pcpo" where
  "cases = Fixrec.run"

text \<open>rewrite rules for cases\<close>

lemma cases_strict [simp]: "cases\<cdot>\<bottom> = \<bottom>"
by (simp add: cases_def)

lemma cases_fail [simp]: "cases\<cdot>fail = \<bottom>"
by (simp add: cases_def)

lemma cases_succeed [simp]: "cases\<cdot>(succeed\<cdot>x) = x"
by (simp add: cases_def)

subsection \<open>Case syntax\<close>

nonterminal Case_pat and Case_syn and Cases_syn

syntax
  "_Case_syntax":: "['a, Cases_syn] => 'b"               ("(Case _ of/ _)" 10)
  "_Case1"      :: "[Case_pat, 'b] => Case_syn"          ("(2_ \<Rightarrow>/ _)" 10)
  ""            :: "Case_syn => Cases_syn"               ("_")
  "_Case2"      :: "[Case_syn, Cases_syn] => Cases_syn"  ("_/ | _")
  "_strip_positions" :: "'a => Case_pat"                 ("_")

syntax (ASCII)
  "_Case1"      :: "[Case_pat, 'b] => Case_syn"          ("(2_ =>/ _)" 10)

translations
  "_Case_syntax x ms" == "CONST cases\<cdot>(ms\<cdot>x)"
  "_Case2 m ms" == "m \<parallel> ms"

text \<open>Parsing Case expressions\<close>

syntax
  "_pat" :: "'a"
  "_variable" :: "'a"
  "_noargs" :: "'a"

translations
  "_Case1 p r" => "CONST branch (_pat p)\<cdot>(_variable p r)"
  "_variable (_args x y) r" => "CONST csplit\<cdot>(_variable x (_variable y r))"
  "_variable _noargs r" => "CONST unit_when\<cdot>r"

parse_translation \<open>
(* rewrite (_pat x) => (succeed) *)
(* rewrite (_variable x t) => (Abs_cfun (%x. t)) *)
 [(\<^syntax_const>\<open>_pat\<close>, fn _ => fn _ => Syntax.const \<^const_syntax>\<open>Fixrec.succeed\<close>),
  Syntax_Trans.mk_binder_tr (\<^syntax_const>\<open>_variable\<close>, \<^const_syntax>\<open>Abs_cfun\<close>)]
\<close>

text \<open>Printing Case expressions\<close>

syntax
  "_match" :: "'a"

print_translation \<open>
  let
    fun dest_LAM (Const (\<^const_syntax>\<open>Rep_cfun\<close>,_) $ Const (\<^const_syntax>\<open>unit_when\<close>,_) $ t) =
          (Syntax.const \<^syntax_const>\<open>_noargs\<close>, t)
    |   dest_LAM (Const (\<^const_syntax>\<open>Rep_cfun\<close>,_) $ Const (\<^const_syntax>\<open>csplit\<close>,_) $ t) =
          let
            val (v1, t1) = dest_LAM t;
            val (v2, t2) = dest_LAM t1;
          in (Syntax.const \<^syntax_const>\<open>_args\<close> $ v1 $ v2, t2) end
    |   dest_LAM (Const (\<^const_syntax>\<open>Abs_cfun\<close>,_) $ t) =
          let
            val abs =
              case t of Abs abs => abs
                | _ => ("x", dummyT, incr_boundvars 1 t $ Bound 0);
            val (x, t') = Syntax_Trans.atomic_abs_tr' abs;
          in (Syntax.const \<^syntax_const>\<open>_variable\<close> $ x, t') end
    |   dest_LAM _ = raise Match; (* too few vars: abort translation *)

    fun Case1_tr' [Const(\<^const_syntax>\<open>branch\<close>,_) $ p, r] =
          let val (v, t) = dest_LAM r in
            Syntax.const \<^syntax_const>\<open>_Case1\<close> $
              (Syntax.const \<^syntax_const>\<open>_match\<close> $ p $ v) $ t
          end;

  in [(\<^const_syntax>\<open>Rep_cfun\<close>, K Case1_tr')] end
\<close>

translations
  "x" <= "_match (CONST succeed) (_variable x)"

subsection \<open>Pattern combinators for data constructors\<close>

type_synonym ('a, 'b) pat = "'a \<rightarrow> 'b match"

definition
  cpair_pat :: "('a, 'c) pat \<Rightarrow> ('b, 'd) pat \<Rightarrow> ('a \<times> 'b, 'c \<times> 'd) pat" where
  "cpair_pat p1 p2 = (\<Lambda>(x, y).
    match_bind\<cdot>(p1\<cdot>x)\<cdot>(\<Lambda> a. match_bind\<cdot>(p2\<cdot>y)\<cdot>(\<Lambda> b. succeed\<cdot>(a, b))))"

definition
  spair_pat ::
  "('a, 'c) pat \<Rightarrow> ('b, 'd) pat \<Rightarrow> ('a::pcpo \<otimes> 'b::pcpo, 'c \<times> 'd) pat" where
  "spair_pat p1 p2 = (\<Lambda>(:x, y:). cpair_pat p1 p2\<cdot>(x, y))"

definition
  sinl_pat :: "('a, 'c) pat \<Rightarrow> ('a::pcpo \<oplus> 'b::pcpo, 'c) pat" where
  "sinl_pat p = sscase\<cdot>p\<cdot>(\<Lambda> x. fail)"

definition
  sinr_pat :: "('b, 'c) pat \<Rightarrow> ('a::pcpo \<oplus> 'b::pcpo, 'c) pat" where
  "sinr_pat p = sscase\<cdot>(\<Lambda> x. fail)\<cdot>p"

definition
  up_pat :: "('a, 'b) pat \<Rightarrow> ('a u, 'b) pat" where
  "up_pat p = fup\<cdot>p"

definition
  TT_pat :: "(tr, unit) pat" where
  "TT_pat = (\<Lambda> b. If b then succeed\<cdot>() else fail)"

definition
  FF_pat :: "(tr, unit) pat" where
  "FF_pat = (\<Lambda> b. If b then fail else succeed\<cdot>())"

definition
  ONE_pat :: "(one, unit) pat" where
  "ONE_pat = (\<Lambda> ONE. succeed\<cdot>())"

text \<open>Parse translations (patterns)\<close>
translations
  "_pat (XCONST Pair x y)" => "CONST cpair_pat (_pat x) (_pat y)"
  "_pat (XCONST spair\<cdot>x\<cdot>y)" => "CONST spair_pat (_pat x) (_pat y)"
  "_pat (XCONST sinl\<cdot>x)" => "CONST sinl_pat (_pat x)"
  "_pat (XCONST sinr\<cdot>x)" => "CONST sinr_pat (_pat x)"
  "_pat (XCONST up\<cdot>x)" => "CONST up_pat (_pat x)"
  "_pat (XCONST TT)" => "CONST TT_pat"
  "_pat (XCONST FF)" => "CONST FF_pat"
  "_pat (XCONST ONE)" => "CONST ONE_pat"

text \<open>CONST version is also needed for constructors with special syntax\<close>
translations
  "_pat (CONST Pair x y)" => "CONST cpair_pat (_pat x) (_pat y)"
  "_pat (CONST spair\<cdot>x\<cdot>y)" => "CONST spair_pat (_pat x) (_pat y)"

text \<open>Parse translations (variables)\<close>
translations
  "_variable (XCONST Pair x y) r" => "_variable (_args x y) r"
  "_variable (XCONST spair\<cdot>x\<cdot>y) r" => "_variable (_args x y) r"
  "_variable (XCONST sinl\<cdot>x) r" => "_variable x r"
  "_variable (XCONST sinr\<cdot>x) r" => "_variable x r"
  "_variable (XCONST up\<cdot>x) r" => "_variable x r"
  "_variable (XCONST TT) r" => "_variable _noargs r"
  "_variable (XCONST FF) r" => "_variable _noargs r"
  "_variable (XCONST ONE) r" => "_variable _noargs r"

translations
  "_variable (CONST Pair x y) r" => "_variable (_args x y) r"
  "_variable (CONST spair\<cdot>x\<cdot>y) r" => "_variable (_args x y) r"

text \<open>Print translations\<close>
translations
  "CONST Pair (_match p1 v1) (_match p2 v2)"
      <= "_match (CONST cpair_pat p1 p2) (_args v1 v2)"
  "CONST spair\<cdot>(_match p1 v1)\<cdot>(_match p2 v2)"
      <= "_match (CONST spair_pat p1 p2) (_args v1 v2)"
  "CONST sinl\<cdot>(_match p1 v1)" <= "_match (CONST sinl_pat p1) v1"
  "CONST sinr\<cdot>(_match p1 v1)" <= "_match (CONST sinr_pat p1) v1"
  "CONST up\<cdot>(_match p1 v1)" <= "_match (CONST up_pat p1) v1"
  "CONST TT" <= "_match (CONST TT_pat) _noargs"
  "CONST FF" <= "_match (CONST FF_pat) _noargs"
  "CONST ONE" <= "_match (CONST ONE_pat) _noargs"

lemma cpair_pat1:
  "branch p\<cdot>r\<cdot>x = \<bottom> \<Longrightarrow> branch (cpair_pat p q)\<cdot>(csplit\<cdot>r)\<cdot>(x, y) = \<bottom>"
apply (simp add: branch_def cpair_pat_def)
apply (cases "p\<cdot>x", simp_all)
done

lemma cpair_pat2:
  "branch p\<cdot>r\<cdot>x = fail \<Longrightarrow> branch (cpair_pat p q)\<cdot>(csplit\<cdot>r)\<cdot>(x, y) = fail"
apply (simp add: branch_def cpair_pat_def)
apply (cases "p\<cdot>x", simp_all)
done

lemma cpair_pat3:
  "branch p\<cdot>r\<cdot>x = succeed\<cdot>s \<Longrightarrow>
   branch (cpair_pat p q)\<cdot>(csplit\<cdot>r)\<cdot>(x, y) = branch q\<cdot>s\<cdot>y"
apply (simp add: branch_def cpair_pat_def)
apply (cases "p\<cdot>x", simp_all)
apply (cases "q\<cdot>y", simp_all)
done

lemmas cpair_pat [simp] =
  cpair_pat1 cpair_pat2 cpair_pat3

lemma spair_pat [simp]:
  "branch (spair_pat p1 p2)\<cdot>r\<cdot>\<bottom> = \<bottom>"
  "\<lbrakk>x \<noteq> \<bottom>; y \<noteq> \<bottom>\<rbrakk>
     \<Longrightarrow> branch (spair_pat p1 p2)\<cdot>r\<cdot>(:x, y:) =
         branch (cpair_pat p1 p2)\<cdot>r\<cdot>(x, y)"
by (simp_all add: branch_def spair_pat_def)

lemma sinl_pat [simp]:
  "branch (sinl_pat p)\<cdot>r\<cdot>\<bottom> = \<bottom>"
  "x \<noteq> \<bottom> \<Longrightarrow> branch (sinl_pat p)\<cdot>r\<cdot>(sinl\<cdot>x) = branch p\<cdot>r\<cdot>x"
  "y \<noteq> \<bottom> \<Longrightarrow> branch (sinl_pat p)\<cdot>r\<cdot>(sinr\<cdot>y) = fail"
by (simp_all add: branch_def sinl_pat_def)

lemma sinr_pat [simp]:
  "branch (sinr_pat p)\<cdot>r\<cdot>\<bottom> = \<bottom>"
  "x \<noteq> \<bottom> \<Longrightarrow> branch (sinr_pat p)\<cdot>r\<cdot>(sinl\<cdot>x) = fail"
  "y \<noteq> \<bottom> \<Longrightarrow> branch (sinr_pat p)\<cdot>r\<cdot>(sinr\<cdot>y) = branch p\<cdot>r\<cdot>y"
by (simp_all add: branch_def sinr_pat_def)

lemma up_pat [simp]:
  "branch (up_pat p)\<cdot>r\<cdot>\<bottom> = \<bottom>"
  "branch (up_pat p)\<cdot>r\<cdot>(up\<cdot>x) = branch p\<cdot>r\<cdot>x"
by (simp_all add: branch_def up_pat_def)

lemma TT_pat [simp]:
  "branch TT_pat\<cdot>(unit_when\<cdot>r)\<cdot>\<bottom> = \<bottom>"
  "branch TT_pat\<cdot>(unit_when\<cdot>r)\<cdot>TT = succeed\<cdot>r"
  "branch TT_pat\<cdot>(unit_when\<cdot>r)\<cdot>FF = fail"
by (simp_all add: branch_def TT_pat_def)

lemma FF_pat [simp]:
  "branch FF_pat\<cdot>(unit_when\<cdot>r)\<cdot>\<bottom> = \<bottom>"
  "branch FF_pat\<cdot>(unit_when\<cdot>r)\<cdot>TT = fail"
  "branch FF_pat\<cdot>(unit_when\<cdot>r)\<cdot>FF = succeed\<cdot>r"
by (simp_all add: branch_def FF_pat_def)

lemma ONE_pat [simp]:
  "branch ONE_pat\<cdot>(unit_when\<cdot>r)\<cdot>\<bottom> = \<bottom>"
  "branch ONE_pat\<cdot>(unit_when\<cdot>r)\<cdot>ONE = succeed\<cdot>r"
by (simp_all add: branch_def ONE_pat_def)

subsection \<open>Wildcards, as-patterns, and lazy patterns\<close>

definition
  wild_pat :: "'a \<rightarrow> unit match" where
  "wild_pat = (\<Lambda> x. succeed\<cdot>())"

definition
  as_pat :: "('a \<rightarrow> 'b match) \<Rightarrow> 'a \<rightarrow> ('a \<times> 'b) match" where
  "as_pat p = (\<Lambda> x. match_bind\<cdot>(p\<cdot>x)\<cdot>(\<Lambda> a. succeed\<cdot>(x, a)))"

definition
  lazy_pat :: "('a \<rightarrow> 'b::pcpo match) \<Rightarrow> ('a \<rightarrow> 'b match)" where
  "lazy_pat p = (\<Lambda> x. succeed\<cdot>(cases\<cdot>(p\<cdot>x)))"

text \<open>Parse translations (patterns)\<close>
translations
  "_pat _" => "CONST wild_pat"

text \<open>Parse translations (variables)\<close>
translations
  "_variable _ r" => "_variable _noargs r"

text \<open>Print translations\<close>
translations
  "_" <= "_match (CONST wild_pat) _noargs"

lemma wild_pat [simp]: "branch wild_pat\<cdot>(unit_when\<cdot>r)\<cdot>x = succeed\<cdot>r"
by (simp add: branch_def wild_pat_def)

lemma as_pat [simp]:
  "branch (as_pat p)\<cdot>(csplit\<cdot>r)\<cdot>x = branch p\<cdot>(r\<cdot>x)\<cdot>x"
apply (simp add: branch_def as_pat_def)
apply (cases "p\<cdot>x", simp_all)
done

lemma lazy_pat [simp]:
  "branch p\<cdot>r\<cdot>x = \<bottom> \<Longrightarrow> branch (lazy_pat p)\<cdot>r\<cdot>x = succeed\<cdot>(r\<cdot>\<bottom>)"
  "branch p\<cdot>r\<cdot>x = fail \<Longrightarrow> branch (lazy_pat p)\<cdot>r\<cdot>x = succeed\<cdot>(r\<cdot>\<bottom>)"
  "branch p\<cdot>r\<cdot>x = succeed\<cdot>s \<Longrightarrow> branch (lazy_pat p)\<cdot>r\<cdot>x = succeed\<cdot>s"
apply (simp_all add: branch_def lazy_pat_def)
apply (cases "p\<cdot>x", simp_all)+
done

subsection \<open>Examples\<close>

term "Case t of (:up\<cdot>(sinl\<cdot>x), sinr\<cdot>y:) \<Rightarrow> (x, y)"

term "\<Lambda> t. Case t of up\<cdot>(sinl\<cdot>a) \<Rightarrow> a | up\<cdot>(sinr\<cdot>b) \<Rightarrow> b"

term "\<Lambda> t. Case t of (:up\<cdot>(sinl\<cdot>_), sinr\<cdot>x:) \<Rightarrow> x"

subsection \<open>ML code for generating definitions\<close>

ML \<open>
local open HOLCF_Library in

infixr 6 ->>;
infix 9 ` ;

val beta_rules =
  @{thms beta_cfun cont_id cont_const cont2cont_APP cont2cont_LAM'} @
  @{thms cont2cont_fst cont2cont_snd cont2cont_Pair};

val beta_ss =
  simpset_of (put_simpset HOL_basic_ss \<^context> addsimps (@{thms simp_thms} @ beta_rules));

fun define_consts
    (specs : (binding * term * mixfix) list)
    (thy : theory)
    : (term list * thm list) * theory =
  let
    fun mk_decl (b, t, mx) = (b, fastype_of t, mx);
    val decls = map mk_decl specs;
    val thy = Cont_Consts.add_consts decls thy;
    fun mk_const (b, T, mx) = Const (Sign.full_name thy b, T);
    val consts = map mk_const decls;
    fun mk_def c (b, t, mx) =
      (Thm.def_binding b, Logic.mk_equals (c, t));
    val defs = map2 mk_def consts specs;
    val (def_thms, thy) =
      Global_Theory.add_defs false (map Thm.no_attributes defs) thy;
  in
    ((consts, def_thms), thy)
  end;

fun prove
    (thy : theory)
    (defs : thm list)
    (goal : term)
    (tacs : {prems: thm list, context: Proof.context} -> tactic list)
    : thm =
  let
    fun tac {prems, context} =
      rewrite_goals_tac context defs THEN
      EVERY (tacs {prems = map (rewrite_rule context defs) prems, context = context})
  in
    Goal.prove_global thy [] [] goal tac
  end;

fun get_vars_avoiding
    (taken : string list)
    (args : (bool * typ) list)
    : (term list * term list) =
  let
    val Ts = map snd args;
    val ns = Name.variant_list taken (Old_Datatype_Prop.make_tnames Ts);
    val vs = map Free (ns ~~ Ts);
    val nonlazy = map snd (filter_out (fst o fst) (args ~~ vs));
  in
    (vs, nonlazy)
  end;

(******************************************************************************)
(************** definitions and theorems for pattern combinators **************)
(******************************************************************************)

fun add_pattern_combinators
    (bindings : binding list)
    (spec : (term * (bool * typ) list) list)
    (lhsT : typ)
    (exhaust : thm)
    (case_const : typ -> term)
    (case_rews : thm list)
    (thy : theory) =
  let

    (* utility functions *)
    fun mk_pair_pat (p1, p2) =
      let
        val T1 = fastype_of p1;
        val T2 = fastype_of p2;
        val (U1, V1) = apsnd dest_matchT (dest_cfunT T1);
        val (U2, V2) = apsnd dest_matchT (dest_cfunT T2);
        val pat_typ = [T1, T2] --->
            (mk_prodT (U1, U2) ->> mk_matchT (mk_prodT (V1, V2)));
        val pat_const = Const (\<^const_name>\<open>cpair_pat\<close>, pat_typ);
      in
        pat_const $ p1 $ p2
      end;
    fun mk_tuple_pat [] = succeed_const \<^Type>\<open>unit\<close>
      | mk_tuple_pat ps = foldr1 mk_pair_pat ps;

    (* define pattern combinators *)
    local
      val tns = map (fst o dest_TFree) (snd (dest_Type lhsT));

      fun pat_eqn (i, (bind, (con, args))) : binding * term * mixfix =
        let
          val pat_bind = Binding.suffix_name "_pat" bind;
          val Ts = map snd args;
          val Vs =
              (map (K "'t") args)
              |> Old_Datatype_Prop.indexify_names
              |> Name.variant_list tns
              |> map (fn t => TFree (t, \<^sort>\<open>pcpo\<close>));
          val patNs = Old_Datatype_Prop.indexify_names (map (K "pat") args);
          val patTs = map2 (fn T => fn V => T ->> mk_matchT V) Ts Vs;
          val pats = map Free (patNs ~~ patTs);
          val fail = mk_fail (mk_tupleT Vs);
          val (vs, nonlazy) = get_vars_avoiding patNs args;
          val rhs = big_lambdas vs (mk_tuple_pat pats ` mk_tuple vs);
          fun one_fun (j, (_, args')) =
            let
              val (vs', nonlazy) = get_vars_avoiding patNs args';
            in if i = j then rhs else big_lambdas vs' fail end;
          val funs = map_index one_fun spec;
          val body = list_ccomb (case_const (mk_matchT (mk_tupleT Vs)), funs);
        in
          (pat_bind, lambdas pats body, NoSyn)
        end;
    in
      val ((pat_consts, pat_defs), thy) =
          define_consts (map_index pat_eqn (bindings ~~ spec)) thy
    end;

    (* syntax translations for pattern combinators *)
    local
      fun syntax c = Lexicon.mark_const (fst (dest_Const c));
      fun app s (l, r) = Ast.mk_appl (Ast.Constant s) [l, r];
      val capp = app \<^const_syntax>\<open>Rep_cfun\<close>;
      val capps = Library.foldl capp

      fun app_var x = Ast.mk_appl (Ast.Constant "_variable") [x, Ast.Variable "rhs"];
      fun app_pat x = Ast.mk_appl (Ast.Constant "_pat") [x];
      fun args_list [] = Ast.Constant "_noargs"
        | args_list xs = foldr1 (app "_args") xs;
      fun one_case_trans (pat, (con, args)) =
        let
          val cname = Ast.Constant (syntax con);
          val pname = Ast.Constant (syntax pat);
          val ns = 1 upto length args;
          val xs = map (fn n => Ast.Variable ("x"^(string_of_int n))) ns;
          val ps = map (fn n => Ast.Variable ("p"^(string_of_int n))) ns;
          val vs = map (fn n => Ast.Variable ("v"^(string_of_int n))) ns;
        in
          [Syntax.Parse_Rule (app_pat (capps (cname, xs)),
            Ast.mk_appl pname (map app_pat xs)),
           Syntax.Parse_Rule (app_var (capps (cname, xs)),
            app_var (args_list xs)),
           Syntax.Print_Rule (capps (cname, ListPair.map (app "_match") (ps,vs)),
            app "_match" (Ast.mk_appl pname ps, args_list vs))]
        end;
      val trans_rules : Ast.ast Syntax.trrule list =
          maps one_case_trans (pat_consts ~~ spec);
    in
      val thy = Sign.add_trrules trans_rules thy;
    end;

    (* prove strictness and reduction rules of pattern combinators *)
    local
      val tns = map (fst o dest_TFree) (snd (dest_Type lhsT));
      val rn = singleton (Name.variant_list tns) "'r";
      val R = TFree (rn, \<^sort>\<open>pcpo\<close>);
      fun pat_lhs (pat, args) =
        let
          val Ts = map snd args;
          val Vs =
              (map (K "'t") args)
              |> Old_Datatype_Prop.indexify_names
              |> Name.variant_list (rn::tns)
              |> map (fn t => TFree (t, \<^sort>\<open>pcpo\<close>));
          val patNs = Old_Datatype_Prop.indexify_names (map (K "pat") args);
          val patTs = map2 (fn T => fn V => T ->> mk_matchT V) Ts Vs;
          val pats = map Free (patNs ~~ patTs);
          val k = Free ("rhs", mk_tupleT Vs ->> R);
          val branch1 = \<^Const>\<open>branch lhsT \<open>mk_tupleT Vs\<close> R\<close>;
          val fun1 = (branch1 $ list_comb (pat, pats)) ` k;
          val branch2 = \<^Const>\<open>branch \<open>mk_tupleT Ts\<close> \<open>mk_tupleT Vs\<close> R\<close>;
          val fun2 = (branch2 $ mk_tuple_pat pats) ` k;
          val taken = "rhs" :: patNs;
        in (fun1, fun2, taken) end;
      fun pat_strict (pat, (con, args)) =
        let
          val (fun1, fun2, taken) = pat_lhs (pat, args);
          val defs = @{thm branch_def} :: pat_defs;
          val goal = mk_trp (mk_strict fun1);
          val rules = @{thms match_bind_simps} @ case_rews;
          fun tacs ctxt = [simp_tac (put_simpset beta_ss ctxt addsimps rules) 1];
        in prove thy defs goal (tacs o #context) end;
      fun pat_apps (i, (pat, (con, args))) =
        let
          val (fun1, fun2, taken) = pat_lhs (pat, args);
          fun pat_app (j, (con', args')) =
            let
              val (vs, nonlazy) = get_vars_avoiding taken args';
              val con_app = list_ccomb (con', vs);
              val assms = map (mk_trp o mk_defined) nonlazy;
              val rhs = if i = j then fun2 ` mk_tuple vs else mk_fail R;
              val concl = mk_trp (mk_eq (fun1 ` con_app, rhs));
              val goal = Logic.list_implies (assms, concl);
              val defs = @{thm branch_def} :: pat_defs;
              val rules = @{thms match_bind_simps} @ case_rews;
              fun tacs ctxt = [asm_simp_tac (put_simpset beta_ss ctxt addsimps rules) 1];
            in prove thy defs goal (tacs o #context) end;
        in map_index pat_app spec end;
    in
      val pat_stricts = map pat_strict (pat_consts ~~ spec);
      val pat_apps = flat (map_index pat_apps (pat_consts ~~ spec));
    end;

  in
    (pat_stricts @ pat_apps, thy)
  end

end
\<close>

(*
Cut from HOLCF/Tools/domain_constructors.ML
in function add_domain_constructors:

    ( * define and prove theorems for pattern combinators * )
    val (pat_thms : thm list, thy : theory) =
      let
        val bindings = map #1 spec;
        fun prep_arg (lazy, sel, T) = (lazy, T);
        fun prep_con c (b, args, mx) = (c, map prep_arg args);
        val pat_spec = map2 prep_con con_consts spec;
      in
        add_pattern_combinators bindings pat_spec lhsT
          exhaust case_const cases thy
      end

*)

end


header {* Syntactic Criteria *}
theory Syntactic_Criteria
  imports Compositionality
begin

context PL_Indis
begin

lemma proper_intros[intro]:
  "proper Done"
  "proper (Atm atm)"
  "proper c1 \<Longrightarrow> proper c2 \<Longrightarrow> proper (Seq c1 c2)"
  "proper c1 \<Longrightarrow> proper c2 \<Longrightarrow> proper (Ch ch c1 c2)"
  "proper c \<Longrightarrow> proper (While tst c)"
  "properL cs \<Longrightarrow> proper (Par cs)"
  "properL cs \<Longrightarrow> proper (ParT cs)"
  "(\<And>c. c \<in> set cs \<Longrightarrow> proper c) \<Longrightarrow> cs \<noteq> [] \<Longrightarrow> properL cs"
  by auto

lemma discr:
  "discr Done"
  "presAtm atm \<Longrightarrow> discr (Atm atm)"
  "discr c1 \<Longrightarrow> discr c2 \<Longrightarrow> discr (Seq c1 c2)"
  "discr c1 \<Longrightarrow> discr c2 \<Longrightarrow> discr (Ch ch c1 c2)"
  "discr c \<Longrightarrow> discr (While tst c)"
  "properL cs \<Longrightarrow> (\<And>c. c \<in> set cs \<Longrightarrow> discr c) \<Longrightarrow> discr (Par cs)"
  "properL cs \<Longrightarrow> (\<And>c. c \<in> set cs \<Longrightarrow> discr c) \<Longrightarrow> discr (ParT cs)"
  by (auto intro!: discr_Par discr_ParT)

lemma siso:
  "compatAtm atm \<Longrightarrow> siso (Atm atm)"
  "siso c1 \<Longrightarrow> siso c2 \<Longrightarrow> siso (Seq c1 c2)"
  "compatCh ch \<Longrightarrow> siso c1 \<Longrightarrow> siso c2 \<Longrightarrow> siso (Ch ch c1 c2)"
  "compatTst tst \<Longrightarrow> siso c \<Longrightarrow> siso (While tst c)"
  "properL cs \<Longrightarrow> (\<And>c. c \<in> set cs \<Longrightarrow> siso c) \<Longrightarrow> siso (Par cs)"
  "properL cs \<Longrightarrow> (\<And>c. c \<in> set cs \<Longrightarrow> siso c) \<Longrightarrow> siso (ParT cs)"
  by (auto intro!: siso_Par siso_ParT)

lemma Sbis:
  "compatAtm atm \<Longrightarrow> Atm atm \<approx>s Atm atm"
  "siso c1 \<Longrightarrow> c2 \<approx>s c2 \<Longrightarrow> Seq c1 c2 \<approx>s Seq c1 c2"
  "proper c1 \<Longrightarrow> proper c2 \<Longrightarrow> c1 \<approx>s c1 \<Longrightarrow> discr c2 \<Longrightarrow> Seq c1 c2 \<approx>s Seq c1 c2"
  "compatCh ch \<Longrightarrow> c1 \<approx>s c1 \<Longrightarrow> c2 \<approx>s c2 \<Longrightarrow> Ch ch c1 c2 \<approx>s Ch ch c1 c2"
  "properL cs \<Longrightarrow> (\<And>c. c \<in> set cs \<Longrightarrow> c \<approx>s c) \<Longrightarrow> Par cs \<approx>s Par cs"
  by (auto intro!: Par_Sbis)

lemma ZObis:
  "compatAtm atm \<Longrightarrow> Atm atm \<approx>01 Atm atm"
  "siso c1 \<Longrightarrow> c2 \<approx>01 c2 \<Longrightarrow> Seq c1 c2 \<approx>01 Seq c1 c2"
  "proper c1 \<Longrightarrow> proper c2 \<Longrightarrow> c1 \<approx>01 c1 \<Longrightarrow> discr c2 \<Longrightarrow> Seq c1 c2 \<approx>01 Seq c1 c2"
  "compatCh ch \<Longrightarrow> c1 \<approx>01 c1 \<Longrightarrow> c2 \<approx>01 c2 \<Longrightarrow> Ch ch c1 c2 \<approx>01 Ch ch c1 c2"
  "properL cs \<Longrightarrow> (\<And>c. c \<in> set cs \<Longrightarrow> c \<approx>s c) \<Longrightarrow> ParT cs \<approx>01 ParT cs"
  by (auto intro!: ParT_ZObis)

lemma discr_imp_Sbis: "proper c \<Longrightarrow> discr c \<Longrightarrow> c \<approx>s c"
  by auto

lemma siso_imp_Sbis: "siso c \<Longrightarrow> c \<approx>s c"
  by auto

lemma Sbis_imp_ZObis: "c \<approx>s c \<Longrightarrow> c \<approx>01 c"
  by auto

(* The syntactic predicates: SC_\<phi> corresponds to the paper's overlined \<phi>: *)

fun SC_discr where
  "SC_discr Done          \<longleftrightarrow> True"
| "SC_discr (Atm atm)     \<longleftrightarrow> presAtm atm"
| "SC_discr (Seq c1 c2)   \<longleftrightarrow> SC_discr c1 \<and> SC_discr c2"
| "SC_discr (Ch ch c1 c2) \<longleftrightarrow> SC_discr c1 \<and> SC_discr c2"
| "SC_discr (While tst c) \<longleftrightarrow> SC_discr c"
| "SC_discr (ParT cs) \<longleftrightarrow> (\<forall>c\<in>set cs. SC_discr c)"
| "SC_discr (Par cs)  \<longleftrightarrow> (\<forall>c\<in>set cs. SC_discr c)"

theorem SC_discr_discr[intro]: "proper c \<Longrightarrow> SC_discr c \<Longrightarrow> discr c"
  by (induct c) (auto intro!: discr)

fun SC_siso where
  "SC_siso Done           \<longleftrightarrow> True"
| "SC_siso (Atm atm)      \<longleftrightarrow> compatAtm atm"
| "SC_siso (Seq c1 c2)    \<longleftrightarrow> SC_siso c1 \<and> SC_siso c2"
| "SC_siso (Ch ch c1 c2)  \<longleftrightarrow> compatCh ch \<and> SC_siso c1 \<and> SC_siso c2"
| "SC_siso (While tst c)  \<longleftrightarrow> compatTst tst \<and> SC_siso c"
| "SC_siso (Par cs)   \<longleftrightarrow> (\<forall>c\<in>set cs. SC_siso c)"
| "SC_siso (ParT cs)  \<longleftrightarrow> (\<forall>c\<in>set cs. SC_siso c)"

theorem SC_siso_siso[intro]: "proper c \<Longrightarrow> SC_siso c \<Longrightarrow> siso c"
  by (induct c) (auto intro!: siso)

fun SC_Sbis where
  "SC_Sbis Done           \<longleftrightarrow> True"
| "SC_Sbis (Atm atm)      \<longleftrightarrow> compatAtm atm"
| "SC_Sbis (Seq c1 c2)    \<longleftrightarrow> (SC_siso c1 \<and> SC_Sbis c2) \<or>
                             (SC_Sbis c1 \<and> SC_discr c2) \<or>
                             SC_discr (Seq c1 c2) \<or> SC_siso (Seq c1 c2)"
| "SC_Sbis (Ch ch c1 c2)  \<longleftrightarrow> (if compatCh ch
                             then SC_Sbis c1 \<and> SC_Sbis c2
                             else (SC_discr (Ch ch c1 c2) \<or> SC_siso (Ch ch c1 c2)))"
| "SC_Sbis (While tst c)  \<longleftrightarrow> SC_discr (While tst c) \<or> SC_siso (While tst c)"
| "SC_Sbis (Par cs)   \<longleftrightarrow> (\<forall>c\<in>set cs. SC_Sbis c)"
| "SC_Sbis (ParT cs)  \<longleftrightarrow> SC_siso (ParT cs) \<or> SC_discr (ParT cs)"

theorem SC_siso_SCbis[intro]: "SC_siso c \<Longrightarrow> SC_Sbis c"
  by (induct c) auto

theorem SC_discr_SCbis[intro]: "SC_discr c \<Longrightarrow> SC_Sbis c"
  by (induct c) auto

declare SC_siso.simps[simp del]

declare SC_discr.simps[simp del]

theorem SC_Sbis_Sbis[intro]: "proper c \<Longrightarrow> SC_Sbis c \<Longrightarrow> c \<approx>s c"
  by (induct c)
     (auto intro: Sbis discr_imp_Sbis siso_imp_Sbis
           split: split_if_asm)

fun SC_ZObis where
  "SC_ZObis Done           \<longleftrightarrow> True"
| "SC_ZObis (Atm atm)      \<longleftrightarrow> compatAtm atm"
| "SC_ZObis (Seq c1 c2)    \<longleftrightarrow> (SC_siso c1 \<and> SC_ZObis c2) \<or>
                             (SC_ZObis c1 \<and> SC_discr c2) \<or>
                             SC_Sbis (Seq c1 c2)"
| "SC_ZObis (Ch ch c1 c2)  \<longleftrightarrow> (if compatCh ch
                             then SC_ZObis c1 \<and> SC_ZObis c2
                             else SC_Sbis (Ch ch c1 c2))"
| "SC_ZObis (While tst c)  \<longleftrightarrow> SC_Sbis (While tst c)"
| "SC_ZObis (Par cs)   \<longleftrightarrow> SC_Sbis (Par cs)"
| "SC_ZObis (ParT cs)  \<longleftrightarrow> (\<forall>c\<in>set cs. SC_Sbis c)"

theorem SC_Sbis_SC_ZObis[intro]: "SC_Sbis c \<Longrightarrow> SC_ZObis c"
  by (induct c) (auto simp: SC_siso.simps SC_discr.simps)

declare SC_Sbis.simps[simp del]

theorem SC_ZObis_ZObis: "proper c \<Longrightarrow> SC_ZObis c \<Longrightarrow> c \<approx>01 c"
  apply (induct c)
  apply (auto intro: Sbis_imp_ZObis ZObis split: split_if_asm)
  apply (auto intro!: ZObis(5))
  done

end

end


(******************************************************************************)
(* Project: Isabelle/UTP: Unifying Theories of Programming in Isabelle/HOL    *)
(* File: ustate.thy                                                           *)
(* Authors: Frank Zeyda and Simon Foster (University of York, UK)             *)
(* Emails: frank.zeyda@gmail.com and simon.foster@york.ac.uk                  *)
(******************************************************************************)
(* LAST REVIEWED: 09 Jun 2022 *)

section \<open>Universal State\<close>

theory ustate
imports utype uval uvar
begin

text \<open>
  In this theory, we define a notion of state space (binding) for universal
  values. This is through a new type @{text uspace}. We consider states as
  total bindings so that there is no notion of frame and all variables are
  assigned a value. An important property of state bindings is that they are
  well-typed by construction; this is the main reason why we need the axiom
  @{thm [source] utypes_non_empty} in our @{text axiomatization}.
\<close>

no_notation
  converse  ("(_\<inverse>)" [1000] 999)

default_sort injectable

subsection \<open>State Type\<close>

text \<open>
  As before, total functions are used to encode states. This is possible due
  to the axiom @{thm [source] utypes_non_empty} which enforces non-emptiness
  of all model types, irrespective of them being injectable into @{type uval}
  or not. It guarantees the existence of a well-typed binding and this here is
  needed to discharge the non-emptiness assumption of the type definition.
\<close>

typedef ustate = "{b::uvar \<Rightarrow> uval. \<forall>v. (b v) :\<^sub>u (type v)}"
apply (rule_tac x = "\<lambda>v. some_uval (type v)" in exI)
apply (clarsimp)
apply (rule some_uval_typed)
done

text \<open>\fixme{Is there a way to fix the warning about relators below?}\<close>

setup_lifting type_definition_ustate

subsection \<open>Constants\<close>

subsubsection \<open>Some State\<close>

text \<open>Constant that yields some arbitrary (albeit well-typed) state.\<close>

lift_definition some_ustate :: "ustate" ("\<sigma>\<^sub>0")
is "\<lambda>v. some_uval (type v)"
apply (rule some_uval_typed)
done

subsection \<open>Operators\<close>

text \<open>
  The operators we introduce are application, state updated, state override,
  and congruence. For application and update, we provide both a monomorphic
  and polymorphic versions of the operator. Strictly, state update could be
  expressed in terms of override with a singleton binding i.e.~if we added a
  construct to create such bindings.
\<close>

subsubsection \<open>Application\<close>

text \<open>Both a monomorphic and polymorphic version is provided.\<close>

lift_definition ustate_app_mono :: "ustate \<Rightarrow> uvar \<Rightarrow> uval"
is "\<lambda>s v. s v"
done

notation ustate_app_mono ("_\<cdot>_" [1000, 1000] 1000)

definition ustate_app_poly :: "ustate \<Rightarrow> 'a var \<Rightarrow> 'a" where
[transfer_unfold]: "ustate_app_poly s v = ProjU s\<cdot>(v\<down>)"

notation ustate_app_poly ("_\<star>_" [1000, 1000] 1000)

subsubsection \<open>State Update\<close>

text \<open>Both a monomorphic and polymorphic version is provided.\<close>

lift_definition ustate_upd_mono :: "ustate \<Rightarrow> uvar \<Rightarrow> uval \<Rightarrow> ustate"
is "\<lambda>s v x. if x :\<^sub>u (type v) then s(v := x) else s"
apply (transfer')
apply (simp add: typing)
done

definition ustate_upd_poly :: "ustate \<Rightarrow>  'a var \<Rightarrow> 'a \<Rightarrow> ustate" where
[transfer_unfold]: "ustate_upd_poly s v x = ustate_upd_mono s v\<down> (InjU x)"

text \<open>Syntax for State Update\<close>

nonterminal ubinds and ubind

text \<open>The below is inspired by Isabelle's syntax for function update.\<close>

syntax
  "_ubind_mono" :: "uvar \<Rightarrow> uval \<Rightarrow> ubind"      ("(2_ :=\<^sub>u/ _)")
  "_ubind_poly" :: "'a var \<Rightarrow> 'a \<Rightarrow> ubind"      ("(2_ :=/ _)")
  ""            :: "ubind \<Rightarrow> ubinds"            ("_")
  "_ubinds"     :: "ubind \<Rightarrow> ubinds \<Rightarrow> ubinds"  ("_,/ _")
  "_update"     :: "ustate \<Rightarrow> ubinds \<Rightarrow> ustate" ("_/'((_)')\<^sub>s" [1000, 0] 1000)

translations
  "_update s (_ubinds b bs)" \<rightleftharpoons> "_update (_update s b) bs"
  "_update s (_ubind_mono x y)" \<rightleftharpoons> "(CONST ustate_upd_mono) s x y"
  "_update s (_ubind_poly x y)" \<rightleftharpoons> "(CONST ustate_upd_poly) s x y"

subsubsection \<open>Override\<close>

lift_definition ustate_override :: "ustate \<Rightarrow> ustate \<Rightarrow> uvar set \<Rightarrow> ustate"
is "override_on"
apply (rename_tac s\<^sub>1 s\<^sub>2 vs v)
apply (case_tac "v \<in> vs")
apply (simp_all)
done

notation ustate_override ("_ \<oplus>\<^sub>s _ on _" [55, 56, 56] 55)

subsubsection \<open>Congruence\<close>

text \<open>Two states are congruent if they agree over a given set of variables.\<close>

lift_definition ustate_cong_on :: "ustate \<Rightarrow> ustate \<Rightarrow> uvar set \<Rightarrow> bool"
is "\<lambda>b1 b2 vs. \<forall>v\<in>vs. (b1 v) = (b2 v)"
done

notation ustate_cong_on ("_ \<cong>\<^sub>b _ on _" [51, 51, 0] 50)

subsection \<open>Theorems\<close>

theorem ustate_eq:
"b1 = b2 \<longleftrightarrow> (\<forall>v. b1\<cdot>v = b2\<cdot>v)"
apply (transfer')
apply (fold fun_eq_iff)
apply (rule refl)
done

theorem ustate_eqI [rule_format]:
"(\<forall>v. b1\<cdot>v = b2\<cdot>v) \<Longrightarrow> b1 = b2"
apply (subst ustate_eq)
apply (assumption)
done

paragraph \<open>Application Laws\<close>

theorem ustate_upd_mono_app [simp]:
"x :\<^sub>u (type v) \<Longrightarrow> s(v :=\<^sub>u x)\<^sub>s\<cdot>w = (if v = w then x else s\<cdot>w)"
apply (transfer')
apply (clarsimp)
done

theorem ustate_upd_poly_app1 [simp]:
"s(v := x)\<^sub>s\<star>w = (if v = w then x else s\<star>w)"
apply (unfold ustate_app_poly_def)
apply (unfold ustate_upd_poly_def)
apply (clarsimp)
done

text \<open>
  Note that the following theorem is not subsumed by the one above. This is
  because the types of the polymorphic types of the variables @{text v} and
  @{text w} may be different whereas above the have to be the same.
\<close>

theorem ustate_upd_poly_app2 [simp]:
"v\<down> \<noteq> w\<down> \<Longrightarrow> s(v := x)\<^sub>s\<star>w = s\<star>w"
apply (unfold ustate_app_poly_def)
apply (unfold ustate_upd_poly_def)
apply (clarsimp)+
done

lemma ustate_upd_mono_override [simp]:
"v = w \<Longrightarrow> y :\<^sub>u (type w) \<Longrightarrow> \<sigma>(v :=\<^sub>u x, w :=\<^sub>u y)\<^sub>s = \<sigma>(w :=\<^sub>u y)\<^sub>s"
apply (transfer)
apply (rule ext)
apply (clarsimp)
done

lemma ustate_upd_poly_override [simp]:
"v\<down> = w\<down> \<Longrightarrow> \<sigma>(v := x, w := y)\<^sub>s = \<sigma>(w := y)\<^sub>s"
apply (transfer)
apply (rule ext)
apply (clarsimp)
apply (simp add: p_type_rel_def)
done

theorem ustate_override_mono_app [simp]:
"(s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on vs)\<cdot>v = (if v \<in> vs then s\<^sub>2\<cdot>v else s\<^sub>1\<cdot>v)"
apply (transfer')
apply (clarsimp)
done

theorem ustate_override_poly_app [simp]:
"(s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on vs)\<star>v = (if v\<down> \<in> vs then s\<^sub>2\<star>v else s\<^sub>1\<star>v)"
apply (transfer')
apply (clarsimp)
done

paragraph \<open>Override Laws\<close>

text \<open>
  Many of the theorems here mirror those for @{term "f \<oplus> g on a"} in theory
  @{text ucommon} (see Section \ref{sec:override_laws}).
\<close>

theorem ustate_override_empty [simp]:
"s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on {} = s\<^sub>1"
apply (transfer')
apply (rule override_on_empty)
done

theorem ustate_override_UVAR [simp]:
"s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on UVAR = s\<^sub>2"
apply (transfer')
apply (rule override_on_UNIV)
done

theorem ustate_override_idem [simp]:
"s \<oplus>\<^sub>s s on vs = s"
apply (transfer')
apply (rule override_on_idem)
done

theorem ustate_override_comm:
"(s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on vs) = (s\<^sub>2 \<oplus>\<^sub>s s\<^sub>1 on -vs)"
apply (transfer')
apply (rule override_on_comm)
done

theorem ustate_override_assoc:
"(s\<^sub>1 \<oplus> s\<^sub>2 on vs\<^sub>1) \<oplus> s\<^sub>3 on vs\<^sub>2 = s\<^sub>1 \<oplus> (s\<^sub>2 \<oplus> s\<^sub>3 on vs\<^sub>2) on (vs\<^sub>1 \<union> vs\<^sub>2)"
apply (transfer')
apply (rule override_on_assoc)
done

theorem ustate_override_cancel [simp]:
"s\<^sub>1 \<oplus>\<^sub>s (s\<^sub>2 \<oplus>\<^sub>s s\<^sub>3 on vs) on vs = s\<^sub>1 \<oplus>\<^sub>s s\<^sub>3 on vs"
"(s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on vs) \<oplus>\<^sub>s s\<^sub>3 on vs = s\<^sub>1 \<oplus>\<^sub>s s\<^sub>3 on vs"
"s\<^sub>1 \<oplus>\<^sub>s (s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on vs\<^sub>1) on vs\<^sub>2 = s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on (vs\<^sub>1 \<inter> vs\<^sub>2)"
"(s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on vs\<^sub>1) \<oplus>\<^sub>s s\<^sub>2 on vs\<^sub>2 = s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on (vs\<^sub>1 \<union> vs\<^sub>2)"
"s\<^sub>1 \<oplus>\<^sub>s (s\<^sub>2 \<oplus>\<^sub>s s\<^sub>1 on vs\<^sub>2) on vs\<^sub>1 = s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on (vs\<^sub>1 - vs\<^sub>2)"
"(s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on vs\<^sub>1) \<oplus>\<^sub>s s\<^sub>1 on vs\<^sub>2 = s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on (vs\<^sub>1 - vs\<^sub>2)"
apply (transfer', rule override_on_cancel(1))
apply (transfer', rule override_on_cancel(2))
apply (transfer', rule override_on_cancel(3))
apply (transfer', rule override_on_cancel(4))
apply (transfer', rule override_on_cancel(5))
apply (transfer', rule override_on_cancel(6))
done

text \<open>\todo{How about a polymorphic version of the following law?}\<close>

theorem ustate_override_singleton [simp]:
"s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on {v} = s\<^sub>1(v :=\<^sub>u s\<^sub>2\<cdot>v)\<^sub>s"
apply (transfer)
apply (subst override_on_singleton)
apply (clarsimp)
done

theorem ustate_override_reorder:
"vs\<^sub>1 \<inter> vs\<^sub>2 = {} \<Longrightarrow>
 (s\<^sub>1 \<oplus>\<^sub>s s\<^sub>2 on vs\<^sub>1) \<oplus>\<^sub>s s\<^sub>3 on vs\<^sub>2 = (s\<^sub>1 \<oplus>\<^sub>s s\<^sub>3 on vs\<^sub>2) \<oplus>\<^sub>s s\<^sub>2 on vs\<^sub>1"
apply (transfer')
apply (rule override_on_reorder)
apply (auto)
done

subsection \<open>Transfer\<close>

theorem ex_ustate_transfer_0:
"(\<exists>s::ustate. P) \<longleftrightarrow> P"
apply (clarsimp)
done

theorem ex_ustate_transfer_1:
"(\<exists>s::ustate. P s\<star>v) \<longleftrightarrow> (\<exists>v. P v)"
apply (rule iffI)
apply (safe)
\<comment> \<open>Subgoal 1\<close>
apply (rule_tac x = "s\<star>v" in exI)
apply (assumption)
\<comment> \<open>Subgoal 2\<close>
apply (rename_tac x)
apply (rule_tac x = "\<sigma>(v := x)\<^sub>s" in exI)
apply (clarsimp)
done

theorem ex_ustate_transfer_2:
"distinct [v1\<down>, v2\<down>] \<Longrightarrow>
(\<exists>s::ustate. P s\<star>v1 s\<star>v2) \<longleftrightarrow> (\<exists>v1 v2. P v1 v2)"
apply (rule iffI)
apply (safe)
\<comment> \<open>Subgoal 1\<close>
apply (rule_tac x = "s\<star>v1" in exI)
apply (rule_tac x = "s\<star>v2" in exI)
apply (assumption)
\<comment> \<open>Subgoal 2\<close>
apply (rename_tac x1 x2)
apply (rule_tac x = "\<sigma>(v1 := x1, v2 := x2)\<^sub>s" in exI)
apply (clarsimp)
done

theorem ex_ustate_transfer_3:
"distinct [v1\<down>, v2\<down>, v3\<down>] \<Longrightarrow>
 (\<exists>s::ustate. P s\<star>v1 s\<star>v2 s\<star>v3) \<longleftrightarrow> (\<exists>v1 v2 v3. P v1 v2 v3)"
apply (rule iffI)
apply (safe)
\<comment> \<open>Subgoal 1\<close>
apply (rule_tac x = "s\<star>v1" in exI)
apply (rule_tac x = "s\<star>v2" in exI)
apply (rule_tac x = "s\<star>v3" in exI)
apply (assumption)
\<comment> \<open>Subgoal 2\<close>
apply (rename_tac x1 x2 x3)
apply (rule_tac x = "\<sigma>(v1 := x1, v2 := x2, v3 := x3)\<^sub>s" in exI)
apply (clarsimp)
done

theorem ex_ustate_transfer_4:
"distinct [v1\<down>, v2\<down>, v3\<down>, v4\<down>] \<Longrightarrow>
 (\<exists>s::ustate. P s\<star>v1 s\<star>v2 s\<star>v3 s\<star>v4) \<longleftrightarrow> (\<exists>v1 v2 v3 v4. P v1 v2 v3 v4)"
apply (rule iffI)
apply (safe)
\<comment> \<open>Subgoal 1\<close>
apply (rule_tac x = "s\<star>v1" in exI)
apply (rule_tac x = "s\<star>v2" in exI)
apply (rule_tac x = "s\<star>v3" in exI)
apply (rule_tac x = "s\<star>v4" in exI)
apply (assumption)
\<comment> \<open>Subgoal 2\<close>
apply (rename_tac x1 x2 x3 x4)
apply (rule_tac x = "\<sigma>(v1 := x1, v2 := x2, v3 := x3, v4 := x4)\<^sub>s" in exI)
apply (clarsimp)
done

theorem ex_ustate_transfer_5:
"distinct [v1\<down>, v2\<down>, v3\<down>, v4\<down>, v5\<down>] \<Longrightarrow>
 (\<exists>s::ustate. P s\<star>v1 s\<star>v2 s\<star>v3 s\<star>v4 s\<star>v5) \<longleftrightarrow> (\<exists>v1 v2 v3 v4 v5. P v1 v2 v3 v4 v5)"
apply (rule iffI)
apply (safe)
\<comment> \<open>Subgoal 1\<close>
apply (rule_tac x = "s\<star>v1" in exI)
apply (rule_tac x = "s\<star>v2" in exI)
apply (rule_tac x = "s\<star>v3" in exI)
apply (rule_tac x = "s\<star>v4" in exI)
apply (rule_tac x = "s\<star>v5" in exI)
apply (assumption)
\<comment> \<open>Subgoal 2\<close>
apply (rename_tac x1 x2 x3 x4 x5)
apply (rule_tac x = "\<sigma>(v1 := x1, v2 := x2, v3 := x3, v4 := x4, v5 := x5)\<^sub>s" in exI)
apply (clarsimp)
done

lemmas ex_ustate_transfer =
  ex_ustate_transfer_0
  ex_ustate_transfer_1
  ex_ustate_transfer_2
  ex_ustate_transfer_3
  ex_ustate_transfer_4
  ex_ustate_transfer_5

theorem all_ustate_transfer_0:
"(\<forall>s::ustate. P) \<longleftrightarrow> P"
apply (clarsimp)
done

theorem all_ustate_transfer_1:
"(\<forall>s::ustate. P s\<star>v) \<longleftrightarrow> (\<forall>v. P v)"
apply (rule iffI)
apply (simp_all)
apply (clarsimp)
apply (rename_tac x)
apply (drule_tac x = "\<sigma>(v := x)\<^sub>s" in spec)
apply (clarsimp)
done

theorem all_ustate_transfer_2:
"distinct [v1\<down>, v2\<down>] \<Longrightarrow>
 (\<forall>s::ustate. P s\<star>v1 s\<star>v2) \<longleftrightarrow> (\<forall>v1 v2. P v1 v2)"
apply (rule iffI)
apply (simp_all)
apply (clarsimp)
apply (rename_tac x1 x2)
apply (drule_tac x = "\<sigma>(v1 := x1, v2 := x2)\<^sub>s" in spec)
apply (clarsimp)
done

theorem all_ustate_transfer_3:
"distinct [v1\<down>, v2\<down>, v3\<down>] \<Longrightarrow>
 (\<forall>s::ustate. P s\<star>v1 s\<star>v2 s\<star>v3) \<longleftrightarrow> (\<forall>v1 v2 v3. P v1 v2 v3)"
apply (rule iffI)
apply (simp_all)
apply (clarsimp)
apply (rename_tac x1 x2 x3)
apply (drule_tac x = "\<sigma>(v1 := x1, v2 := x2, v3 := x3)\<^sub>s" in spec)
apply (clarsimp)
done

theorem all_ustate_transfer_4:
"distinct [v1\<down>, v2\<down>, v3\<down>, v4\<down>] \<Longrightarrow>
 (\<forall>s::ustate. P s\<star>v1 s\<star>v2 s\<star>v3 s\<star>v4) \<longleftrightarrow> (\<forall>v1 v2 v3 v4. P v1 v2 v3 v4)"
apply (rule iffI)
apply (simp_all)
apply (clarsimp)
apply (rename_tac x1 x2 x3 x4)
apply (drule_tac x = "\<sigma>(v1 := x1, v2 := x2, v3 := x3, v4 := x4)\<^sub>s" in spec)
apply (clarsimp)
done

theorem all_ustate_transfer_5:
"distinct [v1\<down>, v2\<down>, v3\<down>, v4\<down>, v5\<down>] \<Longrightarrow>
 (\<forall>s::ustate. P s\<star>v1 s\<star>v2 s\<star>v3 s\<star>v4 s\<star>v5) \<longleftrightarrow> (\<forall>v1 v2 v3 v4 v5. P v1 v2 v3 v4 v5)"
apply (rule iffI)
apply (simp_all)
apply (clarsimp)
apply (rename_tac x1 x2 x3 x4 x5)
apply (drule_tac x = "\<sigma>(v1 := x1, v2 := x2, v3 := x3, v4 := x4, v5 := x5)\<^sub>s" in spec)
apply (clarsimp)
done

lemmas all_ustate_transfer =
  all_ustate_transfer_0
  all_ustate_transfer_1
  all_ustate_transfer_2
  all_ustate_transfer_3
  all_ustate_transfer_4
  all_ustate_transfer_5

theorem meta_ustate_transfer_0:
"(\<And>s::ustate. PROP P) \<equiv> P"
apply (clarsimp)
done

theorem meta_ustate_transfer_1:
"(\<And>s::ustate. P s\<star>v) \<equiv> (\<And>v. P v)"
apply (atomize (full))
apply (simp add: all_ustate_transfer_1)
done

theorem meta_ustate_transfer_2:
"distinct [v1\<down>, v2\<down>] \<Longrightarrow>
 (\<And>s::ustate. P s\<star>v1 s\<star>v2) \<equiv> (\<And>v1 v2. P v1 v2)"
apply (atomize (full))
apply (simp add: all_ustate_transfer_2)
done

theorem meta_ustate_transfer_3:
"distinct [v1\<down>, v2\<down>, v3\<down>] \<Longrightarrow>
 (\<And>s::ustate. P s\<star>v1 s\<star>v2 s\<star>v3) \<equiv> (\<And>v1 v2 v3. P v1 v2 v3)"
apply (atomize (full))
apply (simp add: all_ustate_transfer_3)
done

theorem meta_ustate_transfer_4:
"distinct [v1\<down>, v2\<down>, v3\<down>, v4\<down>] \<Longrightarrow>
 (\<And>s::ustate. P s\<star>v1 s\<star>v2 s\<star>v3 s\<star>v4) \<equiv> (\<And>v1 v2 v3 v4. P v1 v2 v3 v4)"
apply (atomize (full))
apply (simp add: all_ustate_transfer_4)
done

theorem meta_ustate_transfer_5:
"distinct [v1\<down>, v2\<down>, v3\<down>, v4\<down>, v5\<down>] \<Longrightarrow>
 (\<And>s::ustate. P s\<star>v1 s\<star>v2 s\<star>v3 s\<star>v4 s\<star>v5) \<equiv> (\<And>v1 v2 v3 v4 v5. P v1 v2 v3 v4 v5)"
apply (atomize (full))
apply (simp add:all_ustate_transfer_5)
done

lemmas meta_ustate_transfer =
  meta_ustate_transfer_0
  meta_ustate_transfer_1
  meta_ustate_transfer_2
  meta_ustate_transfer_3
  meta_ustate_transfer_4
  meta_ustate_transfer_5

named_theorems ustate_transfer "ustate transfer rules"

declare meta_ustate_transfer [ustate_transfer]
declare all_ustate_transfer [ustate_transfer]
declare ex_ustate_transfer [ustate_transfer]

text \<open>@{text simp} alone is not sufficient as we require HO unification.\<close>

method ustate_transfer =
  (subst ustate_transfer)+
end