(* Title: Program Correctness Component Based on Modal Kleene Algebra
   Author: Peixin You
*)

section \<open>Verification Component Based on Modal Kleene Algebra\<close>

theory MKA
  imports KA Store

begin

subsection \<open>Definitions\<close>

class antidomain_kleene_algebra = kleene_algebra +
  fixes ad :: "'a \<Rightarrow> 'a"
  assumes ad_annil [simp]: "ad x \<cdot> x = 0"
  and ad_local_sub [simp]: "ad (x \<cdot> y) \<le> ad (x \<cdot> ad (ad y))"
  and ad_compl1 [simp]: "ad (ad x) + ad x = 1"

begin

definition dom_op :: "'a \<Rightarrow> 'a" ("do") where
  "do x = ad (ad x)"

definition fdia :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" where
  "fdia x y = do (x \<cdot> y)"

definition fbox :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" where
  "fbox x y = ad (x \<cdot> ad y)"

end

class antirange_kleene_algebra = kleene_algebra +
  fixes ar :: "'a \<Rightarrow> 'a"
  assumes ar_annil [simp]: "x \<cdot> ar x  = 0"
  and ar_local_sub [simp]: "ar (x \<cdot> y) \<le> ar (ar (ar x) \<cdot> y)"
  and ar_compl1 [simp]: "ar (ar x) + ar x = 1"

begin

definition range_op :: "'a \<Rightarrow> 'a" ("ra") where
  "ra x = ar (ar x)"

definition bdia :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" where
  "bdia x y = ra (y \<cdot> x)"

definition bbox :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"  where
  "bbox x y = ar (ar y \<cdot> x)"

end

class modal_kleene_algebra = antidomain_kleene_algebra + antirange_kleene_algebra

subsection \<open>Formalisation of Opposition Duality\<close>

sublocale antirange_kleene_algebra \<subseteq> op_arka: antidomain_kleene_algebra "(+)" "0" "1" "\<lambda>x y. y \<cdot> x" "(\<le>)" "(<)" _ ar
  rewrites "op_arka.dom_op x = ra x"
  and "op_arka.fdia x y = bdia x y"
  and "op_arka.fbox x y = bbox x y"
proof -
  show "class.antidomain_kleene_algebra (+) 0 1 (\<lambda>x y. y \<cdot> x) (\<le>) (<) star ar"
    by unfold_locales (simp_all add: mult_assoc distr distl star_inductl star_inductr)
  then interpret op_arka: antidomain_kleene_algebra "(+)" "0" "1" "(\<lambda>x y. y \<cdot> x)" "(\<le>)" "(<)" star ar.
  show "op_arka.dom_op x = ra x"
    by (simp add: range_op_def op_arka.dom_op_def)
  show "op_arka.fdia x y = bdia x y"
    by (simp add: bdia_def range_op_def op_arka.dom_op_def op_arka.fdia_def)
  show "op_arka.fbox x y = bbox x y"
    by (simp add: bbox_def op_arka.fbox_def)
qed

sublocale antidomain_kleene_algebra \<subseteq> arka_op: antirange_kleene_algebra "(+)" "0" "1" "(\<lambda>x y. y \<cdot> x)" "(\<le>)" "(<)" star ad
  rewrites "arka_op.range_op x = do x"
  and "arka_op.bdia x y = fdia x y"
  and "arka_op.bbox x y = fbox x y"
proof -
  show "class.antirange_kleene_algebra (+) 0 1 (\<lambda>x y. y \<cdot> x) (\<le>) (<) star ad"
    by unfold_locales (simp_all add: mult_assoc distl distr star_inductl star_inductr)
  then interpret arka_op: antirange_kleene_algebra "(+)" "0" "1" "(\<lambda>x y. y \<cdot> x)" "(\<le>)" "(<)" star ad.
  show "arka_op.range_op x = do x"
    by (simp add: arka_op.range_op_def dom_op_def)
  show "arka_op.bdia x y = fdia x y"
    by (simp add: arka_op.bdia_def arka_op.range_op_def dom_op_def fdia_def)
  show "arka_op.bbox x y = fbox x y"
    by (simp add: arka_op.bbox_def fbox_def)
qed

subsection \<open>Basic Properties\<close>

context antidomain_kleene_algebra
begin

lemma a_subid_aux: "ad x \<cdot> y \<le> y"
  by (metis ad_compl1 add.commute add_ubl mult.left_neutral mult_isor)

lemma d1_a [simp]: "do x \<cdot> x = x"
  unfolding dom_op_def by (metis add_0_right ad_annil ad_compl1 distr mult_1_left)

lemma ad_one [simp]: "ad 1 = 0"
  by (metis ad_annil mult_1_right)

lemma ad_zero [simp]: "ad 0 = 1"
  by (metis ad_one ad_compl1 add_0_right)

lemma ad_compl2 [simp]: "ad x \<cdot> do x = 0"
  by (metis antisym arka_op.ar_annil arka_op.ar_local_sub dom_op_def mult_1_left mult_isor zero_least)

lemma ad_d: "(ad x \<cdot> y = 0) = (do x \<cdot> y = y)"
  by (metis ad_compl2 add_commute dom_op_def ad_compl1 add_0_left annil distr mult_1_left mult_assoc)

lemma d_a_closed [simp]: "ad (do x) = ad x"
  by (metis ad_one ad_zero ad_zero d1_a dom_op_def ad_annil ad_compl1 annir distl mult_1_right)

lemma a_idem [simp]: "ad x \<cdot> ad x = ad x"
  by (metis d1_a d_a_closed dom_op_def)

lemma meet_ord: "(ad x \<le> ad y) = (ad x \<cdot> ad y = ad x)"
  by (metis a_subid_aux d1_a d_a_closed dom_op_def antisym mult_1_right mult_isol)

lemma d_wloc: "(x \<cdot> y = 0) = (x \<cdot> do y = 0)"
  by (metis a_subid_aux d1_a dom_op_def ad_annil ad_local_sub antisym mult_1_right mult_assoc)

lemma gla: "(ad x \<cdot> y = 0) = (ad x \<le> ad y)"
  apply standard
   apply (smt a_subid_aux add_commute d_wloc dom_op_def ad_compl1 add_0_right distl mult_1_right)
  by (metis ad_annil annir mult_assoc meet_ord)

lemma a_local [simp]: "ad (x \<cdot> do y) = ad (x \<cdot> y)"
  by (smt d_wloc gla ad_annil antisym mult_assoc)

lemma a_supdist: "ad (x + y) \<le> ad x"
  by (metis gla ad_annil add_0_right add_ubl distl order_def)

lemma a_antitone: "x \<le> y \<Longrightarrow> ad y \<le> ad x"
  by (metis a_supdist order_def)

lemma d_iso: "x \<le> y \<Longrightarrow> do x \<le> do y"
  by (simp add: a_antitone dom_op_def)

lemma d_a_ord: "(do x \<le> do y) = (ad y \<le> ad x)"
  using a_antitone dom_op_def by fastforce

lemma llp: "(do y \<cdot> x = x) = (do x \<le> do y)"
  by (metis a_antitone ad_d d_a_closed dom_op_def gla)

lemma a_comm: "ad x \<cdot> ad y = ad y \<cdot> ad x"
  by (rule antisym) (metis a_local a_subid_aux d1_a d_a_closed d_iso dom_op_def eq_refl mult_1_right mult_iso)+

lemma a_closed [simp]: "do (ad x \<cdot> ad y) = ad x \<cdot> ad y"
  by (smt a_comm a_idem a_subid_aux ad_zero d1_a d_a_closed d_iso dom_op_def mult_1_right mult_assoc meet_ord)

lemma a_de_morgan: "ad (ad x \<cdot> ad y) = do x + do y"
  by (simp add: dom_op_def)

lemma d1_sum_var: "x + y \<le> (do x + do y) \<cdot> (x + y)"
  by (simp add: add_commute add_iso add_ubl distl distr)

lemma a_dual_add: "ad (x + y) = ad x \<cdot> ad y"
  apply (rule antisym)
  apply (metis a_supdist add_commute  mult_isor meet_ord)
  by (metis a_closed a_de_morgan a_exp a_subid_aux d1_sum_var antisym  order_def)

lemma d_add: "do (x + y) = do x + do y"
  by (simp add: a_dual_add dom_op_def)

lemma a_absorb1 [simp]: "ad x \<cdot> (ad x + ad y) = ad x"
  using a_dual_add a_supdist add_commute distl order_def by auto

lemma a_absorb2 [simp]: "ad x + ad x \<cdot> ad y = ad x"
  using a_dual_add a_supdist add_commute order_def by auto

lemma a_dist: "ad x + ad y \<cdot> ad z = (ad x + ad y) \<cdot> (ad x + ad z)"
  by (smt a_absorb1 a_subid_aux abel_semigroup.commute abel_semigroup.left_commute add.abel_semigroup_axioms distl distr order_def)

lemma a_lbl: "ad x \<cdot> ad y \<le> ad x"
  using a_dual_add a_supdist by simp

lemma a_lower: "ad x \<le> ad y \<Longrightarrow> ad x \<le> ad z \<Longrightarrow> ad x \<le> ad y \<cdot> ad z"
  by (simp add: a_dist order_def)

lemma a_glb: "(ad x \<le> ad y \<and> ad x \<le> ad z) = (ad x \<le> ad y \<cdot> ad z)"
  using a_lbl a_lower a_subid_aux dual_order.trans by blast

lemma at_shunt: "(ad x \<cdot> ad y \<le> ad z) = (ad x \<le> do y + ad z)"
  by (metis a_dual_add a_exp gla mult_assoc)

lemma a_comp_dist [simp]: "(ad p + ad q) \<cdot> (do p + ad t) = ad p \<cdot> ad t + do p \<cdot> ad q"
proof-
  have "(ad p + ad q) \<cdot> (do p + ad t) = ad p \<cdot> ad t + do p \<cdot> ad q + (ad p + do p) \<cdot> ad q \<cdot> ad t"
    using a_comm ad_compl2 add_commute add_assoc arka_op.ar_compl1 distl distr dom_op_def by simp
  also have "\<dots> = ad p \<cdot> ad t + do p \<cdot> ad q + ad p \<cdot> ad q \<cdot> ad t + do p \<cdot> ad q \<cdot> ad t"
    by (simp add: add_assoc distr)
  also have "\<dots> = (1 + ad q) \<cdot> ad p \<cdot> ad t + (1 + ad t) \<cdot> do p \<cdot> ad q"
    by (smt a_comm add_commute add.left_commute arka_op.distl arka_op.range_op_def mult.semigroup_axioms mult_1_left semigroup.assoc)
  finally show ?thesis
    by (metis a_absorb2 ad_zero mult_1_left)
qed

lemma pcorrect_if1: "ad p \<cdot> x \<le> x \<cdot> ad q \<Longrightarrow> ad p \<cdot> x \<cdot> do q = 0"
  by (smt d_wloc ad_annil add_0_right annir arka_op.mult_assoc distr order_def)

lemma pcorrect_if2: "ad p \<cdot> x \<cdot> do q = 0 \<Longrightarrow> ad p \<cdot> x \<cdot> ad q = ad p \<cdot> x"
  by (metis a_absorb2 d_a_closed local.arka_op.annil arka_op.ar_annil arka_op.ar_compl1 arka_op.distr arka_op.range_op_def mult_1_right)

lemma pcorrect_if3: "ad p \<cdot> x = ad p \<cdot> x \<cdot> ad q \<Longrightarrow> ad p \<cdot> x \<le> x \<cdot> ad q"
  by (metis a_subid_aux mult_isor)

lemma pcorrect_iff1: "(ad p \<cdot> x \<le> x \<cdot> ad q) = (ad p \<cdot> x \<cdot> do q = 0)"
   by (metis pcorrect_if1 pcorrect_if2 pcorrect_if3)

lemma pcorrect_iff2: "(ad p \<cdot> x \<cdot> do q = 0) = (ad p \<cdot> x \<cdot> ad q = ad p \<cdot> x)"
  by (metis pcorrect_if1 pcorrect_if2 pcorrect_if3)

lemma pcorrect_iff2_op: "(do p \<cdot> x \<cdot> ad q = 0) = (x \<cdot> ad q = ad p \<cdot> x \<cdot> ad q)"
  by (metis ad_d d_a_closed arka_op.mult_assoc dom_op_def)

lemma pcorrect_iff3_op: "(x \<cdot> ad q = ad p \<cdot> x \<cdot> ad q) = (x \<cdot> ad q \<le> ad p \<cdot> x)"
  apply standard
  apply (metis a_subid_aux mult_1_right mult_isol)
  by (metis a_antitone a_exp d_a_closed llp add_lub arka_op.mult_assoc dom_op_def)

lemma pcorrect_iff1_op: "(x \<cdot> ad q \<le> ad p \<cdot> x) = (do p \<cdot> x \<cdot> ad q = 0)"
  by (simp add: pcorrect_iff2_op pcorrect_iff3_op)

lemma pcorrect_var: "(ad p \<cdot> x \<le> x \<cdot> ad q) = (x \<cdot> do q \<le> do p \<cdot> x)"
  using d_a_closed  dom_op_def pcorrect_iff1 pcorrect_iff1_op by auto

lemma pcorrect_var2: "(do p \<cdot> x \<le> x \<cdot> do q) = (x \<cdot> ad q \<le> ad p \<cdot> x)"
  by (metis d_a_closed local.dom_op_def pcorrect_iff1 pcorrect_iff1_op)

lemma ad_star [simp]: "ad (x\<^sup>\<star>) = 0"
  by (metis a_dual_add ad_one annil star_unfoldl_eq)

end

context antidomain_kleene_algebra
begin

subsection \<open>Forward Diamond and Box Operators\<close>

lemma fbox_fdia: "fbox x p = ad (fdia x (ad p))"
  by (simp add: fbox_def fdia_def)

lemma fdia_fbox: "fdia x p = ad (fbox x (ad p))"
  using a_local dom_op_def fbox_def fdia_def by simp

lemma fdia_demod: "(fdia x y \<le> do z) = (x \<cdot> do y \<le> do z \<cdot> x)"
  by (unfold fdia_def, metis a_local arka_op.mult_assoc dom_op_def llp pcorrect_iff3_op)

lemma fbox_demod: "(do y \<le> fbox x z) = (do y \<cdot> x  \<le> x \<cdot> do z)"
  by (unfold fbox_def, metis arka_op.mult_assoc d_a_closed dom_op_def gla pcorrect_iff1)

lemma fdia_dom [simp]: "fdia x 1 = do x"
  by (simp add: fdia_def)

lemma fbox_dom [simp]: "fbox x 0 = ad x"
  by (simp add: fbox_def)

lemma fdia_one [simp]: "fdia 1 x = do x"
  by (simp add: fdia_def)

lemma fbox_zero [simp]: "fbox 0 x = 1"
  by (simp add: fbox_def)

lemma fdia_zero_var [simp]: "fdia 0 x = 0"
  by (simp add: dom_op_def fdia_def)

lemma fbox_zero_var [simp]: "fbox 1 x = do x"
  by (simp add: dom_op_def fbox_def)

lemma fbox_one_1 [simp]: "fbox x 1 = 1"
  by (simp add: fbox_def)

lemma fdia_add1: "fdia x (y + z) = fdia x y + fdia x z"
  by (simp add: a_dual_add distl dom_op_def fdia_def)

lemma fbox_add1: "fbox x (do y \<cdot> do z) = fbox x y \<cdot> fbox x z"
  by (metis a_dual_add a_local arka_op.distr dom_op_def fbox_def)

lemma fdia_add2: "fdia (x + y) z = fdia x z + fdia y z"
  by (simp add: a_dual_add distr dom_op_def fdia_def)

