(*  Title:      ZF/CardinalArith.thy
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
    Copyright   1994  University of Cambridge
*)

section\<open>Cardinal Arithmetic Without the Axiom of Choice\<close>

theory CardinalArith imports Cardinal OrderArith ArithSimp Finite begin

definition
  InfCard       :: "i=>o"  where
    "InfCard(i) == Card(i) & nat \<le> i"

definition
  cmult         :: "[i,i]=>i"       (infixl "\<otimes>" 70)  where
    "i \<otimes> j == |i*j|"

definition
  cadd          :: "[i,i]=>i"       (infixl "\<oplus>" 65)  where
    "i \<oplus> j == |i+j|"

definition
  csquare_rel   :: "i=>i"  where
    "csquare_rel(K) ==
          rvimage(K*K,
                  lam <x,y>:K*K. <x \<union> y, x, y>,
                  rmult(K,Memrel(K), K*K, rmult(K,Memrel(K), K,Memrel(K))))"

definition
  jump_cardinal :: "i=>i"  where
    \<comment>\<open>This definition is more complex than Kunen's but it more easily proved to
        be a cardinal\<close>
    "jump_cardinal(K) ==
         \<Union>X\<in>Pow(K). {z. r \<in> Pow(K*K), well_ord(X,r) & z = ordertype(X,r)}"

definition
  csucc         :: "i=>i"  where
    \<comment>\<open>needed because @{term "jump_cardinal(K)"} might not be the successor
        of @{term K}\<close>
    "csucc(K) == \<mu> L. Card(L) & K<L"

lemma Card_Union [simp,intro,TC]:
  assumes A: "\<And>x. x\<in>A \<Longrightarrow> Card(x)" shows "Card(\<Union>(A))"
proof (rule CardI)
  show "Ord(\<Union>A)" using A
    by (simp add: Card_is_Ord)
next
  fix j
  assume j: "j < \<Union>A"
  hence "\<exists>c\<in>A. j < c & Card(c)" using A
    by (auto simp add: lt_def intro: Card_is_Ord)
  then obtain c where c: "c\<in>A" "j < c" "Card(c)"
    by blast
  hence jls: "j \<prec> c"
    by (simp add: lt_Card_imp_lesspoll)
  { assume eqp: "j \<approx> \<Union>A"
    have  "c \<lesssim> \<Union>A" using c
      by (blast intro: subset_imp_lepoll)
    also have "... \<approx> j"  by (rule eqpoll_sym [OF eqp])
    also have "... \<prec> c"  by (rule jls)
    finally have "c \<prec> c" .
    hence False
      by auto
  } thus "\<not> j \<approx> \<Union>A" by blast
qed

lemma Card_UN: "(!!x. x \<in> A ==> Card(K(x))) ==> Card(\<Union>x\<in>A. K(x))"
  by blast

lemma Card_OUN [simp,intro,TC]:
     "(!!x. x \<in> A ==> Card(K(x))) ==> Card(\<Union>x<A. K(x))"
  by (auto simp add: OUnion_def Card_0)

lemma in_Card_imp_lesspoll: "[| Card(K); b \<in> K |] ==> b \<prec> K"
apply (unfold lesspoll_def)
apply (simp add: Card_iff_initial)
apply (fast intro!: le_imp_lepoll ltI leI)
done

subsection\<open>Cardinal addition\<close>

text\<open>Note: Could omit proving the algebraic laws for cardinal addition and
multiplication.  On finite cardinals these operations coincide with
addition and multiplication of natural numbers; on infinite cardinals they
coincide with union (maximum).  Either way we get most laws for free.\<close>

subsubsection\<open>Cardinal addition is commutative\<close>

lemma sum_commute_eqpoll: "A+B \<approx> B+A"
proof (unfold eqpoll_def, rule exI)
  show "(\<lambda>z\<in>A+B. case(Inr,Inl,z)) \<in> bij(A+B, B+A)"
    by (auto intro: lam_bijective [where d = "case(Inr,Inl)"])
qed

lemma cadd_commute: "i \<oplus> j = j \<oplus> i"
apply (unfold cadd_def)
apply (rule sum_commute_eqpoll [THEN cardinal_cong])
done

subsubsection\<open>Cardinal addition is associative\<close>

lemma sum_assoc_eqpoll: "(A+B)+C \<approx> A+(B+C)"
apply (unfold eqpoll_def)
apply (rule exI)
apply (rule sum_assoc_bij)
done

text\<open>Unconditional version requires AC\<close>
lemma well_ord_cadd_assoc:
  assumes i: "well_ord(i,ri)" and j: "well_ord(j,rj)" and k: "well_ord(k,rk)"
  shows "(i \<oplus> j) \<oplus> k = i \<oplus> (j \<oplus> k)"
proof (unfold cadd_def, rule cardinal_cong)
  have "|i + j| + k \<approx> (i + j) + k"
    by (blast intro: sum_eqpoll_cong well_ord_cardinal_eqpoll eqpoll_refl well_ord_radd i j)
  also have "...  \<approx> i + (j + k)"
    by (rule sum_assoc_eqpoll)
  also have "...  \<approx> i + |j + k|"
    by (blast intro: sum_eqpoll_cong well_ord_cardinal_eqpoll eqpoll_refl well_ord_radd j k eqpoll_sym)
  finally show "|i + j| + k \<approx> i + |j + k|" .
qed

subsubsection\<open>0 is the identity for addition\<close>

lemma sum_0_eqpoll: "0+A \<approx> A"
apply (unfold eqpoll_def)
apply (rule exI)
apply (rule bij_0_sum)
done

lemma cadd_0 [simp]: "Card(K) ==> 0 \<oplus> K = K"
apply (unfold cadd_def)
apply (simp add: sum_0_eqpoll [THEN cardinal_cong] Card_cardinal_eq)
done

subsubsection\<open>Addition by another cardinal\<close>

lemma sum_lepoll_self: "A \<lesssim> A+B"
proof (unfold lepoll_def, rule exI)
  show "(\<lambda>x\<in>A. Inl (x)) \<in> inj(A, A + B)"
    by (simp add: inj_def)
qed

(*Could probably weaken the premises to well_ord(K,r), or removing using AC*)

lemma cadd_le_self:
  assumes K: "Card(K)" and L: "Ord(L)" shows "K \<le> (K \<oplus> L)"
proof (unfold cadd_def)
  have "K \<le> |K|"
    by (rule Card_cardinal_le [OF K])
  moreover have "|K| \<le> |K + L|" using K L
    by (blast intro: well_ord_lepoll_imp_Card_le sum_lepoll_self
                     well_ord_radd well_ord_Memrel Card_is_Ord)
  ultimately show "K \<le> |K + L|"
    by (blast intro: le_trans)
qed

subsubsection\<open>Monotonicity of addition\<close>

lemma sum_lepoll_mono:
     "[| A \<lesssim> C;  B \<lesssim> D |] ==> A + B \<lesssim> C + D"
apply (unfold lepoll_def)
apply (elim exE)
apply (rule_tac x = "\<lambda>z\<in>A+B. case (%w. Inl(f`w), %y. Inr(fa`y), z)" in exI)
apply (rule_tac d = "case (%w. Inl(converse(f) `w), %y. Inr(converse(fa) ` y))"
       in lam_injective)
apply (typecheck add: inj_is_fun, auto)
done

lemma cadd_le_mono:
    "[| K' \<le> K;  L' \<le> L |] ==> (K' \<oplus> L') \<le> (K \<oplus> L)"
apply (unfold cadd_def)
apply (safe dest!: le_subset_iff [THEN iffD1])
apply (rule well_ord_lepoll_imp_Card_le)
apply (blast intro: well_ord_radd well_ord_Memrel)
apply (blast intro: sum_lepoll_mono subset_imp_lepoll)
done

subsubsection\<open>Addition of finite cardinals is "ordinary" addition\<close>

lemma sum_succ_eqpoll: "succ(A)+B \<approx> succ(A+B)"
apply (unfold eqpoll_def)
apply (rule exI)
apply (rule_tac c = "%z. if z=Inl (A) then A+B else z"
            and d = "%z. if z=A+B then Inl (A) else z" in lam_bijective)
   apply simp_all
apply (blast dest: sym [THEN eq_imp_not_mem] elim: mem_irrefl)+
done

(*Pulling the  succ(...)  outside the |...| requires m, n \<in> nat  *)
(*Unconditional version requires AC*)
lemma cadd_succ_lemma:
  assumes "Ord(m)" "Ord(n)" shows "succ(m) \<oplus> n = |succ(m \<oplus> n)|"
proof (unfold cadd_def)
  have [intro]: "m + n \<approx> |m + n|" using assms
    by (blast intro: eqpoll_sym well_ord_cardinal_eqpoll well_ord_radd well_ord_Memrel)

  have "|succ(m) + n| = |succ(m + n)|"
    by (rule sum_succ_eqpoll [THEN cardinal_cong])
  also have "... = |succ(|m + n|)|"
    by (blast intro: succ_eqpoll_cong cardinal_cong)
  finally show "|succ(m) + n| = |succ(|m + n|)|" .
qed

lemma nat_cadd_eq_add:
  assumes m: "m \<in> nat" and [simp]: "n \<in> nat" shows"m \<oplus> n = m #+ n"
using m
proof (induct m)
  case 0 thus ?case by (simp add: nat_into_Card cadd_0)
next
  case (succ m) thus ?case by (simp add: cadd_succ_lemma nat_into_Card Card_cardinal_eq)
qed

subsection\<open>Cardinal multiplication\<close>

subsubsection\<open>Cardinal multiplication is commutative\<close>

lemma prod_commute_eqpoll: "A*B \<approx> B*A"
apply (unfold eqpoll_def)
apply (rule exI)
apply (rule_tac c = "%<x,y>.<y,x>" and d = "%<x,y>.<y,x>" in lam_bijective,
       auto)
done

lemma cmult_commute: "i \<otimes> j = j \<otimes> i"
apply (unfold cmult_def)
apply (rule prod_commute_eqpoll [THEN cardinal_cong])
done

subsubsection\<open>Cardinal multiplication is associative\<close>

lemma prod_assoc_eqpoll: "(A*B)*C \<approx> A*(B*C)"
apply (unfold eqpoll_def)
apply (rule exI)
apply (rule prod_assoc_bij)
done

text\<open>Unconditional version requires AC\<close>
lemma well_ord_cmult_assoc:
  assumes i: "well_ord(i,ri)" and j: "well_ord(j,rj)" and k: "well_ord(k,rk)"
  shows "(i \<otimes> j) \<otimes> k = i \<otimes> (j \<otimes> k)"
proof (unfold cmult_def, rule cardinal_cong)
  have "|i * j| * k \<approx> (i * j) * k"
    by (blast intro: prod_eqpoll_cong well_ord_cardinal_eqpoll eqpoll_refl well_ord_rmult i j)
  also have "...  \<approx> i * (j * k)"
    by (rule prod_assoc_eqpoll)
  also have "...  \<approx> i * |j * k|"
    by (blast intro: prod_eqpoll_cong well_ord_cardinal_eqpoll eqpoll_refl well_ord_rmult j k eqpoll_sym)
  finally show "|i * j| * k \<approx> i * |j * k|" .
qed

subsubsection\<open>Cardinal multiplication distributes over addition\<close>

lemma sum_prod_distrib_eqpoll: "(A+B)*C \<approx> (A*C)+(B*C)"
apply (unfold eqpoll_def)
apply (rule exI)
apply (rule sum_prod_distrib_bij)
done

lemma well_ord_cadd_cmult_distrib:
  assumes i: "well_ord(i,ri)" and j: "well_ord(j,rj)" and k: "well_ord(k,rk)"
  shows "(i \<oplus> j) \<otimes> k = (i \<otimes> k) \<oplus> (j \<otimes> k)"
proof (unfold cadd_def cmult_def, rule cardinal_cong)
  have "|i + j| * k \<approx> (i + j) * k"
    by (blast intro: prod_eqpoll_cong well_ord_cardinal_eqpoll eqpoll_refl well_ord_radd i j)
  also have "...  \<approx> i * k + j * k"
    by (rule sum_prod_distrib_eqpoll)
  also have "...  \<approx> |i * k| + |j * k|"
    by (blast intro: sum_eqpoll_cong well_ord_cardinal_eqpoll well_ord_rmult i j k eqpoll_sym)
  finally show "|i + j| * k \<approx> |i * k| + |j * k|" .
qed

subsubsection\<open>Multiplication by 0 yields 0\<close>

lemma prod_0_eqpoll: "0*A \<approx> 0"
apply (unfold eqpoll_def)
apply (rule exI)
apply (rule lam_bijective, safe)
done

lemma cmult_0 [simp]: "0 \<otimes> i = 0"
by (simp add: cmult_def prod_0_eqpoll [THEN cardinal_cong])

subsubsection\<open>1 is the identity for multiplication\<close>

lemma prod_singleton_eqpoll: "{x}*A \<approx> A"
apply (unfold eqpoll_def)
apply (rule exI)
apply (rule singleton_prod_bij [THEN bij_converse_bij])
done

lemma cmult_1 [simp]: "Card(K) ==> 1 \<otimes> K = K"
apply (unfold cmult_def succ_def)
apply (simp add: prod_singleton_eqpoll [THEN cardinal_cong] Card_cardinal_eq)
done

subsection\<open>Some inequalities for multiplication\<close>

lemma prod_square_lepoll: "A \<lesssim> A*A"
apply (unfold lepoll_def inj_def)
apply (rule_tac x = "\<lambda>x\<in>A. <x,x>" in exI, simp)
done

(*Could probably weaken the premise to well_ord(K,r), or remove using AC*)
lemma cmult_square_le: "Card(K) ==> K \<le> K \<otimes> K"
apply (unfold cmult_def)
apply (rule le_trans)
apply (rule_tac [2] well_ord_lepoll_imp_Card_le)
apply (rule_tac [3] prod_square_lepoll)
apply (simp add: le_refl Card_is_Ord Card_cardinal_eq)
apply (blast intro: well_ord_rmult well_ord_Memrel Card_is_Ord)
done

subsubsection\<open>Multiplication by a non-zero cardinal\<close>

