(* Property from Case-Analysis for Rippling and Inductive Proof,
   Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010.
   This Isabelle theory is produced using the TIP tool offered at the following website:
     https://github.com/tip-org/tools
   This file was originally provided as part of TIP benchmark at the following website:
     https://github.com/tip-org/benchmarks
   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
   to make it compatible with Isabelle2017.
   Some proofs were added by Yutaka Nagashima.*)
  theory TIP_prop_79
imports "../../Test_Base"
begin

datatype Nat = Z | S "Nat"

fun t2 :: "Nat => Nat => Nat" where
"t2 (Z) y = Z"
| "t2 (S z) (Z) = S z"
| "t2 (S z) (S x2) = t2 z x2"

theorem property0 :
  "((t2 (t2 (S m) n) (S k)) = (t2 (t2 m n) k))"
  oops

end


theory prop_38
imports Main
        "$HIPSTER_HOME/IsaHipster"
begin
  datatype 'a list = Nil2 | Cons2 "'a" "'a list"
  datatype Nat = Z | S "Nat"
  fun equal2 :: "Nat => Nat => bool" where
  "equal2 (Z) (Z) = True"
  | "equal2 (Z) (S z) = False"
  | "equal2 (S x2) (Z) = False"
  | "equal2 (S x2) (S y2) = equal2 x2 y2"
  fun elem :: "Nat => Nat list => bool" where
  "elem x (Nil2) = False"
  | "elem x (Cons2 z xs) = (if equal2 x z then True else elem x xs)"
  fun append :: "'a list => 'a list => 'a list" where
  "append (Nil2) y = y"
  | "append (Cons2 z xs) y = Cons2 z (append xs y)"
  (*hipster equal2 elem append *)

  theorem x0 :
    "(elem x y) ==> ((elem x z) ==> (elem x (append y z)))"
    by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>)
end


(*  Title:      HOL/Library/Linear_Temporal_Logic_on_Streams.thy
    Author:     Andrei Popescu, TU Muenchen
    Author:     Dmitriy Traytel, TU Muenchen
*)

section \<open>Linear Temporal Logic on Streams\<close>

theory Linear_Temporal_Logic_on_Streams
  imports Stream Sublist Extended_Nat Infinite_Set
begin

section\<open>Preliminaries\<close>

lemma shift_prefix:
assumes "xl @- xs = yl @- ys" and "length xl \<le> length yl"
shows "prefix xl yl"
using assms proof(induct xl arbitrary: yl xs ys)
  case (Cons x xl yl xs ys)
  thus ?case by (cases yl) auto
qed auto

lemma shift_prefix_cases:
assumes "xl @- xs = yl @- ys"
shows "prefix xl yl \<or> prefix yl xl"
using shift_prefix[OF assms]
by (cases "length xl \<le> length yl") (metis, metis assms nat_le_linear shift_prefix)

section\<open>Linear temporal logic\<close>

text \<open>Propositional connectives:\<close>

abbreviation (input) IMPL (infix "impl" 60)
where "\<phi> impl \<psi> \<equiv> \<lambda> xs. \<phi> xs \<longrightarrow> \<psi> xs"

abbreviation (input) OR (infix "or" 60)
where "\<phi> or \<psi> \<equiv> \<lambda> xs. \<phi> xs \<or> \<psi> xs"

abbreviation (input) AND (infix "aand" 60)
where "\<phi> aand \<psi> \<equiv> \<lambda> xs. \<phi> xs \<and> \<psi> xs"

abbreviation (input) not where "not \<phi> \<equiv> \<lambda> xs. \<not> \<phi> xs"

abbreviation (input) "true \<equiv> \<lambda> xs. True"

abbreviation (input) "false \<equiv> \<lambda> xs. False"

lemma impl_not_or: "\<phi> impl \<psi> = (not \<phi>) or \<psi>"
by blast

lemma not_or: "not (\<phi> or \<psi>) = (not \<phi>) aand (not \<psi>)"
by blast

lemma not_aand: "not (\<phi> aand \<psi>) = (not \<phi>) or (not \<psi>)"
by blast

lemma non_not[simp]: "not (not \<phi>) = \<phi>" by simp

text \<open>Temporal (LTL) connectives:\<close>

fun holds where "holds P xs \<longleftrightarrow> P (shd xs)"
fun nxt where "nxt \<phi> xs = \<phi> (stl xs)"

definition "HLD s = holds (\<lambda>x. x \<in> s)"

abbreviation HLD_nxt (infixr "\<cdot>" 65) where
  "s \<cdot> P \<equiv> HLD s aand nxt P"

context
  notes [[inductive_internals]]
begin

inductive ev for \<phi> where
base: "\<phi> xs \<Longrightarrow> ev \<phi> xs"
|
step: "ev \<phi> (stl xs) \<Longrightarrow> ev \<phi> xs"

coinductive alw for \<phi> where
alw: "\<lbrakk>\<phi> xs; alw \<phi> (stl xs)\<rbrakk> \<Longrightarrow> alw \<phi> xs"

\<comment> \<open>weak until:\<close>
coinductive UNTIL (infix "until" 60) for \<phi> \<psi> where
base: "\<psi> xs \<Longrightarrow> (\<phi> until \<psi>) xs"
|
step: "\<lbrakk>\<phi> xs; (\<phi> until \<psi>) (stl xs)\<rbrakk> \<Longrightarrow> (\<phi> until \<psi>) xs"

end

lemma holds_mono:
assumes holds: "holds P xs" and 0: "\<And> x. P x \<Longrightarrow> Q x"
shows "holds Q xs"
using assms by auto

lemma holds_aand:
"(holds P aand holds Q) steps \<longleftrightarrow> holds (\<lambda> step. P step \<and> Q step) steps" by auto

lemma HLD_iff: "HLD s \<omega> \<longleftrightarrow> shd \<omega> \<in> s"
  by (simp add: HLD_def)

lemma HLD_Stream[simp]: "HLD X (x ## \<omega>) \<longleftrightarrow> x \<in> X"
  by (simp add: HLD_iff)

lemma nxt_mono:
assumes nxt: "nxt \<phi> xs" and 0: "\<And> xs. \<phi> xs \<Longrightarrow> \<psi> xs"
shows "nxt \<psi> xs"
using assms by auto

declare ev.intros[intro]
declare alw.cases[elim]

lemma ev_induct_strong[consumes 1, case_names base step]:
  "ev \<phi> x \<Longrightarrow> (\<And>xs. \<phi> xs \<Longrightarrow> P xs) \<Longrightarrow> (\<And>xs. ev \<phi> (stl xs) \<Longrightarrow> \<not> \<phi> xs \<Longrightarrow> P (stl xs) \<Longrightarrow> P xs) \<Longrightarrow> P x"
  by (induct rule: ev.induct) auto

lemma alw_coinduct[consumes 1, case_names alw stl]:
  "X x \<Longrightarrow> (\<And>x. X x \<Longrightarrow> \<phi> x) \<Longrightarrow> (\<And>x. X x \<Longrightarrow> \<not> alw \<phi> (stl x) \<Longrightarrow> X (stl x)) \<Longrightarrow> alw \<phi> x"
  using alw.coinduct[of X x \<phi>] by auto

lemma ev_mono:
assumes ev: "ev \<phi> xs" and 0: "\<And> xs. \<phi> xs \<Longrightarrow> \<psi> xs"
shows "ev \<psi> xs"
using ev by induct (auto simp: 0)

lemma alw_mono:
assumes alw: "alw \<phi> xs" and 0: "\<And> xs. \<phi> xs \<Longrightarrow> \<psi> xs"
shows "alw \<psi> xs"
using alw by coinduct (auto simp: 0)

lemma until_monoL:
assumes until: "(\<phi>1 until \<psi>) xs" and 0: "\<And> xs. \<phi>1 xs \<Longrightarrow> \<phi>2 xs"
shows "(\<phi>2 until \<psi>) xs"
using until by coinduct (auto elim: UNTIL.cases simp: 0)

lemma until_monoR:
assumes until: "(\<phi> until \<psi>1) xs" and 0: "\<And> xs. \<psi>1 xs \<Longrightarrow> \<psi>2 xs"
shows "(\<phi> until \<psi>2) xs"
using until by coinduct (auto elim: UNTIL.cases simp: 0)

lemma until_mono:
assumes until: "(\<phi>1 until \<psi>1) xs" and
0: "\<And> xs. \<phi>1 xs \<Longrightarrow> \<phi>2 xs" "\<And> xs. \<psi>1 xs \<Longrightarrow> \<psi>2 xs"
shows "(\<phi>2 until \<psi>2) xs"
using until by coinduct (auto elim: UNTIL.cases simp: 0)

lemma until_false: "\<phi> until false = alw \<phi>"
proof-
  {fix xs assume "(\<phi> until false) xs" hence "alw \<phi> xs"
   by coinduct (auto elim: UNTIL.cases)
  }
  moreover
  {fix xs assume "alw \<phi> xs" hence "(\<phi> until false) xs"
   by coinduct auto
  }
  ultimately show ?thesis by blast
qed

lemma ev_nxt: "ev \<phi> = (\<phi> or nxt (ev \<phi>))"
by (rule ext) (metis ev.simps nxt.simps)

lemma alw_nxt: "alw \<phi> = (\<phi> aand nxt (alw \<phi>))"
by (rule ext) (metis alw.simps nxt.simps)

lemma ev_ev[simp]: "ev (ev \<phi>) = ev \<phi>"
proof-
  {fix xs
   assume "ev (ev \<phi>) xs" hence "ev \<phi> xs"
   by induct auto
  }
  thus ?thesis by auto
qed

lemma alw_alw[simp]: "alw (alw \<phi>) = alw \<phi>"
proof-
  {fix xs
   assume "alw \<phi> xs" hence "alw (alw \<phi>) xs"
   by coinduct auto
  }
  thus ?thesis by auto
qed

lemma ev_shift:
assumes "ev \<phi> xs"
shows "ev \<phi> (xl @- xs)"
using assms by (induct xl) auto

lemma ev_imp_shift:
assumes "ev \<phi> xs"  shows "\<exists> xl xs2. xs = xl @- xs2 \<and> \<phi> xs2"
using assms by induct (metis shift.simps(1), metis shift.simps(2) stream.collapse)+

lemma alw_ev_shift: "alw \<phi> xs1 \<Longrightarrow> ev (alw \<phi>) (xl @- xs1)"
by (auto intro: ev_shift)

lemma alw_shift:
assumes "alw \<phi> (xl @- xs)"
shows "alw \<phi> xs"
using assms by (induct xl) auto

lemma ev_ex_nxt:
assumes "ev \<phi> xs"
shows "\<exists> n. (nxt ^^ n) \<phi> xs"
using assms proof induct
  case (base xs) thus ?case by (intro exI[of _ 0]) auto
next
  case (step xs)
  then obtain n where "(nxt ^^ n) \<phi> (stl xs)" by blast
  thus ?case by (intro exI[of _ "Suc n"]) (metis funpow.simps(2) nxt.simps o_def)
qed

lemma alw_sdrop:
assumes "alw \<phi> xs"  shows "alw \<phi> (sdrop n xs)"
by (metis alw_shift assms stake_sdrop)

lemma nxt_sdrop: "(nxt ^^ n) \<phi> xs \<longleftrightarrow> \<phi> (sdrop n xs)"
by (induct n arbitrary: xs) auto

definition "wait \<phi> xs \<equiv> LEAST n. (nxt ^^ n) \<phi> xs"

lemma nxt_wait:
assumes "ev \<phi> xs"  shows "(nxt ^^ (wait \<phi> xs)) \<phi> xs"
unfolding wait_def using ev_ex_nxt[OF assms] by(rule LeastI_ex)

lemma nxt_wait_least:
assumes ev: "ev \<phi> xs" and nxt: "(nxt ^^ n) \<phi> xs"  shows "wait \<phi> xs \<le> n"
unfolding wait_def using ev_ex_nxt[OF ev] by (metis Least_le nxt)

lemma sdrop_wait:
assumes "ev \<phi> xs"  shows "\<phi> (sdrop (wait \<phi> xs) xs)"
using nxt_wait[OF assms] unfolding nxt_sdrop .