lemma fbox_add2: "fbox (x + y) z = fbox x z \<cdot> fbox y z"
  by (simp add: a_dual_add fbox_def distr)

lemma fdia_comp: "fdia (x \<cdot> y) z = fdia x (fdia y z)"
  using a_local arka_op.mult_assoc arka_op.range_op_def fdia_def by auto

lemma fbox_comp: "fbox (x \<cdot> y) z = fbox x (fbox y z)"
  using a_local dom_op_def fbox_def mult_assoc by auto

lemma fdia_iso1: "do x \<le> do y \<Longrightarrow> fdia z x \<le> fdia z y"
  by (metis a_dual_add a_exp a_local arka_op.distr dom_op_def fdia_def order_def)

lemma fbox_iso: "do x \<le> do y \<Longrightarrow> fbox z x \<le> fbox z y"
  by (metis a_antitone d_a_closed fbox_def mult_isol)

lemma fdia_iso2: "x \<le> y \<Longrightarrow> fdia x z \<le> fdia y z"
  by (simp add: d_iso fdia_def mult_isor)

lemma fbox_anti: "x \<le> y \<Longrightarrow> fbox y z \<le> fbox x z"
  by (simp add: a_antitone fbox_fdia fdia_iso2)

lemma fdia_export: "ad y \<cdot> fdia x z = fdia (ad y \<cdot> x) z"
  using a_closed dom_op_def fdia_def fdia_comp by simp

lemma fbox_export: "ad y + fbox x y = fbox (do y \<cdot> x) y"
  by (metis fbox_fdia fdia_export a_exp d_a_closed  dom_op_def)

lemma fdia_diff: "fdia x (do y \<cdot> ad z) \<le> fdia x y + ad (fdia x z)"
  by (metis fdia_iso1 a_closed a_lbl add_ubl dom_op_def dual_order.trans)

lemma fbox_diff: "fbox x (do y + ad z) \<le> fbox x y + ad (fbox x z)"
proof-
  have "fbox x (do y + ad z) \<cdot> fbox x z \<le> fbox x y"
    by (metis add_commute fbox_add1 fbox_iso a_closed a_idem arka_op.range_op_def at_shunt d1_sum_var d_add)
  thus ?thesis
    by (simp add: add_commute at_shunt dom_op_def fbox_def)
qed

lemma fdia_star_unfoldl [simp]: "fdia 1 y + fdia x (fdia (x\<^sup>\<star>) y) = fdia (x\<^sup>\<star>) y"
  by (metis fdia_add2 fdia_comp star_unfoldl_eq)

lemma fbox_star_unfoldl [simp]: "fbox 1 y \<cdot> fbox x (fbox (x\<^sup>\<star>) y) = fbox (x\<^sup>\<star>) y"
  by (metis fbox_add2 fbox_comp star_unfoldl_eq)

lemma fdia_star_unfoldr [simp]: "fdia 1 y + fdia (x\<^sup>\<star>) (fdia x y) = fdia (x\<^sup>\<star>) y"
  by (metis fdia_add2 fdia_comp star_unfoldr_eq)

lemma fbox_star_unfoldr [simp]: "fbox 1 y \<cdot> fbox (x\<^sup>\<star>) (fbox x y) = fbox (x\<^sup>\<star>) y"
  by (metis fbox_add2 fbox_comp star_unfoldr_eq)

lemma fdia_star_inductl_var: "fdia x y \<le> do y \<Longrightarrow> fdia (x\<^sup>\<star>) y \<le> do y"
  by (simp add: fdia_demod star_sim2)

lemma fbox_star_inductl_var: "do y \<le> fbox x y \<Longrightarrow> do y \<le> fbox (x\<^sup>\<star>) y"
  using d_a_ord fdia_star_inductl_var dom_op_def fbox_def fdia_def by auto

lemma fdia_star_inductl: "do z + fdia x y \<le> do y \<Longrightarrow> fdia (x\<^sup>\<star>) z \<le> do y"
  using fdia_iso1 fdia_star_inductl_var add_lub dual_order.trans by blast

lemma fbox_star_inductl: "do y \<le> do z \<cdot> fbox x y \<Longrightarrow> do y \<le> fbox (x\<^sup>\<star>) z"
  by (metis a_comm a_subid_aux fbox_fdia fbox_iso fbox_star_inductl_var dom_op_def dual_order.trans)

end

subsection \<open>Coherence, Galois Connections and Conjugations\<close>

context modal_kleene_algebra
begin

lemma dr_coh_aux1 [simp]: "ar x \<cdot> do (ra x) = 0"
proof-
  have "ar x \<cdot> ra x = 0"
    by (simp add: range_op_def)
  thus "ar x \<cdot> do (ra x) = 0"
    using d_wloc by simp
qed

lemma dr_coh_aux2 [simp]: "ra x \<cdot> do (ra x) \<cdot> ar x = 0"
proof-
  have "ra x \<cdot> do (ra x) \<cdot> ar x \<le> ra x \<cdot> ar x"
    by (metis a_subid_aux arka_op.mult_assoc dom_op_def mult_isol)
  also have "\<dots> = 0"
    by simp
  finally show ?thesis
    using order_def by simp
qed

lemma dr_coh [simp]: "do (ra x) = ra x"
proof -
  have "do (ra x) = (ar x + ra x) \<cdot> do (ra x)"
    using add_commute op_arka.ad_compl1 range_op_def by auto
  also have "\<dots> = ar x \<cdot> do (ra x) + ra x \<cdot> do (ra x) \<cdot> (ar x + ra x)"
    by (metis (mono_tags, lifting) add_commute arka_op.distl mult_1_right op_arka.ad_compl1 range_op_def)
  also have "\<dots> =  0 + ra x \<cdot> do (ra x) \<cdot> ar x + ra x \<cdot> do (ra x) \<cdot> ra x"
    using distl by simp
  also have "\<dots> = 0 + ra x \<cdot> ra x"
    by (simp add: mult.semigroup_axioms semigroup.assoc)
  also have "\<dots> = ra x"
    by (simp add: local.range_op_def)
  finally show ?thesis.
qed

lemma rd_coh [simp]: "ra (do x) = do x"
  by (smt dr_coh a_comm ad_compl2 ad_d dom_op_def op_arka.d_wloc)

lemma do_ra: "(do x = x) = (ra x = x)"
  by (metis dr_coh rd_coh)

lemma do_ra_alg: "{x. do x = x} = {x. ra x = x}"
  by (simp add: do_ra)

lemma dr_zero: "(x \<cdot> y = 0) = (ra x \<cdot> do y = 0)"
  by (metis d_wloc op_arka.d_wloc)

lemma fdia_bbox_galois:
  assumes "do p = p" and "do q = q"
  shows "(fdia x p \<le> q) = (p \<le> bbox x q)"
  by (metis assms fdia_demod op_arka.fbox_demod rd_coh)

lemma dia_conjugation:
  assumes "do p = p" and "do q = q"
  shows "(p \<cdot> fdia x q = 0) = (bdia x p \<cdot> q = 0)"
proof-
  have "(p \<cdot> fdia x q = 0) = (fdia x q \<le> ad p)"
    by (metis assms ad_d dom_op_def fdia_fbox gla llp)
  also have "\<dots> = (q \<le> bbox x (ar p))"
    by (metis assms do_ra fdia_bbox_galois ad_d local.dom_op_def op_arka.a_idem op_arka.ad_d range_op_def)
  also have "\<dots> = (q \<le> ar (bdia x p))"
    by (metis assms op_arka.fbox_fdia range_op_def rd_coh)
  also have "\<dots> = (bdia x p \<cdot> q = 0)"
    by (metis assms op_arka.gla range_op_def rd_coh)
  finally show ?thesis.
qed

lemma box_conjugation:
  assumes "do p = p" and "do q = q"
  shows "(p + fbox x q = 1) = (bbox x p + q = 1)"
proof-
  have "(p + fbox x q = 1) = (ad p \<cdot> ad (fbox x q) = 0)"
    by (metis assms a_dual_add a_exp a_local ad_one ad_zero dom_op_def fbox_def)
  also have "\<dots> = (ad p \<cdot> fdia x (ad q) = 0)"
    by (simp add: dom_op_def fbox_def fdia_def)
  also have "\<dots> = (bdia x (ar p) \<cdot> ar q = 0)"
    by (smt assms dia_conjugation do_ra ad_d dom_op_def op_arka.a_idem op_arka.ad_d range_op_def)
  also have "\<dots> = (ar (bbox x p) \<cdot> ar q = 0)"
    by (simp add: op_arka.fbox_def op_arka.fdia_def range_op_def)
  also have "\<dots> = (bbox x p + q = 1)"
    by (metis \<open>(bdia x (ar p) \<cdot> ar q = 0) = (ar (bbox x p) \<cdot> ar q = 0)\<close> add_commute assms op_arka.a_dual_add op_arka.a_exp op_arka.ad_one op_arka.ad_zero op_arka.fbox_fdia rd_coh)
  finally show ?thesis.
qed

end

subsection \<open>Algebraic Laws for VCG\<close>

context antidomain_kleene_algebra
begin

definition cond :: "'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a" ("if _ then _ else _ fi" [64,64,64] 63) where
  "if p then x else y fi = do p \<cdot> x + ad p \<cdot> y"

definition while :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" ("while _ do _ od" [64,64] 63) where
  "while p do x od = (do p \<cdot> x)\<^sup>\<star> \<cdot> ad p"

definition while_inv :: "'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a" ("while _ inv _ do _ od" [64,64,64] 63) where
  "while p inv i do x od = while p do x od"

lemma while_if: "while p do x od = if p then x \<cdot> (while p do x od) else 1 fi"
  by (smt abel_semigroup.commute cond_def a_comm ad_zero add.abel_semigroup_axioms distr mult.semigroup_axioms star_unfoldl_eq semigroup.assoc while_def)

lemma fbox_cond: "fbox (if p then x else y fi) q = (ad p + fbox x q) \<cdot> (do p + fbox y q)"
proof-
  have "fbox (if p then x else y fi) q = fbox (do p \<cdot> x + ad p \<cdot> y) q"
    by (simp add: cond_def)
  also have "\<dots> = fbox (do p \<cdot> x) q \<cdot> fbox (ad p \<cdot> y) q"
    by (simp add: fbox_add2)
  also have "\<dots> = (ad p + fbox x q) \<cdot> (do p + fbox y q)"
    by (metis a_exp arka_op.mult_assoc d_a_closed dom_op_def fbox_def)
  finally show ?thesis.
qed

lemma fbox_condl: "do p \<cdot> fbox (if p then x else y fi) q = do p \<cdot> fbox x q"
proof-
  have "do p \<cdot> fbox (if p then x else y fi) q = do p \<cdot> (ad p + fbox x q) \<cdot> (do p + fbox y q)"
    by (simp add: fbox_cond arka_op.mult_assoc)
  also have "\<dots> = do p \<cdot> fbox x q \<cdot> (do p + fbox y q)"
    by (simp add: distl dom_op_def)
  also have "\<dots> = do p \<cdot> fbox x q"
    by (metis a_absorb1 a_comm arka_op.mult_assoc dom_op_def fbox_fdia)
  finally show ?thesis.
qed

lemma fbox_condr: "ad p \<cdot> fbox (if p then x else y fi) q = ad p \<cdot> fbox y q"
proof-
  have "ad p \<cdot> fbox (if p then x else y fi) q = ad p \<cdot> (ad p + fbox x q) \<cdot> (do p + fbox y q)"
    by (simp add: fbox_cond arka_op.mult_assoc)
  also have "\<dots> = ad p \<cdot> (do p + fbox y q)"
    by (simp add: fbox_def)
  also have "\<dots> = ad p \<cdot> fbox y q"
    by (simp add: arka_op.distr)
  finally show ?thesis.
qed

lemma fbox_cond_var: "fbox (if p then x else y fi) q = (do p \<cdot> fbox x q) + (ad p \<cdot> fbox y q)"
  using add_commute fbox_cond fbox_def by simp

lemma fbox_while:
  assumes "do p \<cdot> do t \<le> fbox x p"
  shows "do p \<le> fbox (while t do x od) (do p \<cdot> ad t)"
proof -
  have  "do p \<cdot> do t \<cdot> x \<le> do t \<cdot> x \<cdot> do p"
    by (metis assms a_exp arka_op.mult_assoc at_shunt dom_op_def fbox_def fbox_demod)
  hence "do p \<cdot> (do t \<cdot> x)\<^sup>\<star> \<cdot> ad t \<le> (do t \<cdot> x)\<^sup>\<star> \<cdot> do p \<cdot> ad t"
    by (metis arka_op.mult_assoc mult_isor star_sim1)
  also have "\<dots> = (do t \<cdot> x)\<^sup>\<star> \<cdot> ad t \<cdot> do p \<cdot> ad t"
    by (metis add_commute a_dual_add add_ubl arka_op.mult_assoc dom_op_def order_def)
  finally show ?thesis
    using a_closed arka_op.range_op_def fbox_demod mult.semigroup_axioms semigroup.assoc while_def by fastforce
qed

lemma fbox_whilet: "do p \<cdot> fbox (while p do x od) q = do p \<cdot> fbox x (fbox (while p do x od) q)"
  by (metis fbox_condl fbox_comp while_if)

lemma fbox_whilef: "ad p \<cdot> fbox (while p do x od) q = ad p \<cdot> do q"
  by (metis fbox_condr fbox_zero_var while_if)

lemma fbox_while_inv:
  assumes "do p \<le> do i"
  and "do i \<cdot> ad t \<le> do q"
  and "do i \<cdot> do t \<le> fbox x i"
shows "do p \<le> fbox (while t inv i do x od) q"
  by (unfold while_inv_def, smt assms fbox_while a_closed distl dom_op_def dual_order.trans fbox_demod order_def)

end

subsection \<open>Relation and State Transformer KAD\<close>

definition rel_ad :: "'a rel \<Rightarrow> 'a rel" ("ad\<^sub>r") where
  "rel_ad R = {(x,x) | x. \<not>(\<exists>y. (x,y) \<in> R)}"

interpretation rel_aka: antidomain_kleene_algebra "(\<union>)" "{}" Id "(;)" "(\<subseteq>)" "(\<subset>)" rtrancl "ad\<^sub>r"
  by unfold_locales (auto simp: rel_ad_def)

definition sta_ad :: "'a sta \<Rightarrow> 'a sta" ("ad\<^sub>s")where
  "sta_ad f x = (if f x = {} then {x} else {})"

interpretation sta_aka: antidomain_kleene_algebra "(+\<^sub>K)" "\<nu>" "\<eta>" "(\<circ>\<^sub>K)" "(\<sqsubseteq>)" "(\<sqsubset>)" kstar "ad\<^sub>s"
  apply (unfold_locales, unfold sta_iff sta_ad_def kcomp_iff kleq_iff kadd_iff)
  by clarsimp+ (auto simp: kcomp_def)

lemma rel_d_fix_subid: "(rel_aka.dom_op R = R) = (R \<subseteq> Id)"
  unfolding rel_aka.dom_op_def rel_ad_def Id_def by force

lemma sta_d_fix_subid: "(sta_aka.dom_op f = f) = (f \<sqsubseteq> \<eta>)"
  unfolding sta_iff sta_aka.dom_op_def sta_ad_def kleq_iff by force

subsection \<open>Optimised Laws for VCG\<close>

abbreviation rcond :: "'a pred \<Rightarrow> 'a rel \<Rightarrow> 'a rel \<Rightarrow> 'a rel" ("rif _ then _ else _ fi" [64,64,64] 63) where
  "rif P then R else S fi \<equiv> rel_aka.cond \<lceil>P\<rceil>\<^sub>r R S"

abbreviation rwhile :: "'a pred \<Rightarrow> 'a rel \<Rightarrow> 'a rel" ("rwhile _ do _ od" [64,64] 63) where
  "rwhile P do R od \<equiv> rel_aka.while \<lceil>P\<rceil>\<^sub>r R"