lemma prod_lepoll_self: "b \<in> B ==> A \<lesssim> A*B"
apply (unfold lepoll_def inj_def)
apply (rule_tac x = "\<lambda>x\<in>A. <x,b>" in exI, simp)
done

(*Could probably weaken the premises to well_ord(K,r), or removing using AC*)
lemma cmult_le_self:
    "[| Card(K);  Ord(L);  0<L |] ==> K \<le> (K \<otimes> L)"
apply (unfold cmult_def)
apply (rule le_trans [OF Card_cardinal_le well_ord_lepoll_imp_Card_le])
  apply assumption
 apply (blast intro: well_ord_rmult well_ord_Memrel Card_is_Ord)
apply (blast intro: prod_lepoll_self ltD)
done

subsubsection\<open>Monotonicity of multiplication\<close>

lemma prod_lepoll_mono:
     "[| A \<lesssim> C;  B \<lesssim> D |] ==> A * B  \<lesssim>  C * D"
apply (unfold lepoll_def)
apply (elim exE)
apply (rule_tac x = "lam <w,y>:A*B. <f`w, fa`y>" in exI)
apply (rule_tac d = "%<w,y>. <converse (f) `w, converse (fa) `y>"
       in lam_injective)
apply (typecheck add: inj_is_fun, auto)
done

lemma cmult_le_mono:
    "[| K' \<le> K;  L' \<le> L |] ==> (K' \<otimes> L') \<le> (K \<otimes> L)"
apply (unfold cmult_def)
apply (safe dest!: le_subset_iff [THEN iffD1])
apply (rule well_ord_lepoll_imp_Card_le)
 apply (blast intro: well_ord_rmult well_ord_Memrel)
apply (blast intro: prod_lepoll_mono subset_imp_lepoll)
done

subsection\<open>Multiplication of finite cardinals is "ordinary" multiplication\<close>

lemma prod_succ_eqpoll: "succ(A)*B \<approx> B + A*B"
apply (unfold eqpoll_def)
apply (rule exI)
apply (rule_tac c = "%<x,y>. if x=A then Inl (y) else Inr (<x,y>)"
            and d = "case (%y. <A,y>, %z. z)" in lam_bijective)
apply safe
apply (simp_all add: succI2 if_type mem_imp_not_eq)
done

(*Unconditional version requires AC*)
lemma cmult_succ_lemma:
    "[| Ord(m);  Ord(n) |] ==> succ(m) \<otimes> n = n \<oplus> (m \<otimes> n)"
apply (unfold cmult_def cadd_def)
apply (rule prod_succ_eqpoll [THEN cardinal_cong, THEN trans])
apply (rule cardinal_cong [symmetric])
apply (rule sum_eqpoll_cong [OF eqpoll_refl well_ord_cardinal_eqpoll])
apply (blast intro: well_ord_rmult well_ord_Memrel)
done

lemma nat_cmult_eq_mult: "[| m \<in> nat;  n \<in> nat |] ==> m \<otimes> n = m#*n"
apply (induct_tac m)
apply (simp_all add: cmult_succ_lemma nat_cadd_eq_add)
done

lemma cmult_2: "Card(n) ==> 2 \<otimes> n = n \<oplus> n"
by (simp add: cmult_succ_lemma Card_is_Ord cadd_commute [of _ 0])

lemma sum_lepoll_prod:
  assumes C: "2 \<lesssim> C" shows "B+B \<lesssim> C*B"
proof -
  have "B+B \<lesssim> 2*B"
    by (simp add: sum_eq_2_times)
  also have "... \<lesssim> C*B"
    by (blast intro: prod_lepoll_mono lepoll_refl C)
  finally show "B+B \<lesssim> C*B" .
qed

lemma lepoll_imp_sum_lepoll_prod: "[| A \<lesssim> B; 2 \<lesssim> A |] ==> A+B \<lesssim> A*B"
by (blast intro: sum_lepoll_mono sum_lepoll_prod lepoll_trans lepoll_refl)

subsection\<open>Infinite Cardinals are Limit Ordinals\<close>

(*This proof is modelled upon one assuming nat<=A, with injection
  \<lambda>z\<in>cons(u,A). if z=u then 0 else if z \<in> nat then succ(z) else z
  and inverse %y. if y \<in> nat then nat_case(u, %z. z, y) else y.  \
  If f \<in> inj(nat,A) then range(f) behaves like the natural numbers.*)