lemma sdrop_wait_least:
assumes ev: "ev \<phi> xs" and nxt: "\<phi> (sdrop n xs)"  shows "wait \<phi> xs \<le> n"
using assms nxt_wait_least unfolding nxt_sdrop by auto

lemma nxt_ev: "(nxt ^^ n) \<phi> xs \<Longrightarrow> ev \<phi> xs"
by (induct n arbitrary: xs) auto

lemma not_ev: "not (ev \<phi>) = alw (not \<phi>)"
proof(rule ext, safe)
  fix xs assume "not (ev \<phi>) xs" thus "alw (not \<phi>) xs"
  by (coinduct) auto
next
  fix xs assume "ev \<phi> xs" and "alw (not \<phi>) xs" thus False
  by (induct) auto
qed

lemma not_alw: "not (alw \<phi>) = ev (not \<phi>)"
proof-
  have "not (alw \<phi>) = not (alw (not (not \<phi>)))" by simp
  also have "... = ev (not \<phi>)" unfolding not_ev[symmetric] by simp
  finally show ?thesis .
qed

lemma not_ev_not[simp]: "not (ev (not \<phi>)) = alw \<phi>"
unfolding not_ev by simp

lemma not_alw_not[simp]: "not (alw (not \<phi>)) = ev \<phi>"
unfolding not_alw by simp

lemma alw_ev_sdrop:
assumes "alw (ev \<phi>) (sdrop m xs)"
shows "alw (ev \<phi>) xs"
using assms
by coinduct (metis alw_nxt ev_shift funpow_swap1 nxt.simps nxt_sdrop stake_sdrop)

lemma ev_alw_imp_alw_ev:
assumes "ev (alw \<phi>) xs"  shows "alw (ev \<phi>) xs"
using assms by induct (metis (full_types) alw_mono ev.base, metis alw alw_nxt ev.step)

lemma alw_aand: "alw (\<phi> aand \<psi>) = alw \<phi> aand alw \<psi>"
proof-
  {fix xs assume "alw (\<phi> aand \<psi>) xs" hence "(alw \<phi> aand alw \<psi>) xs"
   by (auto elim: alw_mono)
  }
  moreover
  {fix xs assume "(alw \<phi> aand alw \<psi>) xs" hence "alw (\<phi> aand \<psi>) xs"
   by coinduct auto
  }
  ultimately show ?thesis by blast
qed

lemma ev_or: "ev (\<phi> or \<psi>) = ev \<phi> or ev \<psi>"
proof-
  {fix xs assume "(ev \<phi> or ev \<psi>) xs" hence "ev (\<phi> or \<psi>) xs"
   by (auto elim: ev_mono)
  }
  moreover
  {fix xs assume "ev (\<phi> or \<psi>) xs" hence "(ev \<phi> or ev \<psi>) xs"
   by induct auto
  }
  ultimately show ?thesis by blast
qed

lemma ev_alw_aand:
assumes \<phi>: "ev (alw \<phi>) xs" and \<psi>: "ev (alw \<psi>) xs"
shows "ev (alw (\<phi> aand \<psi>)) xs"
proof-
  obtain xl xs1 where xs1: "xs = xl @- xs1" and \<phi>\<phi>: "alw \<phi> xs1"
  using \<phi> by (metis ev_imp_shift)
  moreover obtain yl ys1 where xs2: "xs = yl @- ys1" and \<psi>\<psi>: "alw \<psi> ys1"
  using \<psi> by (metis ev_imp_shift)
  ultimately have 0: "xl @- xs1 = yl @- ys1" by auto
  hence "prefix xl yl \<or> prefix yl xl" using shift_prefix_cases by auto
  thus ?thesis proof
    assume "prefix xl yl"
    then obtain yl1 where yl: "yl = xl @ yl1" by (elim prefixE)
    have xs1': "xs1 = yl1 @- ys1" using 0 unfolding yl by simp
    have "alw \<phi> ys1" using \<phi>\<phi> unfolding xs1' by (metis alw_shift)
    hence "alw (\<phi> aand \<psi>) ys1" using \<psi>\<psi> unfolding alw_aand by auto
    thus ?thesis unfolding xs2 by (auto intro: alw_ev_shift)
  next
    assume "prefix yl xl"
    then obtain xl1 where xl: "xl = yl @ xl1" by (elim prefixE)
    have ys1': "ys1 = xl1 @- xs1" using 0 unfolding xl by simp
    have "alw \<psi> xs1" using \<psi>\<psi> unfolding ys1' by (metis alw_shift)
    hence "alw (\<phi> aand \<psi>) xs1" using \<phi>\<phi> unfolding alw_aand by auto
    thus ?thesis unfolding xs1 by (auto intro: alw_ev_shift)
  qed
qed

lemma ev_alw_alw_impl:
assumes "ev (alw \<phi>) xs" and "alw (alw \<phi> impl ev \<psi>) xs"
shows "ev \<psi> xs"
using assms by induct auto

lemma ev_alw_stl[simp]: "ev (alw \<phi>) (stl x) \<longleftrightarrow> ev (alw \<phi>) x"
by (metis (full_types) alw_nxt ev_nxt nxt.simps)

lemma alw_alw_impl_ev:
"alw (alw \<phi> impl ev \<psi>) = (ev (alw \<phi>) impl alw (ev \<psi>))" (is "?A = ?B")
proof-
  {fix xs assume "?A xs \<and> ev (alw \<phi>) xs" hence "alw (ev \<psi>) xs"
    by coinduct (auto elim: ev_alw_alw_impl)
  }
  moreover
  {fix xs assume "?B xs" hence "?A xs"
   by coinduct auto
  }
  ultimately show ?thesis by blast
qed

lemma ev_alw_impl:
assumes "ev \<phi> xs" and "alw (\<phi> impl \<psi>) xs"  shows "ev \<psi> xs"
using assms by induct auto

lemma ev_alw_impl_ev:
assumes "ev \<phi> xs" and "alw (\<phi> impl ev \<psi>) xs"  shows "ev \<psi> xs"
using ev_alw_impl[OF assms] by simp

lemma alw_mp:
assumes "alw \<phi> xs" and "alw (\<phi> impl \<psi>) xs"
shows "alw \<psi> xs"
proof-
  {assume "alw \<phi> xs \<and> alw (\<phi> impl \<psi>) xs" hence ?thesis
   by coinduct auto
  }
  thus ?thesis using assms by auto
qed

lemma all_imp_alw:
assumes "\<And> xs. \<phi> xs"  shows "alw \<phi> xs"
proof-
  {assume "\<forall> xs. \<phi> xs"
   hence ?thesis by coinduct auto
  }
  thus ?thesis using assms by auto
qed

lemma alw_impl_ev_alw:
assumes "alw (\<phi> impl ev \<psi>) xs"
shows "alw (ev \<phi> impl ev \<psi>) xs"
using assms by coinduct (auto dest: ev_alw_impl)

lemma ev_holds_sset:
"ev (holds P) xs \<longleftrightarrow> (\<exists> x \<in> sset xs. P x)" (is "?L \<longleftrightarrow> ?R")
proof safe
  assume ?L thus ?R by induct (metis holds.simps stream.set_sel(1), metis stl_sset)
next
  fix x assume "x \<in> sset xs" "P x"
  thus ?L by (induct rule: sset_induct) (simp_all add: ev.base ev.step)
qed

text \<open>LTL as a program logic:\<close>
lemma alw_invar:
assumes "\<phi> xs" and "alw (\<phi> impl nxt \<phi>) xs"
shows "alw \<phi> xs"
proof-
  {assume "\<phi> xs \<and> alw (\<phi> impl nxt \<phi>) xs" hence ?thesis
   by coinduct auto
  }
  thus ?thesis using assms by auto
qed

lemma variance:
assumes 1: "\<phi> xs" and 2: "alw (\<phi> impl (\<psi> or nxt \<phi>)) xs"
shows "(alw \<phi> or ev \<psi>) xs"
proof-
  {assume "\<not> ev \<psi> xs" hence "alw (not \<psi>) xs" unfolding not_ev[symmetric] .
   moreover have "alw (not \<psi> impl (\<phi> impl nxt \<phi>)) xs"
   using 2 by coinduct auto
   ultimately have "alw (\<phi> impl nxt \<phi>) xs" by(auto dest: alw_mp)
   with 1 have "alw \<phi> xs" by(rule alw_invar)
  }
  thus ?thesis by blast
qed

lemma ev_alw_imp_nxt:
assumes e: "ev \<phi> xs" and a: "alw (\<phi> impl (nxt \<phi>)) xs"
shows "ev (alw \<phi>) xs"
proof-
  obtain xl xs1 where xs: "xs = xl @- xs1" and \<phi>: "\<phi> xs1"
  using e by (metis ev_imp_shift)
  have "\<phi> xs1 \<and> alw (\<phi> impl (nxt \<phi>)) xs1" using a \<phi> unfolding xs by (metis alw_shift)
  hence "alw \<phi> xs1" by(coinduct xs1 rule: alw.coinduct) auto
  thus ?thesis unfolding xs by (auto intro: alw_ev_shift)
qed

inductive ev_at :: "('a stream \<Rightarrow> bool) \<Rightarrow> nat \<Rightarrow> 'a stream \<Rightarrow> bool" for P :: "'a stream \<Rightarrow> bool" where
  base: "P \<omega> \<Longrightarrow> ev_at P 0 \<omega>"
| step:"\<not> P \<omega> \<Longrightarrow> ev_at P n (stl \<omega>) \<Longrightarrow> ev_at P (Suc n) \<omega>"

inductive_simps ev_at_0[simp]: "ev_at P 0 \<omega>"
inductive_simps ev_at_Suc[simp]: "ev_at P (Suc n) \<omega>"

lemma ev_at_imp_snth: "ev_at P n \<omega> \<Longrightarrow> P (sdrop n \<omega>)"
  by (induction n arbitrary: \<omega>) auto

lemma ev_at_HLD_imp_snth: "ev_at (HLD X) n \<omega> \<Longrightarrow> \<omega> !! n \<in> X"
  by (auto dest!: ev_at_imp_snth simp: HLD_iff)

lemma ev_at_HLD_single_imp_snth: "ev_at (HLD {x}) n \<omega> \<Longrightarrow> \<omega> !! n = x"
  by (drule ev_at_HLD_imp_snth) simp

lemma ev_at_unique: "ev_at P n \<omega> \<Longrightarrow> ev_at P m \<omega> \<Longrightarrow> n = m"
proof (induction arbitrary: m rule: ev_at.induct)
  case (base \<omega>) then show ?case
    by (simp add: ev_at.simps[of _ _ \<omega>])
next
  case (step \<omega> n) from step.prems step.hyps step.IH[of "m - 1"] show ?case
    by (auto simp add: ev_at.simps[of _ _ \<omega>])
qed

lemma ev_iff_ev_at: "ev P \<omega> \<longleftrightarrow> (\<exists>n. ev_at P n \<omega>)"
proof
  assume "ev P \<omega>" then show "\<exists>n. ev_at P n \<omega>"
    by (induction rule: ev_induct_strong) (auto intro: ev_at.intros)
next
  assume "\<exists>n. ev_at P n \<omega>"
  then obtain n where "ev_at P n \<omega>"
    by auto
  then show "ev P \<omega>"
    by induction auto
qed

lemma ev_at_shift: "ev_at (HLD X) i (stake (Suc i) \<omega> @- \<omega>' :: 's stream) \<longleftrightarrow> ev_at (HLD X) i \<omega>"
  by (induction i arbitrary: \<omega>) (auto simp: HLD_iff)

lemma ev_iff_ev_at_unique: "ev P \<omega> \<longleftrightarrow> (\<exists>!n. ev_at P n \<omega>)"
  by (auto intro: ev_at_unique simp: ev_iff_ev_at)

lemma alw_HLD_iff_streams: "alw (HLD X) \<omega> \<longleftrightarrow> \<omega> \<in> streams X"
proof
  assume "alw (HLD X) \<omega>" then show "\<omega> \<in> streams X"
  proof (coinduction arbitrary: \<omega>)
    case (streams \<omega>) then show ?case by (cases \<omega>) auto
  qed