abbreviation rwhile_inv :: "'a pred \<Rightarrow> 'a pred \<Rightarrow> 'a rel \<Rightarrow> 'a rel" ("rwhile _ inv _ do _ od" [64,64,64] 63) where
  "rwhile P inv I do R od \<equiv> rel_aka.while_inv \<lceil>P\<rceil>\<^sub>r \<lceil>I\<rceil>\<^sub>r R"

abbreviation scond :: "'a pred \<Rightarrow> 'a sta \<Rightarrow> 'a sta \<Rightarrow> 'a sta" ("sif _ then _ else _ fi" [64,64,64] 63) where
  "sif P then f else g fi \<equiv> sta_aka.cond \<lceil>P\<rceil>\<^sub>s f g"

abbreviation swhile :: "'a pred \<Rightarrow> 'a sta \<Rightarrow> 'a sta" ("swhile _ do _ od" [64,64] 63) where
  "swhile P do f od \<equiv> sta_aka.while \<lceil>P\<rceil>\<^sub>s f"

abbreviation swhile_inv :: "'a pred \<Rightarrow> 'a pred \<Rightarrow> 'a sta \<Rightarrow> 'a sta" ("swhile _ inv _ do _ od" [64,64,64] 63) where
  "swhile P inv I do f od \<equiv> sta_aka.while_inv \<lceil>P\<rceil>\<^sub>s \<lceil>I\<rceil>\<^sub>s f"

lemma rel_fbox_subid: "rel_aka.fbox R P \<subseteq> Id"
  using rel_aka.fbox_anti by force

lemma sta_fbox_subid: "sta_aka.fbox f P \<sqsubseteq> \<eta>"
  by (simp add: kleq_iff sta_ad_def sta_aka.fbox_fdia)

lemma rel_dom_pred [simp]: "rel_aka.dom_op \<lceil>P\<rceil>\<^sub>r = \<lceil>P\<rceil>\<^sub>r"
  unfolding p2r_def rel_aka.dom_op_def rel_ad_def by simp

lemma rel_ad_pred [simp]: "ad\<^sub>r \<lceil>P\<rceil>\<^sub>r = \<lceil>\<lambda>s. \<not> P s\<rceil>\<^sub>r"
  unfolding p2r_def rel_ad_def by simp

lemma sta_dom_pred [simp]: "sta_aka.dom_op \<lceil>P\<rceil>\<^sub>s = \<lceil>P\<rceil>\<^sub>s"
  unfolding p2s_def sta_aka.dom_op_def sta_ad_def sta_iff by simp

lemma sta_ad_pred [simp]: "ad\<^sub>s \<lceil>P\<rceil>\<^sub>s = \<lceil>\<lambda>s. \<not> P s\<rceil>\<^sub>s"
  unfolding p2s_def sta_ad_def sta_iff by simp

abbreviation "rfbox R Q \<equiv> \<lfloor>rel_aka.fbox R \<lceil>Q\<rceil>\<^sub>r\<rfloor>\<^sub>r"

abbreviation "sfbox R Q \<equiv> \<lfloor>sta_aka.fbox R \<lceil>Q\<rceil>\<^sub>s\<rfloor>\<^sub>s"

lemma rfbox_p2r2p: "rel_aka.fbox R \<lceil>P\<rceil>\<^sub>r = \<lceil>rfbox R P\<rceil>\<^sub>r"
  by (simp add: p2r2p rel_fbox_subid)

lemma sfbox_p2s2p: "sta_aka.fbox R \<lceil>P\<rceil>\<^sub>s = \<lceil>sfbox R P\<rceil>\<^sub>s"
  by (simp add: p2s2p sta_fbox_subid)

lemma rfbox_unfold: "rfbox R P s = (\<forall>s'. (s,s') \<in> R \<longrightarrow> P s')"
  unfolding p2r_def r2p_def rel_aka.fbox_def rel_ad_def by force

lemma sfbox_unfold: "sfbox f P s = (\<forall>s'. s' \<in> f s \<longrightarrow> P s')"
  unfolding p2s_def s2p_def sta_aka.fbox_def sta_ad_def kcomp_def by force

lemma rfbox_seq [simp]: "rfbox (R ; S) P s = rfbox R (rfbox S P) s"
  by (metis rel_aka.fbox_comp rfbox_p2r2p)

lemma rfbox_seq_var:
  assumes "\<forall>s. w s \<longrightarrow> rfbox y z s"
   and "\<forall>s. v s \<longrightarrow> rfbox x w s"
  shows "\<forall>s. v s \<longrightarrow> rfbox (x ; y) z s"
  by (metis assms rfbox_seq rfbox_unfold)

lemma sfbox_seq [simp]: "sfbox (f \<circ>\<^sub>K g) P s = sfbox f (sfbox g P) s"
  by (metis sfbox_p2s2p sta_aka.fbox_comp)

lemma sfbox_seq_var:
  assumes "\<forall>s. w s \<longrightarrow> sfbox y z s"
  and "\<forall>s. v s \<longrightarrow> sfbox x w s"
  shows "\<forall>s. v s \<longrightarrow> sfbox (x \<circ>\<^sub>K y) z s"
  by (metis assms sfbox_seq sfbox_unfold)

lemma rfbox_cond [simp]: "rfbox (rif P then R else S fi) Q s = ((P s \<longrightarrow> rfbox R Q s) \<and> (\<not> P s \<longrightarrow> rfbox S Q s))"
  by (unfold rfbox_unfold rel_aka.cond_def relcomp_unfold, simp, unfold p2r_def, force)

lemma rfbox_cond_var: "rfbox (rif P then R else S fi) Q s = ((P s \<and> rfbox R Q s) \<or>  (\<not> P s \<and> rfbox S Q s))"
  by (metis (no_types, hide_lams) rfbox_cond)

lemma sfbox_cond [simp]: "sfbox (sif P then f else g fi) Q s = ((P s \<longrightarrow> sfbox f Q s) \<and> (\<not> P s \<longrightarrow> sfbox g Q s))"
  by (unfold sfbox_unfold sta_aka.cond_def sta_iff kadd_def kcomp_iff, simp, unfold p2s_def kcomp_iff, force)

lemma sfbox_cond_var: "sfbox (sif P then f else g fi) Q s = ((P s \<and> sfbox f Q s) \<or>  (\<not> P s \<and> sfbox g Q s))"
  unfolding sfbox_cond fun_eq_iff by force

lemma rfbox_while_inv:
  assumes "\<forall>s. P s \<longrightarrow> I s"
  and "\<forall>s. I s \<longrightarrow> \<not> T s \<longrightarrow> Q s"
  and "\<forall>s. I s \<longrightarrow> T s \<longrightarrow> rfbox R I s"
  shows "\<forall>s. P s \<longrightarrow> rfbox (rwhile T inv I do R od) Q s"
proof-
  have a: "\<lceil>P\<rceil>\<^sub>r \<subseteq> \<lceil>I\<rceil>\<^sub>r"
    using assms by simp
  have b: "\<lceil>I\<rceil>\<^sub>r ; ad\<^sub>r \<lceil>T\<rceil>\<^sub>r \<subseteq> \<lceil>Q\<rceil>\<^sub>r"
    by (simp add: assms(2))
  have c: "\<lceil>I\<rceil>\<^sub>r ; \<lceil>T\<rceil>\<^sub>r \<subseteq> rel_aka.fbox R \<lceil>I\<rceil>\<^sub>r"
    by (smt assms(3) p2r_comp p2r_imp rfbox_p2r2p)
  hence "rel_aka.dom_op \<lceil>P\<rceil>\<^sub>r \<subseteq> rel_aka.fbox (rel_aka.while_inv \<lceil>T\<rceil>\<^sub>r \<lceil>I\<rceil>\<^sub>r R) \<lceil>Q\<rceil>\<^sub>r"
    apply (intro rel_aka.fbox_while_inv)
    using a b by simp_all
  thus ?thesis
    by (smt p2r_imp rel_dom_pred rfbox_p2r2p)
qed

lemma sfbox_while_inv:
  assumes "\<forall>s. P s \<longrightarrow> I s"
  and "\<forall>s. I s \<longrightarrow> \<not> T s \<longrightarrow> Q s"
  and "\<forall>s. I s \<longrightarrow> T s \<longrightarrow> sfbox f I s"
  shows "\<forall>s. P s \<longrightarrow> sfbox (swhile T inv I do f od) Q s"
proof-
  have a: "\<lceil>P\<rceil>\<^sub>s \<sqsubseteq> \<lceil>I\<rceil>\<^sub>s"
    using assms by simp
  have b: "\<lceil>I\<rceil>\<^sub>s \<circ>\<^sub>K ad\<^sub>s \<lceil>T\<rceil>\<^sub>s \<sqsubseteq> \<lceil>Q\<rceil>\<^sub>s"
    by (simp add: assms(2))
  have c: "\<lceil>I\<rceil>\<^sub>s \<circ>\<^sub>K \<lceil>T\<rceil>\<^sub>s \<sqsubseteq> sta_aka.fbox f \<lceil>I\<rceil>\<^sub>s"
    by (smt assms(3) p2s_comp p2s_imp sfbox_p2s2p)
  hence "sta_aka.dom_op \<lceil>P\<rceil>\<^sub>s \<sqsubseteq> sta_aka.fbox (sta_aka.while_inv \<lceil>T\<rceil>\<^sub>s \<lceil>I\<rceil>\<^sub>s f) \<lceil>Q\<rceil>\<^sub>s"
    apply (intro sta_aka.fbox_while_inv)
    using a b by simp_all
  thus ?thesis
     by (smt p2s_imp sta_dom_pred sfbox_p2s2p)
 qed

lemma rfbox_while_inv_break:
  assumes "\<forall>s. P s \<longrightarrow> rfbox S I s"
  and "\<forall>s. I s \<longrightarrow> \<not> T s \<longrightarrow> Q s"
  and "\<forall>s. I s \<longrightarrow>  T s \<longrightarrow> rfbox R I s"
  shows "\<forall>s. P s \<longrightarrow> rfbox (S ; (rwhile T inv I do R od)) Q s"
  apply (intro rfbox_seq_var rfbox_while_inv)
  using assms by simp_all

lemma sfbox_while_inv_break:
  assumes "\<forall>s. P s \<longrightarrow> sfbox g I s"
  and "\<forall>s. I s \<longrightarrow> \<not> T s \<longrightarrow> Q s"
  and "\<forall>s. I s \<longrightarrow>  T s \<longrightarrow> sfbox f I s"
  shows "\<forall>s. P s \<longrightarrow> sfbox (g \<circ>\<^sub>K (swhile T inv I do f od)) Q s"
  apply (intro sfbox_seq_var sfbox_while_inv)
  using assms by simp_all

subsection \<open>Store and Assignment Semantics\<close>

text \<open>We reuse the store from KAT\<close>

lemma mka_rel_assign [simp]: "rel_aka.fbox (v :=\<^sub>r e) \<lceil>Q\<rceil>\<^sub>r = \<lceil>\<lambda>s. Q (set v e s)\<rceil>\<^sub>r"
  by (auto simp: rel_aka.fbox_def rel_assign_def rel_ad_def p2r_def)

lemma mka_sta_assign [simp]: "sta_aka.fbox (v :=\<^sub>s e) \<lceil>Q\<rceil>\<^sub>s = \<lceil>\<lambda>s. Q (set v e s)\<rceil>\<^sub>s"
  by (auto simp: sta_iff sta_aka.fbox_def sta_assign_def kcomp_def sta_ad_def p2s_def)

lemma rfbox_assign [simp]: "rfbox (v :=\<^sub>r e) Q s = Q (set v e s)"
  by simp

lemma sfbox_assign [simp]: "sfbox (v :=\<^sub>s e) Q s = Q (set v e s)"
  by simp

subsection \<open>Examples\<close>

lemma svar_swap:
  "s ''x'' = m \<and> s ''y'' = n \<Longrightarrow>
    sfbox ((''z'' :=\<^sub>s (\<lambda>s. s ''x''))\<circ>\<^sub>K
    (''x'' :=\<^sub>s (\<lambda>s. s ''y''))\<circ>\<^sub>K
    (''y'' :=\<^sub>s (\<lambda>s. s ''z'')))
   (\<lambda>s. s ''x'' = n \<and> s ''y'' = m) s"
  by simp

lemma rvar_swap:
  "s ''x'' = m \<and> s ''y'' = n \<Longrightarrow>
    rfbox ((''z'' :=\<^sub>r (\<lambda>s. s ''x''));
    (''x'' :=\<^sub>r (\<lambda>s. s ''y''));
    (''y'' :=\<^sub>r (\<lambda>s. s ''z'')))
   (\<lambda>s. s ''x'' = n \<and> s ''y'' = m) s"
  by simp

lemma rmaximum:
  "\<forall>s::int store.
   rfbox (rif (\<lambda>s. s ''x'' \<ge> s ''y'')
    then (''z'' :=\<^sub>r (\<lambda>s. s ''x''))
    else (''z'' :=\<^sub>r (\<lambda>s. s ''y''))
    fi)
   (\<lambda>s. s ''z'' = max (s ''x'') (s ''y'')) s"
  by force

lemma smaximum:
  "\<forall>s::int store.
   sfbox (sif (\<lambda>s. s ''x'' \<ge> s ''y'')
    then (''z'' :=\<^sub>s (\<lambda>s. s ''x''))
    else (''z'' :=\<^sub>s (\<lambda>s. s ''y''))
    fi)
   (\<lambda>s. s ''z'' = max (s ''x'') (s ''y'')) s"
  by force

lemma rinteger_division:
"\<forall>s::nat store. 0 < y \<longrightarrow>
    rfbox ((''q'' :=\<^sub>r (\<lambda>s. 0));
    (''r'' :=\<^sub>r (\<lambda>s. x));
    (rwhile (\<lambda>s. y \<le> s ''r'') inv (\<lambda>s. x = s ''q'' * y + s ''r'')
     do
      (''q'' :=\<^sub>r (\<lambda>s. s ''q'' + 1)) ;
      (''r'' :=\<^sub>r (\<lambda>s. s ''r'' - y))
     od))
  (\<lambda>s. x = s ''q'' * y + s ''r'' \<and> s ''r'' < y) s"
  by (intro rfbox_seq_var rfbox_while_inv, auto simp: imp_refl)
(*  by (rule rfbox_while_inv_break) simp_all*)

lemma sinteger_division:
"\<forall>s::nat store. 0 < y \<longrightarrow>
    sfbox ((''q'' :=\<^sub>s (\<lambda>s. 0)) \<circ>\<^sub>K
    (''r'' :=\<^sub>s (\<lambda>s. x))  \<circ>\<^sub>K
    (swhile (\<lambda>s. y \<le> s ''r'') inv (\<lambda>s. x = s ''q'' * y + s ''r'')
     do
      (''q'' :=\<^sub>s (\<lambda>s. s ''q'' + 1)) \<circ>\<^sub>K
      (''r'' :=\<^sub>s (\<lambda>s. s ''r'' - y))
     od))
  (\<lambda>s. x = s ''q'' * y + s ''r'' \<and> s ''r'' < y) s"
  by (rule sfbox_while_inv_break) simp_all

end


(*  Title:      HOL/Library/Order_Continuity.thy
    Author:     David von Oheimb, TU München
    Author:     Johannes Hölzl, TU München
*)

section \<open>Continuity and iterations\<close>

theory Order_Continuity
imports Complex_Main Countable_Complete_Lattices
begin

(* TODO: Generalize theory to chain-complete partial orders *)

lemma SUP_nat_binary:
  "(sup A (SUP x\<in>Collect ((<) (0::nat)). B)) = (sup A B::'a::countable_complete_lattice)"
  apply (subst image_constant)
   apply auto
  done

