(*  Title:      HOL/Predicate.thy
    Author:     Lukas Bulwahn and Florian Haftmann, TU Muenchen
*)

section {* Predicates as enumerations *}

theory Predicate
imports String
begin

subsection {* The type of predicate enumerations (a monad) *}

datatype (plugins only: code extraction) (dead 'a) pred = Pred "'a \<Rightarrow> bool"

primrec eval :: "'a pred \<Rightarrow> 'a \<Rightarrow> bool" where
  eval_pred: "eval (Pred f) = f"

lemma Pred_eval [simp]:
  "Pred (eval x) = x"
  by (cases x) simp

lemma pred_eqI:
  "(\<And>w. eval P w \<longleftrightarrow> eval Q w) \<Longrightarrow> P = Q"
  by (cases P, cases Q) (auto simp add: fun_eq_iff)

lemma pred_eq_iff:
  "P = Q \<Longrightarrow> (\<And>w. eval P w \<longleftrightarrow> eval Q w)"
  by (simp add: pred_eqI)

instantiation pred :: (type) complete_lattice
begin

definition
  "P \<le> Q \<longleftrightarrow> eval P \<le> eval Q"

definition
  "P < Q \<longleftrightarrow> eval P < eval Q"

definition
  "\<bottom> = Pred \<bottom>"

lemma eval_bot [simp]:
  "eval \<bottom>  = \<bottom>"
  by (simp add: bot_pred_def)

definition
  "\<top> = Pred \<top>"

lemma eval_top [simp]:
  "eval \<top>  = \<top>"
  by (simp add: top_pred_def)

definition
  "P \<sqinter> Q = Pred (eval P \<sqinter> eval Q)"

lemma eval_inf [simp]:
  "eval (P \<sqinter> Q) = eval P \<sqinter> eval Q"
  by (simp add: inf_pred_def)

definition
  "P \<squnion> Q = Pred (eval P \<squnion> eval Q)"

lemma eval_sup [simp]:
  "eval (P \<squnion> Q) = eval P \<squnion> eval Q"
  by (simp add: sup_pred_def)

definition
  "\<Sqinter>A = Pred (INFIMUM A eval)"

lemma eval_Inf [simp]:
  "eval (\<Sqinter>A) = INFIMUM A eval"
  by (simp add: Inf_pred_def)

definition
  "\<Squnion>A = Pred (SUPREMUM A eval)"

lemma eval_Sup [simp]:
  "eval (\<Squnion>A) = SUPREMUM A eval"
  by (simp add: Sup_pred_def)

instance proof
qed (auto intro!: pred_eqI simp add: less_eq_pred_def less_pred_def le_fun_def less_fun_def)

end

lemma eval_INF [simp]:
  "eval (INFIMUM A f) = INFIMUM A (eval \<circ> f)"
  using eval_Inf [of "f ` A"] by simp

lemma eval_SUP [simp]:
  "eval (SUPREMUM A f) = SUPREMUM A (eval \<circ> f)"
  using eval_Sup [of "f ` A"] by simp

instantiation pred :: (type) complete_boolean_algebra
begin

definition
  "- P = Pred (- eval P)"

lemma eval_compl [simp]:
  "eval (- P) = - eval P"
  by (simp add: uminus_pred_def)

definition
  "P - Q = Pred (eval P - eval Q)"

lemma eval_minus [simp]:
  "eval (P - Q) = eval P - eval Q"
  by (simp add: minus_pred_def)

instance proof
qed (auto intro!: pred_eqI)

end

definition single :: "'a \<Rightarrow> 'a pred" where
  "single x = Pred ((op =) x)"

lemma eval_single [simp]:
  "eval (single x) = (op =) x"
  by (simp add: single_def)

definition bind :: "'a pred \<Rightarrow> ('a \<Rightarrow> 'b pred) \<Rightarrow> 'b pred" (infixl "\<guillemotright>=" 70) where
  "P \<guillemotright>= f = (SUPREMUM {x. eval P x} f)"

lemma eval_bind [simp]:
  "eval (P \<guillemotright>= f) = eval (SUPREMUM {x. eval P x} f)"
  by (simp add: bind_def)

lemma bind_bind:
  "(P \<guillemotright>= Q) \<guillemotright>= R = P \<guillemotright>= (\<lambda>x. Q x \<guillemotright>= R)"
  by (rule pred_eqI) auto

lemma bind_single:
  "P \<guillemotright>= single = P"
  by (rule pred_eqI) auto

lemma single_bind:
  "single x \<guillemotright>= P = P x"
  by (rule pred_eqI) auto

lemma bottom_bind:
  "\<bottom> \<guillemotright>= P = \<bottom>"
  by (rule pred_eqI) auto

lemma sup_bind:
  "(P \<squnion> Q) \<guillemotright>= R = P \<guillemotright>= R \<squnion> Q \<guillemotright>= R"
  by (rule pred_eqI) auto

lemma Sup_bind:
  "(\<Squnion>A \<guillemotright>= f) = \<Squnion>((\<lambda>x. x \<guillemotright>= f) ` A)"
  by (rule pred_eqI) auto

lemma pred_iffI:
  assumes "\<And>x. eval A x \<Longrightarrow> eval B x"
  and "\<And>x. eval B x \<Longrightarrow> eval A x"
  shows "A = B"
  using assms by (auto intro: pred_eqI)

lemma singleI: "eval (single x) x"
  by simp

lemma singleI_unit: "eval (single ()) x"
  by simp

lemma singleE: "eval (single x) y \<Longrightarrow> (y = x \<Longrightarrow> P) \<Longrightarrow> P"
  by simp

lemma singleE': "eval (single x) y \<Longrightarrow> (x = y \<Longrightarrow> P) \<Longrightarrow> P"
  by simp

lemma bindI: "eval P x \<Longrightarrow> eval (Q x) y \<Longrightarrow> eval (P \<guillemotright>= Q) y"
  by auto

lemma bindE: "eval (R \<guillemotright>= Q) y \<Longrightarrow> (\<And>x. eval R x \<Longrightarrow> eval (Q x) y \<Longrightarrow> P) \<Longrightarrow> P"
  by auto

lemma botE: "eval \<bottom> x \<Longrightarrow> P"
  by auto

lemma supI1: "eval A x \<Longrightarrow> eval (A \<squnion> B) x"
  by auto

lemma supI2: "eval B x \<Longrightarrow> eval (A \<squnion> B) x"
  by auto

lemma supE: "eval (A \<squnion> B) x \<Longrightarrow> (eval A x \<Longrightarrow> P) \<Longrightarrow> (eval B x \<Longrightarrow> P) \<Longrightarrow> P"
  by auto

lemma single_not_bot [simp]:
  "single x \<noteq> \<bottom>"
  by (auto simp add: single_def bot_pred_def fun_eq_iff)

lemma not_bot:
  assumes "A \<noteq> \<bottom>"
  obtains x where "eval A x"
  using assms by (cases A) (auto simp add: bot_pred_def)

subsection {* Emptiness check and definite choice *}

definition is_empty :: "'a pred \<Rightarrow> bool" where
  "is_empty A \<longleftrightarrow> A = \<bottom>"

lemma is_empty_bot:
  "is_empty \<bottom>"
  by (simp add: is_empty_def)

lemma not_is_empty_single:
  "\<not> is_empty (single x)"
  by (auto simp add: is_empty_def single_def bot_pred_def fun_eq_iff)

lemma is_empty_sup:
  "is_empty (A \<squnion> B) \<longleftrightarrow> is_empty A \<and> is_empty B"
  by (auto simp add: is_empty_def)

definition singleton :: "(unit \<Rightarrow> 'a) \<Rightarrow> 'a pred \<Rightarrow> 'a" where
  "singleton dfault A = (if \<exists>!x. eval A x then THE x. eval A x else dfault ())"

lemma singleton_eqI:
  "\<exists>!x. eval A x \<Longrightarrow> eval A x \<Longrightarrow> singleton dfault A = x"
  by (auto simp add: singleton_def)

lemma eval_singletonI:
  "\<exists>!x. eval A x \<Longrightarrow> eval A (singleton dfault A)"
proof -
  assume assm: "\<exists>!x. eval A x"
  then obtain x where x: "eval A x" ..
  with assm have "singleton dfault A = x" by (rule singleton_eqI)
  with x show ?thesis by simp
qed

lemma single_singleton:
  "\<exists>!x. eval A x \<Longrightarrow> single (singleton dfault A) = A"
proof -
  assume assm: "\<exists>!x. eval A x"
  then have "eval A (singleton dfault A)"
    by (rule eval_singletonI)
  moreover from assm have "\<And>x. eval A x \<Longrightarrow> singleton dfault A = x"
    by (rule singleton_eqI)
  ultimately have "eval (single (singleton dfault A)) = eval A"
    by (simp (no_asm_use) add: single_def fun_eq_iff) blast
  then have "\<And>x. eval (single (singleton dfault A)) x = eval A x"
    by simp
  then show ?thesis by (rule pred_eqI)
qed

lemma singleton_undefinedI:
  "\<not> (\<exists>!x. eval A x) \<Longrightarrow> singleton dfault A = dfault ()"
  by (simp add: singleton_def)

lemma singleton_bot:
  "singleton dfault \<bottom> = dfault ()"
  by (auto simp add: bot_pred_def intro: singleton_undefinedI)

lemma singleton_single:
  "singleton dfault (single x) = x"
  by (auto simp add: intro: singleton_eqI singleI elim: singleE)

lemma singleton_sup_single_single:
  "singleton dfault (single x \<squnion> single y) = (if x = y then x else dfault ())"
proof (cases "x = y")
  case True then show ?thesis by (simp add: singleton_single)
next
  case False
  have "eval (single x \<squnion> single y) x"
    and "eval (single x \<squnion> single y) y"
  by (auto intro: supI1 supI2 singleI)
  with False have "\<not> (\<exists>!z. eval (single x \<squnion> single y) z)"
    by blast
  then have "singleton dfault (single x \<squnion> single y) = dfault ()"
    by (rule singleton_undefinedI)
  with False show ?thesis by simp
qed

lemma singleton_sup_aux:
  "singleton dfault (A \<squnion> B) = (if A = \<bottom> then singleton dfault B
    else if B = \<bottom> then singleton dfault A
    else singleton dfault
      (single (singleton dfault A) \<squnion> single (singleton dfault B)))"
proof (cases "(\<exists>!x. eval A x) \<and> (\<exists>!y. eval B y)")
  case True then show ?thesis by (simp add: single_singleton)