next
  assume "\<omega> \<in> streams X" then show "alw (HLD X) \<omega>"
  proof (coinduction arbitrary: \<omega>)
    case (alw \<omega>) then show ?case by (cases \<omega>) auto
  qed
qed

lemma not_HLD: "not (HLD X) = HLD (- X)"
  by (auto simp: HLD_iff)

lemma not_alw_iff: "\<not> (alw P \<omega>) \<longleftrightarrow> ev (not P) \<omega>"
  using not_alw[of P] by (simp add: fun_eq_iff)

lemma not_ev_iff: "\<not> (ev P \<omega>) \<longleftrightarrow> alw (not P) \<omega>"
  using not_alw_iff[of "not P" \<omega>, symmetric]  by simp

lemma ev_Stream: "ev P (x ## s) \<longleftrightarrow> P (x ## s) \<or> ev P s"
  by (auto elim: ev.cases)

lemma alw_ev_imp_ev_alw:
  assumes "alw (ev P) \<omega>" shows "ev (P aand alw (ev P)) \<omega>"
proof -
  have "ev P \<omega>" using assms by auto
  from this assms show ?thesis
    by induct auto
qed

lemma ev_False: "ev (\<lambda>x. False) \<omega> \<longleftrightarrow> False"
proof
  assume "ev (\<lambda>x. False) \<omega>" then show False
    by induct auto
qed auto

lemma alw_False: "alw (\<lambda>x. False) \<omega> \<longleftrightarrow> False"
  by auto

lemma ev_iff_sdrop: "ev P \<omega> \<longleftrightarrow> (\<exists>m. P (sdrop m \<omega>))"
proof safe
  assume "ev P \<omega>" then show "\<exists>m. P (sdrop m \<omega>)"
    by (induct rule: ev_induct_strong) (auto intro: exI[of _ 0] exI[of _ "Suc n" for n])
next
  fix m assume "P (sdrop m \<omega>)" then show "ev P \<omega>"
    by (induct m arbitrary: \<omega>) auto
qed

lemma alw_iff_sdrop: "alw P \<omega> \<longleftrightarrow> (\<forall>m. P (sdrop m \<omega>))"
proof safe
  fix m assume "alw P \<omega>" then show "P (sdrop m \<omega>)"
    by (induct m arbitrary: \<omega>) auto
next
  assume "\<forall>m. P (sdrop m \<omega>)" then show "alw P \<omega>"
    by (coinduction arbitrary: \<omega>) (auto elim: allE[of _ 0] allE[of _ "Suc n" for n])
qed

lemma infinite_iff_alw_ev: "infinite {m. P (sdrop m \<omega>)} \<longleftrightarrow> alw (ev P) \<omega>"
  unfolding infinite_nat_iff_unbounded_le alw_iff_sdrop ev_iff_sdrop
  by simp (metis le_Suc_ex le_add1)

lemma alw_inv:
  assumes stl: "\<And>s. f (stl s) = stl (f s)"
  shows "alw P (f s) \<longleftrightarrow> alw (\<lambda>x. P (f x)) s"
proof
  assume "alw P (f s)" then show "alw (\<lambda>x. P (f x)) s"
    by (coinduction arbitrary: s rule: alw_coinduct)
       (auto simp: stl)
next
  assume "alw (\<lambda>x. P (f x)) s" then show "alw P (f s)"
    by (coinduction arbitrary: s rule: alw_coinduct) (auto simp flip: stl)
qed

lemma ev_inv:
  assumes stl: "\<And>s. f (stl s) = stl (f s)"
  shows "ev P (f s) \<longleftrightarrow> ev (\<lambda>x. P (f x)) s"
proof
  assume "ev P (f s)" then show "ev (\<lambda>x. P (f x)) s"
    by (induction "f s" arbitrary: s) (auto simp: stl)
next
  assume "ev (\<lambda>x. P (f x)) s" then show "ev P (f s)"
    by induction (auto simp flip: stl)
qed

lemma alw_smap: "alw P (smap f s) \<longleftrightarrow> alw (\<lambda>x. P (smap f x)) s"
  by (rule alw_inv) simp

lemma ev_smap: "ev P (smap f s) \<longleftrightarrow> ev (\<lambda>x. P (smap f x)) s"
  by (rule ev_inv) simp

lemma alw_cong:
  assumes P: "alw P \<omega>" and eq: "\<And>\<omega>. P \<omega> \<Longrightarrow> Q1 \<omega> \<longleftrightarrow> Q2 \<omega>"
  shows "alw Q1 \<omega> \<longleftrightarrow> alw Q2 \<omega>"
proof -
  from eq have "(alw P aand Q1) = (alw P aand Q2)" by auto
  then have "alw (alw P aand Q1) \<omega> = alw (alw P aand Q2) \<omega>" by auto
  with P show "alw Q1 \<omega> \<longleftrightarrow> alw Q2 \<omega>"
    by (simp add: alw_aand)
qed

lemma ev_cong:
  assumes P: "alw P \<omega>" and eq: "\<And>\<omega>. P \<omega> \<Longrightarrow> Q1 \<omega> \<longleftrightarrow> Q2 \<omega>"
  shows "ev Q1 \<omega> \<longleftrightarrow> ev Q2 \<omega>"
proof -
  from P have "alw (\<lambda>xs. Q1 xs \<longrightarrow> Q2 xs) \<omega>" by (rule alw_mono) (simp add: eq)
  moreover from P have "alw (\<lambda>xs. Q2 xs \<longrightarrow> Q1 xs) \<omega>" by (rule alw_mono) (simp add: eq)
  moreover note ev_alw_impl[of Q1 \<omega> Q2] ev_alw_impl[of Q2 \<omega> Q1]
  ultimately show "ev Q1 \<omega> \<longleftrightarrow> ev Q2 \<omega>"
    by auto
qed

lemma alwD: "alw P x \<Longrightarrow> P x"
  by auto

lemma alw_alwD: "alw P \<omega> \<Longrightarrow> alw (alw P) \<omega>"
  by simp

lemma alw_ev_stl: "alw (ev P) (stl \<omega>) \<longleftrightarrow> alw (ev P) \<omega>"
  by (auto intro: alw.intros)

lemma holds_Stream: "holds P (x ## s) \<longleftrightarrow> P x"
  by simp

lemma holds_eq1[simp]: "holds ((=) x) = HLD {x}"
  by rule (auto simp: HLD_iff)

lemma holds_eq2[simp]: "holds (\<lambda>y. y = x) = HLD {x}"
  by rule (auto simp: HLD_iff)

lemma not_holds_eq[simp]: "holds (- (=) x) = not (HLD {x})"
  by rule (auto simp: HLD_iff)

text \<open>Strong until\<close>

context
  notes [[inductive_internals]]
begin

inductive suntil (infix "suntil" 60) for \<phi> \<psi> where
  base: "\<psi> \<omega> \<Longrightarrow> (\<phi> suntil \<psi>) \<omega>"
| step: "\<phi> \<omega> \<Longrightarrow> (\<phi> suntil \<psi>) (stl \<omega>) \<Longrightarrow> (\<phi> suntil \<psi>) \<omega>"

inductive_simps suntil_Stream: "(\<phi> suntil \<psi>) (x ## s)"

end

lemma suntil_induct_strong[consumes 1, case_names base step]:
  "(\<phi> suntil \<psi>) x \<Longrightarrow>
    (\<And>\<omega>. \<psi> \<omega> \<Longrightarrow> P \<omega>) \<Longrightarrow>
    (\<And>\<omega>. \<phi> \<omega> \<Longrightarrow> \<not> \<psi> \<omega> \<Longrightarrow> (\<phi> suntil \<psi>) (stl \<omega>) \<Longrightarrow> P (stl \<omega>) \<Longrightarrow> P \<omega>) \<Longrightarrow> P x"
  using suntil.induct[of \<phi> \<psi> x P] by blast

lemma ev_suntil: "(\<phi> suntil \<psi>) \<omega> \<Longrightarrow> ev \<psi> \<omega>"
  by (induct rule: suntil.induct) auto

lemma suntil_inv:
  assumes stl: "\<And>s. f (stl s) = stl (f s)"
  shows "(P suntil Q) (f s) \<longleftrightarrow> ((\<lambda>x. P (f x)) suntil (\<lambda>x. Q (f x))) s"
proof
  assume "(P suntil Q) (f s)" then show "((\<lambda>x. P (f x)) suntil (\<lambda>x. Q (f x))) s"
    by (induction "f s" arbitrary: s) (auto simp: stl intro: suntil.intros)
next
  assume "((\<lambda>x. P (f x)) suntil (\<lambda>x. Q (f x))) s" then show "(P suntil Q) (f s)"
    by induction (auto simp flip: stl intro: suntil.intros)
qed

lemma suntil_smap: "(P suntil Q) (smap f s) \<longleftrightarrow> ((\<lambda>x. P (smap f x)) suntil (\<lambda>x. Q (smap f x))) s"
  by (rule suntil_inv) simp

lemma hld_smap: "HLD x (smap f s) = holds (\<lambda>y. f y \<in> x) s"
  by (simp add: HLD_def)

lemma suntil_mono:
  assumes eq: "\<And>\<omega>. P \<omega> \<Longrightarrow> Q1 \<omega> \<Longrightarrow> Q2 \<omega>" "\<And>\<omega>. P \<omega> \<Longrightarrow> R1 \<omega> \<Longrightarrow> R2 \<omega>"
  assumes *: "(Q1 suntil R1) \<omega>" "alw P \<omega>" shows "(Q2 suntil R2) \<omega>"
  using * by induct (auto intro: eq suntil.intros)

lemma suntil_cong:
  "alw P \<omega> \<Longrightarrow> (\<And>\<omega>. P \<omega> \<Longrightarrow> Q1 \<omega> \<longleftrightarrow> Q2 \<omega>) \<Longrightarrow> (\<And>\<omega>. P \<omega> \<Longrightarrow> R1 \<omega> \<longleftrightarrow> R2 \<omega>) \<Longrightarrow>
    (Q1 suntil R1) \<omega> \<longleftrightarrow> (Q2 suntil R2) \<omega>"
  using suntil_mono[of P Q1 Q2 R1 R2 \<omega>] suntil_mono[of P Q2 Q1 R2 R1 \<omega>] by auto

lemma ev_suntil_iff: "ev (P suntil Q) \<omega> \<longleftrightarrow> ev Q \<omega>"
proof
  assume "ev (P suntil Q) \<omega>" then show "ev Q \<omega>"
   by induct (auto dest: ev_suntil)
next
  assume "ev Q \<omega>" then show "ev (P suntil Q) \<omega>"
    by induct (auto intro: suntil.intros)
qed

lemma true_suntil: "((\<lambda>_. True) suntil P) = ev P"
  by (simp add: suntil_def ev_def)

lemma suntil_lfp: "(\<phi> suntil \<psi>) = lfp (\<lambda>P s. \<psi> s \<or> (\<phi> s \<and> P (stl s)))"
  by (simp add: suntil_def)

lemma sfilter_P[simp]: "P (shd s) \<Longrightarrow> sfilter P s = shd s ## sfilter P (stl s)"
  using sfilter_Stream[of P "shd s" "stl s"] by simp

lemma sfilter_not_P[simp]: "\<not> P (shd s) \<Longrightarrow> sfilter P s = sfilter P (stl s)"
  using sfilter_Stream[of P "shd s" "stl s"] by simp