lemma INF_nat_binary:
  "inf A (INF x\<in>Collect ((<) (0::nat)). B) = (inf A B::'a::countable_complete_lattice)"
  apply (subst image_constant)
   apply auto
  done

text \<open>
  The name \<open>continuous\<close> is already taken in \<open>Complex_Main\<close>, so we use
  \<open>sup_continuous\<close> and \<open>inf_continuous\<close>. These names appear sometimes in literature
  and have the advantage that these names are duals.
\<close>

named_theorems order_continuous_intros

subsection \<open>Continuity for complete lattices\<close>

definition
  sup_continuous :: "('a::countable_complete_lattice \<Rightarrow> 'b::countable_complete_lattice) \<Rightarrow> bool"
where
  "sup_continuous F \<longleftrightarrow> (\<forall>M::nat \<Rightarrow> 'a. mono M \<longrightarrow> F (SUP i. M i) = (SUP i. F (M i)))"

lemma sup_continuousD: "sup_continuous F \<Longrightarrow> mono M \<Longrightarrow> F (SUP i::nat. M i) = (SUP i. F (M i))"
  by (auto simp: sup_continuous_def)

lemma sup_continuous_mono:
  "mono F" if "sup_continuous F"
proof
  fix A B :: "'a"
  assume "A \<le> B"
  let ?f = "\<lambda>n::nat. if n = 0 then A else B"
  from \<open>A \<le> B\<close> have "incseq ?f"
    by (auto intro: monoI)
  with \<open>sup_continuous F\<close> have *: "F (SUP i. ?f i) = (SUP i. F (?f i))"
    by (auto dest: sup_continuousD)
  from \<open>A \<le> B\<close> have "B = sup A B"
    by (simp add: le_iff_sup)
  then have "F B = F (sup A B)"
    by simp
  also have "\<dots> = sup (F A) (F B)"
    using * by (simp add: if_distrib SUP_nat_binary cong del: SUP_cong)
  finally show "F A \<le> F B"
    by (simp add: le_iff_sup)
qed

lemma [order_continuous_intros]:
  shows sup_continuous_const: "sup_continuous (\<lambda>x. c)"
    and sup_continuous_id: "sup_continuous (\<lambda>x. x)"
    and sup_continuous_apply: "sup_continuous (\<lambda>f. f x)"
    and sup_continuous_fun: "(\<And>s. sup_continuous (\<lambda>x. P x s)) \<Longrightarrow> sup_continuous P"
    and sup_continuous_If: "sup_continuous F \<Longrightarrow> sup_continuous G \<Longrightarrow> sup_continuous (\<lambda>f. if C then F f else G f)"
  by (auto simp: sup_continuous_def image_comp)

lemma sup_continuous_compose:
  assumes f: "sup_continuous f" and g: "sup_continuous g"
  shows "sup_continuous (\<lambda>x. f (g x))"
  unfolding sup_continuous_def
proof safe
  fix M :: "nat \<Rightarrow> 'c"
  assume M: "mono M"
  then have "mono (\<lambda>i. g (M i))"
    using sup_continuous_mono[OF g] by (auto simp: mono_def)
  with M show "f (g (Sup (M ` UNIV))) = (SUP i. f (g (M i)))"
    by (auto simp: sup_continuous_def g[THEN sup_continuousD] f[THEN sup_continuousD])
qed

lemma sup_continuous_sup[order_continuous_intros]:
  "sup_continuous f \<Longrightarrow> sup_continuous g \<Longrightarrow> sup_continuous (\<lambda>x. sup (f x) (g x))"
  by (simp add: sup_continuous_def ccSUP_sup_distrib)

lemma sup_continuous_inf[order_continuous_intros]:
  fixes P Q :: "'a :: countable_complete_lattice \<Rightarrow> 'b :: countable_complete_distrib_lattice"
  assumes P: "sup_continuous P" and Q: "sup_continuous Q"
  shows "sup_continuous (\<lambda>x. inf (P x) (Q x))"
  unfolding sup_continuous_def
proof (safe intro!: antisym)
  fix M :: "nat \<Rightarrow> 'a" assume M: "incseq M"
  have "inf (P (SUP i. M i)) (Q (SUP i. M i)) \<le> (SUP j i. inf (P (M i)) (Q (M j)))"
    by (simp add: sup_continuousD[OF P M] sup_continuousD[OF Q M] inf_ccSUP ccSUP_inf)
  also have "\<dots> \<le> (SUP i. inf (P (M i)) (Q (M i)))"
  proof (intro ccSUP_least)
    fix i j from M assms[THEN sup_continuous_mono] show "inf (P (M i)) (Q (M j)) \<le> (SUP i. inf (P (M i)) (Q (M i)))"
      by (intro ccSUP_upper2[of _ "sup i j"] inf_mono) (auto simp: mono_def)
  qed auto
  finally show "inf (P (SUP i. M i)) (Q (SUP i. M i)) \<le> (SUP i. inf (P (M i)) (Q (M i)))" .

  show "(SUP i. inf (P (M i)) (Q (M i))) \<le> inf (P (SUP i. M i)) (Q (SUP i. M i))"
    unfolding sup_continuousD[OF P M] sup_continuousD[OF Q M] by (intro ccSUP_least inf_mono ccSUP_upper) auto
qed

lemma sup_continuous_and[order_continuous_intros]:
  "sup_continuous P \<Longrightarrow> sup_continuous Q \<Longrightarrow> sup_continuous (\<lambda>x. P x \<and> Q x)"
  using sup_continuous_inf[of P Q] by simp

lemma sup_continuous_or[order_continuous_intros]:
  "sup_continuous P \<Longrightarrow> sup_continuous Q \<Longrightarrow> sup_continuous (\<lambda>x. P x \<or> Q x)"
  by (auto simp: sup_continuous_def)

lemma sup_continuous_lfp:
  assumes "sup_continuous F" shows "lfp F = (SUP i. (F ^^ i) bot)" (is "lfp F = ?U")
proof (rule antisym)
  note mono = sup_continuous_mono[OF \<open>sup_continuous F\<close>]
  show "?U \<le> lfp F"
  proof (rule SUP_least)
    fix i show "(F ^^ i) bot \<le> lfp F"
    proof (induct i)
      case (Suc i)
      have "(F ^^ Suc i) bot = F ((F ^^ i) bot)" by simp
      also have "\<dots> \<le> F (lfp F)" by (rule monoD[OF mono Suc])
      also have "\<dots> = lfp F" by (simp add: lfp_fixpoint[OF mono])
      finally show ?case .
    qed simp
  qed
  show "lfp F \<le> ?U"
  proof (rule lfp_lowerbound)
    have "mono (\<lambda>i::nat. (F ^^ i) bot)"
    proof -
      { fix i::nat have "(F ^^ i) bot \<le> (F ^^ (Suc i)) bot"
        proof (induct i)
          case 0 show ?case by simp
        next
          case Suc thus ?case using monoD[OF mono Suc] by auto
        qed }
      thus ?thesis by (auto simp add: mono_iff_le_Suc)
    qed
    hence "F ?U = (SUP i. (F ^^ Suc i) bot)"
      using \<open>sup_continuous F\<close> by (simp add: sup_continuous_def)
    also have "\<dots> \<le> ?U"
      by (fast intro: SUP_least SUP_upper)
    finally show "F ?U \<le> ?U" .
  qed
qed

lemma lfp_transfer_bounded:
  assumes P: "P bot" "\<And>x. P x \<Longrightarrow> P (f x)" "\<And>M. (\<And>i. P (M i)) \<Longrightarrow> P (SUP i::nat. M i)"
  assumes \<alpha>: "\<And>M. mono M \<Longrightarrow> (\<And>i::nat. P (M i)) \<Longrightarrow> \<alpha> (SUP i. M i) = (SUP i. \<alpha> (M i))"
  assumes f: "sup_continuous f" and g: "sup_continuous g"
  assumes [simp]: "\<And>x. P x \<Longrightarrow> x \<le> lfp f \<Longrightarrow> \<alpha> (f x) = g (\<alpha> x)"
  assumes g_bound: "\<And>x. \<alpha> bot \<le> g x"
  shows "\<alpha> (lfp f) = lfp g"
proof (rule antisym)
  note mono_g = sup_continuous_mono[OF g]
  note mono_f = sup_continuous_mono[OF f]
  have lfp_bound: "\<alpha> bot \<le> lfp g"
    by (subst lfp_unfold[OF mono_g]) (rule g_bound)

  have P_pow: "P ((f ^^ i) bot)" for i
    by (induction i) (auto intro!: P)
  have incseq_pow: "mono (\<lambda>i. (f ^^ i) bot)"
    unfolding mono_iff_le_Suc
  proof
    fix i show "(f ^^ i) bot \<le> (f ^^ (Suc i)) bot"
    proof (induct i)
      case Suc thus ?case using monoD[OF sup_continuous_mono[OF f] Suc] by auto
    qed (simp add: le_fun_def)
  qed
  have P_lfp: "P (lfp f)"
    using P_pow unfolding sup_continuous_lfp[OF f] by (auto intro!: P)

  have iter_le_lfp: "(f ^^ n) bot \<le> lfp f" for n
    apply (induction n)
    apply simp
    apply (subst lfp_unfold[OF mono_f])
    apply (auto intro!: monoD[OF mono_f])
    done

  have "\<alpha> (lfp f) = (SUP i. \<alpha> ((f^^i) bot))"
    unfolding sup_continuous_lfp[OF f] using incseq_pow P_pow by (rule \<alpha>)
  also have "\<dots> \<le> lfp g"
  proof (rule SUP_least)
    fix i show "\<alpha> ((f^^i) bot) \<le> lfp g"
    proof (induction i)
      case (Suc n) then show ?case
        by (subst lfp_unfold[OF mono_g]) (simp add: monoD[OF mono_g] P_pow iter_le_lfp)
    qed (simp add: lfp_bound)
  qed
  finally show "\<alpha> (lfp f) \<le> lfp g" .

  show "lfp g \<le> \<alpha> (lfp f)"
  proof (induction rule: lfp_ordinal_induct[OF mono_g])
    case (1 S) then show ?case
      by (subst lfp_unfold[OF sup_continuous_mono[OF f]])
         (simp add: monoD[OF mono_g] P_lfp)
  qed (auto intro: Sup_least)
qed

lemma lfp_transfer:
  "sup_continuous \<alpha> \<Longrightarrow> sup_continuous f \<Longrightarrow> sup_continuous g \<Longrightarrow>
    (\<And>x. \<alpha> bot \<le> g x) \<Longrightarrow> (\<And>x. x \<le> lfp f \<Longrightarrow> \<alpha> (f x) = g (\<alpha> x)) \<Longrightarrow> \<alpha> (lfp f) = lfp g"
  by (rule lfp_transfer_bounded[where P=top]) (auto dest: sup_continuousD)

definition
  inf_continuous :: "('a::countable_complete_lattice \<Rightarrow> 'b::countable_complete_lattice) \<Rightarrow> bool"
where
  "inf_continuous F \<longleftrightarrow> (\<forall>M::nat \<Rightarrow> 'a. antimono M \<longrightarrow> F (INF i. M i) = (INF i. F (M i)))"

lemma inf_continuousD: "inf_continuous F \<Longrightarrow> antimono M \<Longrightarrow> F (INF i::nat. M i) = (INF i. F (M i))"
  by (auto simp: inf_continuous_def)

lemma inf_continuous_mono:
  "mono F" if "inf_continuous F"
proof
  fix A B :: "'a"
  assume "A \<le> B"
  let ?f = "\<lambda>n::nat. if n = 0 then B else A"
  from \<open>A \<le> B\<close> have "decseq ?f"
    by (auto intro: antimonoI)
  with \<open>inf_continuous F\<close> have *: "F (INF i. ?f i) = (INF i. F (?f i))"
    by (auto dest: inf_continuousD)
  from \<open>A \<le> B\<close> have "A = inf B A"
    by (simp add: inf.absorb_iff2)
  then have "F A = F (inf B A)"
    by simp
  also have "\<dots> = inf (F B) (F A)"
    using * by (simp add: if_distrib INF_nat_binary cong del: INF_cong)
  finally show "F A \<le> F B"
    by (simp add: inf.absorb_iff2)
qed

lemma [order_continuous_intros]:
  shows inf_continuous_const: "inf_continuous (\<lambda>x. c)"
    and inf_continuous_id: "inf_continuous (\<lambda>x. x)"
    and inf_continuous_apply: "inf_continuous (\<lambda>f. f x)"
    and inf_continuous_fun: "(\<And>s. inf_continuous (\<lambda>x. P x s)) \<Longrightarrow> inf_continuous P"
    and inf_continuous_If: "inf_continuous F \<Longrightarrow> inf_continuous G \<Longrightarrow> inf_continuous (\<lambda>f. if C then F f else G f)"
  by (auto simp: inf_continuous_def image_comp)

lemma inf_continuous_inf[order_continuous_intros]:
  "inf_continuous f \<Longrightarrow> inf_continuous g \<Longrightarrow> inf_continuous (\<lambda>x. inf (f x) (g x))"
  by (simp add: inf_continuous_def ccINF_inf_distrib)

lemma inf_continuous_sup[order_continuous_intros]:
  fixes P Q :: "'a :: countable_complete_lattice \<Rightarrow> 'b :: countable_complete_distrib_lattice"
  assumes P: "inf_continuous P" and Q: "inf_continuous Q"
  shows "inf_continuous (\<lambda>x. sup (P x) (Q x))"
  unfolding inf_continuous_def
proof (safe intro!: antisym)
  fix M :: "nat \<Rightarrow> 'a" assume M: "decseq M"
  show "sup (P (INF i. M i)) (Q (INF i. M i)) \<le> (INF i. sup (P (M i)) (Q (M i)))"
    unfolding inf_continuousD[OF P M] inf_continuousD[OF Q M] by (intro ccINF_greatest sup_mono ccINF_lower) auto

  have "(INF i. sup (P (M i)) (Q (M i))) \<le> (INF j i. sup (P (M i)) (Q (M j)))"
  proof (intro ccINF_greatest)
    fix i j from M assms[THEN inf_continuous_mono] show "sup (P (M i)) (Q (M j)) \<ge> (INF i. sup (P (M i)) (Q (M i)))"
      by (intro ccINF_lower2[of _ "sup i j"] sup_mono) (auto simp: mono_def antimono_def)
  qed auto
  also have "\<dots> \<le> sup (P (INF i. M i)) (Q (INF i. M i))"
    by (simp add: inf_continuousD[OF P M] inf_continuousD[OF Q M] ccINF_sup sup_ccINF)
  finally show "sup (P (INF i. M i)) (Q (INF i. M i)) \<ge> (INF i. sup (P (M i)) (Q (M i)))" .
qed

lemma inf_continuous_and[order_continuous_intros]:
  "inf_continuous P \<Longrightarrow> inf_continuous Q \<Longrightarrow> inf_continuous (\<lambda>x. P x \<and> Q x)"
  using inf_continuous_inf[of P Q] by simp

lemma inf_continuous_or[order_continuous_intros]:
  "inf_continuous P \<Longrightarrow> inf_continuous Q \<Longrightarrow> inf_continuous (\<lambda>x. P x \<or> Q x)"
  using inf_continuous_sup[of P Q] by simp

lemma inf_continuous_compose:
  assumes f: "inf_continuous f" and g: "inf_continuous g"
  shows "inf_continuous (\<lambda>x. f (g x))"
  unfolding inf_continuous_def