next
  case False
  from False have A_or_B:
    "singleton dfault A = dfault () \<or> singleton dfault B = dfault ()"
    by (auto intro!: singleton_undefinedI)
  then have rhs: "singleton dfault
    (single (singleton dfault A) \<squnion> single (singleton dfault B)) = dfault ()"
    by (auto simp add: singleton_sup_single_single singleton_single)
  from False have not_unique:
    "\<not> (\<exists>!x. eval A x) \<or> \<not> (\<exists>!y. eval B y)" by simp
  show ?thesis proof (cases "A \<noteq> \<bottom> \<and> B \<noteq> \<bottom>")
    case True
    then obtain a b where a: "eval A a" and b: "eval B b"
      by (blast elim: not_bot)
    with True not_unique have "\<not> (\<exists>!x. eval (A \<squnion> B) x)"
      by (auto simp add: sup_pred_def bot_pred_def)
    then have "singleton dfault (A \<squnion> B) = dfault ()" by (rule singleton_undefinedI)
    with True rhs show ?thesis by simp
  next
    case False then show ?thesis by auto
  qed
qed

lemma singleton_sup:
  "singleton dfault (A \<squnion> B) = (if A = \<bottom> then singleton dfault B
    else if B = \<bottom> then singleton dfault A
    else if singleton dfault A = singleton dfault B then singleton dfault A else dfault ())"
using singleton_sup_aux [of dfault A B] by (simp only: singleton_sup_single_single)

subsection {* Derived operations *}

definition if_pred :: "bool \<Rightarrow> unit pred" where
  if_pred_eq: "if_pred b = (if b then single () else \<bottom>)"

definition holds :: "unit pred \<Rightarrow> bool" where
  holds_eq: "holds P = eval P ()"

definition not_pred :: "unit pred \<Rightarrow> unit pred" where
  not_pred_eq: "not_pred P = (if eval P () then \<bottom> else single ())"

lemma if_predI: "P \<Longrightarrow> eval (if_pred P) ()"
  unfolding if_pred_eq by (auto intro: singleI)

lemma if_predE: "eval (if_pred b) x \<Longrightarrow> (b \<Longrightarrow> x = () \<Longrightarrow> P) \<Longrightarrow> P"
  unfolding if_pred_eq by (cases b) (auto elim: botE)

lemma not_predI: "\<not> P \<Longrightarrow> eval (not_pred (Pred (\<lambda>u. P))) ()"
  unfolding not_pred_eq eval_pred by (auto intro: singleI)

lemma not_predI': "\<not> eval P () \<Longrightarrow> eval (not_pred P) ()"
  unfolding not_pred_eq by (auto intro: singleI)

lemma not_predE: "eval (not_pred (Pred (\<lambda>u. P))) x \<Longrightarrow> (\<not> P \<Longrightarrow> thesis) \<Longrightarrow> thesis"
  unfolding not_pred_eq
  by (auto split: split_if_asm elim: botE)

lemma not_predE': "eval (not_pred P) x \<Longrightarrow> (\<not> eval P x \<Longrightarrow> thesis) \<Longrightarrow> thesis"
  unfolding not_pred_eq
  by (auto split: split_if_asm elim: botE)
lemma "f () = False \<or> f () = True"
by simp

lemma closure_of_bool_cases [no_atp]:
  fixes f :: "unit \<Rightarrow> bool"
  assumes "f = (\<lambda>u. False) \<Longrightarrow> P f"
  assumes "f = (\<lambda>u. True) \<Longrightarrow> P f"
  shows "P f"
proof -
  have "f = (\<lambda>u. False) \<or> f = (\<lambda>u. True)"
    apply (cases "f ()")
    apply (rule disjI2)
    apply (rule ext)
    apply (simp add: unit_eq)
    apply (rule disjI1)
    apply (rule ext)
    apply (simp add: unit_eq)
    done
  from this assms show ?thesis by blast
qed

lemma unit_pred_cases:
  assumes "P \<bottom>"
  assumes "P (single ())"
  shows "P Q"
using assms unfolding bot_pred_def bot_fun_def bot_bool_def empty_def single_def proof (cases Q)
  fix f
  assume "P (Pred (\<lambda>u. False))" "P (Pred (\<lambda>u. () = u))"
  then have "P (Pred f)"
    by (cases _ f rule: closure_of_bool_cases) simp_all
  moreover assume "Q = Pred f"
  ultimately show "P Q" by simp
qed

lemma holds_if_pred:
  "holds (if_pred b) = b"
unfolding if_pred_eq holds_eq
by (cases b) (auto intro: singleI elim: botE)

lemma if_pred_holds:
  "if_pred (holds P) = P"
unfolding if_pred_eq holds_eq
by (rule unit_pred_cases) (auto intro: singleI elim: botE)

lemma is_empty_holds:
  "is_empty P \<longleftrightarrow> \<not> holds P"
unfolding is_empty_def holds_eq
by (rule unit_pred_cases) (auto elim: botE intro: singleI)

definition map :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a pred \<Rightarrow> 'b pred" where
  "map f P = P \<guillemotright>= (single o f)"

lemma eval_map [simp]:
  "eval (map f P) = (\<Squnion>x\<in>{x. eval P x}. (\<lambda>y. f x = y))"
  by (auto simp add: map_def comp_def)

functor map: map
  by (rule ext, rule pred_eqI, auto)+

subsection {* Implementation *}

datatype (plugins only: code extraction) (dead 'a) seq =
  Empty
| Insert "'a" "'a pred"
| Join "'a pred" "'a seq"

primrec pred_of_seq :: "'a seq \<Rightarrow> 'a pred" where
  "pred_of_seq Empty = \<bottom>"
| "pred_of_seq (Insert x P) = single x \<squnion> P"
| "pred_of_seq (Join P xq) = P \<squnion> pred_of_seq xq"

definition Seq :: "(unit \<Rightarrow> 'a seq) \<Rightarrow> 'a pred" where
  "Seq f = pred_of_seq (f ())"

code_datatype Seq

primrec member :: "'a seq \<Rightarrow> 'a \<Rightarrow> bool"  where
  "member Empty x \<longleftrightarrow> False"
| "member (Insert y P) x \<longleftrightarrow> x = y \<or> eval P x"
| "member (Join P xq) x \<longleftrightarrow> eval P x \<or> member xq x"

lemma eval_member:
  "member xq = eval (pred_of_seq xq)"
proof (induct xq)
  case Empty show ?case
  by (auto simp add: fun_eq_iff elim: botE)
next
  case Insert show ?case
  by (auto simp add: fun_eq_iff elim: supE singleE intro: supI1 supI2 singleI)
next
  case Join then show ?case
  by (auto simp add: fun_eq_iff elim: supE intro: supI1 supI2)
qed

lemma eval_code [(* FIXME declare simp *)code]: "eval (Seq f) = member (f ())"
  unfolding Seq_def by (rule sym, rule eval_member)

primrec "apply" :: "('a \<Rightarrow> 'b pred) \<Rightarrow> 'a seq \<Rightarrow> 'b seq" where
  "apply f Empty = Empty"
| "apply f (Insert x P) = Join (f x) (Join (P \<guillemotright>= f) Empty)"
| "apply f (Join P xq) = Join (P \<guillemotright>= f) (apply f xq)"

lemma apply_bind:
  "pred_of_seq (apply f xq) = pred_of_seq xq \<guillemotright>= f"
proof (induct xq)
  case Empty show ?case
    by (simp add: bottom_bind)
next
  case Insert show ?case
    by (simp add: single_bind sup_bind)
next
  case Join then show ?case
    by (simp add: sup_bind)
qed

lemma bind_code [code]:
  "Seq g \<guillemotright>= f = Seq (\<lambda>u. apply f (g ()))"
  unfolding Seq_def by (rule sym, rule apply_bind)

lemma bot_set_code [code]:
  "\<bottom> = Seq (\<lambda>u. Empty)"
  unfolding Seq_def by simp

primrec adjunct :: "'a pred \<Rightarrow> 'a seq \<Rightarrow> 'a seq" where
  "adjunct P Empty = Join P Empty"
| "adjunct P (Insert x Q) = Insert x (Q \<squnion> P)"
| "adjunct P (Join Q xq) = Join Q (adjunct P xq)"

lemma adjunct_sup:
  "pred_of_seq (adjunct P xq) = P \<squnion> pred_of_seq xq"
  by (induct xq) (simp_all add: sup_assoc sup_commute sup_left_commute)

lemma sup_code [code]:
  "Seq f \<squnion> Seq g = Seq (\<lambda>u. case f ()
    of Empty \<Rightarrow> g ()
     | Insert x P \<Rightarrow> Insert x (P \<squnion> Seq g)
     | Join P xq \<Rightarrow> adjunct (Seq g) (Join P xq))"
proof (cases "f ()")
  case Empty
  thus ?thesis
    unfolding Seq_def by (simp add: sup_commute [of "\<bottom>"])
next
  case Insert
  thus ?thesis
    unfolding Seq_def by (simp add: sup_assoc)
next
  case Join
  thus ?thesis
    unfolding Seq_def
    by (simp add: adjunct_sup sup_assoc sup_commute sup_left_commute)
qed

primrec contained :: "'a seq \<Rightarrow> 'a pred \<Rightarrow> bool" where
  "contained Empty Q \<longleftrightarrow> True"
| "contained (Insert x P) Q \<longleftrightarrow> eval Q x \<and> P \<le> Q"
| "contained (Join P xq) Q \<longleftrightarrow> P \<le> Q \<and> contained xq Q"

lemma single_less_eq_eval:
  "single x \<le> P \<longleftrightarrow> eval P x"
  by (auto simp add: less_eq_pred_def le_fun_def)

lemma contained_less_eq:
  "contained xq Q \<longleftrightarrow> pred_of_seq xq \<le> Q"
  by (induct xq) (simp_all add: single_less_eq_eval)

lemma less_eq_pred_code [code]:
  "Seq f \<le> Q = (case f ()
   of Empty \<Rightarrow> True
    | Insert x P \<Rightarrow> eval Q x \<and> P \<le> Q
    | Join P xq \<Rightarrow> P \<le> Q \<and> contained xq Q)"
  by (cases "f ()")
    (simp_all add: Seq_def single_less_eq_eval contained_less_eq)

lemma eq_pred_code [code]:
  fixes P Q :: "'a pred"
  shows "HOL.equal P Q \<longleftrightarrow> P \<le> Q \<and> Q \<le> P"
  by (auto simp add: equal)

lemma [code nbe]:
  "HOL.equal (x :: 'a pred) x \<longleftrightarrow> True"
  by (fact equal_refl)

lemma [code]:
  "rec_pred f P = f (eval P)"
  by (cases P) simp