lemma nat_cons_lepoll: "nat \<lesssim> A ==> cons(u,A) \<lesssim> A"
apply (unfold lepoll_def)
apply (erule exE)
apply (rule_tac x =
          "\<lambda>z\<in>cons (u,A).
             if z=u then f`0
             else if z \<in> range (f) then f`succ (converse (f) `z) else z"
       in exI)
apply (rule_tac d =
          "%y. if y \<in> range(f) then nat_case (u, %z. f`z, converse(f) `y)
                              else y"
       in lam_injective)
apply (fast intro!: if_type apply_type intro: inj_is_fun inj_converse_fun)
apply (simp add: inj_is_fun [THEN apply_rangeI]
                 inj_converse_fun [THEN apply_rangeI]
                 inj_converse_fun [THEN apply_funtype])
done

lemma nat_cons_eqpoll: "nat \<lesssim> A ==> cons(u,A) \<approx> A"
apply (erule nat_cons_lepoll [THEN eqpollI])
apply (rule subset_consI [THEN subset_imp_lepoll])
done

(*Specialized version required below*)
lemma nat_succ_eqpoll: "nat \<subseteq> A ==> succ(A) \<approx> A"
apply (unfold succ_def)
apply (erule subset_imp_lepoll [THEN nat_cons_eqpoll])
done

lemma InfCard_nat: "InfCard(nat)"
apply (unfold InfCard_def)
apply (blast intro: Card_nat le_refl Card_is_Ord)
done

lemma InfCard_is_Card: "InfCard(K) ==> Card(K)"
apply (unfold InfCard_def)
apply (erule conjunct1)
done

lemma InfCard_Un:
    "[| InfCard(K);  Card(L) |] ==> InfCard(K \<union> L)"
apply (unfold InfCard_def)
apply (simp add: Card_Un Un_upper1_le [THEN [2] le_trans]  Card_is_Ord)
done

(*Kunen's Lemma 10.11*)
lemma InfCard_is_Limit: "InfCard(K) ==> Limit(K)"
apply (unfold InfCard_def)
apply (erule conjE)
apply (frule Card_is_Ord)
apply (rule ltI [THEN non_succ_LimitI])
apply (erule le_imp_subset [THEN subsetD])
apply (safe dest!: Limit_nat [THEN Limit_le_succD])
apply (unfold Card_def)
apply (drule trans)
apply (erule le_imp_subset [THEN nat_succ_eqpoll, THEN cardinal_cong])
apply (erule Ord_cardinal_le [THEN lt_trans2, THEN lt_irrefl])
apply (rule le_eqI, assumption)
apply (rule Ord_cardinal)
done

(*** An infinite cardinal equals its square (Kunen, Thm 10.12, page 29) ***)

(*A general fact about ordermap*)
lemma ordermap_eqpoll_pred:
    "[| well_ord(A,r);  x \<in> A |] ==> ordermap(A,r)`x \<approx> Order.pred(A,x,r)"
apply (unfold eqpoll_def)
apply (rule exI)
apply (simp add: ordermap_eq_image well_ord_is_wf)
apply (erule ordermap_bij [THEN bij_is_inj, THEN restrict_bij,
                           THEN bij_converse_bij])
apply (rule pred_subset)
done

subsubsection\<open>Establishing the well-ordering\<close>

lemma well_ord_csquare:
  assumes K: "Ord(K)" shows "well_ord(K*K, csquare_rel(K))"
proof (unfold csquare_rel_def, rule well_ord_rvimage)
  show "(\<lambda>\<langle>x,y\<rangle>\<in>K \<times> K. \<langle>x \<union> y, x, y\<rangle>) \<in> inj(K \<times> K, K \<times> K \<times> K)" using K
    by (force simp add: inj_def intro: lam_type Un_least_lt [THEN ltD] ltI)
next
  show "well_ord(K \<times> K \<times> K, rmult(K, Memrel(K), K \<times> K, rmult(K, Memrel(K), K, Memrel(K))))"
    using K by (blast intro: well_ord_rmult well_ord_Memrel)
qed

subsubsection\<open>Characterising initial segments of the well-ordering\<close>

lemma csquareD:
 "[| <<x,y>, <z,z>> \<in> csquare_rel(K);  x<K;  y<K;  z<K |] ==> x \<le> z & y \<le> z"
apply (unfold csquare_rel_def)
apply (erule rev_mp)
apply (elim ltE)
apply (simp add: rvimage_iff Un_absorb Un_least_mem_iff ltD)
apply (safe elim!: mem_irrefl intro!: Un_upper1_le Un_upper2_le)
apply (simp_all add: lt_def succI2)
done

lemma pred_csquare_subset:
    "z<K ==> Order.pred(K*K, <z,z>, csquare_rel(K)) \<subseteq> succ(z)*succ(z)"
apply (unfold Order.pred_def)
apply (safe del: SigmaI dest!: csquareD)
apply (unfold lt_def, auto)
done

lemma csquare_ltI:
 "[| x<z;  y<z;  z<K |] ==>  <<x,y>, <z,z>> \<in> csquare_rel(K)"
apply (unfold csquare_rel_def)
apply (subgoal_tac "x<K & y<K")
 prefer 2 apply (blast intro: lt_trans)
apply (elim ltE)
apply (simp add: rvimage_iff Un_absorb Un_least_mem_iff ltD)
done

(*Part of the traditional proof.  UNUSED since it's harder to prove & apply *)
lemma csquare_or_eqI:
 "[| x \<le> z;  y \<le> z;  z<K |] ==> <<x,y>, <z,z>> \<in> csquare_rel(K) | x=z & y=z"
apply (unfold csquare_rel_def)
apply (subgoal_tac "x<K & y<K")
 prefer 2 apply (blast intro: lt_trans1)
apply (elim ltE)
apply (simp add: rvimage_iff Un_absorb Un_least_mem_iff ltD)
apply (elim succE)
apply (simp_all add: subset_Un_iff [THEN iff_sym]
                     subset_Un_iff2 [THEN iff_sym] OrdmemD)
done

subsubsection\<open>The cardinality of initial segments\<close>

lemma ordermap_z_lt:
      "[| Limit(K);  x<K;  y<K;  z=succ(x \<union> y) |] ==>
          ordermap(K*K, csquare_rel(K)) ` <x,y> <
          ordermap(K*K, csquare_rel(K)) ` <z,z>"
apply (subgoal_tac "z<K & well_ord (K*K, csquare_rel (K))")
prefer 2 apply (blast intro!: Un_least_lt Limit_has_succ
                              Limit_is_Ord [THEN well_ord_csquare], clarify)
apply (rule csquare_ltI [THEN ordermap_mono, THEN ltI])
apply (erule_tac [4] well_ord_is_wf)
apply (blast intro!: Un_upper1_le Un_upper2_le Ord_ordermap elim!: ltE)+
done

text\<open>Kunen: "each @{term"\<langle>x,y\<rangle> \<in> K \<times> K"} has no more than @{term"z \<times> z"} predecessors..." (page 29)\<close>
lemma ordermap_csquare_le:
  assumes K: "Limit(K)" and x: "x<K" and y: " y<K"
  defines "z \<equiv> succ(x \<union> y)"
  shows "|ordermap(K \<times> K, csquare_rel(K)) ` \<langle>x,y\<rangle>| \<le> |succ(z)| \<otimes> |succ(z)|"
proof (unfold cmult_def, rule well_ord_lepoll_imp_Card_le)
  show "well_ord(|succ(z)| \<times> |succ(z)|,
                 rmult(|succ(z)|, Memrel(|succ(z)|), |succ(z)|, Memrel(|succ(z)|)))"
    by (blast intro: Ord_cardinal well_ord_Memrel well_ord_rmult)
next
  have zK: "z<K" using x y K z_def
    by (blast intro: Un_least_lt Limit_has_succ)
  hence oz: "Ord(z)" by (elim ltE)
  have "ordermap(K \<times> K, csquare_rel(K)) ` \<langle>x,y\<rangle> \<lesssim> ordermap(K \<times> K, csquare_rel(K)) ` \<langle>z,z\<rangle>"
    using z_def
    by (blast intro: ordermap_z_lt leI le_imp_lepoll K x y)
  also have "... \<approx>  Order.pred(K \<times> K, \<langle>z,z\<rangle>, csquare_rel(K))"
    proof (rule ordermap_eqpoll_pred)
      show "well_ord(K \<times> K, csquare_rel(K))" using K
        by (rule Limit_is_Ord [THEN well_ord_csquare])
    next
      show "\<langle>z, z\<rangle> \<in> K \<times> K" using zK
        by (blast intro: ltD)
    qed
  also have "...  \<lesssim> succ(z) \<times> succ(z)" using zK
    by (rule pred_csquare_subset [THEN subset_imp_lepoll])
  also have "... \<approx> |succ(z)| \<times> |succ(z)|" using oz
    by (blast intro: prod_eqpoll_cong Ord_succ Ord_cardinal_eqpoll eqpoll_sym)
  finally show "ordermap(K \<times> K, csquare_rel(K)) ` \<langle>x,y\<rangle> \<lesssim> |succ(z)| \<times> |succ(z)|" .
qed

text\<open>Kunen: "... so the order type is \<open>\<le>\<close> K"\<close>
lemma ordertype_csquare_le:
  assumes IK: "InfCard(K)" and eq: "\<And>y. y\<in>K \<Longrightarrow> InfCard(y) \<Longrightarrow> y \<otimes> y = y"
  shows "ordertype(K*K, csquare_rel(K)) \<le> K"
proof -
  have  CK: "Card(K)" using IK by (rule InfCard_is_Card)
  hence OK: "Ord(K)"  by (rule Card_is_Ord)
  moreover have "Ord(ordertype(K \<times> K, csquare_rel(K)))" using OK
    by (rule well_ord_csquare [THEN Ord_ordertype])
  ultimately show ?thesis
  proof (rule all_lt_imp_le)
    fix i
    assume i: "i < ordertype(K \<times> K, csquare_rel(K))"
    hence Oi: "Ord(i)" by (elim ltE)
    obtain x y where x: "x \<in> K" and y: "y \<in> K"
                 and ieq: "i = ordermap(K \<times> K, csquare_rel(K)) ` \<langle>x,y\<rangle>"
      using i by (auto simp add: ordertype_unfold elim: ltE)
    hence xy: "Ord(x)" "Ord(y)" "x < K" "y < K" using OK
      by (blast intro: Ord_in_Ord ltI)+
    hence ou: "Ord(x \<union> y)"
      by (simp add: Ord_Un)
    show "i < K"
      proof (rule Card_lt_imp_lt [OF _ Oi CK])
        have "|i| \<le> |succ(succ(x \<union> y))| \<otimes> |succ(succ(x \<union> y))|" using IK xy
          by (auto simp add: ieq intro: InfCard_is_Limit [THEN ordermap_csquare_le])
        moreover have "|succ(succ(x \<union> y))| \<otimes> |succ(succ(x \<union> y))| < K"
          proof (cases rule: Ord_linear2 [OF ou Ord_nat])
            assume "x \<union> y < nat"
            hence "|succ(succ(x \<union> y))| \<otimes> |succ(succ(x \<union> y))| \<in> nat"
              by (simp add: lt_def nat_cmult_eq_mult nat_succI mult_type
                         nat_into_Card [THEN Card_cardinal_eq]  Ord_nat)
            also have "... \<subseteq> K" using IK
              by (simp add: InfCard_def le_imp_subset)
            finally show "|succ(succ(x \<union> y))| \<otimes> |succ(succ(x \<union> y))| < K"
              by (simp add: ltI OK)
          next
            assume natxy: "nat \<le> x \<union> y"
            hence seq: "|succ(succ(x \<union> y))| = |x \<union> y|" using xy
              by (simp add: le_imp_subset nat_succ_eqpoll [THEN cardinal_cong] le_succ_iff)
            also have "... < K" using xy
              by (simp add: Un_least_lt Ord_cardinal_le [THEN lt_trans1])
            finally have "|succ(succ(x \<union> y))| < K" .
            moreover have "InfCard(|succ(succ(x \<union> y))|)" using xy natxy
              by (simp add: seq InfCard_def Card_cardinal nat_le_cardinal)
            ultimately show ?thesis  by (simp add: eq ltD)
          qed
        ultimately show "|i| < K" by (blast intro: lt_trans1)
    qed
  qed
qed

(*Main result: Kunen's Theorem 10.12*)
lemma InfCard_csquare_eq:
  assumes IK: "InfCard(K)" shows "InfCard(K) ==> K \<otimes> K = K"
proof -
  have  OK: "Ord(K)" using IK by (simp add: Card_is_Ord InfCard_is_Card)
  show "InfCard(K) ==> K \<otimes> K = K" using OK
  proof (induct rule: trans_induct)
    case (step i)
    show "i \<otimes> i = i"
    proof (rule le_anti_sym)
      have "|i \<times> i| = |ordertype(i \<times> i, csquare_rel(i))|"
        by (rule cardinal_cong,
          simp add: step.hyps well_ord_csquare [THEN ordermap_bij, THEN bij_imp_eqpoll])
      hence "i \<otimes> i \<le> ordertype(i \<times> i, csquare_rel(i))"
        by (simp add: step.hyps cmult_def Ord_cardinal_le well_ord_csquare [THEN Ord_ordertype])
      moreover
      have "ordertype(i \<times> i, csquare_rel(i)) \<le> i" using step
        by (simp add: ordertype_csquare_le)
      ultimately show "i \<otimes> i \<le> i" by (rule le_trans)
    next
      show "i \<le> i \<otimes> i" using step
        by (blast intro: cmult_square_le InfCard_is_Card)
    qed
  qed
qed

(*Corollary for arbitrary well-ordered sets (all sets, assuming AC)*)
lemma well_ord_InfCard_square_eq:
  assumes r: "well_ord(A,r)" and I: "InfCard(|A|)" shows "A \<times> A \<approx> A"
proof -
  have "A \<times> A \<approx> |A| \<times> |A|"
    by (blast intro: prod_eqpoll_cong well_ord_cardinal_eqpoll eqpoll_sym r)
  also have "... \<approx> A"
    proof (rule well_ord_cardinal_eqE [OF _ r])
      show "well_ord(|A| \<times> |A|, rmult(|A|, Memrel(|A|), |A|, Memrel(|A|)))"
        by (blast intro: Ord_cardinal well_ord_rmult well_ord_Memrel r)
    next
      show "||A| \<times> |A|| = |A|" using InfCard_csquare_eq I
        by (simp add: cmult_def)
    qed
  finally show ?thesis .
qed

lemma InfCard_square_eqpoll: "InfCard(K) ==> K \<times> K \<approx> K"
apply (rule well_ord_InfCard_square_eq)
 apply (erule InfCard_is_Card [THEN Card_is_Ord, THEN well_ord_Memrel])
apply (simp add: InfCard_is_Card [THEN Card_cardinal_eq])
done

lemma Inf_Card_is_InfCard: "[| Card(i); ~ Finite(i) |] ==> InfCard(i)"
by (simp add: InfCard_def Card_is_Ord [THEN nat_le_infinite_Ord])

subsubsection\<open>Toward's Kunen's Corollary 10.13 (1)\<close>

lemma InfCard_le_cmult_eq: "[| InfCard(K);  L \<le> K;  0<L |] ==> K \<otimes> L = K"
apply (rule le_anti_sym)
 prefer 2
 apply (erule ltE, blast intro: cmult_le_self InfCard_is_Card)
apply (frule InfCard_is_Card [THEN Card_is_Ord, THEN le_refl])
apply (rule cmult_le_mono [THEN le_trans], assumption+)
apply (simp add: InfCard_csquare_eq)
done

(*Corollary 10.13 (1), for cardinal multiplication*)
lemma InfCard_cmult_eq: "[| InfCard(K);  InfCard(L) |] ==> K \<otimes> L = K \<union> L"
apply (rule_tac i = K and j = L in Ord_linear_le)
apply (typecheck add: InfCard_is_Card Card_is_Ord)
apply (rule cmult_commute [THEN ssubst])
apply (rule Un_commute [THEN ssubst])
apply (simp_all add: InfCard_is_Limit [THEN Limit_has_0] InfCard_le_cmult_eq
                     subset_Un_iff2 [THEN iffD1] le_imp_subset)
done

lemma InfCard_cdouble_eq: "InfCard(K) ==> K \<oplus> K = K"
apply (simp add: cmult_2 [symmetric] InfCard_is_Card cmult_commute)
apply (simp add: InfCard_le_cmult_eq InfCard_is_Limit Limit_has_0 Limit_has_succ)
done

(*Corollary 10.13 (1), for cardinal addition*)
lemma InfCard_le_cadd_eq: "[| InfCard(K);  L \<le> K |] ==> K \<oplus> L = K"
apply (rule le_anti_sym)
 prefer 2
 apply (erule ltE, blast intro: cadd_le_self InfCard_is_Card)
apply (frule InfCard_is_Card [THEN Card_is_Ord, THEN le_refl])
apply (rule cadd_le_mono [THEN le_trans], assumption+)
apply (simp add: InfCard_cdouble_eq)
done

lemma InfCard_cadd_eq: "[| InfCard(K);  InfCard(L) |] ==> K \<oplus> L = K \<union> L"
apply (rule_tac i = K and j = L in Ord_linear_le)
apply (typecheck add: InfCard_is_Card Card_is_Ord)
apply (rule cadd_commute [THEN ssubst])
apply (rule Un_commute [THEN ssubst])
apply (simp_all add: InfCard_le_cadd_eq subset_Un_iff2 [THEN iffD1] le_imp_subset)
done

(*The other part, Corollary 10.13 (2), refers to the cardinality of the set
  of all n-tuples of elements of K.  A better version for the Isabelle theory
  might be  InfCard(K) ==> |list(K)| = K.
*)

subsection\<open>For Every Cardinal Number There Exists A Greater One\<close>

text\<open>This result is Kunen's Theorem 10.16, which would be trivial using AC\<close>

lemma Ord_jump_cardinal: "Ord(jump_cardinal(K))"
apply (unfold jump_cardinal_def)
apply (rule Ord_is_Transset [THEN [2] OrdI])
 prefer 2 apply (blast intro!: Ord_ordertype)
apply (unfold Transset_def)
apply (safe del: subsetI)
apply (simp add: ordertype_pred_unfold, safe)
apply (rule UN_I)
apply (rule_tac [2] ReplaceI)
   prefer 4 apply (blast intro: well_ord_subset elim!: predE)+
done

(*Allows selective unfolding.  Less work than deriving intro/elim rules*)
lemma jump_cardinal_iff:
     "i \<in> jump_cardinal(K) \<longleftrightarrow>
      (\<exists>r X. r \<subseteq> K*K & X \<subseteq> K & well_ord(X,r) & i = ordertype(X,r))"
apply (unfold jump_cardinal_def)
apply (blast del: subsetI)
done

(*The easy part of Theorem 10.16: jump_cardinal(K) exceeds K*)
lemma K_lt_jump_cardinal: "Ord(K) ==> K < jump_cardinal(K)"
apply (rule Ord_jump_cardinal [THEN [2] ltI])
apply (rule jump_cardinal_iff [THEN iffD2])
apply (rule_tac x="Memrel(K)" in exI)
apply (rule_tac x=K in exI)
apply (simp add: ordertype_Memrel well_ord_Memrel)
apply (simp add: Memrel_def subset_iff)
done

(*The proof by contradiction: the bijection f yields a wellordering of X
  whose ordertype is jump_cardinal(K).  *)
lemma Card_jump_cardinal_lemma:
     "[| well_ord(X,r);  r \<subseteq> K * K;  X \<subseteq> K;
         f \<in> bij(ordertype(X,r), jump_cardinal(K)) |]
      ==> jump_cardinal(K) \<in> jump_cardinal(K)"
apply (subgoal_tac "f O ordermap (X,r) \<in> bij (X, jump_cardinal (K))")
 prefer 2 apply (blast intro: comp_bij ordermap_bij)
apply (rule jump_cardinal_iff [THEN iffD2])
apply (intro exI conjI)
apply (rule subset_trans [OF rvimage_type Sigma_mono], assumption+)
apply (erule bij_is_inj [THEN well_ord_rvimage])
apply (rule Ord_jump_cardinal [THEN well_ord_Memrel])
apply (simp add: well_ord_Memrel [THEN [2] bij_ordertype_vimage]
                 ordertype_Memrel Ord_jump_cardinal)
done

(*The hard part of Theorem 10.16: jump_cardinal(K) is itself a cardinal*)
lemma Card_jump_cardinal: "Card(jump_cardinal(K))"
apply (rule Ord_jump_cardinal [THEN CardI])
apply (unfold eqpoll_def)
apply (safe dest!: ltD jump_cardinal_iff [THEN iffD1])
apply (blast intro: Card_jump_cardinal_lemma [THEN mem_irrefl])
done

subsection\<open>Basic Properties of Successor Cardinals\<close>

lemma csucc_basic: "Ord(K) ==> Card(csucc(K)) & K < csucc(K)"
apply (unfold csucc_def)
apply (rule LeastI)
apply (blast intro: Card_jump_cardinal K_lt_jump_cardinal Ord_jump_cardinal)+
done

lemmas Card_csucc = csucc_basic [THEN conjunct1]

lemmas lt_csucc = csucc_basic [THEN conjunct2]

lemma Ord_0_lt_csucc: "Ord(K) ==> 0 < csucc(K)"
by (blast intro: Ord_0_le lt_csucc lt_trans1)

lemma csucc_le: "[| Card(L);  K<L |] ==> csucc(K) \<le> L"
apply (unfold csucc_def)
apply (rule Least_le)
apply (blast intro: Card_is_Ord)+
done

lemma lt_csucc_iff: "[| Ord(i); Card(K) |] ==> i < csucc(K) \<longleftrightarrow> |i| \<le> K"
apply (rule iffI)
apply (rule_tac [2] Card_lt_imp_lt)
apply (erule_tac [2] lt_trans1)
apply (simp_all add: lt_csucc Card_csucc Card_is_Ord)
apply (rule notI [THEN not_lt_imp_le])
apply (rule Card_cardinal [THEN csucc_le, THEN lt_trans1, THEN lt_irrefl], assumption)
apply (rule Ord_cardinal_le [THEN lt_trans1])
apply (simp_all add: Ord_cardinal Card_is_Ord)
done

lemma Card_lt_csucc_iff:
     "[| Card(K'); Card(K) |] ==> K' < csucc(K) \<longleftrightarrow> K' \<le> K"
by (simp add: lt_csucc_iff Card_cardinal_eq Card_is_Ord)

lemma InfCard_csucc: "InfCard(K) ==> InfCard(csucc(K))"
by (simp add: InfCard_def Card_csucc Card_is_Ord
              lt_csucc [THEN leI, THEN [2] le_trans])

subsubsection\<open>Removing elements from a finite set decreases its cardinality\<close>

lemma Finite_imp_cardinal_cons [simp]:
  assumes FA: "Finite(A)" and a: "a\<notin>A" shows "|cons(a,A)| = succ(|A|)"
proof -
  { fix X
    have "Finite(X) ==> a \<notin> X \<Longrightarrow> cons(a,X) \<lesssim> X \<Longrightarrow> False"
      proof (induct X rule: Finite_induct)
        case 0 thus False  by (simp add: lepoll_0_iff)
      next
        case (cons x Y)
        hence "cons(x, cons(a, Y)) \<lesssim> cons(x, Y)" by (simp add: cons_commute)
        hence "cons(a, Y) \<lesssim> Y" using cons        by (blast dest: cons_lepoll_consD)
        thus False using cons by auto
      qed
  }
  hence [simp]: "~ cons(a,A) \<lesssim> A" using a FA by auto
  have [simp]: "|A| \<approx> A" using Finite_imp_well_ord [OF FA]
    by (blast intro: well_ord_cardinal_eqpoll)
  have "(\<mu> i. i \<approx> cons(a, A)) = succ(|A|)"
    proof (rule Least_equality [OF _ _ notI])
      show "succ(|A|) \<approx> cons(a, A)"
        by (simp add: succ_def cons_eqpoll_cong mem_not_refl a)
    next
      show "Ord(succ(|A|))" by simp
    next
      fix i
      assume i: "i \<le> |A|" "i \<approx> cons(a, A)"
      have "cons(a, A) \<approx> i" by (rule eqpoll_sym) (rule i)
      also have "... \<lesssim> |A|" by (rule le_imp_lepoll) (rule i)
      also have "... \<approx> A"   by simp
      finally have "cons(a, A) \<lesssim> A" .
      thus False by simp
    qed
  thus ?thesis by (simp add: cardinal_def)
qed

lemma Finite_imp_succ_cardinal_Diff:
     "[| Finite(A);  a \<in> A |] ==> succ(|A-{a}|) = |A|"
apply (rule_tac b = A in cons_Diff [THEN subst], assumption)
apply (simp add: Finite_imp_cardinal_cons Diff_subset [THEN subset_Finite])
apply (simp add: cons_Diff)
done

lemma Finite_imp_cardinal_Diff: "[| Finite(A);  a \<in> A |] ==> |A-{a}| < |A|"
apply (rule succ_leE)
apply (simp add: Finite_imp_succ_cardinal_Diff)
done

lemma Finite_cardinal_in_nat [simp]: "Finite(A) ==> |A| \<in> nat"
proof (induct rule: Finite_induct)
  case 0 thus ?case by (simp add: cardinal_0)
next
  case (cons x A) thus ?case by (simp add: Finite_imp_cardinal_cons)
qed

lemma card_Un_Int:
     "[|Finite(A); Finite(B)|] ==> |A| #+ |B| = |A \<union> B| #+ |A \<inter> B|"
apply (erule Finite_induct, simp)
apply (simp add: Finite_Int cons_absorb Un_cons Int_cons_left)
done

lemma card_Un_disjoint:
     "[|Finite(A); Finite(B); A \<inter> B = 0|] ==> |A \<union> B| = |A| #+ |B|"
by (simp add: Finite_Un card_Un_Int)

lemma card_partition:
  assumes FC: "Finite(C)"
  shows
     "Finite (\<Union> C) \<Longrightarrow>
        (\<forall>c\<in>C. |c| = k) \<Longrightarrow>
        (\<forall>c1 \<in> C. \<forall>c2 \<in> C. c1 \<noteq> c2 \<longrightarrow> c1 \<inter> c2 = 0) \<Longrightarrow>
        k #* |C| = |\<Union> C|"
using FC
proof (induct rule: Finite_induct)
  case 0 thus ?case by simp
next
  case (cons x B)
  hence "x \<inter> \<Union>B = 0" by auto
  thus ?case using cons
    by (auto simp add: card_Un_disjoint)
qed

subsubsection\<open>Theorems by Krzysztof Grabczewski, proofs by lcp\<close>

lemmas nat_implies_well_ord = nat_into_Ord [THEN well_ord_Memrel]

lemma nat_sum_eqpoll_sum:
  assumes m: "m \<in> nat" and n: "n \<in> nat" shows "m + n \<approx> m #+ n"
proof -
  have "m + n \<approx> |m+n|" using m n
    by (blast intro: nat_implies_well_ord well_ord_radd well_ord_cardinal_eqpoll eqpoll_sym)
  also have "... = m #+ n" using m n
    by (simp add: nat_cadd_eq_add [symmetric] cadd_def)
  finally show ?thesis .
qed

lemma Ord_subset_natD [rule_format]: "Ord(i) ==> i \<subseteq> nat \<Longrightarrow> i \<in> nat | i=nat"
proof (induct i rule: trans_induct3)
  case 0 thus ?case by auto
next
  case (succ i) thus ?case by auto
next
  case (limit l) thus ?case
    by (blast dest: nat_le_Limit le_imp_subset)
qed

lemma Ord_nat_subset_into_Card: "[| Ord(i); i \<subseteq> nat |] ==> Card(i)"
by (blast dest: Ord_subset_natD intro: Card_nat nat_into_Card)

end


chapter \<open>Specification Framework\<close>

theory Spec_Framework
  imports Phi_BI "Phi_Semantics_Framework.Phi_Semantics_Framework"
  abbrevs "<shifts>" = "\<s>\<h>\<i>\<f>\<t>\<s>"
    and   "<val>" = "\<v>\<a>\<l>"
begin

section \<open>Specification of Value\<close>

type_synonym rassn = \<open>resource set\<close>
type_synonym vassn = \<open>VAL set\<close>

subsection \<open>Primitive \<phi>-Types\<close>

subsubsection \<open>Value\<close>

definition Val :: \<open>VAL \<phi>arg \<Rightarrow> (VAL, 'a) \<phi> \<Rightarrow> ('x::one, 'a) \<phi>\<close> ("\<v>\<a>\<l>[_] _" [22,22] 21)
  where \<open>Val val T = (\<lambda>x. 1 \<s>\<u>\<b>\<j> \<phi>arg.dest val \<in> (x \<Ztypecolon> T))\<close>

lemma Val_expn [\<phi>expns]:
  \<open>(x \<Ztypecolon> Val val T) = (1 \<s>\<u>\<b>\<j> \<phi>arg.dest val \<in> (x \<Ztypecolon> T))\<close>
  unfolding Val_def \<phi>Type_def by (simp add: \<phi>expns)

lemma Val_inhabited [\<phi>inhabitance_rule]:
  \<open>Inhabited (x \<Ztypecolon> Val val T) \<Longrightarrow> (Inhabited (x \<Ztypecolon> T) \<Longrightarrow> C) \<Longrightarrow> C\<close>
  unfolding Inhabited_def by (simp add: \<phi>expns) blast

lemma Val_inhabited_rewr:
  \<open>Inhabited (x \<Ztypecolon> Val val T) \<longleftrightarrow> \<phi>arg.dest val \<in> (x \<Ztypecolon> T)\<close>
  unfolding Inhabited_def by (clarsimp simp add: \<phi>expns)

paragraph \<open>Syntax\<close>

consts anonymous :: 'a

syntax val_syntax :: "logic \<Rightarrow> logic" ("\<v>\<a>\<l> _" [22] 21)

translations
  "\<v>\<a>\<l> x \<Ztypecolon> T" => "x \<Ztypecolon> CONST Val (CONST anonymous) T"
  "\<v>\<a>\<l> T" => "CONST Val (CONST anonymous) T"

ML_file \<open>library/syntax/value.ML\<close>

subsubsection \<open>Abnormality\<close>

definition AbnormalObj :: \<open>VAL \<phi>arg \<Rightarrow> (VAL, 'a) \<phi> \<Rightarrow> ('x::one, 'a) \<phi>\<close>
  where \<open>AbnormalObj \<equiv> Val\<close>

(*TODO: more about exception

Any exception object will be specified by this type. and by this we clarify the difference
between a value and an exception object.
Then in exception specs, any Val is senseless and will be removed.*)

subsection \<open>Semantic Type\<close>

subsubsection \<open>Single Value\<close>

definition \<phi>SemType :: "vassn \<Rightarrow> TY \<Rightarrow> bool"
  where \<open>\<phi>SemType S TY \<longleftrightarrow> S \<subseteq> Well_Type TY\<close>
  \<comment> \<open>Values specified by \<open>S\<close> are all of semantic type \<open>TY\<close>.\<close>

abbreviation \<phi>\<phi>SemType :: "(VAL, 'a) \<phi> \<Rightarrow> TY \<Rightarrow> bool"
  where \<open>\<phi>\<phi>SemType T TY \<equiv> (\<forall>x. \<phi>SemType (x \<Ztypecolon> T) TY)\<close>

(*lemma \<phi>SemType_unique:
  \<open> S \<noteq> {}
\<Longrightarrow> \<phi>SemType S T1
\<Longrightarrow> \<phi>SemType S T2
\<Longrightarrow> T1 = T2\<close>
  unfolding \<phi>SemType_def subset_iff
  using Well_Type_unique by blast *)

(* definition SemTyp_Of :: \<open>VAL set \<Rightarrow> TY\<close>
  where \<open>SemTyp_Of S = (@TY. \<phi>SemType S TY)\<close>

lemma SemTyp_Of_I[intro!, simp]:
  \<open>S \<noteq> {} \<Longrightarrow> \<phi>SemType S TY \<Longrightarrow> SemTyp_Of S = TY\<close>
  unfolding SemTyp_Of_def
  using \<phi>SemType_unique by blast *)

lemma [\<phi>reason 100]:
  \<open> (\<And>x. \<phi>SemType (x \<Ztypecolon> T) TY)
\<Longrightarrow> \<phi>\<phi>SemType T TY\<close>
  ..

subsubsection \<open>Multiple Values\<close>

definition Well_Typed_Vals :: \<open>TY list \<Rightarrow> 'a::VALs \<phi>arg set\<close>
  where \<open>Well_Typed_Vals TYs = {vs. list_all2 (\<lambda>v T. v \<in> Well_Type T) (to_vals (\<phi>arg.dest vs)) TYs}\<close>

definition \<phi>_Have_Types :: \<open>('a::VALs \<phi>arg \<Rightarrow> assn) \<Rightarrow> TY list \<Rightarrow> bool\<close>
  where \<open>\<phi>_Have_Types spec TYs = (\<forall>v. Inhabited (spec v) \<longrightarrow> v \<in> Well_Typed_Vals TYs)\<close>

declare [[\<phi>reason_default_pattern \<open>\<phi>_Have_Types ?S _\<close> \<Rightarrow> \<open>\<phi>_Have_Types ?S _\<close> (100)]]

subsubsection \<open>Reasoning Rules\<close>

declare [[\<phi>reason_default_pattern \<open>\<phi>SemType ?S ?TY\<close> \<Rightarrow> \<open>\<phi>SemType ?S _\<close> (100) ]]

lemma [\<phi>reason 1]:
  \<open>FAIL TEXT(\<open>Fail to reason the semantic type of\<close> X)
\<Longrightarrow> \<phi>SemType X Any\<close>
  by blast

lemma [\<phi>reason 1000]:
  \<open> \<phi>SemType X TY
\<Longrightarrow> \<phi>SemType Y TY
\<Longrightarrow> \<phi>SemType (X + Y) TY\<close>
  unfolding \<phi>SemType_def subset_iff by simp

lemma [\<phi>reason 1000]:
  \<open> \<phi>SemType X TY
\<Longrightarrow> \<phi>SemType (X \<s>\<u>\<b>\<j> P) TY\<close>
  unfolding \<phi>SemType_def subset_iff by (simp add: Subjection_expn)

lemma [\<phi>reason 1000]:
  \<open> (\<And>x. \<phi>SemType (X x) TY)
\<Longrightarrow> \<phi>SemType (ExSet X) TY\<close>
  unfolding \<phi>SemType_def subset_iff by (clarsimp simp add: ExSet_expn)

subsection \<open>Zero Value\<close>

definition \<phi>Zero :: "TY \<Rightarrow> (VAL,'a) \<phi> \<Rightarrow> 'a \<Rightarrow> bool"
  where "\<phi>Zero ty T x \<longleftrightarrow> Zero ty \<in> Some ` (x \<Ztypecolon> T)"

declare [[\<phi>reason_default_pattern \<open>\<phi>Zero ?TY ?T ?x\<close> \<Rightarrow> \<open>\<phi>Zero ?TY ?T _\<close> (100) ]]

subsection \<open>Equality\<close>

definition \<phi>Equal :: "(VAL,'a) \<phi> \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
  where "\<phi>Equal T can_eq eq \<longleftrightarrow> (\<forall>p1 p2 x1 x2 res.
    can_eq x1 x2 \<and> p1 \<in> (x1 \<Ztypecolon> T) \<and> p2 \<in> (x2 \<Ztypecolon> T)
      \<longrightarrow> Can_EqCompare res p1 p2 \<and> (EqCompare p1 p2 = eq x1 x2))"

declare [[\<phi>reason_default_pattern \<open>\<phi>Equal ?TY ?can_eq ?eq\<close> \<Rightarrow> \<open>\<phi>Equal ?TY _ _\<close> (100) ]]

subsection \<open>Functional\<close>

definition is_functional :: \<open>'a set \<Rightarrow> bool\<close>
  where \<open>is_functional S \<longleftrightarrow> (\<forall>x y. x \<in> S \<and> y \<in> S \<longrightarrow> x = y)\<close>

declare [[\<phi>reason_default_pattern \<open>is_functional ?S\<close> \<Rightarrow> \<open>is_functional ?S\<close> (100)]]

lemma is_functional_alt:
  \<open>is_functional S \<longleftrightarrow> (S = {} \<or> (\<exists>x. S = {x}))\<close>
  unfolding is_functional_def by blast

lemma is_functional_I[intro!]:
  \<open> (\<And>x y. x \<in> A \<Longrightarrow> y \<in> A \<Longrightarrow> x = y)
\<Longrightarrow> is_functional A \<close>
  unfolding is_functional_def by blast

lemma is_functional_imp:
  \<open> S \<i>\<m>\<p>\<l>\<i>\<e>\<s> S'
\<Longrightarrow> is_functional S'
\<Longrightarrow> is_functional S\<close>
  unfolding Imply_def is_functional_def
  by blast

lemma is_singletonI'':
  \<open> \<exists>p. p \<in> A \<comment> \<open>TODO: model this\<close>
\<Longrightarrow> (\<And>x y. x \<in> A \<Longrightarrow> y \<in> A \<Longrightarrow> x = y)
\<Longrightarrow> is_singleton A\<close>
  by (metis equals0D is_singletonI')

lemma [\<phi>reason 1]:
  \<open> FAIL TEXT(\<open>Fail to prove\<close> S \<open>is functional\<close>)
\<Longrightarrow> is_functional S\<close>
  by blast

section \<open>Specification of Monadic States\<close>

definition StrictStateSpec :: "('ret::VALs \<phi>arg \<Rightarrow> rassn)
                          \<Rightarrow> (ABNM \<Rightarrow> rassn)
                          \<Rightarrow> 'ret comp set" ("!\<S>")
  where "!\<S> T E = {s. case s of Success val x \<Rightarrow> x \<in> T val
                              | Abnormality val x \<Rightarrow> x \<in> E val
                              | Invalid \<Rightarrow> False
                              | NonTerm \<Rightarrow> False
                              | AssumptionBroken \<Rightarrow> False
                  }"

definition LooseStateSpec  :: "('ret::VALs \<phi>arg \<Rightarrow> rassn)
                          \<Rightarrow> (ABNM \<Rightarrow> rassn)
                          \<Rightarrow> 'ret comp set" ("\<S>")
  where  "\<S> T E = {s. case s of Success val x \<Rightarrow> x \<in> T val
                              | Abnormality val x \<Rightarrow> x \<in> E val
                              | Invalid \<Rightarrow> False
                              | NonTerm \<Rightarrow> True
                              | AssumptionBroken \<Rightarrow> True
                  }"

lemma StrictStateSpec_expn[iff]:
        "Success vs x \<in> !\<S> T E \<equiv> x \<in> T vs"
        "Abnormality v x \<in> !\<S> T E \<equiv> x \<in> E v"
        "\<not> (Invalid \<in> !\<S> T E)"
        "\<not> (NonTerm \<in> !\<S> T E)"
        "\<not> (AssumptionBroken \<in> !\<S> T E)"
        "\<not> {Invalid} \<subseteq> !\<S> T E"
        "\<not> {NonTerm} \<subseteq> !\<S> T E"
        "\<not> {AssumptionBroken} \<subseteq> !\<S> T E"
  and LooseStateSpec_expn[iff]:
        "Success vs x \<in> \<S> T E \<equiv> x \<in> T vs"
        "Abnormality v x \<in> \<S> T E \<equiv> x \<in> E v"
        "\<not> (Invalid \<in> \<S> T E)"
        "(NonTerm \<in> \<S> T E)"
        "(AssumptionBroken \<in> \<S> T E)"
        "\<not> {Invalid} \<subseteq> \<S> T E"
        "{NonTerm} \<subseteq> \<S> T E"
        "{AssumptionBroken} \<subseteq> \<S> T E"
  by (simp_all add: StrictStateSpec_def LooseStateSpec_def)

lemma LooseStateSpec_expn' :
    "x \<in> \<S> T E \<longleftrightarrow> x = NonTerm
                 \<or> x = AssumptionBroken
                 \<or> (\<exists>x' v. x = Success v x' \<and> x' \<in> T v)
                 \<or> (\<exists>x' v. x = Abnormality v x' \<and> x' \<in> E v)"
  by (cases x) simp_all

lemma StrictStateSpec_elim[elim]:
    "s \<in> !\<S> T E
\<Longrightarrow> (\<And>x v. s = Success v x \<Longrightarrow> x \<in> T v \<Longrightarrow> C)
\<Longrightarrow> (\<And>x v. s = Abnormality v x \<Longrightarrow> x \<in> E v \<Longrightarrow> C)
\<Longrightarrow> C" by (cases s) auto

lemma StrictStateSpec_intro[intro]:
    " x \<in> T v \<Longrightarrow> Success v x \<in> !\<S> T E"
    " x \<in> E a \<Longrightarrow> Abnormality a x \<in> !\<S> T E"
  by simp_all

lemma LooseStateSpec_E[elim]:
    "s \<in> \<S> T E
\<Longrightarrow> (\<And>x v. s = Success v x \<Longrightarrow> x \<in> T v \<Longrightarrow> C)
\<Longrightarrow> (\<And>x v. s = Abnormality v x \<Longrightarrow> x \<in> E v \<Longrightarrow> C)
\<Longrightarrow> (s = NonTerm \<Longrightarrow> C)
\<Longrightarrow> (s = AssumptionBroken \<Longrightarrow> C)
\<Longrightarrow> C"
  by (cases s) auto

lemma LooseStateSpec_I[intro]:
  "x \<in> T v \<Longrightarrow> Success v x \<in> \<S> T E"
  "x \<in> E a \<Longrightarrow> Abnormality a x \<in> \<S> T E"
  "NonTerm \<in> \<S> T E"
  "AssumptionBroken \<in> \<S> T E"
  by simp_all

lemma LooseStateSpec_upgrade:
  "s \<in> \<S> T E \<Longrightarrow> s \<noteq> AssumptionBroken \<Longrightarrow> s \<noteq> NonTerm \<Longrightarrow> s \<in> !\<S> T E"
  by (cases s) auto

lemma StrictStateSpec_degrade: "s \<in> !\<S> T E \<Longrightarrow> s \<in> \<S> T E" by (cases s) auto

lemma LooseStateSpec_introByStrict:
  "(s \<noteq> AssumptionBroken \<Longrightarrow> s \<noteq> NonTerm \<Longrightarrow> s \<in> !\<S> T E) \<Longrightarrow> s \<in> \<S> T E"
  by (cases s) auto

lemma StrictStateSpec_subset:
  \<open>(\<And>v. A v \<subseteq> A' v) \<Longrightarrow> (\<And>v. E v \<subseteq> E' v) \<Longrightarrow> !\<S> A E \<subseteq> !\<S> A' E'\<close>
  unfolding subset_iff StrictStateSpec_def by simp
lemma StrictStateSpec_subset'[intro]:
  \<open>(\<And>v. \<forall>s. s \<in> A v \<longrightarrow> s \<in> A' v) \<Longrightarrow> (\<And>v. \<forall>s. s \<in> E v \<longrightarrow> s \<in> E' v) \<Longrightarrow> s \<in> !\<S> A E \<Longrightarrow> s \<in> !\<S> A' E'\<close>
  unfolding StrictStateSpec_def by (cases s; simp)

lemma LooseStateSpec_subset:
  \<open>(\<And>v. A v \<subseteq> A' v) \<Longrightarrow> (\<And>v. E v \<subseteq> E' v) \<Longrightarrow> \<S> A E \<subseteq> \<S> A' E'\<close>
  unfolding subset_iff LooseStateSpec_def by simp
lemma LooseStateSpec_subset'[intro]:
  \<open>(\<And>v. \<forall>s. s \<in> A v \<longrightarrow> s \<in> A' v) \<Longrightarrow> (\<And>v. \<forall>s. s \<in> E v \<longrightarrow> s \<in> E' v) \<Longrightarrow> s \<in> \<S> A E \<Longrightarrow> s \<in> \<S> A' E'\<close>
  unfolding LooseStateSpec_def by (cases s; simp)

lemma LooseStateSpec_plus[iff]:
(*  \<open>\<S> (A + B) E   = \<S> A E + \<S> B E\<close> *)
  \<open>\<S> X (\<lambda>v. EA v + EB v) = \<S> X EA + \<S> X EB\<close>
  unfolding set_eq_iff LooseStateSpec_def by simp_all
lemma StrictStateSpec_plus[iff]:
(*  \<open>!\<S> (A + B) E   = !\<S> A E  + !\<S> B E\<close> *)
  \<open>!\<S> X (\<lambda>v. EA v + EB v) = !\<S> X EA + !\<S> X EB\<close>
  unfolding set_eq_iff StrictStateSpec_def by simp_all

abbreviation \<open>Void \<equiv> (1::assn)\<close>

section \<open>Specification of Fictional Resource\<close>

declare INTERP_SPEC[\<phi>expns]

lemma  INTERP_SPEC_subj[\<phi>expns]:
  \<open> INTERP_SPEC (S \<s>\<u>\<b>\<j> P) = (INTERP_SPEC S \<s>\<u>\<b>\<j> P) \<close>
  unfolding INTERP_SPEC_def by (simp add: \<phi>expns set_eq_iff, blast)

lemma  INTERP_SPEC_ex[\<phi>expns]:
  \<open> INTERP_SPEC (ExSet S) = (\<exists>\<^sup>s x. INTERP_SPEC (S x)) \<close>
  unfolding INTERP_SPEC_def by (simp add: \<phi>expns set_eq_iff, blast)

abbreviation COMMA :: \<open>assn \<Rightarrow> assn \<Rightarrow> assn\<close> ("_\<heavy_comma>/ _" [15,16] 15)
  where \<open>COMMA \<equiv> (*)\<close>

section \<open>Specification of Computation\<close>

definition \<phi>Procedure :: "'ret::VALs proc
                        \<Rightarrow> assn
                        \<Rightarrow> ('ret \<phi>arg \<Rightarrow> assn)
                        \<Rightarrow> (ABNM \<Rightarrow> assn)
                        \<Rightarrow> bool"
    ("\<p>\<r>\<o>\<c> (2_)/ (0\<lbrace> _/ \<longmapsto> _ \<rbrace>)/ \<t>\<h>\<r>\<o>\<w>\<s> (100_)/ " [101,2,2,100] 100)
  where "\<phi>Procedure f T U E \<longleftrightarrow>
    (\<forall>comp R. comp \<in> INTERP_SPEC (R * T) \<longrightarrow> f comp \<subseteq> \<S> (\<lambda>v. INTERP_SPEC (R * U v)) (\<lambda>v. INTERP_SPEC (R * E v)))"

abbreviation \<phi>Procedure_no_exception ("\<p>\<r>\<o>\<c> (2_)/ \<lbrace> (2_) \<longmapsto>/ (2_) \<rbrace>/ " [101,2,2] 100)
  where \<open>\<phi>Procedure_no_exception f T U \<equiv> \<phi>Procedure f T U 0\<close>

lemma \<phi>Procedure_alt:
  \<open>\<p>\<r>\<o>\<c> f \<lbrace> T \<longmapsto> U \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E
\<longleftrightarrow> (\<forall>comp r. comp \<in> INTERP_SPEC ({r} * T) \<longrightarrow> f comp \<subseteq> \<S> (\<lambda>v. INTERP_SPEC ({r} * U v)) (\<lambda>v. INTERP_SPEC ({r} * E v)))\<close>
  apply rule
  apply ((unfold \<phi>Procedure_def)[1], blast)
  unfolding \<phi>Procedure_def INTERP_SPEC subset_iff
  apply (clarsimp simp add: times_set_def split_comp_All INTERP_SPEC_def)
  by metis

lemmas \<phi>Procedure_I = \<phi>Procedure_alt[THEN iffD2]

subsubsection \<open>Syntax\<close>

ML_file \<open>library/syntax/procedure.ML\<close>

section \<open>View Shift\<close>

definition View_Shift
    :: "assn \<Rightarrow> assn \<Rightarrow> bool \<Rightarrow> bool" ("(2_/ \<s>\<h>\<i>\<f>\<t>\<s> _/ \<a>\<n>\<d> _)" [13,13,13] 12)
  where "View_Shift T U P \<longleftrightarrow> (\<forall>x R. x \<in> INTERP_SPEC (R * T) \<longrightarrow> x \<in> INTERP_SPEC (R * U) \<and> P)"

abbreviation Simple_View_Shift
    :: "assn \<Rightarrow> assn \<Rightarrow> bool" ("(2_/ \<s>\<h>\<i>\<f>\<t>\<s> _)"  [13,13] 12)
  where \<open>Simple_View_Shift T U \<equiv> View_Shift T U True\<close>

lemma View_Shift_imply_P:
  \<open> X \<s>\<h>\<i>\<f>\<t>\<s> Y \<a>\<n>\<d> P1
\<Longrightarrow> (P1 \<longrightarrow> P2)
\<Longrightarrow> X \<s>\<h>\<i>\<f>\<t>\<s> Y \<a>\<n>\<d> P2\<close>
  unfolding View_Shift_def
  by blast

lemma view_shift_by_implication[intro?, \<phi>reason 10]:
  \<open> A \<i>\<m>\<p>\<l>\<i>\<e>\<s> B \<a>\<n>\<d> P
\<Longrightarrow> A \<s>\<h>\<i>\<f>\<t>\<s> B \<a>\<n>\<d> P\<close>
  unfolding Imply_def View_Shift_def INTERP_SPEC_def
  by (clarsimp, metis set_mult_expn)

lemma view_shift_0[\<phi>reason 2000 for \<open>0 \<s>\<h>\<i>\<f>\<t>\<s> ?X \<a>\<n>\<d> ?P\<close>]:
  \<open>0 \<s>\<h>\<i>\<f>\<t>\<s> X\<close>
  by (blast intro: view_shift_by_implication zero_implies_any)

lemma view_shift_refl[\<phi>reason 2000 for \<open>?A \<s>\<h>\<i>\<f>\<t>\<s> ?B \<a>\<n>\<d> ?P\<close>]:
  "A \<s>\<h>\<i>\<f>\<t>\<s> A"
  by (blast intro: view_shift_by_implication implies_refl)

lemma view_shift_refl_ty[\<phi>reason 30 for \<open>?x \<Ztypecolon> ?T \<s>\<h>\<i>\<f>\<t>\<s> ?y \<Ztypecolon> ?T \<a>\<n>\<d> ?P\<close>]:
  "\<p>\<r>\<e>\<m>\<i>\<s>\<e> x = y \<Longrightarrow> x \<Ztypecolon> T \<s>\<h>\<i>\<f>\<t>\<s> y \<Ztypecolon> T"
  by (blast intro: view_shift_by_implication implies_refl_ty)

lemma view_shift_union[\<phi>reason 800]:
  \<open> A \<s>\<h>\<i>\<f>\<t>\<s> X \<a>\<n>\<d> P
\<Longrightarrow> A \<s>\<h>\<i>\<f>\<t>\<s> X + Y \<a>\<n>\<d> P\<close>
  \<open> A \<s>\<h>\<i>\<f>\<t>\<s> Y \<a>\<n>\<d> P
\<Longrightarrow> A \<s>\<h>\<i>\<f>\<t>\<s> X + Y \<a>\<n>\<d> P\<close>
  by (simp add: View_Shift_def distrib_left)+

lemma \<phi>view_shift_trans:
  "A \<s>\<h>\<i>\<f>\<t>\<s> B \<a>\<n>\<d> P
    \<Longrightarrow> (P \<Longrightarrow> B \<s>\<h>\<i>\<f>\<t>\<s> C \<a>\<n>\<d> Q)
    \<Longrightarrow> A \<s>\<h>\<i>\<f>\<t>\<s> C \<a>\<n>\<d> P \<and> Q"
  unfolding View_Shift_def by blast

lemma \<phi>frame_view:
  \<open> A \<s>\<h>\<i>\<f>\<t>\<s> B \<a>\<n>\<d> P
\<Longrightarrow> R * A \<s>\<h>\<i>\<f>\<t>\<s> R * B \<a>\<n>\<d> P\<close>
  unfolding View_Shift_def
  by (metis (no_types, lifting) mult.assoc)

lemma \<phi>view_shift_intro_frame:
  "U' \<s>\<h>\<i>\<f>\<t>\<s> U \<a>\<n>\<d> P \<Longrightarrow> R * U' \<s>\<h>\<i>\<f>\<t>\<s> R * U \<a>\<n>\<d> P "
  by (simp add: \<phi>frame_view)

lemma \<phi>view_shift_intro_frame_R:
  "U' \<s>\<h>\<i>\<f>\<t>\<s> U \<a>\<n>\<d> P \<Longrightarrow> U' * R \<s>\<h>\<i>\<f>\<t>\<s> U * R \<a>\<n>\<d> P "
  by (simp add: \<phi>frame_view mult.commute)

section \<open>Hoare Rules \& SL Rules\<close>

subsection \<open>Fundamental Rules\<close>

lemma \<phi>SKIP[simp,intro!]: "\<p>\<r>\<o>\<c> det_lift (Success v) \<lbrace> T v \<longmapsto> T \<rbrace>"
  unfolding \<phi>Procedure_def det_lift_def by clarsimp

lemma \<phi>SEQ:
   "\<p>\<r>\<o>\<c> f \<lbrace> A \<longmapsto> B \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E
\<Longrightarrow> (\<And>vs. \<p>\<r>\<o>\<c> g vs \<lbrace> B vs \<longmapsto> C \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E)
\<Longrightarrow> \<p>\<r>\<o>\<c> (f \<bind> g) \<lbrace> A \<longmapsto> C \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E"
  unfolding \<phi>Procedure_def bind_def apply (clarsimp simp add: subset_iff)
  subgoal for comp R x s
    apply (cases s; clarsimp; cases x; clarsimp; blast) . .

lemma \<phi>frame:
  " \<p>\<r>\<o>\<c> f \<lbrace> A \<longmapsto> B \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E
\<Longrightarrow> \<p>\<r>\<o>\<c> f \<lbrace> R * A \<longmapsto> \<lambda>ret. R * B ret \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> (\<lambda>ex. R * E ex) "
  unfolding \<phi>Procedure_def subset_iff
  apply clarify subgoal premises prems for comp R' s
    using prems(1)[THEN spec[where x=comp], THEN spec[where x=\<open>R' * R\<close>],
          simplified mult.assoc, THEN mp, OF prems(2)] prems(3) by blast .

lemma \<phi>Inhabited:
  \<open>(Inhabited X \<Longrightarrow> \<p>\<r>\<o>\<c> f \<lbrace> X \<longmapsto> Y \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E)
\<Longrightarrow> \<p>\<r>\<o>\<c> f \<lbrace> X \<longmapsto> Y \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E\<close>
  unfolding \<phi>Procedure_def Inhabited_def
  by (meson INTERP_SPEC set_mult_expn)

subsubsection \<open>View Shift\<close>

lemma \<phi>frame_view_right:
  \<open> A \<s>\<h>\<i>\<f>\<t>\<s> B \<a>\<n>\<d> P
\<Longrightarrow> A * R \<s>\<h>\<i>\<f>\<t>\<s> B * R \<a>\<n>\<d> P\<close>
  unfolding View_Shift_def
  by (metis (no_types, lifting) mult.assoc mult.commute)

lemma \<phi>view_trans:
  \<open> A \<s>\<h>\<i>\<f>\<t>\<s> B \<a>\<n>\<d> P1
\<Longrightarrow> (P1 \<Longrightarrow> B \<s>\<h>\<i>\<f>\<t>\<s> C \<a>\<n>\<d> P2)
\<Longrightarrow> A \<s>\<h>\<i>\<f>\<t>\<s> C \<a>\<n>\<d> P1 \<and> P2\<close>
  unfolding View_Shift_def by blast

lemma \<phi>CONSEQ:
   "\<p>\<r>\<o>\<c> f \<lbrace> A  \<longmapsto> B  \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E
\<Longrightarrow> A' \<s>\<h>\<i>\<f>\<t>\<s> A \<a>\<n>\<d> Any1
\<Longrightarrow> (\<And>ret. B ret \<s>\<h>\<i>\<f>\<t>\<s> B' ret \<a>\<n>\<d> Any2)
\<Longrightarrow> (\<And>ex.  E ex \<s>\<h>\<i>\<f>\<t>\<s> E' ex \<a>\<n>\<d> Any3)
\<Longrightarrow> \<p>\<r>\<o>\<c> f \<lbrace> A' \<longmapsto> B' \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E' "
  unfolding \<phi>Procedure_def View_Shift_def subset_iff
  apply clarsimp
  by (smt (verit, del_insts) LooseStateSpec_expn')

subsection \<open>Helper Rules\<close>

lemma \<phi>frame0:
  "\<p>\<r>\<o>\<c> f \<lbrace> A \<longmapsto> B \<rbrace> \<Longrightarrow> \<p>\<r>\<o>\<c> f \<lbrace> R * A \<longmapsto> \<lambda>ret. R * B ret \<rbrace>"
  using \<phi>frame[where E=0, simplified, folded zero_fun_def] .

lemma \<phi>CONSEQ'E:
   "(\<And>v. E v \<s>\<h>\<i>\<f>\<t>\<s> E' v \<a>\<n>\<d> P3)
\<Longrightarrow> \<p>\<r>\<o>\<c> f \<lbrace> A  \<longmapsto> B  \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E
\<Longrightarrow> \<p>\<r>\<o>\<c> f \<lbrace> A \<longmapsto> B \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E' "
  using \<phi>CONSEQ view_shift_refl by blast

lemmas \<phi>CONSEQ'E0 = \<phi>CONSEQ'E[OF view_shift_0, unfolded zero_fun_eta]

subsubsection \<open>Case Analysis\<close>

lemma \<phi>CASE:
  \<open> \<p>\<r>\<o>\<c> f \<lbrace> A \<longmapsto> C \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E
\<Longrightarrow> \<p>\<r>\<o>\<c> f \<lbrace> B \<longmapsto> C \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E
\<Longrightarrow> \<p>\<r>\<o>\<c> f \<lbrace> A + B \<longmapsto> C \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E\<close>
  unfolding \<phi>Procedure_def
  by (simp add: distrib_left)

lemma \<phi>CASE_VS:
  \<open> A \<s>\<h>\<i>\<f>\<t>\<s> Y \<a>\<n>\<d> P1
\<Longrightarrow> B \<s>\<h>\<i>\<f>\<t>\<s> Y \<a>\<n>\<d> P2
\<Longrightarrow> B + A \<s>\<h>\<i>\<f>\<t>\<s> Y \<a>\<n>\<d> P2 \<or> P1\<close>
  unfolding View_Shift_def
  by (simp add: distrib_left)

lemma \<phi>CASE_IMP:
  \<open> A \<i>\<m>\<p>\<l>\<i>\<e>\<s> Y \<a>\<n>\<d> P1
\<Longrightarrow> B \<i>\<m>\<p>\<l>\<i>\<e>\<s> Y \<a>\<n>\<d> P2
\<Longrightarrow> B + A \<i>\<m>\<p>\<l>\<i>\<e>\<s> Y \<a>\<n>\<d> P2 \<or> P1\<close>
  unfolding Imply_def
  by (simp add: distrib_left)

subsubsection \<open>Normalization in Precondition\<close>

lemma norm_precond_conj:
  "(\<p>\<r>\<o>\<c> f \<lbrace> T \<s>\<u>\<b>\<j> P \<longmapsto> Y \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E) = (P \<longrightarrow> \<p>\<r>\<o>\<c> f \<lbrace> T \<longmapsto> Y \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E )"
  unfolding \<phi>Procedure_def by (simp add: \<phi>expns) blast

lemmas norm_precond_conj_metaeq[unfolded atomize_eq[symmetric]] = norm_precond_conj

lemma norm_precond_ex:
  "(\<p>\<r>\<o>\<c> f \<lbrace> ExSet X \<longmapsto> Y \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E) = (\<forall>x. \<p>\<r>\<o>\<c> f \<lbrace> X x \<longmapsto> Y \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> E)"
  unfolding \<phi>Procedure_def by (simp add: \<phi>expns) blast

ML_file \<open>library/syntax/syntax0.ML\<close>

end


(* Author: Tobias Nipkow *)

theory Def_Init_Small
imports Star Def_Init_Exp Def_Init
begin

subsection "Initialization-Sensitive Small Step Semantics"

inductive
  small_step :: "(com \<times> state) \<Rightarrow> (com \<times> state) \<Rightarrow> bool" (infix "\<rightarrow>" 55)
where
Assign:  "aval a s = Some i \<Longrightarrow> (x ::= a, s) \<rightarrow> (SKIP, s(x := Some i))" |

Seq1:   "(SKIP;;c,s) \<rightarrow> (c,s)" |
Seq2:   "(c\<^sub>1,s) \<rightarrow> (c\<^sub>1',s') \<Longrightarrow> (c\<^sub>1;;c\<^sub>2,s) \<rightarrow> (c\<^sub>1';;c\<^sub>2,s')" |

IfTrue:  "bval b s = Some True \<Longrightarrow> (IF b THEN c\<^sub>1 ELSE c\<^sub>2,s) \<rightarrow> (c\<^sub>1,s)" |
IfFalse: "bval b s = Some False \<Longrightarrow> (IF b THEN c\<^sub>1 ELSE c\<^sub>2,s) \<rightarrow> (c\<^sub>2,s)" |

While:   "(WHILE b DO c,s) \<rightarrow> (IF b THEN c;; WHILE b DO c ELSE SKIP,s)"

lemmas small_step_induct = small_step.induct[split_format(complete)]

abbreviation small_steps :: "com * state \<Rightarrow> com * state \<Rightarrow> bool" (infix "\<rightarrow>*" 55)
where "x \<rightarrow>* y == star small_step x y"

subsection "Soundness wrt Small Steps"

theorem progress:
  "D (dom s) c A' \<Longrightarrow> c \<noteq> SKIP \<Longrightarrow> EX cs'. (c,s) \<rightarrow> cs'"
proof (induction c arbitrary: s A')
  case Assign thus ?case by auto (metis aval_Some small_step.Assign)
next
  case (If b c1 c2)
  then obtain bv where "bval b s = Some bv" by (auto dest!:bval_Some)
  then show ?case
    by(cases bv)(auto intro: small_step.IfTrue small_step.IfFalse)
qed (fastforce intro: small_step.intros)+

lemma D_mono:  "D A c M \<Longrightarrow> A \<subseteq> A' \<Longrightarrow> EX M'. D A' c M' & M <= M'"
proof (induction c arbitrary: A A' M)
  case Seq thus ?case by auto (metis D.intros(3))
next
  case (If b c1 c2)
  then obtain M1 M2 where "vars b \<subseteq> A" "D A c1 M1" "D A c2 M2" "M = M1 \<inter> M2"
    by auto
  with If.IH `A \<subseteq> A'` obtain M1' M2'
    where "D A' c1 M1'" "D A' c2 M2'" and "M1 \<subseteq> M1'" "M2 \<subseteq> M2'" by metis
  hence "D A' (IF b THEN c1 ELSE c2) (M1' \<inter> M2')" and "M \<subseteq> M1' \<inter> M2'"
    using `vars b \<subseteq> A` `A \<subseteq> A'` `M = M1 \<inter> M2` by(fastforce intro: D.intros)+
  thus ?case by metis
next
  case While thus ?case by auto (metis D.intros(5) subset_trans)
qed (auto intro: D.intros)

theorem D_preservation:
  "(c,s) \<rightarrow> (c',s') \<Longrightarrow> D (dom s) c A \<Longrightarrow> EX A'. D (dom s') c' A' & A <= A'"
proof (induction arbitrary: A rule: small_step_induct)
  case (While b c s)
  then obtain A' where A': "vars b \<subseteq> dom s" "A = dom s" "D (dom s) c A'" by blast
  then obtain A'' where "D A' c A''" by (metis D_incr D_mono)
  with A' have "D (dom s) (IF b THEN c;; WHILE b DO c ELSE SKIP) (dom s)"
    by (metis D.If[OF `vars b \<subseteq> dom s` D.Seq[OF `D (dom s) c A'` D.While[OF _ `D A' c A''`]] D.Skip] D_incr Int_absorb1 subset_trans)
  thus ?case by (metis D_incr `A = dom s`)
next
  case Seq2 thus ?case by auto (metis D_mono D.intros(3))
qed (auto intro: D.intros)

theorem D_sound:
  "(c,s) \<rightarrow>* (c',s') \<Longrightarrow> D (dom s) c A'
   \<Longrightarrow> (\<exists>cs''. (c',s') \<rightarrow> cs'') \<or> c' = SKIP"
apply(induction arbitrary: A' rule:star_induct)
apply (metis progress)
by (metis D_preservation)

end


subsubsection \<open>States\<close>

theory MultipleStepState
  imports SingleStepState
begin

lemma lm04_24_multiple_step_states:
fixes c :: nat
    and l :: register
    and ic :: configuration
    and p :: program
    and q :: nat
    and a :: nat

  defines "b == B c"
      and "m == length p"

assumes is_val: "is_valid_initial ic p a"
assumes c_gt_cells: "cells_bounded ic p c"
assumes d: "d \<le> m-1" and "0 < d"
    and q: "q > 0"

assumes terminate: "terminates ic p q"

assumes c: "c > 1"

  defines "r \<equiv> RLe ic p b q"
      and "z \<equiv> ZLe ic p b q"
      and "s \<equiv> SKe ic p b q"
      and "e \<equiv> \<Sum>t = 0..q. b^t"

shows "s d = b * (\<Sum>S+ p d s)
           + b * (\<Sum>S- p d (\<lambda>k. z (modifies (p!k)) && s k))
           + b * (\<Sum>S0 p d (\<lambda>k. (e - z (modifies (p!k))) && s k))"
proof -
  have "program_includes_halt p"
    using is_val is_valid_initial_def[of "ic" "p" "a"] is_valid_def[of "ic" "p"] by auto

  have halt_term0: "t \<le> q-1 \<longrightarrow> (if ishalt (p!(fst (steps ic p t))) \<and> d = fst (steps ic p t)
                                    then Suc 0 else 0) = 0" for t
    using terminate terminates_def by auto

  have single_step: "S ic p d (Suc t) = (\<Sum>S+ p d (\<lambda>k. S ic p k t))
                   + (\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t))
                   + (\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t))
                   + (if ishalt (p!(fst (steps ic p t))) \<and> d = fst (steps ic p t) then Suc 0 else 0)" for t
  using lm04_07_one_step_relation_state[of "ic" "p" "a" "d"] is_val `d>0` d
  by (simp add: m_def)

  have b: "b > 0" using b_def B_def by auto
  have halt: "ishalt (p!fst(steps ic p q))" using terminate terminates_def correct_halt_def by auto
  have add_conditions: "(if isadd (p ! k) \<and> d = goes_to (p ! k)
            then (\<Sum>t = 0..q - Suc 0. b ^ t * S ic p k t) + b ^ q * S ic p k q else 0)
         = (if isadd (p ! k) \<and> d = goes_to (p ! k)
            then \<Sum>t = 0..q - Suc 0. b ^ t * S ic p k t else 0)" for k
    apply (cases "p!k"; cases "d = goes_to (p!k)") using q S_def b halt by auto
  have "b * b ^ (q - Suc 0) = b ^ (q - Suc 0 + Suc 0)" using q
    by (simp add: power_eq_if)
  have "(\<lambda>k. (\<Sum>t = 0..(q-1).       b^t * S ic p k t) + b^(Suc (q-1)) * S ic p k (Suc (q-1)))
      = (\<lambda>k. (\<Sum>t = 0..(Suc (q-1)). b^t * S ic p k t))" by auto
  hence "\<Sum>S+ p d (\<lambda>k. (\<Sum>t = 0..(q-1).       b^t * S ic p k t) + b^q * S ic p k (Suc (q-1)))
       = \<Sum>S+ p d (\<lambda>k.  \<Sum>t = 0..(Suc (q-1)). b^t * S ic p k t)" using q
    by auto
  hence add_q: "\<Sum>S+ p d (\<lambda>k. \<Sum>t = 0..(q-1). b^t * S ic p k t)
              = \<Sum>S+ p d (\<lambda>k. \<Sum>t = 0..q. b^t * S ic p k t)"
    by (auto simp add: sum_sadd.simps q add_conditions)

  have "issub (p!k) \<Longrightarrow> b ^ (Suc (q-1)) * (Z ic p (modifies (p ! k)) (Suc (q-1)) *
        (if fst (steps ic p (Suc (q-1))) = k then Suc 0 else 0)) = 0" for k
    by (auto simp: q halt)
  hence sum_equiv_nzero: "issub (p!k) \<Longrightarrow>
        (\<Sum>t = 0..q-1. b ^ t * (Z ic p (modifies (p ! k)) t *
            (if fst (steps ic p t) = k then Suc 0 else 0)))
      = (\<Sum>t = 0..(Suc (q-1)). b ^ t * (Z ic p (modifies (p ! k)) t *
            (if fst (steps ic p t) = k then Suc 0 else 0)))" for k
    using sum.atLeast0_atMost_Suc[of "\<lambda>t. b ^ t * (Z ic p (modifies (p ! k)) t
                                  * (if fst (steps ic p t) = k then Suc 0 else 0))" "q-1"] by auto
  hence sub_nzero_conditions: "(if issub (p ! k) \<and> d = goes_to (p ! k) then
          \<Sum>t = 0..q - Suc 0. b ^ t * (Z ic p (modifies (p ! k)) t * S ic p k t) else 0)
       = (if issub (p ! k) \<and> d = goes_to (p ! k) then
          \<Sum>t = 0..q. b ^ t * (Z ic p (modifies (p ! k)) t * S ic p k t) else 0)" for k
    apply (cases "issub (p!k)") using q S_def halt b by auto
  have "(\<lambda>k. (\<Sum>t=0..(q-1). b^t * (Z ic p (modifies (p!k)) t * S ic p k t))
                    + b^(Suc (q-1)) * (Z ic p (modifies (p!k)) (Suc (q-1)) * S ic p k (Suc (q-1))))
      = (\<lambda>k. \<Sum>t=0..(Suc (q-1)). b^t * (Z ic p (modifies (p!k)) t * S ic p k t))" by auto
  hence sub_nzero_q: "(\<Sum>S- p d (\<lambda>k. \<Sum>t=0..(q-1). b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))
                   = (\<Sum>S- p d (\<lambda>k. \<Sum>t=0..q. b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))"
    by (auto simp: sum_ssub_nzero.simps q sub_nzero_conditions)

  have "issub (p!k) \<Longrightarrow> b ^ (Suc (q-1)) * ((Suc 0 - Z ic p (modifies (p ! k)) (Suc (q-1)))
          * S ic p k (Suc (q-1))) = 0" for k using q halt S_def by auto
  hence sum_equiv_zero: "issub (p!k) \<Longrightarrow>
         (\<Sum>t = 0..q-1. b ^ t * ((Suc 0 - Z ic p (modifies (p ! k)) t) * S ic p k t))
       = (\<Sum>t = 0..Suc (q-1). b ^ t * ((Suc 0 - Z ic p (modifies (p ! k)) t) * S ic p k t))" for k
    using sum.atLeast0_atMost_Suc[of "\<lambda>t. b ^ t * ((Suc 0 - Z ic p (modifies (p ! k)) t)
                                      * S ic p k t)" "q-1"] by auto
  have "(if issub (p ! k) \<and> d = goes_to_alt (p ! k) then
            \<Sum>t = 0..q - Suc 0. b ^ t * ((Suc 0 - Z ic p (modifies (p ! k)) t) * S ic p k t) else 0)
      = (if issub (p ! k) \<and> d = goes_to_alt (p ! k) then
            \<Sum>t = 0..q. b ^ t * ((Suc 0 - Z ic p (modifies (p ! k)) t) * S ic p k t) else 0)" for k
  apply (cases "issub (p!k)") using sum_equiv_zero[of "k"] q by auto
  hence sub_zero_q: "(\<Sum>S0 p d (\<lambda>k.\<Sum>t=0..q-1. b^t * ((1 - Z ic p (modifies(p!k)) t) * S ic p k t)))
                   = (\<Sum>S0 p d (\<lambda>k.\<Sum>t=0..q. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    using sum_ssub_zero.simps q by auto

  (* Start *)
  have "s d = (\<Sum>t = 0..q. b^t * S ic p d t)" using s_def SKe_def by auto
  also have "... = S ic p d 0 + (\<Sum>t = 1..q. b^t * S ic p d t)"
    by (auto simp: q comm_monoid_add_class.sum.atLeast_Suc_atMost)
  also have "... = (\<Sum>t = 1..q. b^t * S ic p d t)"
    using S_def `d>0` is_val is_valid_initial_def[of "ic" "p" "a"] by auto
  also have "... = (\<Sum>t \<in> (Suc ` {0..(q-1)}). b^t * S ic p d t)" using q by auto
  also have "... = (sum  ((\<lambda>t. b^t * S ic p d t) \<circ> Suc)) {0..(q-1)}"
    using comm_monoid_add_class.sum.reindex[of "Suc" "{0..(q-1)}" "(\<lambda>t. b^t * S ic p d t)"] by auto
  also have "... = (\<Sum>t = 0..(q-1). b^(Suc t) *((\<Sum>S+ p d (\<lambda>k. S ic p k t))
                                 + (\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t))
                                 + (\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t))
                                 + (if ishalt (p!(fst (steps ic p t))) \<and> d = fst (steps ic p t)
                                    then Suc 0 else 0)))"
    using single_step by auto
  also have "... = (\<Sum>t = 0..(q-1). b^(Suc t) *((\<Sum>S+ p d (\<lambda>k. S ic p k t))
                                 + (\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t))
                                 + (\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t))))"
    using halt_term0 by auto
  also have "... =  (\<Sum>t = 0..(q-1). (b^(Suc t) * (\<Sum>S+ p d (\<lambda>k. S ic p k t))
                      + b^(Suc t) * (\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t))
                      + b^(Suc t) * (\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t))))"
    by (simp add: algebra_simps)
  also have "... = (\<Sum>t = 0..(q-1). (b^(Suc t) * (\<Sum>S+ p d (\<lambda>k. S ic p k t))))
           +(\<Sum>t=0..(q-1). b^(Suc t)*(\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t)))
           +(\<Sum>t=0..(q-1). b^(Suc t)*(\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    by (auto simp only: sum.distrib)
  also have "... = b * (\<Sum>t = 0..(q-1). (b^t * (\<Sum>S+ p d (\<lambda>k. S ic p k t))))
           + b*(\<Sum>t=0..(q-1). b^t*(\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t)))
           + b*(\<Sum>t=0..(q-1). b^t*(\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    by (auto simp: algebra_simps sum_distrib_left)
  also have "... = b * (\<Sum>t = 0..(q-1). (\<Sum>S+ p d (\<lambda>k. b^t * S ic p k t)))
          + b*(\<Sum>t=0..(q-1). (\<Sum>S- p d (\<lambda>k. b^t * (Z ic p (modifies (p!k)) t * S ic p k t))))
          + b*(\<Sum>t=0..(q-1). (\<Sum>S0 p d (\<lambda>k. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t))))"
    using sum_sadd_distrib sum_ssub_nzero_distrib sum_ssub_zero_distrib by auto
  also have "... = b * (\<Sum>S+ p d (\<lambda>k. \<Sum>t = 0..(q-1). b^t * S ic p k t))
           + b*(\<Sum>S- p d (\<lambda>k. \<Sum>t=0..(q-1). b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))
           + b*(\<Sum>S0 p d (\<lambda>k. \<Sum>t=0..(q-1). b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    using sum_sadd_commutative sum_ssub_nzero_commutative sum_ssub_zero_commutative by auto
  (* extend all sums until q *)
  finally have eq1: "s d = b * (\<Sum>S+ p d (\<lambda>k. \<Sum>t = 0..q. b^t * S ic p k t))
           + b*(\<Sum>S- p d (\<lambda>k. \<Sum>t=0..q. b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))
           + b*(\<Sum>S0 p d (\<lambda>k. \<Sum>t=0..q. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    using add_q sub_nzero_q sub_zero_q by auto
  also have "... = b * (\<Sum>S+ p d (\<lambda>k. s k))
           + b*(\<Sum>S- p d (\<lambda>k. \<Sum>t=0..q. b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))
           + b*(\<Sum>S0 p d (\<lambda>k. \<Sum>t=0..q. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    using SKe_def s_def by auto
  finally have "s d = b * (\<Sum>S+ p d s)
           + b*(\<Sum>S- p d (\<lambda>k. \<Sum>t=0..q. b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))
           + b*(\<Sum>S0 p d (\<lambda>k. \<Sum>t=0..q. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    by auto
  also have "... = b * (\<Sum>S+ p d s)
           + b*(\<Sum>S- p d (\<lambda>k. ZLe ic p b q (modifies (p!k)) && SKe ic p b q k))
           + b*(\<Sum>S0 p d (\<lambda>k. \<Sum>t=0..q. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    using mult_to_bitAND c_gt_cells b_def c by auto
  finally have "s d = b * (\<Sum>S+ p d s)
           + b*(\<Sum>S- p d (\<lambda>k. ZLe ic p b q (modifies (p!k)) && SKe ic p b q k))
           + b*(\<Sum>S0 p d (\<lambda>k. (e - ZLe ic p b q (modifies (p!k))) && SKe ic p b q k))"
    using mult_to_bitAND_state c_gt_cells b_def c e_def by auto
  thus ?thesis using s_def z_def by auto
qed

lemma lm04_25_multiple_step_state1:
fixes c :: nat
    and l :: register
    and ic :: configuration
    and p :: program
    and q :: nat
    and a :: nat

  defines "b == B c"
      and "m == length p"

assumes is_val: "is_valid_initial ic p a"
assumes c_gt_cells: "cells_bounded ic p c"
assumes d: "d=0"
    and q: "q > 0"

assumes terminate: "terminates ic p q"

assumes c: "c > 1"

  defines "r \<equiv> RLe ic p b q"
      and "z \<equiv> ZLe ic p b q"
      and "s \<equiv> SKe ic p b q"
      and "e \<equiv> \<Sum>t = 0..q. b^t"

shows "s d = 1 + b * (\<Sum>S+ p d s)
           + b * (\<Sum>S- p d (\<lambda>k. z (modifies (p!k)) && s k))
           + b * (\<Sum>S0 p d (\<lambda>k. (e - z (modifies (p!k))) && s k))"
proof -
  have "program_includes_halt p"
    using is_val is_valid_initial_def[of "ic" "p" "a"] is_valid_def[of "ic" "p"] by auto
  hence "p \<noteq> []" by auto
  have "\<not> ishalt (p!d)" using d m_def `program_includes_halt p` by auto
  hence "(if ishalt (p ! fst (steps ic p t)) \<and> d = fst (steps ic p t) then Suc 0 else 0) = 0" for t
    by auto
  hence single_step: "\<And>t. S ic p d (Suc t) = (\<Sum>S+ p d (\<lambda>k. S ic p k t))
                   + (\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t))
                   + (\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t))"
  using lm04_07_one_step_relation_state[of "ic" "p" "a" "d"] is_val d `p \<noteq> []` by (simp add: m_def)

  have b: "b > 0" using b_def B_def by auto
  have halt: "ishalt (p!fst(steps ic p q))" using terminate terminates_def correct_halt_def by auto
  have add_conditions: "(if isadd (p ! k) \<and> d = goes_to (p ! k)
            then (\<Sum>t = 0..q - Suc 0. b ^ t * S ic p k t) + b ^ q * S ic p k q else 0)
         = (if isadd (p ! k) \<and> d = goes_to (p ! k)
            then \<Sum>t = 0..q - Suc 0. b ^ t * S ic p k t else 0)" for k
    apply (cases "p!k"; cases "d = goes_to (p!k)") using q S_def b halt by auto
  have "b * b ^ (q - Suc 0) = b ^ (q - Suc 0 + Suc 0)" using q
    by (simp add: power_eq_if)
  have "(\<lambda>k. (\<Sum>t = 0..(q-1).       b^t * S ic p k t) + b^(Suc (q-1)) * S ic p k (Suc (q-1)))
      = (\<lambda>k. (\<Sum>t = 0..(Suc (q-1)). b^t * S ic p k t))" by auto
  hence "\<Sum>S+ p d (\<lambda>k. (\<Sum>t = 0..(q-1).       b^t * S ic p k t) + b^q * S ic p k (Suc (q-1)))
       = \<Sum>S+ p d (\<lambda>k.  \<Sum>t = 0..(Suc (q-1)). b^t * S ic p k t)" using q
    by auto
  hence add_q: "\<Sum>S+ p d (\<lambda>k. \<Sum>t = 0..(q-1). b^t * S ic p k t)
              = \<Sum>S+ p d (\<lambda>k. \<Sum>t = 0..q. b^t * S ic p k t)"
    by (auto simp add: sum_sadd.simps q add_conditions)

  have "issub (p!k) \<Longrightarrow> b ^ (Suc (q-1)) * (Z ic p (modifies (p ! k)) (Suc (q-1)) *
        (if fst (steps ic p (Suc (q-1))) = k then Suc 0 else 0)) = 0" for k
    by (auto simp: q halt)
  hence sum_equiv_nzero: "issub (p!k) \<Longrightarrow>
        (\<Sum>t = 0..q-1. b ^ t * (Z ic p (modifies (p ! k)) t *
            (if fst (steps ic p t) = k then Suc 0 else 0)))
      = (\<Sum>t = 0..(Suc (q-1)). b ^ t * (Z ic p (modifies (p ! k)) t *
            (if fst (steps ic p t) = k then Suc 0 else 0)))" for k
    using sum.atLeast0_atMost_Suc[of "\<lambda>t. b ^ t * (Z ic p (modifies (p ! k)) t
                                  * (if fst (steps ic p t) = k then Suc 0 else 0))" "q-1"] by auto
  hence sub_nzero_conditions: "(if issub (p ! k) \<and> d = goes_to (p ! k) then
          \<Sum>t = 0..q - Suc 0. b ^ t * (Z ic p (modifies (p ! k)) t * S ic p k t) else 0)
       = (if issub (p ! k) \<and> d = goes_to (p ! k) then
          \<Sum>t = 0..q. b ^ t * (Z ic p (modifies (p ! k)) t * S ic p k t) else 0)" for k
    apply (cases "issub (p!k)") using q S_def halt b by auto
  have "(\<lambda>k. (\<Sum>t=0..(q-1). b^t * (Z ic p (modifies (p!k)) t * S ic p k t))
                    + b^(Suc (q-1)) * (Z ic p (modifies (p!k)) (Suc (q-1)) * S ic p k (Suc (q-1))))
      = (\<lambda>k. \<Sum>t=0..(Suc (q-1)). b^t * (Z ic p (modifies (p!k)) t * S ic p k t))" by auto
  hence sub_nzero_q: "(\<Sum>S- p d (\<lambda>k. \<Sum>t=0..(q-1). b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))
                   = (\<Sum>S- p d (\<lambda>k. \<Sum>t=0..q. b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))"
    by (auto simp: sum_ssub_nzero.simps q sub_nzero_conditions)

  have "issub (p!k) \<Longrightarrow> b ^ (Suc (q-1)) * ((Suc 0 - Z ic p (modifies (p ! k)) (Suc (q-1)))
          * S ic p k (Suc (q-1))) = 0" for k using q halt S_def by auto
  hence sum_equiv_zero: "issub (p!k) \<Longrightarrow>
         (\<Sum>t = 0..q-1. b ^ t * ((Suc 0 - Z ic p (modifies (p ! k)) t) * S ic p k t))
       = (\<Sum>t = 0..Suc (q-1). b ^ t * ((Suc 0 - Z ic p (modifies (p ! k)) t) * S ic p k t))" for k
    using sum.atLeast0_atMost_Suc[of "\<lambda>t. b ^ t * ((Suc 0 - Z ic p (modifies (p ! k)) t)
                                      * S ic p k t)" "q-1"] by auto
  have "(if issub (p ! k) \<and> d = goes_to_alt (p ! k) then
            \<Sum>t = 0..q - Suc 0. b ^ t * ((Suc 0 - Z ic p (modifies (p ! k)) t) * S ic p k t) else 0)
      = (if issub (p ! k) \<and> d = goes_to_alt (p ! k) then
            \<Sum>t = 0..q. b ^ t * ((Suc 0 - Z ic p (modifies (p ! k)) t) * S ic p k t) else 0)" for k
  apply (cases "issub (p!k)") using sum_equiv_zero[of "k"] q by auto
  hence sub_zero_q: "(\<Sum>S0 p d (\<lambda>k.\<Sum>t=0..q-1. b^t * ((1 - Z ic p (modifies(p!k)) t) * S ic p k t)))
                   = (\<Sum>S0 p d (\<lambda>k.\<Sum>t=0..q. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    using sum_ssub_zero.simps q by auto

  have S0: "S ic p d 0 = 1" using S_def is_val is_valid_initial_def[of "ic" "p" "a"] d by auto

  (* Start *)
  have "s d = (\<Sum>t = 0..q. b^t * S ic p d t)" using s_def SKe_def by auto
  also have "... = S ic p d 0 + (\<Sum>t = 1..q. b^t * S ic p d t)"
    by (auto simp: q comm_monoid_add_class.sum.atLeast_Suc_atMost)
  also have "... = b^0 * S ic p d 0 + (\<Sum>t = 1..q. b^t * S ic p d t)"
    using S_def is_val is_valid_initial_def[of "ic" "p" "a"] by auto
  also have "... = 1 + (\<Sum>t \<in> (Suc ` {0..(q-1)}). b^t * S ic p d t)" using q S0 by auto
  also have "... = 1 + (sum  ((\<lambda>t. b^t * S ic p d t) \<circ> Suc)) {0..(q-1)}"
    using comm_monoid_add_class.sum.reindex[of "Suc" "{0..(q-1)}" "(\<lambda>t. b^t * S ic p d t)"] by auto
  also have "... = 1 + (\<Sum>t = 0..(q-1). b^(Suc t) *((\<Sum>S+ p d (\<lambda>k. S ic p k t))
                                 + (\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t))
                                 + (\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t))))"
    using single_step by auto
  also have "... = 1 + (\<Sum>t = 0..(q-1). (b^(Suc t) * (\<Sum>S+ p d (\<lambda>k. S ic p k t))
                      + b^(Suc t) * (\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t))
                      + b^(Suc t) * (\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t))))"
    by (simp add: algebra_simps)
  also have "... = 1 + (\<Sum>t = 0..(q-1). (b^(Suc t) * (\<Sum>S+ p d (\<lambda>k. S ic p k t))))
           +(\<Sum>t=0..(q-1). b^(Suc t)*(\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t)))
           +(\<Sum>t=0..(q-1). b^(Suc t)*(\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    by (auto simp only: sum.distrib)
  also have "... = 1 + b * (\<Sum>t = 0..(q-1). (b^t * (\<Sum>S+ p d (\<lambda>k. S ic p k t))))
           + b*(\<Sum>t=0..(q-1). b^t*(\<Sum>S- p d (\<lambda>k. Z ic p (modifies (p!k)) t * S ic p k t)))
           + b*(\<Sum>t=0..(q-1). b^t*(\<Sum>S0 p d (\<lambda>k. (1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    by (auto simp: algebra_simps sum_distrib_left)
  also have "... = 1 + b * (\<Sum>t = 0..(q-1). (\<Sum>S+ p d (\<lambda>k. b^t * S ic p k t)))
          + b*(\<Sum>t=0..(q-1). (\<Sum>S- p d (\<lambda>k. b^t * (Z ic p (modifies (p!k)) t * S ic p k t))))
          + b*(\<Sum>t=0..(q-1). (\<Sum>S0 p d (\<lambda>k. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t))))"
    using sum_sadd_distrib sum_ssub_nzero_distrib sum_ssub_zero_distrib by auto
  also have "... = 1 + b * (\<Sum>S+ p d (\<lambda>k. \<Sum>t = 0..(q-1). b^t * S ic p k t))
           + b*(\<Sum>S- p d (\<lambda>k. \<Sum>t=0..(q-1). b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))
           + b*(\<Sum>S0 p d (\<lambda>k. \<Sum>t=0..(q-1). b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    using sum_sadd_commutative sum_ssub_nzero_commutative sum_ssub_zero_commutative by auto
  (* extend all sums until q *)
  finally have eq1: "s d = 1 + b * (\<Sum>S+ p d (\<lambda>k. \<Sum>t = 0..q. b^t * S ic p k t))
           + b*(\<Sum>S- p d (\<lambda>k. \<Sum>t=0..q. b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))
           + b*(\<Sum>S0 p d (\<lambda>k. \<Sum>t=0..q. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    using add_q sub_nzero_q sub_zero_q by auto
  also have "... = 1 + b * (\<Sum>S+ p d (\<lambda>k. s k))
           + b*(\<Sum>S- p d (\<lambda>k. \<Sum>t=0..q. b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))
           + b*(\<Sum>S0 p d (\<lambda>k. \<Sum>t=0..q. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    using SKe_def s_def by auto
  finally have "s d = 1 + b * (\<Sum>S+ p d s)
           + b*(\<Sum>S- p d (\<lambda>k. \<Sum>t=0..q. b^t * (Z ic p (modifies (p!k)) t * S ic p k t)))
           + b*(\<Sum>S0 p d (\<lambda>k. \<Sum>t=0..q. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    by auto
  also have "... = 1 + b * (\<Sum>S+ p d s)
           + b*(\<Sum>S- p d (\<lambda>k. ZLe ic p b q (modifies (p!k)) && SKe ic p b q k))
           + b*(\<Sum>S0 p d (\<lambda>k. \<Sum>t=0..q. b^t * ((1 - Z ic p (modifies (p!k)) t) * S ic p k t)))"
    using mult_to_bitAND c_gt_cells b_def c by auto
  finally have "s d = 1 + b * (\<Sum>S+ p d s)
           + b*(\<Sum>S- p d (\<lambda>k. ZLe ic p b q (modifies (p!k)) && SKe ic p b q k))
           + b*(\<Sum>S0 p d (\<lambda>k. (e - ZLe ic p b q (modifies (p!k))) && SKe ic p b q k))"
    using mult_to_bitAND_state c_gt_cells b_def c e_def by auto
  thus ?thesis using s_def z_def by auto
qed

lemma halting_condition_04_27:
fixes c :: nat
  and l :: register
  and ic :: configuration
  and p :: program
  and q :: nat
  and a :: nat

defines "b == B c"
    and "m == length p - 1"

assumes is_val: "is_valid_initial ic p a"
    and q: "q > 0"

assumes terminate: "terminates ic p q"

shows "SKe ic p b q m = b ^ q"
proof -
  have halt: "ishalt (p ! (fst (steps ic p q)))"
    using terminate terminates_def correct_halt_def by auto
  have "\<forall>k<length p - 1. \<not> ishalt (p!k)" using is_val is_valid_initial_def[of "ic" "p" "a"]
       is_valid_def[of "ic" "p"] program_includes_halt.simps by blast
  hence "ishalt (p!k) \<Longrightarrow> k \<ge> length p - 1" for k using not_le_imp_less by auto
  hence gt: "fst (steps ic p q) \<ge> m" using halt m_def by auto
  have "fst (steps ic p q) \<le> m"
    using p_contains[of "ic" "p" "a" "q"] is_val m_def by auto
  hence q_steps_m: "fst (steps ic p q) = m" using gt by auto
  hence 1: "S ic p m q = 1" using S_def by auto

  have "ishalt (p!m)" using q_steps_m halt  by auto
  have "\<forall>t<q. \<not> ishalt (p ! (fst (steps ic p t)))" using terminate terminates_def by auto
  hence "\<forall>t<q. \<not> (fst (steps ic p t) = m)" using `ishalt (p!m)` by auto
  hence 0: "t \<le> q-1 \<Longrightarrow> S ic p m t = 0" for t using q S_def[of "ic" "p" "m" "t"] by auto

  have "SKe ic p b q m = (\<Sum>t = 0..(Suc (q-1)). b ^ t * S ic p m t)" by (auto simp: q SKe_def)
  also have "... = (\<Sum>t = 0..(q-1). b^t * S ic p m t) + b ^ (Suc (q-1)) * S ic p m (Suc (q-1))"
    by auto
  also have "... = b ^ q" using 0 1 q by auto
  finally show ?thesis by auto
qed

lemma state_q_bound:
fixes c :: nat
  and l :: register
  and ic :: configuration
  and p :: program
  and q :: nat
  and a :: nat

defines "b == B c"
    and "m == length p - 1"

assumes is_val: "is_valid_initial ic p a"
    and q: "q > 0"
    and terminate: "terminates ic p q"
    and c: "c > 0"

assumes "k<m"

shows "SKe ic p b q k < b ^ q"
proof -
  from b_def have "b>1" using B_def apply auto
    by (metis One_nat_def one_less_numeral_iff power_gt1_lemma semiring_norm(76))
  hence b: "b > 2" using c b_def B_def
    by (smt One_nat_def Suc_le_lessD less_Suc_eq_le less_trans_Suc linorder_neqE_nat
            numeral_2_eq_2 power_Suc0_right power_inject_exp)
  from \<open>k<m\<close> have "\<not> ishalt (p!k)" using is_val
    by (simp add: is_valid_def is_valid_initial_def is_val m_def)
  hence "S ic p k q = 0" using terminate terminates_def correct_halt_def S_def by auto
  hence "SKe ic p b q k = (\<Sum>t = 0..q-1. b ^ t * S ic p k t)"
    using \<open>q>0\<close> apply (auto cong: sum.cong simp: SKe_def) by (metis (no_types, lifting) Suc_pred
          add_cancel_right_right mult_0_right sum.atLeast0_atMost_Suc)
  also have "... \<le> (\<Sum>t = 0..q-1. b^t)" by (auto simp add: S_def gr_implies_not0 sum_mono)
  also have "... < b ^ q"
    using `q>0` sum_bt
    by (metis Suc_diff_1 b)

  finally show ?thesis by auto
qed

end