proof safe
  fix M :: "nat \<Rightarrow> 'c"
  assume M: "antimono M"
  then have "antimono (\<lambda>i. g (M i))"
    using inf_continuous_mono[OF g] by (auto simp: mono_def antimono_def)
  with M show "f (g (Inf (M ` UNIV))) = (INF i. f (g (M i)))"
    by (auto simp: inf_continuous_def g[THEN inf_continuousD] f[THEN inf_continuousD])
qed

lemma inf_continuous_gfp:
  assumes "inf_continuous F" shows "gfp F = (INF i. (F ^^ i) top)" (is "gfp F = ?U")
proof (rule antisym)
  note mono = inf_continuous_mono[OF \<open>inf_continuous F\<close>]
  show "gfp F \<le> ?U"
  proof (rule INF_greatest)
    fix i show "gfp F \<le> (F ^^ i) top"
    proof (induct i)
      case (Suc i)
      have "gfp F = F (gfp F)" by (simp add: gfp_fixpoint[OF mono])
      also have "\<dots> \<le> F ((F ^^ i) top)" by (rule monoD[OF mono Suc])
      also have "\<dots> = (F ^^ Suc i) top" by simp
      finally show ?case .
    qed simp
  qed
  show "?U \<le> gfp F"
  proof (rule gfp_upperbound)
    have *: "antimono (\<lambda>i::nat. (F ^^ i) top)"
    proof -
      { fix i::nat have "(F ^^ Suc i) top \<le> (F ^^ i) top"
        proof (induct i)
          case 0 show ?case by simp
        next
          case Suc thus ?case using monoD[OF mono Suc] by auto
        qed }
      thus ?thesis by (auto simp add: antimono_iff_le_Suc)
    qed
    have "?U \<le> (INF i. (F ^^ Suc i) top)"
      by (fast intro: INF_greatest INF_lower)
    also have "\<dots> \<le> F ?U"
      by (simp add: inf_continuousD \<open>inf_continuous F\<close> *)
    finally show "?U \<le> F ?U" .
  qed
qed

lemma gfp_transfer:
  assumes \<alpha>: "inf_continuous \<alpha>" and f: "inf_continuous f" and g: "inf_continuous g"
  assumes [simp]: "\<alpha> top = top" "\<And>x. \<alpha> (f x) = g (\<alpha> x)"
  shows "\<alpha> (gfp f) = gfp g"
proof -
  have "\<alpha> (gfp f) = (INF i. \<alpha> ((f^^i) top))"
    unfolding inf_continuous_gfp[OF f] by (intro f \<alpha> inf_continuousD antimono_funpow inf_continuous_mono)
  moreover have "\<alpha> ((f^^i) top) = (g^^i) top" for i
    by (induction i; simp)
  ultimately show ?thesis
    unfolding inf_continuous_gfp[OF g] by simp
qed

lemma gfp_transfer_bounded:
  assumes P: "P (f top)" "\<And>x. P x \<Longrightarrow> P (f x)" "\<And>M. antimono M \<Longrightarrow> (\<And>i. P (M i)) \<Longrightarrow> P (INF i::nat. M i)"
  assumes \<alpha>: "\<And>M. antimono M \<Longrightarrow> (\<And>i::nat. P (M i)) \<Longrightarrow> \<alpha> (INF i. M i) = (INF i. \<alpha> (M i))"
  assumes f: "inf_continuous f" and g: "inf_continuous g"
  assumes [simp]: "\<And>x. P x \<Longrightarrow> \<alpha> (f x) = g (\<alpha> x)"
  assumes g_bound: "\<And>x. g x \<le> \<alpha> (f top)"
  shows "\<alpha> (gfp f) = gfp g"
proof (rule antisym)
  note mono_g = inf_continuous_mono[OF g]

  have P_pow: "P ((f ^^ i) (f top))" for i
    by (induction i) (auto intro!: P)

  have antimono_pow: "antimono (\<lambda>i. (f ^^ i) top)"
    unfolding antimono_iff_le_Suc
  proof
    fix i show "(f ^^ Suc i) top \<le> (f ^^ i) top"
    proof (induct i)
      case Suc thus ?case using monoD[OF inf_continuous_mono[OF f] Suc] by auto
    qed (simp add: le_fun_def)
  qed
  have antimono_pow2: "antimono (\<lambda>i. (f ^^ i) (f top))"
  proof
    show "x \<le> y \<Longrightarrow> (f ^^ y) (f top) \<le> (f ^^ x) (f top)" for x y
      using antimono_pow[THEN antimonoD, of "Suc x" "Suc y"]
      unfolding funpow_Suc_right by simp
  qed

  have gfp_f: "gfp f = (INF i. (f ^^ i) (f top))"
    unfolding inf_continuous_gfp[OF f]
  proof (rule INF_eq)
    show "\<exists>j\<in>UNIV. (f ^^ j) (f top) \<le> (f ^^ i) top" for i
      by (intro bexI[of _ "i - 1"]) (auto simp: diff_Suc funpow_Suc_right simp del: funpow.simps(2) split: nat.split)
    show "\<exists>j\<in>UNIV. (f ^^ j) top \<le> (f ^^ i) (f top)" for i
      by (intro bexI[of _ "Suc i"]) (auto simp: funpow_Suc_right simp del: funpow.simps(2))
  qed

  have P_lfp: "P (gfp f)"
    unfolding gfp_f by (auto intro!: P P_pow antimono_pow2)

  have "\<alpha> (gfp f) = (INF i. \<alpha> ((f^^i) (f top)))"
    unfolding gfp_f by (rule \<alpha>) (auto intro!: P_pow antimono_pow2)
  also have "\<dots> \<ge> gfp g"
  proof (rule INF_greatest)
    fix i show "gfp g \<le> \<alpha> ((f^^i) (f top))"
    proof (induction i)
      case (Suc n) then show ?case
        by (subst gfp_unfold[OF mono_g]) (simp add: monoD[OF mono_g] P_pow)
    next
      case 0
      have "gfp g \<le> \<alpha> (f top)"
        by (subst gfp_unfold[OF mono_g]) (rule g_bound)
      then show ?case
        by simp
    qed
  qed
  finally show "gfp g \<le> \<alpha> (gfp f)" .

  show "\<alpha> (gfp f) \<le> gfp g"
  proof (induction rule: gfp_ordinal_induct[OF mono_g])
    case (1 S) then show ?case
      by (subst gfp_unfold[OF inf_continuous_mono[OF f]])
         (simp add: monoD[OF mono_g] P_lfp)
  qed (auto intro: Inf_greatest)
qed

subsubsection \<open>Least fixed points in countable complete lattices\<close>

definition (in countable_complete_lattice) cclfp :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a"
  where "cclfp f = (SUP i. (f ^^ i) bot)"

lemma cclfp_unfold:
  assumes "sup_continuous F" shows "cclfp F = F (cclfp F)"
proof -
  have "cclfp F = (SUP i. F ((F ^^ i) bot))"
    unfolding cclfp_def
    by (subst UNIV_nat_eq) (simp add: image_comp)
  also have "\<dots> = F (cclfp F)"
    unfolding cclfp_def
    by (intro sup_continuousD[symmetric] assms mono_funpow sup_continuous_mono)
  finally show ?thesis .
qed

lemma cclfp_lowerbound: assumes f: "mono f" and A: "f A \<le> A" shows "cclfp f \<le> A"
  unfolding cclfp_def
proof (intro ccSUP_least)
  fix i show "(f ^^ i) bot \<le> A"
  proof (induction i)
    case (Suc i) from monoD[OF f this] A show ?case
      by auto
  qed simp
qed simp

lemma cclfp_transfer:
  assumes "sup_continuous \<alpha>" "mono f"
  assumes "\<alpha> bot = bot" "\<And>x. \<alpha> (f x) = g (\<alpha> x)"
  shows "\<alpha> (cclfp f) = cclfp g"
proof -
  have "\<alpha> (cclfp f) = (SUP i. \<alpha> ((f ^^ i) bot))"
    unfolding cclfp_def by (intro sup_continuousD assms mono_funpow sup_continuous_mono)
  moreover have "\<alpha> ((f ^^ i) bot) = (g ^^ i) bot" for i
    by (induction i) (simp_all add: assms)
  ultimately show ?thesis
    by (simp add: cclfp_def)
qed

end


(* Author: Amine Chaieb, TU Muenchen *)

section{*Fundamental Theorem of Algebra*}

theory Fundamental_Theorem_Algebra
imports Polynomial Complex_Main
begin

subsection {* More lemmas about module of complex numbers *}

text{* The triangle inequality for cmod *}
lemma complex_mod_triangle_sub: "cmod w \<le> cmod (w + z) + norm z"
  using complex_mod_triangle_ineq2[of "w + z" "-z"] by auto

subsection {* Basic lemmas about polynomials *}

lemma poly_bound_exists:
  fixes p :: "'a::{comm_semiring_0,real_normed_div_algebra} poly"
  shows "\<exists>m. m > 0 \<and> (\<forall>z. norm z \<le> r \<longrightarrow> norm (poly p z) \<le> m)"
proof (induct p)
  case 0
  then show ?case by (rule exI[where x=1]) simp
next
  case (pCons c cs)
  from pCons.hyps obtain m where m: "\<forall>z. norm z \<le> r \<longrightarrow> norm (poly cs z) \<le> m"
    by blast
  let ?k = " 1 + norm c + \<bar>r * m\<bar>"
  have kp: "?k > 0"
    using abs_ge_zero[of "r*m"] norm_ge_zero[of c] by arith
  {
    fix z :: 'a
    assume H: "norm z \<le> r"
    from m H have th: "norm (poly cs z) \<le> m"
      by blast
    from H have rp: "r \<ge> 0"
      using norm_ge_zero[of z] by arith
    have "norm (poly (pCons c cs) z) \<le> norm c + norm (z * poly cs z)"
      using norm_triangle_ineq[of c "z* poly cs z"] by simp
    also have "\<dots> \<le> norm c + r * m"
      using mult_mono[OF H th rp norm_ge_zero[of "poly cs z"]]
      by (simp add: norm_mult)
    also have "\<dots> \<le> ?k"
      by simp
    finally have "norm (poly (pCons c cs) z) \<le> ?k" .
  }
  with kp show ?case by blast
qed

text{* Offsetting the variable in a polynomial gives another of same degree *}

definition offset_poly :: "'a::comm_semiring_0 poly \<Rightarrow> 'a \<Rightarrow> 'a poly"
  where "offset_poly p h = fold_coeffs (\<lambda>a q. smult h q + pCons a q) p 0"

lemma offset_poly_0: "offset_poly 0 h = 0"
  by (simp add: offset_poly_def)

lemma offset_poly_pCons:
  "offset_poly (pCons a p) h =
    smult h (offset_poly p h) + pCons a (offset_poly p h)"
  by (cases "p = 0 \<and> a = 0") (auto simp add: offset_poly_def)

lemma offset_poly_single: "offset_poly [:a:] h = [:a:]"
  by (simp add: offset_poly_pCons offset_poly_0)

lemma poly_offset_poly: "poly (offset_poly p h) x = poly p (h + x)"
  apply (induct p)
  apply (simp add: offset_poly_0)
  apply (simp add: offset_poly_pCons algebra_simps)
  done

lemma offset_poly_eq_0_lemma: "smult c p + pCons a p = 0 \<Longrightarrow> p = 0"
  by (induct p arbitrary: a) (simp, force)

lemma offset_poly_eq_0_iff: "offset_poly p h = 0 \<longleftrightarrow> p = 0"
  apply (safe intro!: offset_poly_0)
  apply (induct p)
  apply simp
  apply (simp add: offset_poly_pCons)
  apply (frule offset_poly_eq_0_lemma, simp)
  done

lemma degree_offset_poly: "degree (offset_poly p h) = degree p"
  apply (induct p)
  apply (simp add: offset_poly_0)
  apply (case_tac "p = 0")
  apply (simp add: offset_poly_0 offset_poly_pCons)
  apply (simp add: offset_poly_pCons)
  apply (subst degree_add_eq_right)
  apply (rule le_less_trans [OF degree_smult_le])
  apply (simp add: offset_poly_eq_0_iff)
  apply (simp add: offset_poly_eq_0_iff)
  done

definition "psize p = (if p = 0 then 0 else Suc (degree p))"

lemma psize_eq_0_iff [simp]: "psize p = 0 \<longleftrightarrow> p = 0"
  unfolding psize_def by simp

lemma poly_offset:
  fixes p :: "'a::comm_ring_1 poly"
  shows "\<exists>q. psize q = psize p \<and> (\<forall>x. poly q x = poly p (a + x))"
proof (intro exI conjI)
  show "psize (offset_poly p a) = psize p"
    unfolding psize_def
    by (simp add: offset_poly_eq_0_iff degree_offset_poly)
  show "\<forall>x. poly (offset_poly p a) x = poly p (a + x)"
    by (simp add: poly_offset_poly)
qed

text{* An alternative useful formulation of completeness of the reals *}
lemma real_sup_exists:
  assumes ex: "\<exists>x. P x"
    and bz: "\<exists>z. \<forall>x. P x \<longrightarrow> x < z"
  shows "\<exists>s::real. \<forall>y. (\<exists>x. P x \<and> y < x) \<longleftrightarrow> y < s"
proof
  from bz have "bdd_above (Collect P)"
    by (force intro: less_imp_le)
  then show "\<forall>y. (\<exists>x. P x \<and> y < x) \<longleftrightarrow> y < Sup (Collect P)"
    using ex bz by (subst less_cSup_iff) auto
qed

subsection {* Fundamental theorem of algebra *}
lemma  unimodular_reduce_norm:
  assumes md: "cmod z = 1"
  shows "cmod (z + 1) < 1 \<or> cmod (z - 1) < 1 \<or> cmod (z + ii) < 1 \<or> cmod (z - ii) < 1"
proof -
  obtain x y where z: "z = Complex x y "
    by (cases z) auto
  from md z have xy: "x\<^sup>2 + y\<^sup>2 = 1"
    by (simp add: cmod_def)
  {
    assume C: "cmod (z + 1) \<ge> 1" "cmod (z - 1) \<ge> 1" "cmod (z + ii) \<ge> 1" "cmod (z - ii) \<ge> 1"
    from C z xy have "2 * x \<le> 1" "2 * x \<ge> -1" "2 * y \<le> 1" "2 * y \<ge> -1"
      by (simp_all add: cmod_def power2_eq_square algebra_simps)
    then have "abs (2 * x) \<le> 1" "abs (2 * y) \<le> 1"
      by simp_all
    then have "(abs (2 * x))\<^sup>2 \<le> 1\<^sup>2" "(abs (2 * y))\<^sup>2 \<le> 1\<^sup>2"
      by - (rule power_mono, simp, simp)+
    then have th0: "4 * x\<^sup>2 \<le> 1" "4 * y\<^sup>2 \<le> 1"
      by (simp_all add: power_mult_distrib)
    from add_mono[OF th0] xy have False by simp
  }
  then show ?thesis
    unfolding linorder_not_le[symmetric] by blast
qed

text{* Hence we can always reduce modulus of @{text "1 + b z^n"} if nonzero *}
lemma reduce_poly_simple:
  assumes b: "b \<noteq> 0"
    and n: "n \<noteq> 0"
  shows "\<exists>z. cmod (1 + b * z^n) < 1"
  using n