inductive eq :: "'a \<Rightarrow> 'a \<Rightarrow> bool" where "eq x x"

lemma eq_is_eq: "eq x y \<equiv> (x = y)"
  by (rule eq_reflection) (auto intro: eq.intros elim: eq.cases)

primrec null :: "'a seq \<Rightarrow> bool" where
  "null Empty \<longleftrightarrow> True"
| "null (Insert x P) \<longleftrightarrow> False"
| "null (Join P xq) \<longleftrightarrow> is_empty P \<and> null xq"

lemma null_is_empty:
  "null xq \<longleftrightarrow> is_empty (pred_of_seq xq)"
  by (induct xq) (simp_all add: is_empty_bot not_is_empty_single is_empty_sup)

lemma is_empty_code [code]:
  "is_empty (Seq f) \<longleftrightarrow> null (f ())"
  by (simp add: null_is_empty Seq_def)

primrec the_only :: "(unit \<Rightarrow> 'a) \<Rightarrow> 'a seq \<Rightarrow> 'a" where
  [code del]: "the_only dfault Empty = dfault ()"
| "the_only dfault (Insert x P) = (if is_empty P then x else let y = singleton dfault P in if x = y then x else dfault ())"
| "the_only dfault (Join P xq) = (if is_empty P then the_only dfault xq else if null xq then singleton dfault P
       else let x = singleton dfault P; y = the_only dfault xq in
       if x = y then x else dfault ())"

lemma the_only_singleton:
  "the_only dfault xq = singleton dfault (pred_of_seq xq)"
  by (induct xq)
    (auto simp add: singleton_bot singleton_single is_empty_def
    null_is_empty Let_def singleton_sup)

lemma singleton_code [code]:
  "singleton dfault (Seq f) = (case f ()
   of Empty \<Rightarrow> dfault ()
    | Insert x P \<Rightarrow> if is_empty P then x
        else let y = singleton dfault P in
          if x = y then x else dfault ()
    | Join P xq \<Rightarrow> if is_empty P then the_only dfault xq
        else if null xq then singleton dfault P
        else let x = singleton dfault P; y = the_only dfault xq in
          if x = y then x else dfault ())"
  by (cases "f ()")
   (auto simp add: Seq_def the_only_singleton is_empty_def
      null_is_empty singleton_bot singleton_single singleton_sup Let_def)

definition the :: "'a pred \<Rightarrow> 'a" where
  "the A = (THE x. eval A x)"

lemma the_eqI:
  "(THE x. eval P x) = x \<Longrightarrow> the P = x"
  by (simp add: the_def)

lemma the_eq [code]: "the A = singleton (\<lambda>x. Code.abort (STR ''not_unique'') (\<lambda>_. the A)) A"
  by (rule the_eqI) (simp add: singleton_def the_def)

code_reflect Predicate
  datatypes pred = Seq and seq = Empty | Insert | Join

ML {*
signature PREDICATE =
sig
  val anamorph: ('a -> ('b * 'a) option) -> int -> 'a -> 'b list * 'a
  datatype 'a pred = Seq of (unit -> 'a seq)
  and 'a seq = Empty | Insert of 'a * 'a pred | Join of 'a pred * 'a seq
  val map: ('a -> 'b) -> 'a pred -> 'b pred
  val yield: 'a pred -> ('a * 'a pred) option
  val yieldn: int -> 'a pred -> 'a list * 'a pred
end;

structure Predicate : PREDICATE =
struct

fun anamorph f k x =
 (if k = 0 then ([], x)
  else case f x
   of NONE => ([], x)
    | SOME (v, y) => let
        val k' = k - 1;
        val (vs, z) = anamorph f k' y
      in (v :: vs, z) end);

datatype pred = datatype Predicate.pred
datatype seq = datatype Predicate.seq

fun map f = @{code Predicate.map} f;

fun yield (Seq f) = next (f ())
and next Empty = NONE
  | next (Insert (x, P)) = SOME (x, P)
  | next (Join (P, xq)) = (case yield P
     of NONE => next xq
      | SOME (x, Q) => SOME (x, Seq (fn _ => Join (Q, xq))));

fun yieldn k = anamorph yield k;

end;
*}

text {* Conversion from and to sets *}

definition pred_of_set :: "'a set \<Rightarrow> 'a pred" where
  "pred_of_set = Pred \<circ> (\<lambda>A x. x \<in> A)"

lemma eval_pred_of_set [simp]:
  "eval (pred_of_set A) x \<longleftrightarrow> x \<in>A"
  by (simp add: pred_of_set_def)

definition set_of_pred :: "'a pred \<Rightarrow> 'a set" where
  "set_of_pred = Collect \<circ> eval"

lemma member_set_of_pred [simp]:
  "x \<in> set_of_pred P \<longleftrightarrow> Predicate.eval P x"
  by (simp add: set_of_pred_def)

definition set_of_seq :: "'a seq \<Rightarrow> 'a set" where
  "set_of_seq = set_of_pred \<circ> pred_of_seq"

lemma member_set_of_seq [simp]:
  "x \<in> set_of_seq xq = Predicate.member xq x"
  by (simp add: set_of_seq_def eval_member)

lemma of_pred_code [code]:
  "set_of_pred (Predicate.Seq f) = (case f () of
     Predicate.Empty \<Rightarrow> {}
   | Predicate.Insert x P \<Rightarrow> insert x (set_of_pred P)
   | Predicate.Join P xq \<Rightarrow> set_of_pred P \<union> set_of_seq xq)"
  by (auto split: seq.split simp add: eval_code)

lemma of_seq_code [code]:
  "set_of_seq Predicate.Empty = {}"
  "set_of_seq (Predicate.Insert x P) = insert x (set_of_pred P)"
  "set_of_seq (Predicate.Join P xq) = set_of_pred P \<union> set_of_seq xq"
  by auto

text {* Lazy Evaluation of an indexed function *}

function iterate_upto :: "(natural \<Rightarrow> 'a) \<Rightarrow> natural \<Rightarrow> natural \<Rightarrow> 'a Predicate.pred"
where
  "iterate_upto f n m =
    Predicate.Seq (%u. if n > m then Predicate.Empty
     else Predicate.Insert (f n) (iterate_upto f (n + 1) m))"
by pat_completeness auto

termination by (relation "measure (%(f, n, m). nat_of_natural (m + 1 - n))")
  (auto simp add: less_natural_def)

text {* Misc *}