lemma sfilter_eq:
  assumes "ev (holds P) s"
  shows "sfilter P s = x ## s' \<longleftrightarrow>
    P x \<and> (not (holds P) suntil (HLD {x} aand nxt (\<lambda>s. sfilter P s = s'))) s"
  using assms
  by (induct rule: ev_induct_strong)
     (auto simp add: HLD_iff intro: suntil.intros elim: suntil.cases)

lemma sfilter_streams:
  "alw (ev (holds P)) \<omega> \<Longrightarrow> \<omega> \<in> streams A \<Longrightarrow> sfilter P \<omega> \<in> streams {x\<in>A. P x}"
proof (coinduction arbitrary: \<omega>)
  case (streams \<omega>)
  then have "ev (holds P) \<omega>" by blast
  from this streams show ?case
    by (induct rule: ev_induct_strong) (auto elim: streamsE)
qed

lemma alw_sfilter:
  assumes *: "alw (ev (holds P)) s"
  shows "alw Q (sfilter P s) \<longleftrightarrow> alw (\<lambda>x. Q (sfilter P x)) s"
proof
  assume "alw Q (sfilter P s)" with * show "alw (\<lambda>x. Q (sfilter P x)) s"
  proof (coinduction arbitrary: s rule: alw_coinduct)
    case (stl s)
    then have "ev (holds P) s"
      by blast
    from this stl show ?case
      by (induct rule: ev_induct_strong) auto
  qed auto
next
  assume "alw (\<lambda>x. Q (sfilter P x)) s" with * show "alw Q (sfilter P s)"
  proof (coinduction arbitrary: s rule: alw_coinduct)
    case (stl s)
    then have "ev (holds P) s"
      by blast
    from this stl show ?case
      by (induct rule: ev_induct_strong) auto
  qed auto
qed

lemma ev_sfilter:
  assumes *: "alw (ev (holds P)) s"
  shows "ev Q (sfilter P s) \<longleftrightarrow> ev (\<lambda>x. Q (sfilter P x)) s"
proof
  assume "ev Q (sfilter P s)" from this * show "ev (\<lambda>x. Q (sfilter P x)) s"
  proof (induction "sfilter P s" arbitrary: s rule: ev_induct_strong)
    case (step s)
    then have "ev (holds P) s"
      by blast
    from this step show ?case
      by (induct rule: ev_induct_strong) auto
  qed auto
next
  assume "ev (\<lambda>x. Q (sfilter P x)) s" then show "ev Q (sfilter P s)"
  proof (induction rule: ev_induct_strong)
    case (step s) then show ?case
      by (cases "P (shd s)") auto
  qed auto
qed

lemma holds_sfilter:
  assumes "ev (holds Q) s" shows "holds P (sfilter Q s) \<longleftrightarrow> (not (holds Q) suntil (holds (Q aand P))) s"
proof
  assume "holds P (sfilter Q s)" with assms show "(not (holds Q) suntil (holds (Q aand P))) s"
    by (induct rule: ev_induct_strong) (auto intro: suntil.intros)
next
  assume "(not (holds Q) suntil (holds (Q aand P))) s" then show "holds P (sfilter Q s)"
    by induct auto
qed

lemma suntil_aand_nxt:
  "(\<phi> suntil (\<phi> aand nxt \<psi>)) \<omega> \<longleftrightarrow> (\<phi> aand nxt (\<phi> suntil \<psi>)) \<omega>"
proof
  assume "(\<phi> suntil (\<phi> aand nxt \<psi>)) \<omega>" then show "(\<phi> aand nxt (\<phi> suntil \<psi>)) \<omega>"
    by induction (auto intro: suntil.intros)
next
  assume "(\<phi> aand nxt (\<phi> suntil \<psi>)) \<omega>"
  then have "(\<phi> suntil \<psi>) (stl \<omega>)" "\<phi> \<omega>"
    by auto
  then show "(\<phi> suntil (\<phi> aand nxt \<psi>)) \<omega>"
    by (induction "stl \<omega>" arbitrary: \<omega>)
       (auto elim: suntil.cases intro: suntil.intros)
qed

lemma alw_sconst: "alw P (sconst x) \<longleftrightarrow> P (sconst x)"
proof
  assume "P (sconst x)" then show "alw P (sconst x)"
    by coinduction auto
qed auto

lemma ev_sconst: "ev P (sconst x) \<longleftrightarrow> P (sconst x)"
proof
  assume "ev P (sconst x)" then show "P (sconst x)"
    by (induction "sconst x") auto
qed auto

lemma suntil_sconst: "(\<phi> suntil \<psi>) (sconst x) \<longleftrightarrow> \<psi> (sconst x)"
proof
  assume "(\<phi> suntil \<psi>) (sconst x)" then show "\<psi> (sconst x)"
    by (induction "sconst x") auto
qed (auto intro: suntil.intros)

lemma hld_smap': "HLD x (smap f s) = HLD (f -` x) s"
  by (simp add: HLD_def)

lemma pigeonhole_stream:
  assumes "alw (HLD s) \<omega>"
  assumes "finite s"
  shows "\<exists>x\<in>s. alw (ev (HLD {x})) \<omega>"
proof -
  have "\<forall>i\<in>UNIV. \<exists>x\<in>s. \<omega> !! i = x"
    using \<open>alw (HLD s) \<omega>\<close> by (simp add: alw_iff_sdrop HLD_iff)
  from pigeonhole_infinite_rel[OF infinite_UNIV_nat \<open>finite s\<close> this]
  show ?thesis
    by (simp add: HLD_iff flip: infinite_iff_alw_ev)
qed

lemma ev_eq_suntil: "ev P \<omega> \<longleftrightarrow> (not P suntil P) \<omega>"
proof
  assume "ev P \<omega>" then show "((\<lambda>xs. \<not> P xs) suntil P) \<omega>"
    by (induction rule: ev_induct_strong) (auto intro: suntil.intros)
qed (auto simp: ev_suntil)

section \<open>Weak vs. strong until (contributed by Michael Foster, University of Sheffield)\<close>

lemma suntil_implies_until: "(\<phi> suntil \<psi>) \<omega> \<Longrightarrow> (\<phi> until \<psi>) \<omega>"
  by (induct rule: suntil_induct_strong) (auto intro: UNTIL.intros)

lemma alw_implies_until: "alw \<phi> \<omega> \<Longrightarrow> (\<phi> until \<psi>) \<omega>"
  unfolding until_false[symmetric] by (auto elim: until_mono)

lemma until_ev_suntil: "(\<phi> until \<psi>) \<omega> \<Longrightarrow> ev \<psi> \<omega> \<Longrightarrow> (\<phi> suntil \<psi>) \<omega>"
proof (rotate_tac, induction rule: ev.induct)
  case (base xs)
  then show ?case
    by (simp add: suntil.base)
next
  case (step xs)
  then show ?case
    by (metis UNTIL.cases suntil.base suntil.step)
qed

lemma suntil_as_until: "(\<phi> suntil \<psi>) \<omega> = ((\<phi> until \<psi>) \<omega> \<and> ev \<psi> \<omega>)"
  using ev_suntil suntil_implies_until until_ev_suntil by blast

lemma until_not_relesased_now: "(\<phi> until \<psi>) \<omega> \<Longrightarrow> \<not> \<psi> \<omega> \<Longrightarrow> \<phi> \<omega>"
  using UNTIL.cases by auto

lemma until_must_release_ev: "(\<phi> until \<psi>) \<omega> \<Longrightarrow> ev (not \<phi>) \<omega> \<Longrightarrow> ev \<psi> \<omega>"
proof (rotate_tac, induction rule: ev.induct)
  case (base xs)
  then show ?case
    using until_not_relesased_now by blast
next
  case (step xs)
  then show ?case
    using UNTIL.cases by blast
qed

lemma until_as_suntil: "(\<phi> until \<psi>) \<omega> = ((\<phi> suntil \<psi>) or (alw \<phi>)) \<omega>"
  using alw_implies_until not_alw_iff suntil_implies_until until_ev_suntil until_must_release_ev
  by blast

lemma alw_holds: "alw (holds P) (h##t) = (P h \<and> alw (holds P) t)"
  by (metis alw.simps holds_Stream stream.sel(2))

lemma alw_holds2: "alw (holds P) ss = (P (shd ss) \<and> alw (holds P) (stl ss))"
  by (meson alw.simps holds.elims(2) holds.elims(3))

lemma alw_eq_sconst: "(alw (HLD {h}) t) = (t = sconst h)"
  unfolding sconst_alt alw_HLD_iff_streams streams_iff_sset
  using stream.set_sel(1) by force

lemma sdrop_if_suntil: "(p suntil q) \<omega> \<Longrightarrow> \<exists>j. q (sdrop j \<omega>) \<and> (\<forall>k < j. p (sdrop k \<omega>))"
proof(induction rule: suntil.induct)
  case (base \<omega>)
  then show ?case
    by force
next
  case (step \<omega>)
  then obtain j where "q (sdrop j (stl \<omega>))" "\<forall>k<j. p (sdrop k (stl \<omega>))" by blast
  with step(1,2) show ?case
    using ev_at_imp_snth less_Suc_eq_0_disj by (auto intro!: exI[where x="j+1"])
qed

lemma not_suntil: "(\<not> (p suntil q) \<omega>) = (\<not> (p until q) \<omega> \<or> alw (not q) \<omega>)"
  by (simp add: suntil_as_until alw_iff_sdrop ev_iff_sdrop)

lemma sdrop_until: "q (sdrop j \<omega>) \<Longrightarrow> \<forall>k<j. p (sdrop k \<omega>) \<Longrightarrow> (p until q) \<omega>"
proof(induct j arbitrary: \<omega>)
  case 0
  then show ?case
    by (simp add: UNTIL.base)
next
  case (Suc j)
  then show ?case
    by (metis Suc_mono UNTIL.simps sdrop.simps(1) sdrop.simps(2) zero_less_Suc)
qed

lemma sdrop_suntil: "q (sdrop j \<omega>) \<Longrightarrow> (\<forall>k < j. p (sdrop k \<omega>)) \<Longrightarrow> (p suntil q) \<omega>"
  by (metis ev_iff_sdrop sdrop_until suntil_as_until)

lemma suntil_iff_sdrop: "(p suntil q) \<omega> = (\<exists>j. q (sdrop j \<omega>) \<and> (\<forall>k < j. p (sdrop k \<omega>)))"
  using sdrop_if_suntil sdrop_suntil by blast

end


(*
    Authors:      Jose Divasón
                  Sebastiaan Joosten
                  René Thiemann
                  Akihisa Yamada
*)
theory Hensel_Lifting_Type_Based
imports Hensel_Lifting
begin

subsection\<open>Hensel Lifting in a Type-Based Setting\<close>

(* TODO: Move? *)

lemma degree_smult_eq_iff:
  "degree (smult a p) = degree p \<longleftrightarrow> degree p = 0 \<or> a * lead_coeff p \<noteq> 0"
  by (metis (no_types, lifting) coeff_smult degree_0 degree_smult_le le_antisym
      le_degree le_zero_eq leading_coeff_0_iff)

lemma degree_smult_eqI[intro!]:
  assumes "degree p \<noteq> 0 \<Longrightarrow> a * lead_coeff p \<noteq> 0"
  shows "degree (smult a p) = degree p"
  using assms degree_smult_eq_iff by auto

lemma degree_mult_eq2:
  assumes lc: "lead_coeff p * lead_coeff q \<noteq> 0"
  shows "degree (p * q) = degree p + degree q" (is "_ = ?r")
proof(intro antisym[OF degree_mult_le] le_degree, unfold coeff_mult)
  let ?f = "\<lambda>i. coeff p i * coeff q (?r - i)"
  have "(\<Sum>i\<le>?r. ?f i) = sum ?f {..degree p} + sum ?f {Suc (degree p)..?r}"
    by (rule sum_up_index_split)
  also have "sum ?f {Suc (degree p)..?r} = 0"
    proof-
      { fix x assume "x > degree p"
        then have "coeff p x = 0" by (rule coeff_eq_0)
        then have "?f x = 0" by auto
      }
      then show ?thesis by (intro sum.neutral, auto)
    qed
  also have "sum ?f {..degree p} = sum ?f {..<degree p} + ?f (degree p)"
    by(fold lessThan_Suc_atMost, unfold sum.lessThan_Suc, auto)
  also have "sum ?f {..<degree p} = 0"
    proof-
      {fix x assume "x < degree p"
        then have "coeff q (?r - x) = 0" by (intro coeff_eq_0, auto)
        then have "?f x = 0" by auto
      }
      then show ?thesis by (intro sum.neutral, auto)
    qed
  finally show "(\<Sum>i\<le>?r. ?f i) \<noteq> 0" using assms by (auto simp:)
qed

lemma degree_mult_eq_left_unit:
  fixes p q :: "'a :: comm_semiring_1 poly"
  assumes unit: "lead_coeff p dvd 1" and q0: "q \<noteq> 0"
  shows "degree (p * q) = degree p + degree q"
proof(intro degree_mult_eq2 notI)
  from unit obtain c where "lead_coeff p * c = 1" by (elim dvdE,auto)
  then have "c * lead_coeff p = 1" by (auto simp: ac_simps)
  moreover assume "lead_coeff p * lead_coeff q = 0"
    then have "c * lead_coeff p * lead_coeff q = 0" by (auto simp: ac_simps)
  ultimately have "lead_coeff q = 0" by auto
  with q0 show False by auto
qed

context ring_hom begin
lemma monic_degree_map_poly_hom: "monic p \<Longrightarrow> degree (map_poly hom p) = degree p"
  by (auto intro: degree_map_poly)

lemma monic_map_poly_hom: "monic p \<Longrightarrow> monic (map_poly hom p)"
  by (simp add: monic_degree_map_poly_hom)

end

lemma of_nat_zero:
  assumes "CARD('a::nontriv) dvd n"
  shows "(of_nat n :: 'a mod_ring) = 0"
  apply (transfer fixing: n) using assms by (presburger)

abbreviation rebase :: "'a :: nontriv mod_ring \<Rightarrow> 'b :: nontriv mod_ring "("@_" [100]100)
  where "@x \<equiv> of_int (to_int_mod_ring x)"

abbreviation rebase_poly :: "'a :: nontriv mod_ring poly \<Rightarrow> 'b :: nontriv mod_ring poly" ("#_" [100]100)
  where "#x \<equiv> of_int_poly (to_int_poly x)"

lemma rebase_self [simp]:
  "@x = x"
  by (simp add: of_int_of_int_mod_ring)

lemma map_poly_rebase [simp]:
  "map_poly rebase p = #p"
  by (induct p) simp_all

lemma rebase_poly_0: "#0 = 0"
  by simp

lemma rebase_poly_1: "#1 = 1"
  by simp

lemma rebase_poly_pCons[simp]: "#pCons a p = pCons (@a) (#p)"
by(cases "a = 0 \<and> p = 0", simp, fold map_poly_rebase, subst map_poly_pCons, auto)

lemma rebase_poly_self[simp]: "#p = p" by (induct p, auto)

lemma degree_rebase_poly_le: "degree (#p) \<le> degree p"
  by (fold map_poly_rebase, subst degree_map_poly_le, auto)

lemma(in comm_ring_hom) degree_map_poly_unit: assumes "lead_coeff p dvd 1"
  shows "degree (map_poly hom p) = degree p"
  using hom_dvd_1[OF assms] by (auto intro: degree_map_poly)

lemma mod_mod_le:
  assumes ab: "(a::int) \<le> b" and a0: "0 < a" and c0: "c \<ge> 0" shows "(c mod a) mod b = c mod a"
  by (meson Divides.pos_mod_bound Divides.pos_mod_sign a0 ab less_le_trans mod_pos_pos_trivial)

locale rebase_ge =
  fixes ty1 :: "'a :: nontriv itself" and ty2 :: "'b :: nontriv itself"
  assumes card: "CARD('a) \<le> CARD('b)"
begin

lemma ab: "int CARD('a) \<le> CARD('b)" using card by auto

lemma rebase_eq_0[simp]:
  shows "(@(x :: 'a mod_ring) :: 'b mod_ring) = 0 \<longleftrightarrow> x = 0"
  using card by (transfer, auto)

lemma degree_rebase_poly_eq[simp]:
  shows "degree (#(p :: 'a mod_ring poly) :: 'b mod_ring poly) = degree p"
  by (subst degree_map_poly; simp)

lemma lead_coeff_rebase_poly[simp]:
  "lead_coeff (#(p::'a mod_ring poly) :: 'b mod_ring poly) = @lead_coeff p"
  by simp

lemma to_int_mod_ring_rebase: "to_int_mod_ring(@(x :: 'a mod_ring)::'b mod_ring) = to_int_mod_ring x"
  using card by (transfer, auto)

lemma rebase_id[simp]: "@(@(x::'a mod_ring) :: 'b mod_ring) = @x"
  using card by (transfer, auto)

lemma rebase_poly_id[simp]: "#(#(p::'a mod_ring poly) :: 'b mod_ring poly) = #p" by (induct p, auto)

end

locale rebase_dvd =
  fixes ty1 :: "'a :: nontriv itself" and ty2 :: "'b :: nontriv itself"
  assumes dvd: "CARD('b) dvd CARD('a)"
begin

lemma ab: "CARD('a) \<ge> CARD('b)" by (rule dvd_imp_le[OF dvd], auto)

lemma rebase_id[simp]: "@(@(x::'b mod_ring) :: 'a mod_ring) = x" using ab by (transfer, auto)

lemma rebase_poly_id[simp]: "#(#(p::'b mod_ring poly) :: 'a mod_ring poly) = p" by (induct p, auto)

lemma rebase_of_nat[simp]: "(@(of_nat n :: 'a mod_ring) :: 'b mod_ring) = of_nat n"
  apply transfer apply (rule mod_mod_cancel) using dvd by presburger

lemma mod_1_lift_nat:
  assumes "(of_int (int x) :: 'a mod_ring) = 1"
  shows "(of_int (int x) :: 'b mod_ring) = 1"
proof -
  from assms have "int x mod CARD('a) = 1"
    by transfer
  then have "x mod CARD('a) = 1"
    by (simp add: of_nat_mod [symmetric])
  then have "x mod CARD('b) = 1"
    by (metis dvd mod_mod_cancel one_mod_card)
  then have "int x mod CARD('b) = 1"
    by (simp add: of_nat_mod [symmetric])
  then show ?thesis
    by transfer
qed

sublocale comm_ring_hom "rebase :: 'a mod_ring \<Rightarrow> 'b mod_ring"
proof
  fix x y :: "'a mod_ring"
  show hom_add: "(@(x+y) :: 'b mod_ring) = @x + @y"
    by transfer (simp add: mod_simps dvd mod_mod_cancel)
  show "(@(x*y) :: 'b mod_ring) = @x * @y"
    by transfer (simp add: mod_simps dvd mod_mod_cancel)
qed auto

lemma of_nat_CARD_eq_0[simp]: "(of_nat CARD('a) :: 'b mod_ring) = 0"
  using dvd by (transfer, presburger)

interpretation map_poly_hom: map_poly_comm_ring_hom "rebase :: 'a mod_ring \<Rightarrow> 'b mod_ring"..

sublocale poly: comm_ring_hom "rebase_poly :: 'a mod_ring poly \<Rightarrow> 'b mod_ring poly"
  by (fold map_poly_rebase, unfold_locales)

lemma poly_rebase[simp]: "@poly p x = poly (#(p :: 'a mod_ring poly) :: 'b mod_ring poly) (@(x::'a mod_ring) :: 'b mod_ring)"
  by (fold map_poly_rebase poly_map_poly, rule)

lemma rebase_poly_smult[simp]: "(#(smult a p :: 'a mod_ring poly) :: 'b mod_ring poly) = smult (@a) (#p)"
  by(induct p, auto simp: hom_distribs)

end

locale rebase_mult =
  fixes ty1 :: "'a :: nontriv itself"
    and ty2 :: "'b :: nontriv itself"
    and ty3 :: "'d :: nontriv itself" (* due to some type reason, 'd has to be nontriv. *)
  assumes d: "CARD('a) = CARD('b) * CARD('d)"
begin

sublocale rebase_dvd ty1 ty2 using d by (unfold_locales, auto)

lemma rebase_mult_eq[simp]: "(of_nat CARD('d) * a :: 'a mod_ring) = of_nat CARD('d) * a' \<longleftrightarrow> (@a :: 'b mod_ring) = @a'"
proof-
  from dvd obtain d' where "CARD('a) = d' * CARD('b)" by (elim dvdE, auto)
  then show ?thesis by (transfer, auto simp:d)
qed

lemma rebase_poly_smult_eq[simp]:
  fixes a a' :: "'a mod_ring poly"
  defines "d \<equiv> of_nat CARD('d) :: 'a mod_ring"
  shows "smult d a = smult d a' \<longleftrightarrow> (#a :: 'b mod_ring poly) = #a'" (is "?l \<longleftrightarrow> ?r")
proof (intro iffI)
  assume l: ?l show "?r"
  proof (intro poly_eqI)
    fix n
    from l have "coeff (smult d a) n = coeff (smult d a') n" by auto
    then have "d * coeff a n = d * coeff a' n" by auto
    from this[unfolded d_def rebase_mult_eq]
    show "coeff (#a :: 'b mod_ring poly) n = coeff (#a') n" by auto
  qed
next
  assume r: ?r show ?l
  proof(intro poly_eqI)
    fix n
    from r have "coeff (#a :: 'b mod_ring poly) n = coeff (#a') n" by auto
    then have "(@coeff a n :: 'b mod_ring) = @coeff a' n" by auto
    from this[folded d_def rebase_mult_eq]
    show "coeff (smult d a) n = coeff (smult d a') n" by auto
  qed
qed

lemma rebase_eq_0_imp_ex_mult:
  "(@(a :: 'a mod_ring) :: 'b mod_ring) = 0 \<Longrightarrow> (\<exists>c :: 'd mod_ring. a = of_nat CARD('b) * @c)" (is "?l \<Longrightarrow> ?r")
proof(cases "CARD('a) = CARD('b)")
  case True then show "?l \<Longrightarrow> ?r"
    by (transfer, auto)
next
  case False
  have [simp]: "int CARD('b) mod int CARD('a) = int CARD('b)"
    by(rule mod_pos_pos_trivial, insert ab False, auto)
  {
    fix a
    assume a: "0 \<le> a" "a < int CARD('a)" and mod: "a mod int CARD('b) = 0"
    from mod have "int CARD('b) dvd a" by auto
    then obtain i where *: "a = int CARD('b) * i" by (elim dvdE, auto)
    from * a have "i < int CARD('d)" by (simp add:d)
    moreover
      hence "(i mod int CARD('a)) = i"
        by (metis dual_order.order_iff_strict less_le_trans not_le of_nat_less_iff "*" a(1) a(2)
             mod_pos_pos_trivial mult_less_cancel_right1 nat_neq_iff nontriv of_nat_1)
      with * a have "a = int CARD('b) * (i mod int CARD('a)) mod int CARD('a)"
        by (auto simp:d)
    moreover from * a have "0 \<le> i"
      using linordered_semiring_strict_class.mult_pos_neg of_nat_0_less_iff zero_less_card_finite
      by (simp add: zero_le_mult_iff)
    ultimately have "\<exists>i\<ge>0. i < int CARD('d) \<and> a = int CARD('b) * (i mod int CARD('a)) mod int CARD('a)"
      by (auto intro: exI[of _ i])
  }
  then show "?l \<Longrightarrow> ?r" by (transfer, auto simp:d)
qed

lemma rebase_poly_eq_0_imp_ex_smult:
  "(#(p :: 'a mod_ring poly) :: 'b mod_ring poly) = 0 \<Longrightarrow>
   (\<exists>p' :: 'd mod_ring poly. (p = 0 \<longleftrightarrow> p' = 0) \<and> degree p' \<le> degree p \<and> p = smult (of_nat CARD('b)) (#p'))"
  (is "?l \<Longrightarrow> ?r")
proof(induct p)
  case 0
  then show ?case by (intro exI[of _ 0],auto)
next
  case IH: (pCons a p)
  from IH(3) have "(#p :: 'b mod_ring poly) = 0" by auto
  from IH(2)[OF this] obtain p' :: "'d mod_ring poly"
  where *: "p = 0 \<longleftrightarrow> p' = 0" "degree p' \<le> degree p" "p = smult (of_nat CARD('b)) (#p')" by (elim exE conjE)
  from IH have "(@a :: 'b mod_ring) = 0" by auto
  from rebase_eq_0_imp_ex_mult[OF this]
  obtain a' :: "'d mod_ring" where a': "of_nat CARD('b) * (@a') = a" by auto
  from IH(1) have "pCons a p \<noteq> 0" by auto
  moreover from *(1,2) have "degree (pCons a' p') \<le> degree (pCons a p)" by auto
  moreover from a' *(3)
  have "pCons a p = smult (of_nat CARD('b)) (#pCons a' p')" by auto
  ultimately show ?case by (intro exI[of _ "pCons a' p'"], auto)
qed

end

lemma mod_mod_nat[simp]: "a mod b mod (b * c :: nat) = a mod b" by (simp add: Divides.mod_mult2_eq)

locale Knuth_ex_4_6_2_22_base =
  fixes ty_p :: "'p :: nontriv itself"
    and ty_q :: "'q :: nontriv itself"
    and ty_pq :: "'pq :: nontriv itself"
  assumes pq: "CARD('pq) = CARD('p) * CARD('q)"
    and p_dvd_q: "CARD('p) dvd CARD('q)"
begin

sublocale rebase_q_to_p: rebase_dvd "TYPE('q)" "TYPE('p)" using p_dvd_q by (unfold_locales, auto)
sublocale rebase_pq_to_p: rebase_mult "TYPE('pq)" "TYPE('p)" "TYPE('q)" using pq by (unfold_locales, auto)
sublocale rebase_pq_to_q: rebase_mult "TYPE('pq)" "TYPE('q)" "TYPE('p)" using pq by (unfold_locales, auto)

sublocale rebase_p_to_q: rebase_ge "TYPE('p)" "TYPE ('q)" by (unfold_locales, insert p_dvd_q, simp add: dvd_imp_le)
sublocale rebase_p_to_pq: rebase_ge "TYPE('p)" "TYPE ('pq)" by (unfold_locales, simp add: pq)
sublocale rebase_q_to_pq: rebase_ge "TYPE('q)" "TYPE ('pq)" by (unfold_locales, simp add: pq)

(* TODO: needs ugly workaround to fix 'p... *)
definition "p \<equiv> if (ty_p :: 'p itself) = ty_p then CARD('p) else undefined"
lemma p[simp]: "p \<equiv> CARD('p)" unfolding p_def by auto

definition "q \<equiv> if (ty_q :: 'q itself) = ty_q then CARD('q) else undefined"
lemma q[simp]: "q = CARD('q)" unfolding q_def by auto

lemma p1: "int p > 1"
  using nontriv [where ?'a = 'p] p by simp
lemma q1: "int q > 1"
  using nontriv [where ?'a = 'q] q by simp
lemma q0: "int q > 0"
  using q1 by auto

lemma pq2[simp]: "CARD('pq) = p * q" using pq by simp

lemma qq_eq_0[simp]: "(of_nat CARD('q) * of_nat CARD('q) :: 'pq mod_ring) = 0"
proof-
  have "(of_nat (q * q) :: 'pq mod_ring) = 0" by (rule of_nat_zero, auto simp: p_dvd_q)
  then show ?thesis by auto
qed

lemma of_nat_q[simp]: "of_nat q :: 'q mod_ring \<equiv> 0" by (fold of_nat_card_eq_0, auto)

lemma rebase_rebase[simp]: "(@(@(x::'pq mod_ring) :: 'q mod_ring) :: 'p mod_ring) = @x"
  using p_dvd_q by (transfer) (simp add: mod_mod_cancel)

lemma rebase_rebase_poly[simp]: "(#(#(f::'pq mod_ring poly) :: 'q mod_ring poly) :: 'p mod_ring poly) = #f"
  by (induct f, auto)

end

definition dupe_monic where
  "dupe_monic D H S T U = (case pdivmod_monic (T * U) D of (q,r) \<Rightarrow> (S * U + H * q, r))"

lemma dupe_monic:
  fixes D :: "'a :: prime_card mod_ring poly"
  assumes 1: "D*S + H*T = 1"
  and mon: "monic D"
  and dupe: "dupe_monic D H S T U = (A,B)"
  shows "A * D + B * H = U" "B = 0 \<or> degree B < degree D"
    "coprime D H \<Longrightarrow> A' * D + B' * H = U \<Longrightarrow> B' = 0 \<or> degree B' < degree D \<Longrightarrow> A' = A \<and> B' = B"
proof -
  obtain q r where div: "pdivmod_monic (T * U) D = (q,r)" by force
  from dupe[unfolded dupe_monic_def div split]
  have A: "A = (S * U + H * q)" and B: "B = r" by auto
  from pdivmod_monic[OF mon div] have TU: "T * U = D * q + r" and
    deg: "r = 0 \<or> degree r < degree D" by auto
  hence r: "r = T * U - D * q" by simp
  have "A * D + B * H = (S * U + H * q) * D + (T * U - D * q) * H" unfolding A B r by simp
  also have "... = (D * S + H * T) * U" by (simp add: field_simps)
  also have "D * S + H * T = 1" using 1 by simp
  finally show eq: "A * D + B * H = U" by simp
  show degB: "B = 0 \<or> degree B < degree D" using deg unfolding B by (cases "r = 0", auto)
  assume another: "A' * D + B' * H = U" and degB': "B' = 0 \<or> degree B' < degree D"
    and cop: "coprime D H"
  from degB have degB: "B = 0 \<or> degree B < degree D" by auto
  from degB' have degB': "B' = 0 \<or> degree B' < degree D" by auto
  from mon have D0: "D \<noteq> 0" by auto
  from another eq have "A' * D + B' * H = A * D + B * H" by simp
  from uniqueness_poly_equality[OF cop degB' degB D0 this]
  show "A' = A \<and> B' = B" by auto
qed

locale Knuth_ex_4_6_2_22_main = Knuth_ex_4_6_2_22_base p_ty q_ty pq_ty
  for p_ty :: "'p::nontriv itself"
  and q_ty :: "'q::nontriv itself"
  and pq_ty :: "'pq::nontriv itself" +
  fixes a b :: "'p mod_ring poly" and u :: "'pq mod_ring poly" and v w :: "'q mod_ring poly"
  assumes uvw: "(#u :: 'q mod_ring poly) = v * w"
      and degu: "degree u = degree v + degree w" (* not in Knuth's book *)
      and avbw: "(a * #v + b * #w :: 'p mod_ring poly) = 1"
      and monic_v: "monic v" (* stronger than Knuth's *)
(* not needed!
      and aw: "degree a < degree w" *)
      and bv: "degree b < degree v"
begin

lemma deg_v: "degree (#v :: 'p mod_ring poly) = degree v"
  using monic_v by (simp add: of_int_hom.monic_degree_map_poly_hom)

lemma u0: "u \<noteq> 0" using degu bv by auto

lemma ex_f: "\<exists>f :: 'p mod_ring poly. u = #v * #w + smult (of_nat q) (#f)"
proof-
  from uvw have "(#(u - #v * #w) :: 'q mod_ring poly) = 0" by (auto simp:hom_distribs)
  from rebase_pq_to_q.rebase_poly_eq_0_imp_ex_smult[OF this]
  obtain f :: "'p mod_ring poly" where "u - #v * #w = smult (of_nat q) (#f)" by force
  then have "u = #v * #w + smult (of_nat q) (#f)" by (metis add_diff_cancel_left' add_diff_eq)
  then show ?thesis by (intro exI[of _ f], auto)
qed

definition "f :: 'p mod_ring poly \<equiv> SOME f. u = #v * #w + smult (of_nat q) (#f)"

lemma u: "u = #v * #w + smult (of_nat q) (#f)"
  using ex_f[folded some_eq_ex] f_def by auto

lemma t_ex: "\<exists>t :: 'p mod_ring poly. degree (b * f - t * #v) < degree v"
proof-
  define v' where "v' \<equiv> #v :: 'p mod_ring poly"
  from monic_v
  have 1: "lead_coeff v' = 1" by (simp add: v'_def deg_v)
  then have 4: "v' \<noteq> 0" by auto
  obtain t rem :: "'p mod_ring poly"
  where "pseudo_divmod (b * f) v' = (t,rem)" by force
  from pseudo_divmod[OF 4 this, folded, unfolded 1]
  have "b * f = v' * t + rem" and deg: "rem = 0 \<or> degree rem < degree v'" by auto
  then have "rem = b * f - t * v'" by(auto simp: ac_simps)
  also have "... = b * f - #(#t :: 'p mod_ring poly) * v'" (is "_ = _ - ?t * v'") by simp
  also have "... = b * f - ?t * #v"
    by (unfold v'_def, rule)
  finally have "degree rem = degree ..." by auto
  with deg bv have "degree (b * f - ?t * #v :: 'p mod_ring poly) < degree v" by (auto simp: v'_def deg_v)
  then show ?thesis by (rule exI)
qed

definition t where "t \<equiv> SOME t :: 'p mod_ring poly. degree (b * f - t * #v) < degree v"

definition "v' \<equiv> b * f - t * #v"
definition "w' \<equiv> a * f + t * #w"

lemma f: "w' * #v + v' * #w = f" (is "?l = _")
proof-
  have "?l = f * (a * #v + b * #w :: 'p mod_ring poly)" by (simp add: v'_def w'_def ring_distribs ac_simps)
  also
    from avbw have "(#(a * #v + b * #w) :: 'p mod_ring poly) = 1" by auto
    then have "(a * #v + b * #w :: 'p mod_ring poly) = 1" by auto
  finally show ?thesis by auto
qed

lemma degv': "degree v' < degree v" by (unfold v'_def t_def, rule someI_ex, rule t_ex)

lemma degqf[simp]: "degree (smult (of_nat CARD('q)) (#f :: 'pq mod_ring poly)) = degree (#f :: 'pq mod_ring poly)"
proof (intro degree_smult_eqI)
  assume "degree (#f :: 'pq mod_ring poly) \<noteq> 0"
  then have f0: "degree f \<noteq> 0" by simp
  moreover define l where "l \<equiv> lead_coeff f"
  ultimately have l0: "l \<noteq> 0" by auto
  then show "of_nat CARD('q) * lead_coeff (#f::'pq mod_ring poly) \<noteq> 0"
  apply (unfold rebase_p_to_pq.lead_coeff_rebase_poly, fold l_def)
  apply (transfer)
  using q1 by (simp add: pq mod_mod_cancel)
qed

lemma degw': "degree w' \<le> degree w"
proof(rule ccontr)
  let ?f = "#f :: 'pq mod_ring poly"
  let ?qf = "smult (of_nat q) (#f) :: 'pq mod_ring poly"

  have "degree (#w::'p mod_ring poly) \<le> degree w" by (rule degree_rebase_poly_le)
  also assume "\<not> degree w' \<le> degree w"
  then have 1: "degree w < degree w'" by auto
  finally have 2: "degree (#w :: 'p mod_ring poly) < degree w'" by auto
  then have w'0: "w' \<noteq> 0" by auto

  have 3: "degree (#v * w') = degree (#v :: 'p mod_ring poly) + degree w'"
      using monic_v[unfolded] by (intro degree_monic_mult[OF _ w'0], auto simp: deg_v)

  have "degree f \<le> degree u"
  proof(rule ccontr)
    assume "\<not>?thesis"
    then have *: "degree u < degree f" by auto
    with degu have 1: "degree v + degree w < degree f" by auto
    define lcf where "lcf \<equiv> lead_coeff f"
    with 1 have lcf0: "lcf \<noteq> 0" by (unfold, auto)
    have "degree f = degree ?qf" by simp
    also have "... = degree (#v * #w + ?qf)"
    proof(rule sym, rule degree_add_eq_right)
      from 1 degree_mult_le[of "#v::'pq mod_ring poly" "#w"]
      show "degree (#v * #w :: 'pq mod_ring poly) < degree ?qf" by simp
    qed
    also have "... < degree f" using * u by auto
    finally show "False" by auto
  qed
  with degu have "degree f \<le> degree v + degree w" by auto
  also note f[symmetric]
  finally have "degree (w' * #v + v' * #w) \<le> degree v + degree w".
  moreover have "degree (w' * #v + v' * #w) = degree (w' * #v)"
  proof(rule degree_add_eq_left)
    have "degree (v' * #w) \<le> degree v' + degree (#w :: 'p mod_ring poly)"
      by(rule degree_mult_le)
    also have "... < degree v + degree (#w :: 'p mod_ring poly)" using degv' by auto
    also have "... < degree (#v :: 'p mod_ring poly) + degree w'" using 2 by (auto simp: deg_v)
    also have "... = degree (#v * w')" using 3 by auto
    finally show "degree (v' * #w) < degree (w' * #v)" by (auto simp: ac_simps)
  qed
  ultimately have "degree (w' * #v) \<le> degree v + degree w" by auto
  moreover
    from 3 have "degree (w' * #v) = degree w' + degree v" by (auto simp: ac_simps deg_v)
    with 1 have "degree w + degree v < degree (w' * #v)" by auto
  ultimately show False by auto
qed

abbreviation "qv' \<equiv> smult (of_nat q) (#v') :: 'pq mod_ring poly"
abbreviation "qw' \<equiv> smult (of_nat q) (#w') :: 'pq mod_ring poly"

abbreviation "V \<equiv> #v + qv'"
abbreviation "W \<equiv> #w + qw'"

lemma vV: "v = #V" by (auto simp: v'_def hom_distribs)

lemma wW: "w = #W" by (auto simp: w'_def hom_distribs)

lemma uVW: "u = V * W"
  by (subst u, fold f, simp add: ring_distribs add.left_cancel smult_add_right[symmetric] hom_distribs)

lemma degV: "degree V = degree v"
  and lcV: "lead_coeff V = @lead_coeff v"
  and degW: "degree W = degree w"
proof-
  from p1 q1 have "int p < int p * int q" by auto
  from less_trans[OF _ this]
  have 1: "l < int p \<Longrightarrow> l < int p * int q" for l by auto
  have "degree qv' = degree (#v' :: 'pq mod_ring poly)"
  proof (rule degree_smult_eqI, safe, unfold rebase_p_to_pq.degree_rebase_poly_eq)
    define l where "l \<equiv> lead_coeff v'"
    assume "degree v' > 0"
    then have "lead_coeff v' \<noteq> 0" by auto
    then have "(@l :: 'pq mod_ring) \<noteq> 0" by (simp add: l_def)
    then have "(of_nat q * @l :: 'pq mod_ring) \<noteq> 0"
      apply (transfer fixing:q_ty) using p_dvd_q p1 q1 1 by auto
    moreover assume " of_nat q * coeff (#v') (degree v') = (0 :: 'pq mod_ring)"
    ultimately show False by (auto simp: l_def)
  qed
  also from degv' have "... < degree (#v::'pq mod_ring poly)" by simp
  finally have *: "degree qv' < degree (#v :: 'pq mod_ring poly)".
  from degree_add_eq_left[OF *]
  show **: "degree V = degree v" by (simp add: v'_def)

  from * have "coeff qv' (degree v) = 0" by (intro coeff_eq_0, auto)
  then show "lead_coeff V = @lead_coeff v" by (unfold **, auto simp: v'_def)

  with u0 uVW have "degree (V * W) = degree V + degree W"
    by (intro degree_mult_eq_left_unit, auto simp: monic_v)
  from this[folded uVW, unfolded degu **] show "degree W = degree w" by auto
qed

end

locale Knuth_ex_4_6_2_22_prime = Knuth_ex_4_6_2_22_main ty_p ty_q ty_pq a b u v w
  for ty_p :: "'p :: prime_card itself"
  and ty_q :: "'q :: nontriv itself"
  and ty_pq :: "'pq :: nontriv itself"
  and a b u v w +
  assumes coprime: "coprime (#v :: 'p mod_ring poly) (#w)" (* not in Knuth *)

begin

lemma coprime_preserves: "coprime (#V :: 'p mod_ring poly) (#W)"
  apply (intro coprimeI,simp add: rebase_q_to_p.of_nat_CARD_eq_0[simplified] hom_distribs)
  using coprime by (elim coprimeE, auto)

lemma pre_unique:
  assumes f2: "w'' * #v + v'' * #w = f"
      and degv'': "degree v'' < degree v"
  shows "v'' = v' \<and> w'' = w'"
proof(intro conjI)
  from f f2
  have "w' * #v + v' * #w = w'' * #v + v'' * #w" by auto
  also have "... - w'' * #v = v'' * #w" by auto
  also have "... - v' * #w = (v''- v') * #w" by (auto simp: left_diff_distrib)
  finally have *: "(w' - w'') * #v = (v''- v') * #w" by (auto simp: left_diff_distrib)
  then have "#v dvd (v'' - v') * #w" by (auto intro: dvdI[of _ _ "w' - w''"] simp: ac_simps)
  with coprime have "#v dvd v'' - v'"
    by (simp add: coprime_dvd_mult_left_iff)
  moreover have "degree (v'' - v') < degree v" by (rule degree_diff_less[OF degv'' degv'])
  ultimately have "v'' - v' = 0"
    by (metis deg_v degree_0 gr_implies_not_zero poly_divides_conv0)
  then show "v'' = v'" by auto
  with * have "(w' - w'') * #v = 0" by auto
  with bv have "w' - w'' = 0"
    by (metis deg_v degree_0 gr_implies_not_zero mult_eq_0_iff)
  then show "w'' = w'" by auto
qed

  from lc[unfolded degV2, unfolded V2]
  have "of_nat q * (@coeff v'' (degree v) :: 'pq mod_ring) = of_nat q * 0" by auto
  from this[unfolded q rebase_pq_to_p.rebase_mult_eq]
  have "coeff v'' (degree v) = 0" by simp
  moreover have "degree v'' \<le>  degree v" using deg degV2
    by (metis degree_diff_le le_antisym nat_le_linear rebase_q_to_pq.degree_rebase_poly_eq)
  ultimately have degv'': "degree v'' < degree v"
    using bv eq_zero_or_degree_less by fastforce

  from wW2 have "(#(W2 - #w) :: 'q mod_ring poly) = 0" by (auto simp: hom_distribs)
  from rebase_pq_to_q.rebase_poly_eq_0_imp_ex_smult[OF this] pq
  obtain w'' :: "'p mod_ring poly" where w'': "W2 - #w = smult (of_nat q) (#w'')" by force
  then have W2: "W2 = #w + ..." by (metis add_diff_cancel_left' diff_add_cancel)

  have "u = #v * #w + smult (of_nat q) (#w'' * #v + #v'' * #w) + smult (of_nat (q * q)) (#v'' * #w'')"
    by(simp add: uVW2 V2 W2 ring_distribs smult_add_right ac_simps)
  also have "smult (of_nat (q * q)) (#v'' * #w'' :: 'pq mod_ring poly) = 0" by simp
  finally have "u - #v * #w = smult (of_nat q) (#w'' * #v + #v'' * #w)" by auto
  also have "u - #v * #w = smult (of_nat q) (#f)" by (subst u, simp)
  finally have "w'' * #v + v'' * #w = f" by (simp add: hom_distribs)
  from pre_unique[OF this degv'']
  have pre: "v'' = v'" "w'' = w'" by auto
  with V2 W2 show "V2 = V" "W2 = W" by auto
qed

end

definition
  "hensel_1 (ty ::'p :: prime_card itself)
    (u :: 'pq :: nontriv mod_ring poly) (v :: 'q :: nontriv mod_ring poly) (w :: 'q mod_ring poly) \<equiv>
   if v = 1 then (1,u) else
   let (s, t) = bezout_coefficients (#v :: 'p mod_ring poly) (#w) in
   let (a, b) = dupe_monic (#v::'p mod_ring poly) (#w) s t 1 in
   (Knuth_ex_4_6_2_22_main.V TYPE('q) b u v w, Knuth_ex_4_6_2_22_main.W TYPE('q) a b u v w)"

lemma hensel_1:
  fixes u :: "'pq :: nontriv mod_ring poly"
    and v w :: "'q :: nontriv mod_ring poly"
  assumes "CARD('pq) = CARD('p :: prime_card) * CARD('q)"
      and "CARD('p) dvd CARD('q)"
      and uvw: "#u = v * w"
      and degu: "degree u = degree v + degree w"
      and monic: "monic v"
      and coprime: "coprime (#v :: 'p mod_ring poly) (#w)"
      and out: "hensel_1 TYPE('p) u v w = (V',W')"
  shows "u = V' * W' \<and> v = #V' \<and> w = #W' \<and> degree V' = degree v \<and> degree W' = degree w \<and>
         monic V' \<and> coprime (#V' :: 'p mod_ring poly) (#W')" (is ?main)
    and "(\<forall>V'' W''. u = V'' * W'' \<longrightarrow> v = #V'' \<longrightarrow> w = #W'' \<longrightarrow>
          degree V'' = degree v \<longrightarrow> degree W'' = degree w \<longrightarrow> lead_coeff V'' = @lead_coeff v \<longrightarrow>
          V'' = V' \<and> W'' = W')" (is "?unique")
proof-
  from monic
  have degv: "degree (#v :: 'p mod_ring poly) = degree v"
    by (simp add: of_int_hom.monic_degree_map_poly_hom)
  from monic
  have monic2: "monic (#v :: 'p mod_ring poly)"
    by (auto simp: degv)
  obtain s t where bezout: "bezout_coefficients (#v :: 'p mod_ring poly) (#w) = (s, t)"
    by (auto simp add: prod_eq_iff)
  then have "s * #v + t * #w = gcd (#v :: 'p mod_ring poly) (#w)"
    by (rule bezout_coefficients)
  with coprime have vswt: "#v * s + #w * t = 1"
    by (simp add: ac_simps)
  obtain a b where dupe: "dupe_monic (#v) (#w) s t 1 = (a, b)" by force
  from dupe_monic(1,2)[OF vswt monic2, where U=1, unfolded this]
  have avbw: "a * #v + b * #w = 1" and degb: "b = 0 \<or> degree b < degree (#v::'p mod_ring poly)" by auto
  have "?main \<and> ?unique"
  proof (cases "b = 0")
    case b0: True
    with avbw have "a * #v = 1" by auto
    then have "degree (#v :: 'p mod_ring poly) = 0"
      by (metis degree_1 degree_mult_eq_0 mult_zero_left one_neq_zero)
    from this[unfolded degv] monic_degree_0[OF monic[unfolded]]
    have 1: "v = 1" by auto
    with b0 out uvw have 2: "V' = 1" "W' = u"
      by (unfold split hensel_1_def Let_def dupe) auto
    have 3: ?unique apply (simp add: 1 2) by (metis monic_degree_0 mult.left_neutral)
    with uvw degu show ?thesis unfolding 1 2 by auto
  next
    case b0: False
    with degb degv have degb: "degree b < degree v" by auto
    then have v1: "v \<noteq> 1" by auto
    interpret Knuth_ex_4_6_2_22_prime "TYPE('p)" "TYPE('q)" "TYPE('pq)" a b
      by (unfold_locales; fact assms degb avbw)
    show ?thesis
    proof (intro conjI)
      from out [unfolded hensel_1_def] v1
      have 1 [simp]: "V' = V" "W' = W" by (auto simp: bezout dupe)
      from uVW show "u = V' * W'" by auto
      from degV show [simp]: "degree V' = degree v" by simp
      from degW show [simp]: "degree W' = degree w" by simp
      from lcV have "lead_coeff V' = @lead_coeff v" by simp
      with monic_v show "monic V'" by (simp add:)
      from vV show "v = #V'" by simp
      from wW show "w = #W'" by simp
      from coprime_preserves show "coprime (#V' :: 'p mod_ring poly) (#W')" by simp
      show 9: ?unique by (unfold 1, intro allI conjI impI; rule unique)
    qed
  qed
  then show ?main ?unique by (fact conjunct1, fact conjunct2)
qed

end


(*
  File:         Finite_Map_Multiset.thy
  Author:       Mathias Fleury, Daniela Kaufmann, JKU
  Maintainer:   Mathias Fleury, JKU
*)
theory Finite_Map_Multiset
imports
  "HOL-Library.Finite_Map"
  Nested_Multisets_Ordinals.Duplicate_Free_Multiset
begin

notation image_mset (infixr "`#" 90)

section \<open>Finite maps and multisets\<close>

subsection \<open>Finite sets and multisets\<close>

abbreviation mset_fset :: \<open>'a fset \<Rightarrow> 'a multiset\<close> where
  \<open>mset_fset N \<equiv> mset_set (fset N)\<close>

definition fset_mset :: \<open>'a multiset \<Rightarrow> 'a fset\<close> where
  \<open>fset_mset N \<equiv> Abs_fset (set_mset N)\<close>

lemma fset_mset_mset_fset: \<open>fset_mset (mset_fset N) = N\<close>
  by (auto simp: fset.fset_inverse fset_mset_def)

lemma mset_fset_fset_mset[simp]:
  \<open>mset_fset (fset_mset N) = remdups_mset N\<close>
  by (auto simp: fset.fset_inverse fset_mset_def Abs_fset_inverse remdups_mset_def)

lemma in_fset_mset_mset[simp]: \<open>x |\<in>| fset_mset N \<longleftrightarrow> x \<in># N\<close>
  by (auto simp: fmember_iff_member_fset fset_mset_def Abs_fset_inverse)

subsection \<open>Finite map and multisets\<close>

text \<open>Roughly the same as \<^term>\<open>ran\<close> and \<^term>\<open>dom\<close>, but with duplication in the content (unlike their
  finite sets counterpart) while still working on finite domains (unlike a function mapping).
  Remark that \<^term>\<open>dom_m\<close> (the keys) does not contain duplicates, but we keep for symmetry (and for
  easier use of multiset operators as in the definition of \<^term>\<open>ran_m\<close>).
\<close>
definition dom_m where
  \<open>dom_m N = mset_fset (fmdom N)\<close>

definition ran_m where
  \<open>ran_m N = the `# fmlookup N `# dom_m N\<close>

lemma dom_m_fmdrop[simp]: \<open>dom_m (fmdrop C N) = remove1_mset C (dom_m N)\<close>
  unfolding dom_m_def
  by (cases \<open>C |\<in>| fmdom N\<close>)
    (auto simp: mset_set.remove fmember_iff_member_fset)

lemma dom_m_fmdrop_All: \<open>dom_m (fmdrop C N) = removeAll_mset C (dom_m N)\<close>
  unfolding dom_m_def
  by (cases \<open>C |\<in>| fmdom N\<close>)
    (auto simp: mset_set.remove fmember_iff_member_fset)

lemma dom_m_fmupd[simp]: \<open>dom_m (fmupd k C N) = add_mset k (remove1_mset k (dom_m N))\<close>
  unfolding dom_m_def
  by (cases \<open>k |\<in>| fmdom N\<close>)
    (auto simp: mset_set.remove fmember_iff_member_fset mset_set.insert_remove)

lemma distinct_mset_dom: \<open>distinct_mset (dom_m N)\<close>
  by (simp add: distinct_mset_mset_set dom_m_def)

lemma in_dom_m_lookup_iff: \<open>C \<in># dom_m N' \<longleftrightarrow> fmlookup N' C \<noteq> None\<close>
  by (auto simp: dom_m_def fmdom.rep_eq fmlookup_dom'_iff)

lemma in_dom_in_ran_m[simp]: \<open>i \<in># dom_m N \<Longrightarrow> the (fmlookup N i) \<in># ran_m N\<close>
  by (auto simp: ran_m_def)

lemma fmupd_same[simp]:
  \<open>x1 \<in># dom_m x1aa \<Longrightarrow> fmupd x1 (the (fmlookup x1aa x1)) x1aa = x1aa\<close>
  by (metis fmap_ext fmupd_lookup in_dom_m_lookup_iff option.collapse)

lemma ran_m_fmempty[simp]: \<open>ran_m fmempty = {#}\<close> and
    dom_m_fmempty[simp]: \<open>dom_m fmempty = {#}\<close>
  by (auto simp: ran_m_def dom_m_def)

lemma fmrestrict_set_fmupd:
  \<open>a \<in> xs \<Longrightarrow> fmrestrict_set xs (fmupd a C N) = fmupd a C (fmrestrict_set xs N)\<close>
  \<open>a \<notin> xs \<Longrightarrow> fmrestrict_set xs (fmupd a C N) = fmrestrict_set xs N\<close>
  by (auto simp: fmfilter_alt_defs)

lemma fset_fmdom_fmrestrict_set:
  \<open>fset (fmdom (fmrestrict_set xs N)) = fset (fmdom N) \<inter> xs\<close>
  by (auto simp: fmfilter_alt_defs)

lemma dom_m_fmrestrict_set: \<open>dom_m (fmrestrict_set (set xs) N) = mset xs \<inter># dom_m N\<close>
  using fset_fmdom_fmrestrict_set[of \<open>set xs\<close> N] distinct_mset_dom[of N]
  distinct_mset_inter_remdups_mset[of \<open>mset_fset (fmdom N)\<close> \<open>mset xs\<close>]
  by (auto simp: dom_m_def fset_mset_mset_fset finite_mset_set_inter multiset_inter_commute
    remdups_mset_def)

lemma dom_m_fmrestrict_set': \<open>dom_m (fmrestrict_set xs N) = mset_set (xs \<inter> set_mset (dom_m N))\<close>
  using fset_fmdom_fmrestrict_set[of \<open>xs\<close> N] distinct_mset_dom[of N]
  by (auto simp: dom_m_def fset_mset_mset_fset finite_mset_set_inter multiset_inter_commute
    remdups_mset_def)

lemma indom_mI: \<open>fmlookup m x = Some y \<Longrightarrow> x \<in># dom_m m\<close>
  by (drule fmdomI)  (auto simp: dom_m_def fmember_iff_member_fset)

lemma fmupd_fmdrop_id:
  assumes \<open>k |\<in>| fmdom N'\<close>
  shows \<open>fmupd k (the (fmlookup N' k)) (fmdrop k N') = N'\<close>
proof -
  have [simp]: \<open>map_upd k (the (fmlookup N' k))
       (\<lambda>x. if x \<noteq> k then fmlookup N' x else None) =
     map_upd k (the (fmlookup N' k))
       (fmlookup N')\<close>
    by (auto intro!: ext simp: map_upd_def)
  have [simp]: \<open>map_upd k (the (fmlookup N' k)) (fmlookup N') = fmlookup N'\<close>
    using assms
    by (auto intro!: ext simp: map_upd_def)
  have [simp]: \<open>finite (dom (\<lambda>x. if x = k then None else fmlookup N' x))\<close>
    by (subst dom_if) auto
  show ?thesis
    apply (auto simp: fmupd_def fmupd.abs_eq[symmetric])
    unfolding fmlookup_drop
    apply (simp add: fmlookup_inverse)
    done
qed

lemma fm_member_split: \<open>k |\<in>| fmdom N' \<Longrightarrow> \<exists>N'' v. N' = fmupd k v N'' \<and> the (fmlookup N' k) = v \<and>
    k |\<notin>| fmdom N''\<close>
  by (rule exI[of _ \<open>fmdrop k N'\<close>])
    (auto simp: fmupd_fmdrop_id)

lemma \<open>fmdrop k (fmupd k va N'') = fmdrop k N''\<close>
  by (simp add: fmap_ext)

lemma fmap_ext_fmdom:
  \<open>(fmdom N = fmdom N') \<Longrightarrow> (\<And> x. x |\<in>| fmdom N \<Longrightarrow> fmlookup N x = fmlookup N' x) \<Longrightarrow>
       N = N'\<close>
  by (rule fmap_ext)
    (case_tac \<open>x |\<in>| fmdom N\<close>, auto simp: fmdom_notD)

lemma fmrestrict_set_insert_in:
  \<open>xa  \<in> fset (fmdom N) \<Longrightarrow>
    fmrestrict_set (insert xa l1) N = fmupd xa (the (fmlookup N xa)) (fmrestrict_set l1 N)\<close>
  apply (rule fmap_ext_fmdom)
   apply (auto simp: fset_fmdom_fmrestrict_set fmember_iff_member_fset notin_fset; fail)[]
  apply (auto simp: fmlookup_dom_iff; fail)
  done

lemma fmrestrict_set_insert_notin:
  \<open>xa  \<notin> fset (fmdom N) \<Longrightarrow>
    fmrestrict_set (insert xa l1) N = fmrestrict_set l1 N\<close>
  by (rule fmap_ext_fmdom)
     (auto simp: fset_fmdom_fmrestrict_set fmember_iff_member_fset notin_fset)

lemma fmrestrict_set_insert_in_dom_m[simp]:
  \<open>xa  \<in># dom_m N \<Longrightarrow>
    fmrestrict_set (insert xa l1) N = fmupd xa (the (fmlookup N xa)) (fmrestrict_set l1 N)\<close>
  by (simp add: fmrestrict_set_insert_in dom_m_def)

lemma fmrestrict_set_insert_notin_dom_m[simp]:
  \<open>xa  \<notin># dom_m N \<Longrightarrow>
    fmrestrict_set (insert xa l1) N = fmrestrict_set l1 N\<close>
  by (simp add: fmrestrict_set_insert_notin dom_m_def)

lemma fmlookup_restrict_set_id: \<open>fset (fmdom N) \<subseteq> A \<Longrightarrow> fmrestrict_set A N = N\<close>
  by (metis fmap_ext fmdom'_alt_def fmdom'_notD fmlookup_restrict_set subset_iff)

lemma fmlookup_restrict_set_id': \<open>set_mset (dom_m N) \<subseteq> A \<Longrightarrow> fmrestrict_set A N = N\<close>
  by (rule fmlookup_restrict_set_id)
    (auto simp: dom_m_def)

lemma ran_m_mapsto_upd:
  assumes
    NC: \<open>C \<in># dom_m N\<close>
  shows \<open>ran_m (fmupd C C' N) = add_mset C' (remove1_mset (the (fmlookup N C)) (ran_m N))\<close>
proof -
  define N' where
    \<open>N' = fmdrop C N\<close>
  have N_N': \<open>dom_m N = add_mset C (dom_m N')\<close>
    using NC unfolding N'_def by auto
  have \<open>C \<notin># dom_m N'\<close>
    using NC distinct_mset_dom[of N] unfolding N_N' by auto
  then show ?thesis
    by (auto simp: N_N' ran_m_def mset_set.insert_remove image_mset_remove1_mset_if
      intro!: image_mset_cong)
qed

lemma ran_m_mapsto_upd_notin:
  assumes NC: \<open>C \<notin># dom_m N\<close>
  shows \<open>ran_m (fmupd C C' N) = add_mset C' (ran_m N)\<close>
  using NC
  by (auto simp: ran_m_def mset_set.insert_remove image_mset_remove1_mset_if
      intro!: image_mset_cong split: if_splits)

lemma image_mset_If_eq_notin:
   \<open>C \<notin># A \<Longrightarrow> {#f (if x = C then a x else b x). x \<in># A#} = {# f(b x). x \<in># A #}\<close>
  by (induction A) auto

lemma filter_mset_cong2:
  "(\<And>x. x \<in># M \<Longrightarrow> f x = g x) \<Longrightarrow> M = N \<Longrightarrow> filter_mset f M = filter_mset g N"
  by (hypsubst, rule filter_mset_cong, simp)

lemma ran_m_fmdrop:
  \<open>C \<in># dom_m N \<Longrightarrow>  ran_m (fmdrop C N) = remove1_mset (the (fmlookup N C)) (ran_m N)\<close>
  using distinct_mset_dom[of N]
  by (cases \<open>fmlookup N C\<close>)
    (auto simp: ran_m_def image_mset_If_eq_notin[of C _ \<open>\<lambda>x. fst (the x)\<close>]
     dest!: multi_member_split
     intro!: filter_mset_cong2 image_mset_cong2)

lemma ran_m_fmdrop_notin:
  \<open>C \<notin># dom_m N \<Longrightarrow> ran_m (fmdrop C N) = ran_m N\<close>
  using distinct_mset_dom[of N]
  by (auto simp: ran_m_def image_mset_If_eq_notin[of C _ \<open>\<lambda>x. fst (the x)\<close>]
    dest!: multi_member_split
    intro!: filter_mset_cong2 image_mset_cong2)

lemma ran_m_fmdrop_If:
  \<open>ran_m (fmdrop C N) = (if C \<in># dom_m N then remove1_mset (the (fmlookup N C)) (ran_m N) else ran_m N)\<close>
  using distinct_mset_dom[of N]
  by (auto simp: ran_m_def image_mset_If_eq_notin[of C _ \<open>\<lambda>x. fst (the x)\<close>]
    dest!: multi_member_split
    intro!: filter_mset_cong2 image_mset_cong2)

lemma dom_m_empty_iff[iff]:
  \<open>dom_m NU = {#} \<longleftrightarrow> NU = fmempty\<close>
  by (cases NU) (auto simp: dom_m_def mset_set.insert_remove)

end