proof (induct n rule: nat_less_induct)
  fix n
  assume IH: "\<forall>m<n. m \<noteq> 0 \<longrightarrow> (\<exists>z. cmod (1 + b * z ^ m) < 1)"
  assume n: "n \<noteq> 0"
  let ?P = "\<lambda>z n. cmod (1 + b * z ^ n) < 1"
  {
    assume e: "even n"
    then have "\<exists>m. n = 2 * m"
      by presburger
    then obtain m where m: "n = 2 * m"
      by blast
    from n m have "m \<noteq> 0" "m < n"
      by presburger+
    with IH[rule_format, of m] obtain z where z: "?P z m"
      by blast
    from z have "?P (csqrt z) n"
      by (simp add: m power_mult power2_csqrt)
    then have "\<exists>z. ?P z n" ..
  }
  moreover
  {
    assume o: "odd n"
    have th0: "cmod (complex_of_real (cmod b) / b) = 1"
      using b by (simp add: norm_divide)
    from o have "\<exists>m. n = Suc (2 * m)"
      by presburger+
    then obtain m where m: "n = Suc (2 * m)"
      by blast
    from unimodular_reduce_norm[OF th0] o
    have "\<exists>v. cmod (complex_of_real (cmod b) / b + v^n) < 1"
      apply (cases "cmod (complex_of_real (cmod b) / b + 1) < 1")
      apply (rule_tac x="1" in exI)
      apply simp
      apply (cases "cmod (complex_of_real (cmod b) / b - 1) < 1")
      apply (rule_tac x="-1" in exI)
      apply simp
      apply (cases "cmod (complex_of_real (cmod b) / b + ii) < 1")
      apply (cases "even m")
      apply (rule_tac x="ii" in exI)
      apply (simp add: m power_mult)
      apply (rule_tac x="- ii" in exI)
      apply (simp add: m power_mult)
      apply (cases "even m")
      apply (rule_tac x="- ii" in exI)
      apply (simp add: m power_mult)
      apply (auto simp add: m power_mult)
      apply (rule_tac x="ii" in exI)
      apply (auto simp add: m power_mult)
      done
    then obtain v where v: "cmod (complex_of_real (cmod b) / b + v^n) < 1"
      by blast
    let ?w = "v / complex_of_real (root n (cmod b))"
    from odd_real_root_pow[OF o, of "cmod b"]
    have th1: "?w ^ n = v^n / complex_of_real (cmod b)"
      by (simp add: power_divide of_real_power[symmetric])
    have th2:"cmod (complex_of_real (cmod b) / b) = 1"
      using b by (simp add: norm_divide)
    then have th3: "cmod (complex_of_real (cmod b) / b) \<ge> 0"
      by simp
    have th4: "cmod (complex_of_real (cmod b) / b) *
        cmod (1 + b * (v ^ n / complex_of_real (cmod b))) <
        cmod (complex_of_real (cmod b) / b) * 1"
      apply (simp only: norm_mult[symmetric] distrib_left)
      using b v
      apply (simp add: th2)
      done
    from mult_less_imp_less_left[OF th4 th3]
    have "?P ?w n" unfolding th1 .
    then have "\<exists>z. ?P z n" ..
  }
  ultimately show "\<exists>z. ?P z n" by blast
qed

text{* Bolzano-Weierstrass type property for closed disc in complex plane. *}

lemma metric_bound_lemma: "cmod (x - y) \<le> \<bar>Re x - Re y\<bar> + \<bar>Im x - Im y\<bar>"
  using real_sqrt_sum_squares_triangle_ineq[of "Re x - Re y" 0 0 "Im x - Im y"]
  unfolding cmod_def by simp

lemma bolzano_weierstrass_complex_disc:
  assumes r: "\<forall>n. cmod (s n) \<le> r"
  shows "\<exists>f z. subseq f \<and> (\<forall>e >0. \<exists>N. \<forall>n \<ge> N. cmod (s (f n) - z) < e)"
proof-
  from seq_monosub[of "Re \<circ> s"]
  obtain f where f: "subseq f" "monoseq (\<lambda>n. Re (s (f n)))"
    unfolding o_def by blast
  from seq_monosub[of "Im \<circ> s \<circ> f"]
  obtain g where g: "subseq g" "monoseq (\<lambda>n. Im (s (f (g n))))"
    unfolding o_def by blast
  let ?h = "f \<circ> g"
  from r[rule_format, of 0] have rp: "r \<ge> 0"
    using norm_ge_zero[of "s 0"] by arith
  have th: "\<forall>n. r + 1 \<ge> \<bar>Re (s n)\<bar>"
  proof
    fix n
    from abs_Re_le_cmod[of "s n"] r[rule_format, of n]
    show "\<bar>Re (s n)\<bar> \<le> r + 1" by arith
  qed
  have conv1: "convergent (\<lambda>n. Re (s (f n)))"
    apply (rule Bseq_monoseq_convergent)
    apply (simp add: Bseq_def)
    apply (metis gt_ex le_less_linear less_trans order.trans th)
    apply (rule f(2))
    done
  have th: "\<forall>n. r + 1 \<ge> \<bar>Im (s n)\<bar>"
  proof
    fix n
    from abs_Im_le_cmod[of "s n"] r[rule_format, of n]
    show "\<bar>Im (s n)\<bar> \<le> r + 1"
      by arith
  qed

  have conv2: "convergent (\<lambda>n. Im (s (f (g n))))"
    apply (rule Bseq_monoseq_convergent)
    apply (simp add: Bseq_def)
    apply (metis gt_ex le_less_linear less_trans order.trans th)
    apply (rule g(2))
    done

  from conv1[unfolded convergent_def] obtain x where "LIMSEQ (\<lambda>n. Re (s (f n))) x"
    by blast
  then have x: "\<forall>r>0. \<exists>n0. \<forall>n\<ge>n0. \<bar>Re (s (f n)) - x\<bar> < r"
    unfolding LIMSEQ_iff real_norm_def .

  from conv2[unfolded convergent_def] obtain y where "LIMSEQ (\<lambda>n. Im (s (f (g n)))) y"
    by blast
  then have y: "\<forall>r>0. \<exists>n0. \<forall>n\<ge>n0. \<bar>Im (s (f (g n))) - y\<bar> < r"
    unfolding LIMSEQ_iff real_norm_def .
  let ?w = "Complex x y"
  from f(1) g(1) have hs: "subseq ?h"
    unfolding subseq_def by auto
  {
    fix e :: real
    assume ep: "e > 0"
    then have e2: "e/2 > 0"
      by simp
    from x[rule_format, OF e2] y[rule_format, OF e2]
    obtain N1 N2 where N1: "\<forall>n\<ge>N1. \<bar>Re (s (f n)) - x\<bar> < e / 2"
      and N2: "\<forall>n\<ge>N2. \<bar>Im (s (f (g n))) - y\<bar> < e / 2"
      by blast
    {
      fix n
      assume nN12: "n \<ge> N1 + N2"
      then have nN1: "g n \<ge> N1" and nN2: "n \<ge> N2"
        using seq_suble[OF g(1), of n] by arith+
      from add_strict_mono[OF N1[rule_format, OF nN1] N2[rule_format, OF nN2]]
      have "cmod (s (?h n) - ?w) < e"
        using metric_bound_lemma[of "s (f (g n))" ?w] by simp
    }
    then have "\<exists>N. \<forall>n\<ge>N. cmod (s (?h n) - ?w) < e"
      by blast
  }
  with hs show ?thesis by blast
qed

text{* Polynomial is continuous. *}

lemma poly_cont:
  fixes p :: "'a::{comm_semiring_0,real_normed_div_algebra} poly"
  assumes ep: "e > 0"
  shows "\<exists>d >0. \<forall>w. 0 < norm (w - z) \<and> norm (w - z) < d \<longrightarrow> norm (poly p w - poly p z) < e"
proof -
  obtain q where q: "degree q = degree p" "\<And>x. poly q x = poly p (z + x)"
  proof
    show "degree (offset_poly p z) = degree p"
      by (rule degree_offset_poly)
    show "\<And>x. poly (offset_poly p z) x = poly p (z + x)"
      by (rule poly_offset_poly)
  qed
  have th: "\<And>w. poly q (w - z) = poly p w"
    using q(2)[of "w - z" for w] by simp
  show ?thesis unfolding th[symmetric]
  proof (induct q)
    case 0
    then show ?case
      using ep by auto
  next
    case (pCons c cs)
    from poly_bound_exists[of 1 "cs"]
    obtain m where m: "m > 0" "\<And>z. norm z \<le> 1 \<Longrightarrow> norm (poly cs z) \<le> m"
      by blast
    from ep m(1) have em0: "e/m > 0"
      by (simp add: field_simps)
    have one0: "1 > (0::real)"
      by arith
    from real_lbound_gt_zero[OF one0 em0]
    obtain d where d: "d > 0" "d < 1" "d < e / m"
      by blast
    from d(1,3) m(1) have dm: "d * m > 0" "d * m < e"
      by (simp_all add: field_simps)
    show ?case
    proof (rule ex_forward[OF real_lbound_gt_zero[OF one0 em0]], clarsimp simp add: norm_mult)
      fix d w
      assume H: "d > 0" "d < 1" "d < e/m" "w \<noteq> z" "norm (w - z) < d"
      then have d1: "norm (w-z) \<le> 1" "d \<ge> 0"
        by simp_all
      from H(3) m(1) have dme: "d*m < e"
        by (simp add: field_simps)
      from H have th: "norm (w - z) \<le> d"
        by simp
      from mult_mono[OF th m(2)[OF d1(1)] d1(2) norm_ge_zero] dme
      show "norm (w - z) * norm (poly cs (w - z)) < e"
        by simp
    qed
  qed
qed

text{* Hence a polynomial attains minimum on a closed disc
  in the complex plane. *}
lemma poly_minimum_modulus_disc: "\<exists>z. \<forall>w. cmod w \<le> r \<longrightarrow> cmod (poly p z) \<le> cmod (poly p w)"
proof -
  {
    assume "\<not> r \<ge> 0"
    then have ?thesis
      by (metis norm_ge_zero order.trans)
  }
  moreover
  {
    assume rp: "r \<ge> 0"
    from rp have "cmod 0 \<le> r \<and> cmod (poly p 0) = - (- cmod (poly p 0))"
      by simp
    then have mth1: "\<exists>x z. cmod z \<le> r \<and> cmod (poly p z) = - x"
      by blast
    {
      fix x z
      assume H: "cmod z \<le> r" "cmod (poly p z) = - x" "\<not> x < 1"
      then have "- x < 0 "
        by arith
      with H(2) norm_ge_zero[of "poly p z"] have False
        by simp
    }
    then have mth2: "\<exists>z. \<forall>x. (\<exists>z. cmod z \<le> r \<and> cmod (poly p z) = - x) \<longrightarrow> x < z"
      by blast
    from real_sup_exists[OF mth1 mth2] obtain s where
      s: "\<forall>y. (\<exists>x. (\<exists>z. cmod z \<le> r \<and> cmod (poly p z) = - x) \<and> y < x) \<longleftrightarrow> y < s" by blast
    let ?m = "- s"
    {
      fix y
      from s[rule_format, of "-y"]
      have "(\<exists>z x. cmod z \<le> r \<and> - (- cmod (poly p z)) < y) \<longleftrightarrow> ?m < y"
        unfolding minus_less_iff[of y ] equation_minus_iff by blast
    }
    note s1 = this[unfolded minus_minus]
    from s1[of ?m] have s1m: "\<And>z x. cmod z \<le> r \<Longrightarrow> cmod (poly p z) \<ge> ?m"
      by auto
    {
      fix n :: nat
      from s1[rule_format, of "?m + 1/real (Suc n)"]
      have "\<exists>z. cmod z \<le> r \<and> cmod (poly p z) < - s + 1 / real (Suc n)"
        by simp
    }
    then have th: "\<forall>n. \<exists>z. cmod z \<le> r \<and> cmod (poly p z) < - s + 1 / real (Suc n)" ..
    from choice[OF th] obtain g where
        g: "\<forall>n. cmod (g n) \<le> r" "\<forall>n. cmod (poly p (g n)) <?m + 1 /real(Suc n)"
      by blast
    from bolzano_weierstrass_complex_disc[OF g(1)]
    obtain f z where fz: "subseq f" "\<forall>e>0. \<exists>N. \<forall>n\<ge>N. cmod (g (f n) - z) < e"
      by blast
    {
      fix w
      assume wr: "cmod w \<le> r"
      let ?e = "\<bar>cmod (poly p z) - ?m\<bar>"
      {
        assume e: "?e > 0"
        then have e2: "?e/2 > 0"
          by simp
        from poly_cont[OF e2, of z p] obtain d where
            d: "d > 0" "\<forall>w. 0<cmod (w - z)\<and> cmod(w - z) < d \<longrightarrow> cmod(poly p w - poly p z) < ?e/2"
          by blast
        {
          fix w
          assume w: "cmod (w - z) < d"
          have "cmod(poly p w - poly p z) < ?e / 2"
            using d(2)[rule_format, of w] w e by (cases "w = z") simp_all
        }
        note th1 = this

        from fz(2) d(1) obtain N1 where N1: "\<forall>n\<ge>N1. cmod (g (f n) - z) < d"
          by blast
        from reals_Archimedean2[of "2/?e"] obtain N2 :: nat where N2: "2/?e < real N2"
          by blast
        have th2: "cmod (poly p (g (f (N1 + N2))) - poly p z) < ?e/2"
          using N1[rule_format, of "N1 + N2"] th1 by simp
        {
          fix a b e2 m :: real
          have "a < e2 \<Longrightarrow> \<bar>b - m\<bar> < e2 \<Longrightarrow> 2 * e2 \<le> \<bar>b - m\<bar> + a \<Longrightarrow> False"
            by arith
        }
        note th0 = this
        have ath: "\<And>m x e::real. m \<le> x \<Longrightarrow> x < m + e \<Longrightarrow> \<bar>x - m\<bar> < e"
          by arith
        from s1m[OF g(1)[rule_format]] have th31: "?m \<le> cmod(poly p (g (f (N1 + N2))))" .
        from seq_suble[OF fz(1), of "N1 + N2"]
        have th00: "real (Suc (N1 + N2)) \<le> real (Suc (f (N1 + N2)))"
          by simp
        have th000: "0 \<le> (1::real)" "(1::real) \<le> 1" "real (Suc (N1 + N2)) > 0"
          using N2 by auto
        from frac_le[OF th000 th00]
        have th00: "?m + 1 / real (Suc (f (N1 + N2))) \<le> ?m + 1 / real (Suc (N1 + N2))"
          by simp
        from g(2)[rule_format, of "f (N1 + N2)"]
        have th01:"cmod (poly p (g (f (N1 + N2)))) < - s + 1 / real (Suc (f (N1 + N2)))" .
        from order_less_le_trans[OF th01 th00]
        have th32: "cmod (poly p (g (f (N1 + N2)))) < ?m + (1/ real(Suc (N1 + N2)))" .
        from N2 have "2/?e < real (Suc (N1 + N2))"
          by arith
        with e2 less_imp_inverse_less[of "2/?e" "real (Suc (N1 + N2))"]
        have "?e/2 > 1/ real (Suc (N1 + N2))"
          by (simp add: inverse_eq_divide)
        with ath[OF th31 th32]
        have thc1: "\<bar>cmod (poly p (g (f (N1 + N2)))) - ?m\<bar> < ?e/2"
          by arith
        have ath2: "\<And>a b c m::real. \<bar>a - b\<bar> \<le> c \<Longrightarrow> \<bar>b - m\<bar> \<le> \<bar>a - m\<bar> + c"
          by arith
        have th22: "\<bar>cmod (poly p (g (f (N1 + N2)))) - cmod (poly p z)\<bar> \<le>
            cmod (poly p (g (f (N1 + N2))) - poly p z)"
          by (simp add: norm_triangle_ineq3)
        from ath2[OF th22, of ?m]
        have thc2: "2 * (?e/2) \<le>
            \<bar>cmod(poly p (g (f (N1 + N2)))) - ?m\<bar> + cmod (poly p (g (f (N1 + N2))) - poly p z)"
          by simp
        from th0[OF th2 thc1 thc2] have False .
      }
      then have "?e = 0"
        by auto
      then have "cmod (poly p z) = ?m"
        by simp
      with s1m[OF wr] have "cmod (poly p z) \<le> cmod (poly p w)"
        by simp
    }
    then have ?thesis by blast
  }
  ultimately show ?thesis by blast