declare Inf_set_fold [where 'a = "'a Predicate.pred", code]
declare Sup_set_fold [where 'a = "'a Predicate.pred", code]

(* FIXME: better implement conversion by bisection *)

lemma pred_of_set_fold_sup:
  assumes "finite A"
  shows "pred_of_set A = Finite_Set.fold sup bot (Predicate.single ` A)" (is "?lhs = ?rhs")
proof (rule sym)
  interpret comp_fun_idem "sup :: 'a Predicate.pred \<Rightarrow> 'a Predicate.pred \<Rightarrow> 'a Predicate.pred"
    by (fact comp_fun_idem_sup)
  from `finite A` show "?rhs = ?lhs" by (induct A) (auto intro!: pred_eqI)
qed

lemma pred_of_set_set_fold_sup:
  "pred_of_set (set xs) = fold sup (List.map Predicate.single xs) bot"
proof -
  interpret comp_fun_idem "sup :: 'a Predicate.pred \<Rightarrow> 'a Predicate.pred \<Rightarrow> 'a Predicate.pred"
    by (fact comp_fun_idem_sup)
  show ?thesis by (simp add: pred_of_set_fold_sup fold_set_fold [symmetric])
qed

lemma pred_of_set_set_foldr_sup [code]:
  "pred_of_set (set xs) = foldr sup (List.map Predicate.single xs) bot"
  by (simp add: pred_of_set_set_fold_sup ac_simps foldr_fold fun_eq_iff)

no_notation
  bind (infixl "\<guillemotright>=" 70)

hide_type (open) pred seq
hide_const (open) Pred eval single bind is_empty singleton if_pred not_pred holds
  Empty Insert Join Seq member pred_of_seq "apply" adjunct null the_only eq map the
  iterate_upto
hide_fact (open) null_def member_def

end


(* Title:    HOL/Partial_Function.thy
   Author:   Alexander Krauss, TU Muenchen
*)

section {* Partial Function Definitions *}

theory Partial_Function
imports Complete_Partial_Order Fun_Def_Base Option
keywords "partial_function" :: thy_decl
begin

named_theorems partial_function_mono "monotonicity rules for partial function definitions"
ML_file "Tools/Function/partial_function.ML"

subsection {* Axiomatic setup *}

text {* This techical locale constains the requirements for function
  definitions with ccpo fixed points. *}

definition "fun_ord ord f g \<longleftrightarrow> (\<forall>x. ord (f x) (g x))"
definition "fun_lub L A = (\<lambda>x. L {y. \<exists>f\<in>A. y = f x})"
definition "img_ord f ord = (\<lambda>x y. ord (f x) (f y))"
definition "img_lub f g Lub = (\<lambda>A. g (Lub (f ` A)))"

lemma chain_fun:
  assumes A: "chain (fun_ord ord) A"
  shows "chain ord {y. \<exists>f\<in>A. y = f a}" (is "chain ord ?C")
proof (rule chainI)
  fix x y assume "x \<in> ?C" "y \<in> ?C"
  then obtain f g where fg: "f \<in> A" "g \<in> A"
    and [simp]: "x = f a" "y = g a" by blast
  from chainD[OF A fg]
  show "ord x y \<or> ord y x" unfolding fun_ord_def by auto
qed

lemma call_mono[partial_function_mono]: "monotone (fun_ord ord) ord (\<lambda>f. f t)"
by (rule monotoneI) (auto simp: fun_ord_def)

lemma let_mono[partial_function_mono]:
  "(\<And>x. monotone orda ordb (\<lambda>f. b f x))
  \<Longrightarrow> monotone orda ordb (\<lambda>f. Let t (b f))"
by (simp add: Let_def)

lemma if_mono[partial_function_mono]: "monotone orda ordb F
\<Longrightarrow> monotone orda ordb G
\<Longrightarrow> monotone orda ordb (\<lambda>f. if c then F f else G f)"
unfolding monotone_def by simp

definition "mk_less R = (\<lambda>x y. R x y \<and> \<not> R y x)"

locale partial_function_definitions =
  fixes leq :: "'a \<Rightarrow> 'a \<Rightarrow> bool"
  fixes lub :: "'a set \<Rightarrow> 'a"
  assumes leq_refl: "leq x x"
  assumes leq_trans: "leq x y \<Longrightarrow> leq y z \<Longrightarrow> leq x z"
  assumes leq_antisym: "leq x y \<Longrightarrow> leq y x \<Longrightarrow> x = y"
  assumes lub_upper: "chain leq A \<Longrightarrow> x \<in> A \<Longrightarrow> leq x (lub A)"
  assumes lub_least: "chain leq A \<Longrightarrow> (\<And>x. x \<in> A \<Longrightarrow> leq x z) \<Longrightarrow> leq (lub A) z"

lemma partial_function_lift:
  assumes "partial_function_definitions ord lb"
  shows "partial_function_definitions (fun_ord ord) (fun_lub lb)" (is "partial_function_definitions ?ordf ?lubf")
proof -
  interpret partial_function_definitions ord lb by fact

  show ?thesis
  proof
    fix x show "?ordf x x"
      unfolding fun_ord_def by (auto simp: leq_refl)
  next
    fix x y z assume "?ordf x y" "?ordf y z"
    thus "?ordf x z" unfolding fun_ord_def
      by (force dest: leq_trans)
  next
    fix x y assume "?ordf x y" "?ordf y x"
    thus "x = y" unfolding fun_ord_def
      by (force intro!: dest: leq_antisym)
  next
    fix A f assume f: "f \<in> A" and A: "chain ?ordf A"
    thus "?ordf f (?lubf A)"
      unfolding fun_lub_def fun_ord_def
      by (blast intro: lub_upper chain_fun[OF A] f)
  next
    fix A :: "('b \<Rightarrow> 'a) set" and g :: "'b \<Rightarrow> 'a"
    assume A: "chain ?ordf A" and g: "\<And>f. f \<in> A \<Longrightarrow> ?ordf f g"
    show "?ordf (?lubf A) g" unfolding fun_lub_def fun_ord_def
      by (blast intro: lub_least chain_fun[OF A] dest: g[unfolded fun_ord_def])
   qed
qed

lemma ccpo: assumes "partial_function_definitions ord lb"
  shows "class.ccpo lb ord (mk_less ord)"
using assms unfolding partial_function_definitions_def mk_less_def
by unfold_locales blast+

lemma partial_function_image:
  assumes "partial_function_definitions ord Lub"
  assumes inj: "\<And>x y. f x = f y \<Longrightarrow> x = y"
  assumes inv: "\<And>x. f (g x) = x"
  shows "partial_function_definitions (img_ord f ord) (img_lub f g Lub)"
proof -
  let ?iord = "img_ord f ord"
  let ?ilub = "img_lub f g Lub"

  interpret partial_function_definitions ord Lub by fact
  show ?thesis
  proof
    fix A x assume "chain ?iord A" "x \<in> A"
    then have "chain ord (f ` A)" "f x \<in> f ` A"
      by (auto simp: img_ord_def intro: chainI dest: chainD)
    thus "?iord x (?ilub A)"
      unfolding inv img_lub_def img_ord_def by (rule lub_upper)
  next
    fix A x assume "chain ?iord A"
      and 1: "\<And>z. z \<in> A \<Longrightarrow> ?iord z x"
    then have "chain ord (f ` A)"
      by (auto simp: img_ord_def intro: chainI dest: chainD)
    thus "?iord (?ilub A) x"
      unfolding inv img_lub_def img_ord_def
      by (rule lub_least) (auto dest: 1[unfolded img_ord_def])
  qed (auto simp: img_ord_def intro: leq_refl dest: leq_trans leq_antisym inj)
qed

context partial_function_definitions
begin

abbreviation "le_fun \<equiv> fun_ord leq"
abbreviation "lub_fun \<equiv> fun_lub lub"
abbreviation "fixp_fun \<equiv> ccpo.fixp lub_fun le_fun"
abbreviation "mono_body \<equiv> monotone le_fun leq"
abbreviation "admissible \<equiv> ccpo.admissible lub_fun le_fun"

text {* Interpret manually, to avoid flooding everything with facts about
  orders *}

lemma ccpo: "class.ccpo lub_fun le_fun (mk_less le_fun)"
apply (rule ccpo)
apply (rule partial_function_lift)
apply (rule partial_function_definitions_axioms)
done

text {* The crucial fixed-point theorem *}

lemma mono_body_fixp:
  "(\<And>x. mono_body (\<lambda>f. F f x)) \<Longrightarrow> fixp_fun F = F (fixp_fun F)"
by (rule ccpo.fixp_unfold[OF ccpo]) (auto simp: monotone_def fun_ord_def)

text {* Version with curry/uncurry combinators, to be used by package *}

lemma fixp_rule_uc:
  fixes F :: "'c \<Rightarrow> 'c" and
    U :: "'c \<Rightarrow> 'b \<Rightarrow> 'a" and
    C :: "('b \<Rightarrow> 'a) \<Rightarrow> 'c"
  assumes mono: "\<And>x. mono_body (\<lambda>f. U (F (C f)) x)"
  assumes eq: "f \<equiv> C (fixp_fun (\<lambda>f. U (F (C f))))"
  assumes inverse: "\<And>f. C (U f) = f"
  shows "f = F f"
proof -
  have "f = C (fixp_fun (\<lambda>f. U (F (C f))))" by (simp add: eq)
  also have "... = C (U (F (C (fixp_fun (\<lambda>f. U (F (C f)))))))"
    by (subst mono_body_fixp[of "%f. U (F (C f))", OF mono]) (rule refl)
  also have "... = F (C (fixp_fun (\<lambda>f. U (F (C f)))))" by (rule inverse)
  also have "... = F f" by (simp add: eq)
  finally show "f = F f" .
qed

text {* Fixpoint induction rule *}

lemma fixp_induct_uc:
  fixes F :: "'c \<Rightarrow> 'c" and
    U :: "'c \<Rightarrow> 'b \<Rightarrow> 'a" and
    C :: "('b \<Rightarrow> 'a) \<Rightarrow> 'c" and
    P :: "('b \<Rightarrow> 'a) \<Rightarrow> bool"
  assumes mono: "\<And>x. mono_body (\<lambda>f. U (F (C f)) x)"
  assumes eq: "f \<equiv> C (fixp_fun (\<lambda>f. U (F (C f))))"
  assumes inverse: "\<And>f. U (C f) = f"
  assumes adm: "ccpo.admissible lub_fun le_fun P"
  and bot: "P (\<lambda>_. lub {})"
  assumes step: "\<And>f. P (U f) \<Longrightarrow> P (U (F f))"
  shows "P (U f)"
unfolding eq inverse
apply (rule ccpo.fixp_induct[OF ccpo adm])
apply (insert mono, auto simp: monotone_def fun_ord_def bot fun_lub_def)[2]
by (rule_tac f="C x" in step, simp add: inverse)

text {* Rules for @{term mono_body}: *}

lemma const_mono[partial_function_mono]: "monotone ord leq (\<lambda>f. c)"
by (rule monotoneI) (rule leq_refl)

end

subsection {* Flat interpretation: tailrec and option *}

definition
  "flat_ord b x y \<longleftrightarrow> x = b \<or> x = y"

definition
  "flat_lub b A = (if A \<subseteq> {b} then b else (THE x. x \<in> A - {b}))"

lemma flat_interpretation:
  "partial_function_definitions (flat_ord b) (flat_lub b)"
proof
  fix A x assume 1: "chain (flat_ord b) A" "x \<in> A"
  show "flat_ord b x (flat_lub b A)"
  proof cases
    assume "x = b"
    thus ?thesis by (simp add: flat_ord_def)
  next
    assume "x \<noteq> b"
    with 1 have "A - {b} = {x}"
      by (auto elim: chainE simp: flat_ord_def)
    then have "flat_lub b A = x"
      by (auto simp: flat_lub_def)
    thus ?thesis by (auto simp: flat_ord_def)
  qed
next
  fix A z assume A: "chain (flat_ord b) A"
    and z: "\<And>x. x \<in> A \<Longrightarrow> flat_ord b x z"
  show "flat_ord b (flat_lub b A) z"
  proof cases
    assume "A \<subseteq> {b}"
    thus ?thesis
      by (auto simp: flat_lub_def flat_ord_def)
  next
    assume nb: "\<not> A \<subseteq> {b}"
    then obtain y where y: "y \<in> A" "y \<noteq> b" by auto
    with A have "A - {b} = {y}"
      by (auto elim: chainE simp: flat_ord_def)
    with nb have "flat_lub b A = y"
      by (auto simp: flat_lub_def)
    with z y show ?thesis by auto
  qed
qed (auto simp: flat_ord_def)

interpretation tailrec!:
  partial_function_definitions "flat_ord undefined" "flat_lub undefined"
  where "flat_lub undefined {} \<equiv> undefined"
by (rule flat_interpretation)(simp add: flat_lub_def)

interpretation option!:
  partial_function_definitions "flat_ord None" "flat_lub None"
  where "flat_lub None {} \<equiv> None"
by (rule flat_interpretation)(simp add: flat_lub_def)

abbreviation "tailrec_ord \<equiv> flat_ord undefined"
abbreviation "mono_tailrec \<equiv> monotone (fun_ord tailrec_ord) tailrec_ord"

lemma tailrec_admissible:
  "ccpo.admissible (fun_lub (flat_lub c)) (fun_ord (flat_ord c))
     (\<lambda>a. \<forall>x. a x \<noteq> c \<longrightarrow> P x (a x))"
proof(intro ccpo.admissibleI strip)
  fix A x
  assume chain: "Complete_Partial_Order.chain (fun_ord (flat_ord c)) A"
    and P [rule_format]: "\<forall>f\<in>A. \<forall>x. f x \<noteq> c \<longrightarrow> P x (f x)"
    and defined: "fun_lub (flat_lub c) A x \<noteq> c"
  from defined obtain f where f: "f \<in> A" "f x \<noteq> c"
    by(auto simp add: fun_lub_def flat_lub_def split: split_if_asm)
  hence "P x (f x)" by(rule P)
  moreover from chain f have "\<forall>f' \<in> A. f' x = c \<or> f' x = f x"
    by(auto 4 4 simp add: Complete_Partial_Order.chain_def flat_ord_def fun_ord_def)
  hence "fun_lub (flat_lub c) A x = f x"
    using f by(auto simp add: fun_lub_def flat_lub_def)
  ultimately show "P x (fun_lub (flat_lub c) A x)" by simp
qed

lemma fixp_induct_tailrec:
  fixes F :: "'c \<Rightarrow> 'c" and
    U :: "'c \<Rightarrow> 'b \<Rightarrow> 'a" and
    C :: "('b \<Rightarrow> 'a) \<Rightarrow> 'c" and
    P :: "'b \<Rightarrow> 'a \<Rightarrow> bool" and
    x :: "'b"
  assumes mono: "\<And>x. monotone (fun_ord (flat_ord c)) (flat_ord c) (\<lambda>f. U (F (C f)) x)"
  assumes eq: "f \<equiv> C (ccpo.fixp (fun_lub (flat_lub c)) (fun_ord (flat_ord c)) (\<lambda>f. U (F (C f))))"
  assumes inverse2: "\<And>f. U (C f) = f"
  assumes step: "\<And>f x y. (\<And>x y. U f x = y \<Longrightarrow> y \<noteq> c \<Longrightarrow> P x y) \<Longrightarrow> U (F f) x = y \<Longrightarrow> y \<noteq> c \<Longrightarrow> P x y"
  assumes result: "U f x = y"
  assumes defined: "y \<noteq> c"
  shows "P x y"
proof -
  have "\<forall>x y. U f x = y \<longrightarrow> y \<noteq> c \<longrightarrow> P x y"
    by(rule partial_function_definitions.fixp_induct_uc[OF flat_interpretation, of _ U F C, OF mono eq inverse2])
      (auto intro: step tailrec_admissible simp add: fun_lub_def flat_lub_def)
  thus ?thesis using result defined by blast
qed

lemma admissible_image:
  assumes pfun: "partial_function_definitions le lub"
  assumes adm: "ccpo.admissible lub le (P o g)"
  assumes inj: "\<And>x y. f x = f y \<Longrightarrow> x = y"
  assumes inv: "\<And>x. f (g x) = x"
  shows "ccpo.admissible (img_lub f g lub) (img_ord f le) P"
proof (rule ccpo.admissibleI)
  fix A assume "chain (img_ord f le) A"
  then have ch': "chain le (f ` A)"
    by (auto simp: img_ord_def intro: chainI dest: chainD)
  assume "A \<noteq> {}"
  assume P_A: "\<forall>x\<in>A. P x"
  have "(P o g) (lub (f ` A))" using adm ch'
  proof (rule ccpo.admissibleD)
    fix x assume "x \<in> f ` A"
    with P_A show "(P o g) x" by (auto simp: inj[OF inv])
  qed(simp add: `A \<noteq> {}`)
  thus "P (img_lub f g lub A)" unfolding img_lub_def by simp
qed

lemma admissible_fun:
  assumes pfun: "partial_function_definitions le lub"
  assumes adm: "\<And>x. ccpo.admissible lub le (Q x)"
  shows "ccpo.admissible  (fun_lub lub) (fun_ord le) (\<lambda>f. \<forall>x. Q x (f x))"
proof (rule ccpo.admissibleI)
  fix A :: "('b \<Rightarrow> 'a) set"
  assume Q: "\<forall>f\<in>A. \<forall>x. Q x (f x)"
  assume ch: "chain (fun_ord le) A"
  assume "A \<noteq> {}"
  hence non_empty: "\<And>a. {y. \<exists>f\<in>A. y = f a} \<noteq> {}" by auto
  show "\<forall>x. Q x (fun_lub lub A x)"
    unfolding fun_lub_def
    by (rule allI, rule ccpo.admissibleD[OF adm chain_fun[OF ch] non_empty])
      (auto simp: Q)
qed

abbreviation "option_ord \<equiv> flat_ord None"
abbreviation "mono_option \<equiv> monotone (fun_ord option_ord) option_ord"

lemma bind_mono[partial_function_mono]:
assumes mf: "mono_option B" and mg: "\<And>y. mono_option (\<lambda>f. C y f)"
shows "mono_option (\<lambda>f. Option.bind (B f) (\<lambda>y. C y f))"
proof (rule monotoneI)
  fix f g :: "'a \<Rightarrow> 'b option" assume fg: "fun_ord option_ord f g"
  with mf
  have "option_ord (B f) (B g)" by (rule monotoneD[of _ _ _ f g])
  then have "option_ord (Option.bind (B f) (\<lambda>y. C y f)) (Option.bind (B g) (\<lambda>y. C y f))"
    unfolding flat_ord_def by auto
  also from mg
  have "\<And>y'. option_ord (C y' f) (C y' g)"
    by (rule monotoneD) (rule fg)
  then have "option_ord (Option.bind (B g) (\<lambda>y'. C y' f)) (Option.bind (B g) (\<lambda>y'. C y' g))"
    unfolding flat_ord_def by (cases "B g") auto
  finally (option.leq_trans)
  show "option_ord (Option.bind (B f) (\<lambda>y. C y f)) (Option.bind (B g) (\<lambda>y'. C y' g))" .
qed

lemma flat_lub_in_chain:
  assumes ch: "chain (flat_ord b) A "
  assumes lub: "flat_lub b A = a"
  shows "a = b \<or> a \<in> A"
proof (cases "A \<subseteq> {b}")
  case True
  then have "flat_lub b A = b" unfolding flat_lub_def by simp
  with lub show ?thesis by simp
next
  case False
  then obtain c where "c \<in> A" and "c \<noteq> b" by auto
  { fix z assume "z \<in> A"
    from chainD[OF ch `c \<in> A` this] have "z = c \<or> z = b"
      unfolding flat_ord_def using `c \<noteq> b` by auto }
  with False have "A - {b} = {c}" by auto
  with False have "flat_lub b A = c" by (auto simp: flat_lub_def)
  with `c \<in> A` lub show ?thesis by simp
qed

lemma option_admissible: "option.admissible (%(f::'a \<Rightarrow> 'b option).
  (\<forall>x y. f x = Some y \<longrightarrow> P x y))"
proof (rule ccpo.admissibleI)
  fix A :: "('a \<Rightarrow> 'b option) set"
  assume ch: "chain option.le_fun A"
    and IH: "\<forall>f\<in>A. \<forall>x y. f x = Some y \<longrightarrow> P x y"
  from ch have ch': "\<And>x. chain option_ord {y. \<exists>f\<in>A. y = f x}" by (rule chain_fun)
  show "\<forall>x y. option.lub_fun A x = Some y \<longrightarrow> P x y"
  proof (intro allI impI)
    fix x y assume "option.lub_fun A x = Some y"
    from flat_lub_in_chain[OF ch' this[unfolded fun_lub_def]]
    have "Some y \<in> {y. \<exists>f\<in>A. y = f x}" by simp
    then have "\<exists>f\<in>A. f x = Some y" by auto
    with IH show "P x y" by auto
  qed
qed

lemma fixp_induct_option:
  fixes F :: "'c \<Rightarrow> 'c" and
    U :: "'c \<Rightarrow> 'b \<Rightarrow> 'a option" and
    C :: "('b \<Rightarrow> 'a option) \<Rightarrow> 'c" and
    P :: "'b \<Rightarrow> 'a \<Rightarrow> bool"
  assumes mono: "\<And>x. mono_option (\<lambda>f. U (F (C f)) x)"
  assumes eq: "f \<equiv> C (ccpo.fixp (fun_lub (flat_lub None)) (fun_ord option_ord) (\<lambda>f. U (F (C f))))"
  assumes inverse2: "\<And>f. U (C f) = f"
  assumes step: "\<And>f x y. (\<And>x y. U f x = Some y \<Longrightarrow> P x y) \<Longrightarrow> U (F f) x = Some y \<Longrightarrow> P x y"
  assumes defined: "U f x = Some y"
  shows "P x y"
  using step defined option.fixp_induct_uc[of U F C, OF mono eq inverse2 option_admissible]
  unfolding fun_lub_def flat_lub_def by(auto 9 2)

declaration {* Partial_Function.init "tailrec" @{term tailrec.fixp_fun}
  @{term tailrec.mono_body} @{thm tailrec.fixp_rule_uc} @{thm tailrec.fixp_induct_uc}
  (SOME @{thm fixp_induct_tailrec[where c=undefined]}) *}

declaration {* Partial_Function.init "option" @{term option.fixp_fun}
  @{term option.mono_body} @{thm option.fixp_rule_uc} @{thm option.fixp_induct_uc}
  (SOME @{thm fixp_induct_option}) *}

hide_const (open) chain

end


theory Akra_Bazzi_Approximation
imports
  Complex_Main
  Akra_Bazzi_Method
  "HOL-Decision_Procs.Approximation"
begin

(*
  This is a temporary workaround since recent changes broke approximation of the "powr" function.
  Once it works again, this entire section can be removed.
*)

context akra_bazzi_params_nonzero
begin

lemma sum_alt: "(\<Sum>i<k. as!i * bs!i powr p') = (\<Sum>i<k. as!i * exp (p' * ln (bs!i)))"
proof (intro sum.cong)
  fix i assume "i \<in> {..<k}"
  with b_bounds have "bs!i > 0" by simp
  thus "as!i * bs!i powr p' = as!i * exp (p' * ln (bs!i))" by (simp add: powr_def)
qed simp

lemma akra_bazzi_p_rel_intros_aux:
  "1 < (\<Sum>i<k. as!i * exp (p' * ln (bs!i))) \<Longrightarrow> p' < p"
  "1 > (\<Sum>i<k. as!i * exp (p' * ln (bs!i))) \<Longrightarrow> p' > p"
  "1 \<le> (\<Sum>i<k. as!i * exp (p' * ln (bs!i))) \<Longrightarrow> p' \<le> p"
  "1 \<ge> (\<Sum>i<k. as!i * exp (p' * ln (bs!i))) \<Longrightarrow> p' \<ge> p"
  "(\<Sum>i<k. as!i * exp (x * ln (bs!i))) \<le> 1 \<and> (\<Sum>i<k. as!i * exp (y * ln (bs!i))) \<ge> 1 \<Longrightarrow> p \<in> {y..x}"
  "(\<Sum>i<k. as!i * exp (x * ln (bs!i))) < 1 \<and> (\<Sum>i<k. as!i * exp (y * ln (bs!i))) > 1 \<Longrightarrow> p \<in> {y<..<x}"
  using p_lessI p_greaterI p_leI p_geI p_boundsI p_boundsI' by (simp_all only: sum_alt)
end

lemmas akra_bazzi_p_rel_intros_exp =
  akra_bazzi_params_nonzero.akra_bazzi_p_rel_intros_aux[rotated, OF _ akra_bazzi_params_nonzeroI]

lemma eval_akra_bazzi_sum:
  "(\<Sum>i<0. as!i * exp (x * ln (bs!i))) = 0"
  "(\<Sum>i<Suc 0. (a#as)!i * exp (x * ln ((b#bs)!i))) = a * exp (x * ln b)"
  "(\<Sum>i<Suc k. (a#as)!i * exp (x * ln ((b#bs)!i))) = a * exp (x * ln b) +
      (\<Sum>i<k. as!i * exp (x * ln (bs!i)))"
  apply simp
  apply simp
  apply (induction k arbitrary: a as b bs)
  apply simp_all
  done

(* end workaround *)

ML \<open>
signature AKRA_BAZZI_APPROXIMATION =
sig
  val akra_bazzi_approximate_tac : int -> Proof.context -> int -> tactic
end

structure Akra_Bazzi_Approximation: AKRA_BAZZI_APPROXIMATION =
struct

fun akra_bazzi_approximate_tac prec ctxt =
  let
    val simps = @{thms eval_length eval_akra_bazzi_sum add_0_left add_0_right
                       mult_1_left mult_1_right}
  in
    SELECT_GOAL (
      resolve_tac ctxt @{thms akra_bazzi_p_rel_intros_exp} 1
      THEN ALLGOALS (fn i =>
        if i > 1 then
          SELECT_GOAL (
            Local_Defs.unfold_tac ctxt
              @{thms bex_set_simps ball_set_simps greaterThanLessThan_iff eval_length}
            THEN TRY (SOLVE (Eval_Numeral.eval_numeral_tac ctxt 1))
          ) i
        else
          SELECT_GOAL (Local_Defs.unfold_tac ctxt simps) i
          THEN Approximation.approximation_tac prec [] NONE ctxt i
      )
    )
  end

end;
\<close>

method_setup akra_bazzi_approximate = \<open>
  Scan.lift Parse.nat >>
    (fn prec => fn ctxt =>
      SIMPLE_METHOD' (Akra_Bazzi_Approximation.akra_bazzi_approximate_tac prec ctxt))
\<close> "approximate transcendental Akra-Bazzi parameters"

end


(*  Title:       Proving the Correctness of Disk Paxos

    Author:      Mauro J. Jaskelioff, Stephan Merz, 2005
    Maintainer:  Mauro J. Jaskelioff <mauro at fceia.unr.edu.ar>
*)

theory DiskPaxos_Inv6 imports DiskPaxos_Chosen  begin

subsection \<open>Invariant 6\<close>

text\<open>
The final conjunct of $HInv$ asserts that, once an output has been chosen,
$valueChosen(chosen)$ holds, and each processor's output equals either $chosen$ or
$NotAnInput$.
\<close>

definition HInv6 :: "state \<Rightarrow> bool"
where
  "HInv6 s = ((chosen s \<noteq> NotAnInput \<longrightarrow> valueChosen s (chosen s))
              \<and> (\<forall>p. outpt s p \<in> {chosen s, NotAnInput}))"

theorem HInit_HInv6: "HInit s \<Longrightarrow> HInv6 s"
  by(auto simp add: HInit_def Init_def InitDB_def HInv6_def)

lemma HEndPhase2_Inv6_1:
  assumes act: "HEndPhase2 s s' p"
  and inv: "HInv6 s"
  and inv2b: "Inv2b s"
  and inv2c: "Inv2c s"
  and inv3: "HInv3 s"
  and inv5: "HInv5_inner s p"
  and chosen': "chosen s' \<noteq> NotAnInput"
  shows "valueChosen s' (chosen s')"
proof(cases "chosen s=NotAnInput")
  from inv5 act
  have inv5R: "HInv5_inner_R s p"
    and phase: "phase s p = 2"
    and ep2_maj: "IsMajority {d .    d \<in> disksWritten s p
                                  \<and> (\<forall>q \<in> UNIV - {p}. hasRead s p d q)}"
    by(auto simp add: EndPhase2_def HInv5_inner_def)
  case True
  have p32: "maxBalInp s (bal(dblock s p)) (inp(dblock s p))"
  proof-
    have "\<not>(\<exists>D \<in> MajoritySet.\<exists>q. (\<forall>d\<in>D. bal (dblock s p) < mbal (disk s d q) \<and> \<not> hasRead s p d q))"
    proof auto
      fix D q
      assume Dmaj: "D\<in>MajoritySet"
      from ep2_maj Dmaj majorities_intersect
      have "\<exists>d\<in>D. d \<in> disksWritten s p
        \<and> (\<forall>q \<in> UNIV - {p}. hasRead s p d q)"
        by(auto simp add: MajoritySet_def, blast)
      then obtain d
        where dinD: "d\<in>D"
        and ddisk: "d \<in> disksWritten s p"
        and dhasR: "\<forall>q \<in> UNIV - {p}. hasRead s p d q"
        by auto
      from inv2b
      have "Inv2b_inner s p d"
        by(auto simp add: Inv2b_def)
      with ddisk
      have "disk s d p = dblock s p"
        by(auto simp add: Inv2b_inner_def)
      with inv2c phase
      have "bal (dblock s p) = mbal(disk s d p)"
        by(auto simp add: Inv2c_def Inv2c_inner_def)
      with dhasR dinD
      show "\<exists>d\<in>D. bal (dblock s p) < mbal (disk s d q) \<longrightarrow> hasRead s p d q"
        by auto
    qed
    with inv5R
    show ?thesis
      by(auto simp add: HInv5_inner_R_def)
  qed
  have p33: "maxBalInp s' (bal(dblock s' p)) (chosen s')"
  proof -
    from act
    have outpt': "outpt s' = (outpt s) (p:= inp (dblock s p))"
      by(auto simp add: EndPhase2_def)
    have outpt'_q: "\<forall>q. p\<noteq>q \<longrightarrow> outpt s' q = NotAnInput"
    proof auto
      fix q
      assume pnq: "p\<noteq>q"
      from outpt' pnq
      have "outpt s' q= outpt s q"
        by(auto simp add: EndPhase2_def)
      with True inv2c
      show "outpt s' q= NotAnInput"
        by(auto simp add: Inv2c_def Inv2c_inner_def)
    qed
    from True act chosen'
    have "chosen s' = inp (dblock s p)"
    proof(auto simp add: HNextPart_def split: if_split_asm)
      fix pa
      assume outpt'_pa: "outpt s' pa \<noteq> NotAnInput"
      from outpt'_q
      have someeq2: "\<And>pa. outpt s' pa \<noteq> NotAnInput \<Longrightarrow> pa=p"
        by auto
      with outpt'_pa
      have "outpt s' p \<noteq> NotAnInput"
        by auto
      from some_equality[of "\<lambda>p. outpt s' p \<noteq> NotAnInput", OF this someeq2]
      have "(SOME p. outpt s' p \<noteq> NotAnInput) = p" .
      with outpt'
      show  "outpt s' (SOME p. outpt s' p \<noteq> NotAnInput) = inp (dblock s p)"
        by auto
    qed
    moreover
    from act
    have"bal(dblock s' p) = bal(dblock s p)"
      by(auto simp add: EndPhase2_def)
    ultimately
    have "maxBalInp s (bal(dblock s' p)) (chosen s')"
      using p32
      by auto
    with HEndPhase2_allBlocks[OF act]
    show ?thesis
      by(auto simp add: maxBalInp_def)
  qed
  from ep2_maj inv2b majorities_intersect
  have "\<exists>D\<in>MajoritySet. (\<forall>d\<in>D.   disk s d p = dblock s p
                              \<and> (\<forall>q \<in> UNIV - {p}. hasRead s p d q))"
    by(auto simp add: Inv2b_def Inv2b_inner_def MajoritySet_def)
  then obtain D
    where Dmaj: "D\<in>MajoritySet"
    and p34: "\<forall>d\<in>D.   disk s d p = dblock s p
    \<and> (\<forall>q \<in> UNIV - {p}. hasRead s p d q)"
    by auto
  have p35: "\<forall>q. \<forall>d\<in>D. ( phase s q=1 \<and> bal(dblock s p)\<le>mbal(dblock s q)\<and> hasRead s q d p)
                        \<longrightarrow> \<lparr>block=dblock s p, proc=p\<rparr>\<in>blocksRead s q d"
  proof auto
    fix q d
    assume dD: "d\<in>D" and phase_q: "phase s q= Suc 0"
      and bal_mbal: "bal(dblock s p)\<le>mbal(dblock s q)" and hasRead: "hasRead s q d p"
    from phase inv2c
    have "bal(dblock s p)=mbal(dblock s p)"
      by(auto simp add: Inv2c_def Inv2c_inner_def)
    moreover
    from inv2c phase
    have "\<forall>br\<in>blocksRead s p d. mbal(block br) < mbal(dblock s p)"
      by(auto simp add: Inv2c_def Inv2c_inner_def)
    ultimately
    have p41: "\<lparr>block=dblock s q, proc=q\<rparr>\<notin>blocksRead s p d"
      using bal_mbal
      by auto
    from phase phase_q
    have "p\<noteq>q" by auto
    with p34 dD
    have "hasRead s p d q"
      by auto
    with phase phase_q hasRead inv3 p41
    show "\<lparr>block = dblock s p, proc = p\<rparr> \<in> blocksRead s q d"
      by(auto simp add: HInv3_def HInv3_inner_def
                        HInv3_L_def HInv3_R_def)
  qed
  have p36: "\<forall>q. \<forall>d\<in>D. phase s' q=1 \<and> bal(dblock s p) \<le> mbal(dblock s' q) \<and> hasRead s' q d p
                        \<longrightarrow> (\<exists>br\<in>blocksRead s' q d. bal(block br) = bal(dblock s p))"
  proof(auto)
    fix q d
    assume dD: "d \<in> D" and phase_q: "phase s' q = Suc 0"
           and bal: "bal (dblock s p) \<le> mbal (dblock s' q)"
           and hasRead: "hasRead s' q d p"
    from phase_q act
    have "phase s' q=phase s q \<and> dblock s' q=dblock s q \<and> hasRead s' q d p=hasRead s q d p \<and> blocksRead s' q d=blocksRead s q d"
      by(auto simp add: EndPhase2_def hasRead_def InitializePhase_def)
    with p35 phase_q bal hasRead dD
    have "\<lparr>block=dblock s p, proc=p\<rparr>\<in>blocksRead s' q d"
      by auto
    thus "\<exists>br\<in>blocksRead s' q d. bal(block br) = bal(dblock s p)"
      by force
  qed
  hence p36_2: "\<forall>q. \<forall>d\<in>D. phase s' q=1 \<and> bal(dblock s p) \<le> mbal(dblock s' q) \<and> hasRead s' q d p
                         \<longrightarrow> (\<exists>br\<in>blocksRead s' q d. bal(dblock s p) \<le> bal(block br))"
    by force
  from act
  have bal_dblock: "bal(dblock s' p)=bal(dblock s p)"
    and disk: "disk s'= disk s"
    by(auto simp add: EndPhase2_def)
  from bal_dblock p33
  have "maxBalInp s' (bal(dblock s p)) (chosen s')"
    by auto
  moreover
  from disk p34
  have  "\<forall>d\<in>D. bal(dblock s p) \<le> bal(disk s' d p) "
    by auto
  ultimately
  have "maxBalInp s' (bal(dblock s p)) (chosen s') \<and>
           (\<exists>D\<in>MajoritySet.
                   \<forall>d\<in>D. bal(dblock s p) \<le> bal (disk s' d p) \<and>
                         (\<forall>q. phase s' q = Suc 0 \<and>
                              bal(dblock s p) \<le> mbal (dblock s' q) \<and> hasRead s' q d p \<longrightarrow>
                              (\<exists>br\<in>blocksRead s' q d. bal(dblock s p) \<le> bal (block br))))"
    using p36_2 Dmaj
    by auto
  moreover
  from phase inv2c
  have "bal(dblock s p)\<in> Ballot p"
    by(auto simp add: Inv2c_def Inv2c_inner_def)
  ultimately
  show ?thesis
    by(auto simp add: valueChosen_def)
next
  case False
  with act
  have p31: "chosen s' = chosen s"
    by(auto simp add: HNextPart_def)
  from False inv
  have "valueChosen s (chosen s)"
    by(auto simp add: HInv6_def)
  from HEndPhase2_valueChosen[OF act this] p31 False InputsOrNi
  show ?thesis
    by auto
qed

lemma valueChosen_equal_case:
  assumes max_v: "maxBalInp s b v"
  and Dmaj: "D \<in> MajoritySet"
  and asm_v: "\<forall>d\<in>D. b \<le> bal (disk s d p)"
  and max_w: "maxBalInp s ba w"
  and Damaj: "Da \<in> MajoritySet"
  and asm_w: "\<forall>d\<in>Da. ba \<le> bal (disk s d pa)"
  and b_ba: "b\<le>ba"
  shows "v=w"
proof -
  have "\<forall>d. disk s d pa \<in> allBlocks s"
    by(auto simp add: allBlocks_def blocksOf_def)
  with majorities_intersect Dmaj Damaj
  have "\<exists>d\<in>D\<inter>Da. disk s d pa \<in> allBlocks s"
    by(auto simp add: MajoritySet_def, blast)
  then obtain d
    where dinmaj: "d\<in>D\<inter>Da" and dab: "disk s d pa \<in> allBlocks s"
    by auto
  with asm_w
  have ba: "ba \<le> bal (disk s d pa)"
    by auto
  with b_ba
  have "b \<le> bal (disk s d pa)"
    by auto
  with max_v dab
  have v_value: "inp (disk s d pa) = v"
    by(auto simp add: maxBalInp_def)
  from ba max_w dab
  have w_value: "inp (disk s d pa) = w"
    by(auto simp add: maxBalInp_def)
  with v_value
  show ?thesis by auto
qed

lemma valueChosen_equal:
  assumes v: "valueChosen s v"
  and w: "valueChosen s w"
  shows "v=w" using assms
proof (auto simp add: valueChosen_def)
  fix a b aa ba p D pa Da
  assume max_v: "maxBalInp s b v"
    and Dmaj: "D \<in> MajoritySet"
    and asm_v: "\<forall>d\<in>D. b \<le> bal (disk s d p) \<and>
              (\<forall>q. phase s q = Suc 0 \<and>
                   b \<le> mbal (dblock s q) \<and> hasRead s q d p \<longrightarrow>
                   (\<exists>br\<in>blocksRead s q d. b \<le> bal (block br)))"
    and max_w: "maxBalInp s ba w"
    and Damaj: "Da \<in> MajoritySet"
    and asm_w: "\<forall>d\<in>Da. ba \<le> bal (disk s d pa) \<and>
              (\<forall>q. phase s q = Suc 0 \<and>
                   ba \<le> mbal (dblock s q) \<and> hasRead s q d pa \<longrightarrow>
                   (\<exists>br\<in>blocksRead s q d. ba \<le> bal (block br)))"
  from asm_v
  have asm_v: "\<forall>d\<in>D. b \<le> bal (disk s d p)" by auto
  from asm_w
  have asm_w: "\<forall>d\<in>Da. ba \<le> bal (disk s d pa)" by auto
  show "v=w"
  proof(cases "b\<le>ba")
    case True
    from valueChosen_equal_case[OF max_v Dmaj asm_v max_w Damaj asm_w True]
    show ?thesis .
  next
    case False
    from valueChosen_equal_case[OF max_w Damaj asm_w max_v Dmaj asm_v] False
    show ?thesis
      by auto
  qed
qed

lemma HEndPhase2_Inv6_2:
  assumes act: "HEndPhase2 s s' p"
  and inv: "HInv6 s"
  and inv2b: "Inv2b s"
  and inv2c: "Inv2c s"
  and inv3: "HInv3 s"
  and inv5: "HInv5_inner s p"
  and asm: "outpt s' r \<noteq> NotAnInput"
  shows "outpt s' r = chosen s'"
proof(cases "chosen s=NotAnInput")
  case True
  with inv2c
  have "\<forall>q. outpt s q = NotAnInput"
    by(auto simp add: Inv2c_def Inv2c_inner_def)
  with True act asm
  show ?thesis
    by(auto simp add: EndPhase2_def HNextPart_def
               split: if_split_asm)
next
  case False
  with inv
  have p31: "valueChosen s (chosen s)"
    by(auto simp add: HInv6_def)
  with False act
  have "chosen s'\<noteq> NotAnInput"
    by(auto simp add: HNextPart_def)
  from HEndPhase2_Inv6_1[OF act inv inv2b inv2c inv3 inv5 this]
  have p32: "valueChosen s'(chosen s')" .
  from False InputsOrNi
  have "chosen s \<in> Inputs" by auto
  from valueChosen_equal[OF HEndPhase2_valueChosen[OF act p31 this] p32]
  have p33: "chosen s = chosen s'" .
  from act
  have maj: "IsMajority {d .    d \<in> disksWritten s p
                             \<and> (\<forall>q \<in> UNIV - {p}. hasRead s p d q)}" (is "IsMajority ?D")
    and phase: "phase s p = 2"
    by(auto simp add: EndPhase2_def)
  show ?thesis
  proof(cases "outpt s r = NotAnInput")
    case True
    with asm act
    have p41: "r=p"
      by(auto simp add: EndPhase2_def split: if_split_asm)
    from maj
    have p42: "\<exists>D\<in>MajoritySet. \<forall>d\<in>D. \<forall>q\<in>UNIV-{p}. hasRead s p d q"
      by(auto simp add: MajoritySet_def)
    have p43: "\<not>(\<exists>D\<in>MajoritySet. \<exists>q. (\<forall>d\<in>D.    bal(dblock s p) < mbal(disk s d q)
                                             \<and> \<not>hasRead s p d q))"
    proof auto
      fix D q
      assume Dmaj: "D \<in> MajoritySet"
      show "\<exists>d\<in>D. bal (dblock s p) < mbal (disk s d q) \<longrightarrow> hasRead s p d q"
      proof(cases "p=q")
        assume pq: "p=q"
        thus ?thesis
        proof auto
          from maj majorities_intersect Dmaj
          have "?D\<inter>D\<noteq>{}"
            by(auto simp add: MajoritySet_def)
          hence "\<exists>d\<in>?D\<inter>D. d\<in> disksWritten s p" by auto
          then obtain d where d: "d\<in> disksWritten s p" and "d\<in>?D\<inter>D"
            by auto
          hence dD: "d\<in>D" by auto
          from d inv2b
          have "disk s d p = dblock s p"
            by(auto simp add: Inv2b_def Inv2b_inner_def)
          with inv2c phase
          have "bal(dblock s p) = mbal(disk s d p) "
            by(auto simp add: Inv2c_def Inv2c_inner_def)
          with dD pq
          show  "\<exists>d\<in>D. bal (dblock s q) < mbal (disk s d q) \<longrightarrow> hasRead s q d q"
            by auto
        qed
      next
        case False
        with p42
        have "\<exists>D\<in>MajoritySet. \<forall>d\<in>D. hasRead s p d q"
          by auto
        with majorities_intersect Dmaj
        show ?thesis
          by(auto simp add: MajoritySet_def, blast)
      qed
    qed
    with inv5 act
    have p44: "maxBalInp s (bal(dblock s p)) (inp(dblock s p))"
      by(auto simp add: EndPhase2_def HInv5_inner_def
                        HInv5_inner_R_def)
    have "\<exists>bk\<in>allBlocks s. \<exists>b\<in>(UN p. Ballot p). (maxBalInp s b (chosen s)) \<and> b\<le> bal bk"
    proof -
      have disk_allblks: "\<forall>d p. disk s d p \<in> allBlocks s"
        by(auto simp add: allBlocks_def blocksOf_def)
      from p31
      have "\<exists>b\<in> (UN p. Ballot p). maxBalInp s b (chosen s) \<and>
      (\<exists>p. \<exists>D\<in>MajoritySet.(\<forall>d\<in>D.  b \<le> bal(disk s d p)))"
        by(auto simp add: valueChosen_def, force)
      with majority_nonempty obtain b p D d
        where "IsMajority D \<and> b\<in> (UN p. Ballot p) \<and>
               maxBalInp s b (chosen s) \<and> d\<in>D \<and> b \<le> bal(disk s d p)"
        by(auto simp add: MajoritySet_def, blast)
      with disk_allblks
      show ?thesis
        by(auto)
    qed
    then obtain bk b
      where p45_bk: "bk\<in>allBlocks s \<and> b\<le> bal bk"
        and p45_b: "b\<in>(UN p. Ballot p) \<and> (maxBalInp s b (chosen s))"
      by auto
    have p46: "inp(dblock s p) = chosen s"
    proof(cases "b \<le> bal(dblock s p)")
      case True
      have "dblock s p \<in> allBlocks s"
        by(auto simp add: allBlocks_def blocksOf_def)
      with p45_b True
      show ?thesis
        by(auto simp add: maxBalInp_def)
    next
      case False
      from p44 p45_bk False
      have "inp bk = inp(dblock s p)"
        by(auto simp add: maxBalInp_def)
      with p45_b p45_bk
      show ?thesis
        by(auto simp add: maxBalInp_def)
    qed
    with p41 p33 act
    show ?thesis
      by(auto simp add: EndPhase2_def)
  next
    case False
    from inv2c
    have "Inv2c_inner s r"
      by(auto simp add: Inv2c_def)
    with False asm inv2c act
    have "outpt s' r = outpt s r"
      by(auto simp add: Inv2c_inner_def EndPhase2_def
                 split: if_split_asm)
    with inv p33 False
    show ?thesis
      by(auto simp add: HInv6_def)
  qed
qed

theorem HEndPhase2_Inv6:
  assumes act: "HEndPhase2 s s' p"
  and inv: "HInv6 s"
  and inv2b: "Inv2b s"
  and inv2c: "Inv2c s"
  and inv3: "HInv3 s"
  and inv5: "HInv5_inner s p"
  shows "HInv6 s'"
proof(auto simp add: HInv6_def)
  assume "chosen s' \<noteq> NotAnInput"
  from HEndPhase2_Inv6_1[OF act inv inv2b inv2c inv3 inv5 this]
  show "valueChosen s' (chosen s')" .
next
  fix p
  assume "outpt s' p\<noteq> NotAnInput"
  from HEndPhase2_Inv6_2[OF act inv inv2b inv2c inv3 inv5 this]
  show "outpt s' p = chosen s'" .
qed

lemma outpt_chosen:
  assumes outpt: "outpt s = outpt s'"
  and inv2c: "Inv2c s"
  and nextp: "HNextPart s s'"
  shows "chosen s' = chosen s"
proof -
  from inv2c
  have "chosen s = NotAnInput \<longrightarrow> (\<forall>p. outpt s p = NotAnInput)"
    by(auto simp add: Inv2c_inner_def Inv2c_def)
  with outpt nextp
  show ?thesis
    by(auto simp add: HNextPart_def)
qed

lemma outpt_Inv6:
  "\<lbrakk> outpt s = outpt s'; \<forall>p. outpt s p \<in> {chosen s, NotAnInput};
     Inv2c s; HNextPart s s' \<rbrakk> \<Longrightarrow> \<forall>p. outpt s' p \<in> {chosen s', NotAnInput}"
  using outpt_chosen
  by auto

theorem HStartBallot_Inv6:
  assumes act: "HStartBallot s s' p"
  and inv: "HInv6 s"
  and inv2c: "Inv2c s"
  shows "HInv6 s'"
proof -
  from outpt_chosen act inv2c inv
  have "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s (chosen s')"
    by(auto simp add: StartBallot_def HInv6_def)
  from HStartBallot_valueChosen[OF act] this InputsOrNi
  have t1: "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s' (chosen s')"
    by auto
  from act
  have outpt: "outpt s = outpt s'"
    by(auto simp add: StartBallot_def)
  from outpt_Inv6[OF outpt] act inv2c inv
  have "\<forall>p. outpt s' p = chosen s' \<or> outpt s' p = NotAnInput"
    by(auto simp add: HInv6_def)
  with t1
  show ?thesis
    by(simp add: HInv6_def)
qed

theorem HPhase1or2Write_Inv6:
  assumes act: "HPhase1or2Write s s' p d"
  and inv: "HInv6 s"
  and inv4: "HInv4a s p"
  and inv2c: "Inv2c s"
  shows "HInv6 s'"
proof -
  from outpt_chosen act inv2c inv
  have "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s (chosen s')"
    by(auto simp add: Phase1or2Write_def HInv6_def)
  from HPhase1or2Write_valueChosen[OF act] inv4 this InputsOrNi
  have t1: "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s' (chosen s')"
    by auto
  from act
  have outpt: "outpt s = outpt s'"
    by(auto simp add: Phase1or2Write_def)
  from outpt_Inv6[OF outpt] act inv2c inv
  have "\<forall>p. outpt s' p = chosen s' \<or> outpt s' p = NotAnInput"
    by(auto simp add: HInv6_def)
  with t1
  show ?thesis
    by(simp add: HInv6_def)
qed

theorem HPhase1or2ReadThen_Inv6:
  assumes act: "HPhase1or2ReadThen s s' p d q"
  and inv: "HInv6 s"
  and inv2c: "Inv2c s"
  shows "HInv6 s'"
proof -
  from outpt_chosen act inv2c inv
  have "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s (chosen s')"
    by(auto simp add: Phase1or2ReadThen_def HInv6_def)
  from HPhase1or2ReadThen_valueChosen[OF act] this InputsOrNi
  have t1: "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s' (chosen s')"
    by auto
  from act
  have outpt: "outpt s = outpt s'"
    by(auto simp add: Phase1or2ReadThen_def)
  from outpt_Inv6[OF outpt] act inv2c inv
  have "\<forall>p. outpt s' p = chosen s' \<or> outpt s' p = NotAnInput"
    by(auto simp add: HInv6_def)
  with t1
  show ?thesis
    by(simp add: HInv6_def)
qed

theorem HPhase1or2ReadElse_Inv6:
  assumes act: "HPhase1or2ReadElse s s' p d q"
  and inv: "HInv6 s"
  and inv2c: "Inv2c s"
  shows "HInv6 s'"
  using assms and HStartBallot_Inv6
  by(auto simp add: Phase1or2ReadElse_def)

theorem HEndPhase1_Inv6:
  assumes act: "HEndPhase1 s s' p"
  and inv: "HInv6 s"
  and inv1: "Inv1 s"
  and inv2a: "Inv2a s"
  and inv2b: "Inv2b s"
  and inv2c: "Inv2c s"
  shows "HInv6 s'"
proof -
  from outpt_chosen act inv2c inv
  have "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s (chosen s')"
    by(auto simp add: EndPhase1_def HInv6_def)
  from HEndPhase1_valueChosen[OF act] inv1 inv2a inv2b this InputsOrNi
  have t1: "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s' (chosen s')"
    by auto
  from act
  have outpt: "outpt s = outpt s'"
    by(auto simp add: EndPhase1_def)
  from outpt_Inv6[OF outpt] act inv2c inv
  have "\<forall>p. outpt s' p = chosen s' \<or> outpt s' p = NotAnInput"
    by(auto simp add: HInv6_def)
  with t1
  show ?thesis
    by(simp add: HInv6_def)
qed

lemma outpt_chosen_2:
  assumes outpt: "outpt s' = (outpt s) (p:= NotAnInput)"
  and inv2c: "Inv2c s"
  and nextp: "HNextPart s s'"
  shows "chosen s = chosen s'"
proof -
  from inv2c
  have "chosen s = NotAnInput \<longrightarrow> (\<forall>p. outpt s p = NotAnInput)"
    by(auto simp add: Inv2c_inner_def Inv2c_def)
  with outpt nextp
  show ?thesis
    by(auto simp add: HNextPart_def)
qed

lemma outpt_HInv6_2:
  assumes outpt: "outpt s' = (outpt s) (p:= NotAnInput)"
  and inv: "\<forall>p. outpt s p \<in> {chosen s, NotAnInput}"
  and inv2c: "Inv2c s"
  and nextp: "HNextPart s s'"
  shows "\<forall>p. outpt s' p \<in> {chosen s', NotAnInput}"
proof -
  from outpt_chosen_2[OF outpt inv2c nextp]
  have "chosen s = chosen s'" .
  with inv outpt
  show ?thesis
    by auto
qed

theorem HFail_Inv6:
  assumes act: "HFail s s' p"
  and inv: "HInv6 s"
  and inv2c: "Inv2c s"
  shows "HInv6 s'"
proof -
  from outpt_chosen_2 act inv2c inv
  have "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s (chosen s')"
    by(auto simp add: Fail_def HInv6_def)
  from HFail_valueChosen[OF act] this InputsOrNi
  have t1: "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s' (chosen s')"
    by auto
  from act
  have outpt: "outpt s' = (outpt s) (p:=NotAnInput) "
    by(auto simp add: Fail_def)
  from outpt_HInv6_2[OF outpt] act inv2c inv
  have "\<forall>p. outpt s' p = chosen s' \<or> outpt s' p = NotAnInput"
    by(auto simp add: HInv6_def)
  with t1
  show ?thesis
    by(simp add: HInv6_def)
qed

theorem HPhase0Read_Inv6:
  assumes act: "HPhase0Read s s' p d"
  and inv: "HInv6 s"
  and inv2c: "Inv2c s"
  shows "HInv6 s'"
proof -
  from outpt_chosen act inv2c inv
  have "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s (chosen s')"
    by(auto simp add: Phase0Read_def HInv6_def)
  from HPhase0Read_valueChosen[OF act] this InputsOrNi
  have t1: "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s' (chosen s')"
    by auto
  from act
  have outpt: "outpt s = outpt s'"
    by(auto simp add: Phase0Read_def)
  from outpt_Inv6[OF outpt] act inv2c inv
  have "\<forall>p. outpt s' p = chosen s' \<or> outpt s' p = NotAnInput"
    by(auto simp add: HInv6_def)
  with t1
  show ?thesis
    by(simp add: HInv6_def)
qed

theorem HEndPhase0_Inv6:
  assumes act: "HEndPhase0 s s' p"
  and inv: "HInv6 s"
  and inv1: "Inv1 s"
  and inv2c: "Inv2c s"
  shows "HInv6 s'"
proof -
  from outpt_chosen act inv2c inv
  have "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s (chosen s')"
    by(auto simp add: EndPhase0_def HInv6_def)
  from HEndPhase0_valueChosen[OF act] inv1 this InputsOrNi
  have t1: "chosen s' \<noteq> NotAnInput \<longrightarrow> valueChosen s' (chosen s')"
    by auto
  from act
  have outpt: "outpt s = outpt s'"
    by(auto simp add: EndPhase0_def)
  from outpt_Inv6[OF outpt] act inv2c inv
  have "\<forall>p. outpt s' p = chosen s' \<or> outpt s' p = NotAnInput"
    by(auto simp add: HInv6_def)
  with t1
  show ?thesis
    by(simp add: HInv6_def)
qed

text\<open>
  $HInv1 \wedge HInv2 \wedge HInv2' \wedge HInv3 \wedge HInv4 \wedge HInv5 \wedge HInv6$
  is an invariant of $HNext$.
\<close>

lemma I2f:
  assumes nxt: "HNext s s'"
  and inv: "HInv1 s \<and> HInv2 s \<and> HInv2 s' \<and> HInv3 s \<and> HInv4 s \<and> HInv5 s \<and> HInv6 s"
  shows "HInv6 s'" using assms
  by(auto simp add: HNext_def Next_def,
     auto simp add: HInv2_def intro: HStartBallot_Inv6,
     auto intro: HPhase0Read_Inv6,
     auto simp add: HInv4_def intro: HPhase1or2Write_Inv6,
     auto simp add: Phase1or2Read_def
          intro: HPhase1or2ReadThen_Inv6
                 HPhase1or2ReadElse_Inv6,
     auto simp add: EndPhase1or2_def HInv1_def HInv5_def
          intro: HEndPhase1_Inv6
                 HEndPhase2_Inv6,
     auto intro: HFail_Inv6,
     auto intro: HEndPhase0_Inv6)

end