qed

text {* Nonzero polynomial in z goes to infinity as z does. *}

lemma poly_infinity:
  fixes p:: "'a::{comm_semiring_0,real_normed_div_algebra} poly"
  assumes ex: "p \<noteq> 0"
  shows "\<exists>r. \<forall>z. r \<le> norm z \<longrightarrow> d \<le> norm (poly (pCons a p) z)"
  using ex
proof (induct p arbitrary: a d)
  case 0
  then show ?case by simp
next
  case (pCons c cs a d)
  show ?case
  proof (cases "cs = 0")
    case False
    with pCons.hyps obtain r where r: "\<forall>z. r \<le> norm z \<longrightarrow> d + norm a \<le> norm (poly (pCons c cs) z)"
      by blast
    let ?r = "1 + \<bar>r\<bar>"
    {
      fix z :: 'a
      assume h: "1 + \<bar>r\<bar> \<le> norm z"
      have r0: "r \<le> norm z"
        using h by arith
      from r[rule_format, OF r0] have th0: "d + norm a \<le> 1 * norm(poly (pCons c cs) z)"
        by arith
      from h have z1: "norm z \<ge> 1"
        by arith
      from order_trans[OF th0 mult_right_mono[OF z1 norm_ge_zero[of "poly (pCons c cs) z"]]]
      have th1: "d \<le> norm(z * poly (pCons c cs) z) - norm a"
        unfolding norm_mult by (simp add: algebra_simps)
      from norm_diff_ineq[of "z * poly (pCons c cs) z" a]
      have th2: "norm (z * poly (pCons c cs) z) - norm a \<le> norm (poly (pCons a (pCons c cs)) z)"
        by (simp add: algebra_simps)
      from th1 th2 have "d \<le> norm (poly (pCons a (pCons c cs)) z)"
        by arith
    }
    then show ?thesis by blast
  next
    case True
    with pCons.prems have c0: "c \<noteq> 0"
      by simp
    {
      fix z :: 'a
      assume h: "(\<bar>d\<bar> + norm a) / norm c \<le> norm z"
      from c0 have "norm c > 0"
        by simp
      from h c0 have th0: "\<bar>d\<bar> + norm a \<le> norm (z * c)"
        by (simp add: field_simps norm_mult)
      have ath: "\<And>mzh mazh ma. mzh \<le> mazh + ma \<Longrightarrow> \<bar>d\<bar> + ma \<le> mzh \<Longrightarrow> d \<le> mazh"
        by arith
      from norm_diff_ineq[of "z * c" a] have th1: "norm (z * c) \<le> norm (a + z * c) + norm a"
        by (simp add: algebra_simps)
      from ath[OF th1 th0] have "d \<le> norm (poly (pCons a (pCons c cs)) z)"
        using True by simp
    }
    then show ?thesis by blast
  qed
qed

text {* Hence polynomial's modulus attains its minimum somewhere. *}
lemma poly_minimum_modulus: "\<exists>z.\<forall>w. cmod (poly p z) \<le> cmod (poly p w)"
proof (induct p)
  case 0
  then show ?case by simp
next
  case (pCons c cs)
  show ?case
  proof (cases "cs = 0")
    case False
    from poly_infinity[OF False, of "cmod (poly (pCons c cs) 0)" c]
    obtain r where r: "\<And>z. r \<le> cmod z \<Longrightarrow> cmod (poly (pCons c cs) 0) \<le> cmod (poly (pCons c cs) z)"
      by blast
    have ath: "\<And>z r. r \<le> cmod z \<or> cmod z \<le> \<bar>r\<bar>"
      by arith
    from poly_minimum_modulus_disc[of "\<bar>r\<bar>" "pCons c cs"]
    obtain v where v: "\<And>w. cmod w \<le> \<bar>r\<bar> \<Longrightarrow> cmod (poly (pCons c cs) v) \<le> cmod (poly (pCons c cs) w)"
      by blast
    {
      fix z
      assume z: "r \<le> cmod z"
      from v[of 0] r[OF z] have "cmod (poly (pCons c cs) v) \<le> cmod (poly (pCons c cs) z)"
        by simp
    }
    note v0 = this
    from v0 v ath[of r] show ?thesis
      by blast
  next
    case True
    with pCons.hyps show ?thesis by simp
  qed
qed

text{* Constant function (non-syntactic characterization). *}
definition "constant f \<longleftrightarrow> (\<forall>x y. f x = f y)"

lemma nonconstant_length: "\<not> constant (poly p) \<Longrightarrow> psize p \<ge> 2"
  by (induct p) (auto simp: constant_def psize_def)

lemma poly_replicate_append: "poly (monom 1 n * p) (x::'a::comm_ring_1) = x^n * poly p x"
  by (simp add: poly_monom)

text {* Decomposition of polynomial, skipping zero coefficients
  after the first.  *}

lemma poly_decompose_lemma:
  assumes nz: "\<not> (\<forall>z. z \<noteq> 0 \<longrightarrow> poly p z = (0::'a::idom))"
  shows "\<exists>k a q. a \<noteq> 0 \<and> Suc (psize q + k) = psize p \<and> (\<forall>z. poly p z = z^k * poly (pCons a q) z)"
  unfolding psize_def
  using nz
proof (induct p)
  case 0
  then show ?case by simp
next
  case (pCons c cs)
  show ?case
  proof (cases "c = 0")
    case True
    from pCons.hyps pCons.prems True show ?thesis
      apply (auto)
      apply (rule_tac x="k+1" in exI)
      apply (rule_tac x="a" in exI, clarsimp)
      apply (rule_tac x="q" in exI)
      apply auto
      done
  next
    case False
    show ?thesis
      apply (rule exI[where x=0])
      apply (rule exI[where x=c], auto simp add: False)
      done
  qed
qed

lemma poly_decompose:
  assumes nc: "\<not> constant (poly p)"
  shows "\<exists>k a q. a \<noteq> (0::'a::idom) \<and> k \<noteq> 0 \<and>
               psize q + k + 1 = psize p \<and>
              (\<forall>z. poly p z = poly p 0 + z^k * poly (pCons a q) z)"
  using nc
proof (induct p)
  case 0
  then show ?case
    by (simp add: constant_def)
next
  case (pCons c cs)
  {
    assume C: "\<forall>z. z \<noteq> 0 \<longrightarrow> poly cs z = 0"
    {
      fix x y
      from C have "poly (pCons c cs) x = poly (pCons c cs) y"
        by (cases "x = 0") auto
    }
    with pCons.prems have False
      by (auto simp add: constant_def)
  }
  then have th: "\<not> (\<forall>z. z \<noteq> 0 \<longrightarrow> poly cs z = 0)" ..
  from poly_decompose_lemma[OF th]
  show ?case
    apply clarsimp
    apply (rule_tac x="k+1" in exI)
    apply (rule_tac x="a" in exI)
    apply simp
    apply (rule_tac x="q" in exI)
    apply (auto simp add: psize_def split: if_splits)
    done
qed

text{* Fundamental theorem of algebra *}

lemma fundamental_theorem_of_algebra:
  assumes nc: "\<not> constant (poly p)"
  shows "\<exists>z::complex. poly p z = 0"
  using nc
proof (induct "psize p" arbitrary: p rule: less_induct)
  case less
  let ?p = "poly p"
  let ?ths = "\<exists>z. ?p z = 0"

  from nonconstant_length[OF less(2)] have n2: "psize p \<ge> 2" .
  from poly_minimum_modulus obtain c where c: "\<forall>w. cmod (?p c) \<le> cmod (?p w)"
    by blast

  show ?ths
  proof (cases "?p c = 0")
    case True
    then show ?thesis by blast
  next
    case False
    note pc0 = this
    from poly_offset[of p c] obtain q where q: "psize q = psize p" "\<forall>x. poly q x = ?p (c + x)"
      by blast
    {
      assume h: "constant (poly q)"
      from q(2) have th: "\<forall>x. poly q (x - c) = ?p x"
        by auto
      {
        fix x y
        from th have "?p x = poly q (x - c)"
          by auto
        also have "\<dots> = poly q (y - c)"
          using h unfolding constant_def by blast
        also have "\<dots> = ?p y"
          using th by auto
        finally have "?p x = ?p y" .
      }
      with less(2) have False
        unfolding constant_def by blast
    }
    then have qnc: "\<not> constant (poly q)"
      by blast
    from q(2) have pqc0: "?p c = poly q 0"
      by simp
    from c pqc0 have cq0: "\<forall>w. cmod (poly q 0) \<le> cmod (?p w)"
      by simp
    let ?a0 = "poly q 0"
    from pc0 pqc0 have a00: "?a0 \<noteq> 0"
      by simp
    from a00 have qr: "\<forall>z. poly q z = poly (smult (inverse ?a0) q) z * ?a0"
      by simp
    let ?r = "smult (inverse ?a0) q"
    have lgqr: "psize q = psize ?r"
      using a00
      unfolding psize_def degree_def
      by (simp add: poly_eq_iff)
    {
      assume h: "\<And>x y. poly ?r x = poly ?r y"
      {
        fix x y
        from qr[rule_format, of x] have "poly q x = poly ?r x * ?a0"
          by auto
        also have "\<dots> = poly ?r y * ?a0"
          using h by simp
        also have "\<dots> = poly q y"
          using qr[rule_format, of y] by simp
        finally have "poly q x = poly q y" .
      }
      with qnc have False
        unfolding constant_def by blast
    }
    then have rnc: "\<not> constant (poly ?r)"
      unfolding constant_def by blast
    from qr[rule_format, of 0] a00 have r01: "poly ?r 0 = 1"
      by auto
    {
      fix w
      have "cmod (poly ?r w) < 1 \<longleftrightarrow> cmod (poly q w / ?a0) < 1"
        using qr[rule_format, of w] a00 by (simp add: divide_inverse ac_simps)
      also have "\<dots> \<longleftrightarrow> cmod (poly q w) < cmod ?a0"
        using a00 unfolding norm_divide by (simp add: field_simps)
      finally have "cmod (poly ?r w) < 1 \<longleftrightarrow> cmod (poly q w) < cmod ?a0" .
    }
    note mrmq_eq = this
    from poly_decompose[OF rnc] obtain k a s where
      kas: "a \<noteq> 0" "k \<noteq> 0" "psize s + k + 1 = psize ?r"
        "\<forall>z. poly ?r z = poly ?r 0 + z^k* poly (pCons a s) z" by blast
    {
      assume "psize p = k + 1"
      with kas(3) lgqr[symmetric] q(1) have s0: "s = 0"
        by auto
      {
        fix w
        have "cmod (poly ?r w) = cmod (1 + a * w ^ k)"
          using kas(4)[rule_format, of w] s0 r01 by (simp add: algebra_simps)
      }
      note hth = this [symmetric]
      from reduce_poly_simple[OF kas(1,2)] have "\<exists>w. cmod (poly ?r w) < 1"
        unfolding hth by blast
    }
    moreover
    {
      assume kn: "psize p \<noteq> k + 1"
      from kn kas(3) q(1) lgqr have k1n: "k + 1 < psize p"
        by simp
      have th01: "\<not> constant (poly (pCons 1 (monom a (k - 1))))"
        unfolding constant_def poly_pCons poly_monom
        using kas(1)
        apply simp
        apply (rule exI[where x=0])
        apply (rule exI[where x=1])
        apply simp
        done
      from kas(1) kas(2) have th02: "k + 1 = psize (pCons 1 (monom a (k - 1)))"
        by (simp add: psize_def degree_monom_eq)
      from less(1) [OF k1n [simplified th02] th01]
      obtain w where w: "1 + w^k * a = 0"
        unfolding poly_pCons poly_monom
        using kas(2) by (cases k) (auto simp add: algebra_simps)
      from poly_bound_exists[of "cmod w" s] obtain m where
        m: "m > 0" "\<forall>z. cmod z \<le> cmod w \<longrightarrow> cmod (poly s z) \<le> m" by blast
      have w0: "w \<noteq> 0"
        using kas(2) w by (auto simp add: power_0_left)
      from w have "(1 + w ^ k * a) - 1 = 0 - 1"
        by simp
      then have wm1: "w^k * a = - 1"
        by simp
      have inv0: "0 < inverse (cmod w ^ (k + 1) * m)"
        using norm_ge_zero[of w] w0 m(1)
        by (simp add: inverse_eq_divide zero_less_mult_iff)
      with real_lbound_gt_zero[OF zero_less_one] obtain t where
        t: "t > 0" "t < 1" "t < inverse (cmod w ^ (k + 1) * m)" by blast
      let ?ct = "complex_of_real t"
      let ?w = "?ct * w"
      have "1 + ?w^k * (a + ?w * poly s ?w) = 1 + ?ct^k * (w^k * a) + ?w^k * ?w * poly s ?w"
        using kas(1) by (simp add: algebra_simps power_mult_distrib)
      also have "\<dots> = complex_of_real (1 - t^k) + ?w^k * ?w * poly s ?w"
        unfolding wm1 by simp
      finally have "cmod (1 + ?w^k * (a + ?w * poly s ?w)) =
        cmod (complex_of_real (1 - t^k) + ?w^k * ?w * poly s ?w)"
        by metis
      with norm_triangle_ineq[of "complex_of_real (1 - t^k)" "?w^k * ?w * poly s ?w"]
      have th11: "cmod (1 + ?w^k * (a + ?w * poly s ?w)) \<le> \<bar>1 - t^k\<bar> + cmod (?w^k * ?w * poly s ?w)"
        unfolding norm_of_real by simp
      have ath: "\<And>x t::real. 0 \<le> x \<Longrightarrow> x < t \<Longrightarrow> t \<le> 1 \<Longrightarrow> \<bar>1 - t\<bar> + x < 1"
        by arith
      have "t * cmod w \<le> 1 * cmod w"
        apply (rule mult_mono)
        using t(1,2)
        apply auto
        done
      then have tw: "cmod ?w \<le> cmod w"
        using t(1) by (simp add: norm_mult)
      from t inv0 have "t * (cmod w ^ (k + 1) * m) < 1"
        by (simp add: field_simps)
      with zero_less_power[OF t(1), of k] have th30: "t^k * (t* (cmod w ^ (k + 1) * m)) < t^k * 1"
        by (metis comm_mult_strict_left_mono)
      have "cmod (?w^k * ?w * poly s ?w) = t^k * (t* (cmod w ^ (k + 1) * cmod (poly s ?w)))"
        using w0 t(1)
        by (simp add: algebra_simps power_mult_distrib norm_power norm_mult)
      then have "cmod (?w^k * ?w * poly s ?w) \<le> t^k * (t* (cmod w ^ (k + 1) * m))"
        using t(1,2) m(2)[rule_format, OF tw] w0
        by auto
      with th30 have th120: "cmod (?w^k * ?w * poly s ?w) < t^k"
        by simp
      from power_strict_mono[OF t(2), of k] t(1) kas(2) have th121: "t^k \<le> 1"
        by auto
      from ath[OF norm_ge_zero[of "?w^k * ?w * poly s ?w"] th120 th121]
      have th12: "\<bar>1 - t^k\<bar> + cmod (?w^k * ?w * poly s ?w) < 1" .
      from th11 th12 have "cmod (1 + ?w^k * (a + ?w * poly s ?w)) < 1"
        by arith
      then have "cmod (poly ?r ?w) < 1"
        unfolding kas(4)[rule_format, of ?w] r01 by simp
      then have "\<exists>w. cmod (poly ?r w) < 1"
        by blast
    }
    ultimately have cr0_contr: "\<exists>w. cmod (poly ?r w) < 1"
      by blast
    from cr0_contr cq0 q(2) show ?thesis
      unfolding mrmq_eq not_less[symmetric] by auto
  qed
qed

text {* Alternative version with a syntactic notion of constant polynomial. *}

lemma fundamental_theorem_of_algebra_alt:
  assumes nc: "\<not> (\<exists>a l. a \<noteq> 0 \<and> l = 0 \<and> p = pCons a l)"
  shows "\<exists>z. poly p z = (0::complex)"
  using nc
proof (induct p)
  case 0
  then show ?case by simp
next
  case (pCons c cs)
  show ?case
  proof (cases "c = 0")
    case True
    then show ?thesis by auto
  next
    case False
    {
      assume nc: "constant (poly (pCons c cs))"
      from nc[unfolded constant_def, rule_format, of 0]
      have "\<forall>w. w \<noteq> 0 \<longrightarrow> poly cs w = 0" by auto
      then have "cs = 0"
      proof (induct cs)
        case 0
        then show ?case by simp
      next
        case (pCons d ds)
        show ?case
        proof (cases "d = 0")
          case True
          then show ?thesis using pCons.prems pCons.hyps by simp
        next
          case False
          from poly_bound_exists[of 1 ds] obtain m where
            m: "m > 0" "\<forall>z. \<forall>z. cmod z \<le> 1 \<longrightarrow> cmod (poly ds z) \<le> m" by blast
          have dm: "cmod d / m > 0"
            using False m(1) by (simp add: field_simps)
          from real_lbound_gt_zero[OF dm zero_less_one] obtain x where
            x: "x > 0" "x < cmod d / m" "x < 1" by blast
          let ?x = "complex_of_real x"
          from x have cx: "?x \<noteq> 0"  "cmod ?x \<le> 1"
            by simp_all
          from pCons.prems[rule_format, OF cx(1)]
          have cth: "cmod (?x*poly ds ?x) = cmod d"
            by (simp add: eq_diff_eq[symmetric])
          from m(2)[rule_format, OF cx(2)] x(1)
          have th0: "cmod (?x*poly ds ?x) \<le> x*m"
            by (simp add: norm_mult)
          from x(2) m(1) have "x * m < cmod d"
            by (simp add: field_simps)
          with th0 have "cmod (?x*poly ds ?x) \<noteq> cmod d"
            by auto
          with cth show ?thesis
            by blast
        qed
      qed
    }
    then have nc: "\<not> constant (poly (pCons c cs))"
      using pCons.prems False by blast
    from fundamental_theorem_of_algebra[OF nc] show ?thesis .
  qed
qed

subsection{* Nullstellensatz, degrees and divisibility of polynomials *}

lemma nullstellensatz_lemma:
  fixes p :: "complex poly"
  assumes "\<forall>x. poly p x = 0 \<longrightarrow> poly q x = 0"
    and "degree p = n"
    and "n \<noteq> 0"
  shows "p dvd (q ^ n)"
  using assms
proof (induct n arbitrary: p q rule: nat_less_induct)
  fix n :: nat
  fix p q :: "complex poly"
  assume IH: "\<forall>m<n. \<forall>p q.
                 (\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longrightarrow>
                 degree p = m \<longrightarrow> m \<noteq> 0 \<longrightarrow> p dvd (q ^ m)"
    and pq0: "\<forall>x. poly p x = 0 \<longrightarrow> poly q x = 0"
    and dpn: "degree p = n"
    and n0: "n \<noteq> 0"
  from dpn n0 have pne: "p \<noteq> 0" by auto
  let ?ths = "p dvd (q ^ n)"
  {
    fix a
    assume a: "poly p a = 0"
    {
      assume oa: "order a p \<noteq> 0"
      let ?op = "order a p"
      from pne have ap: "([:- a, 1:] ^ ?op) dvd p" "\<not> [:- a, 1:] ^ (Suc ?op) dvd p"
        using order by blast+
      note oop = order_degree[OF pne, unfolded dpn]
      {
        assume q0: "q = 0"
        then have ?ths using n0
          by (simp add: power_0_left)
      }
      moreover
      {
        assume q0: "q \<noteq> 0"
        from pq0[rule_format, OF a, unfolded poly_eq_0_iff_dvd]
        obtain r where r: "q = [:- a, 1:] * r" by (rule dvdE)
        from ap(1) obtain s where s: "p = [:- a, 1:] ^ ?op * s"
          by (rule dvdE)
        have sne: "s \<noteq> 0" using s pne by auto
        {
          assume ds0: "degree s = 0"
          from ds0 obtain k where kpn: "s = [:k:]"
            by (cases s) (auto split: if_splits)
          from sne kpn have k: "k \<noteq> 0" by simp
          let ?w = "([:1/k:] * ([:-a,1:] ^ (n - ?op))) * (r ^ n)"
          have "q ^ n = p * ?w"
            apply (subst r)
            apply (subst s)
            apply (subst kpn)
            using k oop [of a]
            apply (subst power_mult_distrib)
            apply simp
            apply (subst power_add [symmetric])
            apply simp
            done
          then have ?ths
            unfolding dvd_def by blast
        }
        moreover
        {
          assume ds0: "degree s \<noteq> 0"
          from ds0 sne dpn s oa
            have dsn: "degree s < n"
              apply auto
              apply (erule ssubst)
              apply (simp add: degree_mult_eq degree_linear_power)
              done
            {
              fix x assume h: "poly s x = 0"
              {
                assume xa: "x = a"
                from h[unfolded xa poly_eq_0_iff_dvd] obtain u where u: "s = [:- a, 1:] * u"
                  by (rule dvdE)
                have "p = [:- a, 1:] ^ (Suc ?op) * u"
                  apply (subst s)
                  apply (subst u)
                  apply (simp only: power_Suc ac_simps)
                  done
                with ap(2)[unfolded dvd_def] have False
                  by blast
              }
              note xa = this
              from h have "poly p x = 0"
                by (subst s) simp
              with pq0 have "poly q x = 0"
                by blast
              with r xa have "poly r x = 0"
                by auto
            }
            note impth = this
            from IH[rule_format, OF dsn, of s r] impth ds0
            have "s dvd (r ^ (degree s))"
              by blast
            then obtain u where u: "r ^ (degree s) = s * u" ..
            then have u': "\<And>x. poly s x * poly u x = poly r x ^ degree s"
              by (simp only: poly_mult[symmetric] poly_power[symmetric])
            let ?w = "(u * ([:-a,1:] ^ (n - ?op))) * (r ^ (n - degree s))"
            from oop[of a] dsn have "q ^ n = p * ?w"
              apply -
              apply (subst s)
              apply (subst r)
              apply (simp only: power_mult_distrib)
              apply (subst mult.assoc [where b=s])
              apply (subst mult.assoc [where a=u])
              apply (subst mult.assoc [where b=u, symmetric])
              apply (subst u [symmetric])
              apply (simp add: ac_simps power_add [symmetric])
              done
            then have ?ths
              unfolding dvd_def by blast
        }
        ultimately have ?ths by blast
      }
      ultimately have ?ths by blast
    }
    then have ?ths using a order_root pne by blast
  }
  moreover
  {
    assume exa: "\<not> (\<exists>a. poly p a = 0)"
    from fundamental_theorem_of_algebra_alt[of p] exa
    obtain c where ccs: "c \<noteq> 0" "p = pCons c 0"
      by blast
    then have pp: "\<And>x. poly p x = c"
      by simp
    let ?w = "[:1/c:] * (q ^ n)"
    from ccs have "(q ^ n) = (p * ?w)"
      by simp
    then have ?ths
      unfolding dvd_def by blast
  }
  ultimately show ?ths by blast
qed

lemma nullstellensatz_univariate:
  "(\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longleftrightarrow>
    p dvd (q ^ (degree p)) \<or> (p = 0 \<and> q = 0)"
proof -
  {
    assume pe: "p = 0"
    then have eq: "(\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longleftrightarrow> q = 0"
      by (auto simp add: poly_all_0_iff_0)
    {
      assume "p dvd (q ^ (degree p))"
      then obtain r where r: "q ^ (degree p) = p * r" ..
      from r pe have False by simp
    }
    with eq pe have ?thesis by blast
  }
  moreover
  {
    assume pe: "p \<noteq> 0"
    {
      assume dp: "degree p = 0"
      then obtain k where k: "p = [:k:]" "k \<noteq> 0" using pe
        by (cases p) (simp split: if_splits)
      then have th1: "\<forall>x. poly p x \<noteq> 0"
        by simp
      from k dp have "q ^ (degree p) = p * [:1/k:]"
        by (simp add: one_poly_def)
      then have th2: "p dvd (q ^ (degree p))" ..
      from th1 th2 pe have ?thesis
        by blast
    }
    moreover
    {
      assume dp: "degree p \<noteq> 0"
      then obtain n where n: "degree p = Suc n "
        by (cases "degree p") auto
      {
        assume "p dvd (q ^ (Suc n))"
        then obtain u where u: "q ^ (Suc n) = p * u" ..
        {
          fix x
          assume h: "poly p x = 0" "poly q x \<noteq> 0"
          then have "poly (q ^ (Suc n)) x \<noteq> 0"
            by simp
          then have False using u h(1)
            by (simp only: poly_mult) simp
        }
      }
      with n nullstellensatz_lemma[of p q "degree p"] dp
      have ?thesis by auto
    }
    ultimately have ?thesis by blast
  }
  ultimately show ?thesis by blast
qed

text {* Useful lemma *}

lemma constant_degree:
  fixes p :: "'a::{idom,ring_char_0} poly"
  shows "constant (poly p) \<longleftrightarrow> degree p = 0" (is "?lhs = ?rhs")
proof
  assume l: ?lhs
  from l[unfolded constant_def, rule_format, of _ "0"]
  have th: "poly p = poly [:poly p 0:]"
    by auto
  then have "p = [:poly p 0:]"
    by (simp add: poly_eq_poly_eq_iff)
  then have "degree p = degree [:poly p 0:]"
    by simp
  then show ?rhs
    by simp
next
  assume r: ?rhs
  then obtain k where "p = [:k:]"
    by (cases p) (simp split: if_splits)
  then show ?lhs
    unfolding constant_def by auto
qed

lemma divides_degree:
  assumes pq: "p dvd (q:: complex poly)"
  shows "degree p \<le> degree q \<or> q = 0"
  by (metis dvd_imp_degree_le pq)

text {* Arithmetic operations on multivariate polynomials. *}

lemma mpoly_base_conv:
  fixes x :: "'a::comm_ring_1"
  shows "0 = poly 0 x" "c = poly [:c:] x" "x = poly [:0,1:] x"
  by simp_all

lemma mpoly_norm_conv:
  fixes x :: "'a::comm_ring_1"
  shows "poly [:0:] x = poly 0 x" "poly [:poly 0 y:] x = poly 0 x"
  by simp_all

lemma mpoly_sub_conv:
  fixes x :: "'a::comm_ring_1"
  shows "poly p x - poly q x = poly p x + -1 * poly q x"
  by simp

lemma poly_pad_rule: "poly p x = 0 \<Longrightarrow> poly (pCons 0 p) x = 0"
  by simp

lemma poly_cancel_eq_conv:
  fixes x :: "'a::field"
  shows "x = 0 \<Longrightarrow> a \<noteq> 0 \<Longrightarrow> y = 0 \<longleftrightarrow> a * y - b * x = 0"
  by auto

lemma poly_divides_pad_rule:
  fixes p:: "('a::comm_ring_1) poly"
  assumes pq: "p dvd q"
  shows "p dvd (pCons 0 q)"
proof -
  have "pCons 0 q = q * [:0,1:]" by simp
  then have "q dvd (pCons 0 q)" ..
  with pq show ?thesis by (rule dvd_trans)
qed

lemma poly_divides_conv0:
  fixes p:: "'a::field poly"
  assumes lgpq: "degree q < degree p"
    and lq: "p \<noteq> 0"
  shows "p dvd q \<longleftrightarrow> q = 0" (is "?lhs \<longleftrightarrow> ?rhs")
proof
  assume r: ?rhs
  then have "q = p * 0" by simp
  then show ?lhs ..
next
  assume l: ?lhs
  show ?rhs
  proof (cases "q = 0")
    case True
    then show ?thesis by simp
  next
    assume q0: "q \<noteq> 0"
    from l q0 have "degree p \<le> degree q"
      by (rule dvd_imp_degree_le)
    with lgpq show ?thesis by simp
  qed
qed

lemma poly_divides_conv1:
  fixes p :: "'a::field poly"
  assumes a0: "a \<noteq> 0"
    and pp': "p dvd p'"
    and qrp': "smult a q - p' = r"
  shows "p dvd q \<longleftrightarrow> p dvd r" (is "?lhs \<longleftrightarrow> ?rhs")
proof
  from pp' obtain t where t: "p' = p * t" ..
  {
    assume l: ?lhs
    then obtain u where u: "q = p * u" ..
    have "r = p * (smult a u - t)"
      using u qrp' [symmetric] t by (simp add: algebra_simps)
    then show ?rhs ..
  next
    assume r: ?rhs
    then obtain u where u: "r = p * u" ..
    from u [symmetric] t qrp' [symmetric] a0
    have "q = p * smult (1/a) (u + t)" by (simp add: algebra_simps)
    then show ?lhs ..
  }
qed

lemma basic_cqe_conv1:
  "(\<exists>x. poly p x = 0 \<and> poly 0 x \<noteq> 0) \<longleftrightarrow> False"
  "(\<exists>x. poly 0 x \<noteq> 0) \<longleftrightarrow> False"
  "(\<exists>x. poly [:c:] x \<noteq> 0) \<longleftrightarrow> c \<noteq> 0"
  "(\<exists>x. poly 0 x = 0) \<longleftrightarrow> True"
  "(\<exists>x. poly [:c:] x = 0) \<longleftrightarrow> c = 0"
  by simp_all

lemma basic_cqe_conv2:
  assumes l: "p \<noteq> 0"
  shows "\<exists>x. poly (pCons a (pCons b p)) x = (0::complex)"
proof -
  {
    fix h t
    assume h: "h \<noteq> 0" "t = 0" and "pCons a (pCons b p) = pCons h t"
    with l have False by simp
  }
  then have th: "\<not> (\<exists> h t. h \<noteq> 0 \<and> t = 0 \<and> pCons a (pCons b p) = pCons h t)"
    by blast
  from fundamental_theorem_of_algebra_alt[OF th] show ?thesis
    by auto
qed

lemma  basic_cqe_conv_2b: "(\<exists>x. poly p x \<noteq> (0::complex)) \<longleftrightarrow> p \<noteq> 0"
  by (metis poly_all_0_iff_0)

lemma basic_cqe_conv3:
  fixes p q :: "complex poly"
  assumes l: "p \<noteq> 0"
  shows "(\<exists>x. poly (pCons a p) x = 0 \<and> poly q x \<noteq> 0) \<longleftrightarrow> \<not> (pCons a p) dvd (q ^ psize p)"
proof -
  from l have dp: "degree (pCons a p) = psize p"
    by (simp add: psize_def)
  from nullstellensatz_univariate[of "pCons a p" q] l
  show ?thesis
    by (metis dp pCons_eq_0_iff)
qed

lemma basic_cqe_conv4:
  fixes p q :: "complex poly"
  assumes h: "\<And>x. poly (q ^ n) x = poly r x"
  shows "p dvd (q ^ n) \<longleftrightarrow> p dvd r"
proof -
  from h have "poly (q ^ n) = poly r"
    by auto
  then have "(q ^ n) = r"
    by (simp add: poly_eq_poly_eq_iff)
  then show "p dvd (q ^ n) \<longleftrightarrow> p dvd r"
    by simp
qed

lemma poly_const_conv:
  fixes x :: "'a::comm_ring_1"
  shows "poly [:c:] x = y \<longleftrightarrow> c = y"
  by simp

end