theory LiarsStreetModal       (*Christoph Benzmüller, 2020*)
  imports Main
begin
(*unimportant*) nitpick_params [user_axioms,assms=true,format=2,box=false,show_all]
(*unimportant*) declare [[show_abbrevs=false]]

(*** NOTE: This is still a failing attempt to address "Says" — but lets see how far we get ***)

(*Type declarations and type abbreviations*)
typedecl i (*Possible worlds*)
type_synonym \<sigma> = "i\<Rightarrow>bool" (*World-lifted propositions*)
type_synonym \<tau> = "i\<Rightarrow>i\<Rightarrow>bool" (*Type of accessibility relations*)
type_synonym \<mu> = "\<sigma>\<Rightarrow>\<sigma>" (*Unary modal connectives*)
type_synonym \<nu> = "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>" (*Binary modal connectives*)

(***********************************************************************************
 ******************  Modal Logic Connectives ***************************************
 ***********************************************************************************)

(*Modal logic connectives (operating on truth-sets)*)
abbreviation MFalse::\<sigma> ("\<^bold>\<bottom>") where "\<^bold>\<bottom> \<equiv> \<lambda>w. False"
abbreviation MTrue::\<sigma> ("\<^bold>\<top>") where "\<^bold>\<top> \<equiv> \<lambda>w. True"
abbreviation MNeg::\<mu> ("\<^bold>\<not>_") where "\<^bold>\<not>\<phi> \<equiv> \<lambda>w.\<not>(\<phi> w)"
abbreviation MOr::\<nu> ("_\<^bold>\<and>_") where "\<phi>\<^bold>\<and>\<psi> \<equiv> \<lambda>w.(\<phi> w)\<and>(\<psi> w)"
abbreviation MAnd::\<nu> ("_\<^bold>\<or>_") where "\<phi>\<^bold>\<or>\<psi> \<equiv> \<lambda>w.(\<phi> w)\<or>(\<psi> w)"
abbreviation MImp::\<nu> ("_\<^bold>\<rightarrow>_") where "\<phi>\<^bold>\<rightarrow>\<psi> \<equiv> \<lambda>w.(\<phi> w)\<longrightarrow>(\<psi> w)"
abbreviation MEquiv::\<nu> ("_\<^bold>\<leftrightarrow>_") where "\<phi>\<^bold>\<leftrightarrow>\<psi> \<equiv> \<lambda>w.(\<phi> w)\<longleftrightarrow>(\<psi> w)"

abbreviation MBox::"\<tau>\<Rightarrow>\<mu>" ("\<^bold>[_\<^bold>] _") where "\<^bold>[r\<^bold>] \<phi> \<equiv> \<lambda>w.\<forall>v.(r w v)\<longrightarrow>(\<phi> v)"
abbreviation MDia::"\<tau>\<Rightarrow>\<mu>" ("\<^bold><_\<^bold>> _") where "\<^bold><r\<^bold>> \<phi> \<equiv> \<lambda>w.\<exists>v.(r w v)\<and>(\<phi> v)"

(*Polymorphic possibilist quantification*)
abbreviation MAllPoss ("\<^bold>\<forall>") where "\<^bold>\<forall>\<Phi> \<equiv> \<lambda>w.\<forall>x.(\<Phi> x w)"
abbreviation MAllPossB (binder"\<^bold>\<forall>"[8]9) where "\<^bold>\<forall>x. \<phi>(x) \<equiv> \<^bold>\<forall>\<phi>"
abbreviation MExPoss ("\<^bold>\<exists>") where "\<^bold>\<exists>\<Phi> \<equiv> \<lambda>w.\<exists>x.(\<Phi> x w)"
abbreviation MExPossB (binder"\<^bold>\<exists>"[8]9) where "\<^bold>\<exists>x. \<phi>(x) \<equiv> \<^bold>\<exists>\<phi>"

(*Meta-logical predicate for global validity*)
abbreviation MgValid::"\<sigma>\<Rightarrow>bool" ("\<lfloor>_\<rfloor>") where "\<lfloor>\<psi>\<rfloor> \<equiv>  \<forall>w. \<psi> w"
(*Meta-logical predicate for local validity*)
consts cw::i
abbreviation MlValid::"\<sigma>\<Rightarrow>bool" ("\<lfloor>_\<rfloor>\<^sub>c\<^sub>w") where "\<lfloor>\<psi>\<rfloor>\<^sub>c\<^sub>w \<equiv>  \<psi> cw"

(*Consistency, Barcan and converse Barcan formula*)
lemma True nitpick[satisfy] oops  (*Model found by Nitpick*)
lemma "\<lfloor>(\<^bold>\<forall>x.\<^bold>[r\<^bold>](\<phi> x)) \<^bold>\<rightarrow> \<^bold>[r\<^bold>](\<^bold>\<forall>x. \<phi> x)\<rfloor>" by simp
lemma "\<lfloor>(\<^bold>[r\<^bold>](\<^bold>\<forall>x.(\<phi> x))) \<^bold>\<rightarrow> \<^bold>\<forall>x.\<^bold>[r\<^bold>](\<phi> x)\<rfloor>" by simp

(***********************************************************************************
 ******************  Some Basic Types of our Ontology ******************************
 ***********************************************************************************)

(* There are some kids, could be many more *)
consts Nilda::\<tau> Carla::\<tau>
axiomatization where Different: "Carla \<noteq> Nilda"

(* There are some roads, could be many more *)
datatype Street = LiarsStreet | TruthtellersRoad

(***********************************************************************************
 ******************  Controlled Natural Language Library ***************************
 ******************  Logic and Modalities ******************************************
 ***********************************************************************************)

(*** NL phrases: standard logical connectives; examples ***)
abbreviation And ("_ and _") where "X and Y \<equiv> X \<^bold>\<and> Y"
abbreviation Or ("_ or _") where "X or Y \<equiv> X \<^bold>\<or> Y"
abbreviation Not ("not _") where "not X \<equiv> \<^bold>\<not>X"
abbreviation If_then ("If _ then _") where "If X then Y \<equiv> X \<^bold>\<rightarrow> Y"

(*** NL phrases: modal connectives; examples ***)

(* We can introduce modal NL phrases *)
definition  Says::"\<tau>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>"  ("_ says _")  where "X says \<phi> \<equiv> \<^bold>[X\<^bold>] \<phi> "
definition  Knows::"\<tau>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>"  ("_ knows _") where "X knows \<phi> \<equiv> \<^bold>[X\<^bold>] \<phi> "

(* We can introduce some further derived modal NL phrases *)
definition Lies ("lies _") where "lies X \<equiv> \<^bold>\<forall>Y. If (X says Y) then not Y"
definition Says_the_truth ("says-the-truth _")
  where "says-the-truth X \<equiv> \<^bold>\<forall>Y. If (X says Y) then Y"

(* We add the above defintions to our "bag" called "Defs" — Unimportant *)
named_theorems Defs
declare Says_def [Defs] Knows_def [Defs] Lies_def [Defs] Says_the_truth_def [Defs]

(***********************************************************************************
 ****************** Controlled Natural Language Library ****************************
 ****************** Domain specific concepts ***************************************
 ***********************************************************************************)

(* Uninterpreted predicate: Lives_in *)
consts Lives_in::"\<tau>\<Rightarrow>Street\<Rightarrow>\<sigma>" ("_ lives-in _")

(* Further derived NL phrases that concern "Lives_in" *)
definition Lives_not_in ("_ lives-not-in _")
  where "X lives-not-in G \<equiv> not (X lives-in G)"
definition Neither_nor_live_in ("neither _ nor _ live-in _")
  where "neither X nor Y live-in G \<equiv> (not (X lives-in G)) and (not (Y lives-in G))"
definition Both_live_in ("both _ and _ live-in _")
  where "both X and Y live-in G \<equiv> (X lives-in G) and (Y lives-in G)"

(* We add the above defintions to our "bag" called "Defs" — Unimportant *)
declare Lives_not_in_def [Defs] Neither_nor_live_in_def [Defs] Both_live_in_def [Defs]

(***********************************************************************************
 ****************** Example Queries ************************************************
 ***********************************************************************************)

axiomatization where
A1:  "\<lfloor>If (X lives-in LiarsStreet) then (lies X)\<rfloor>"  and
A2:  "\<lfloor>If (X lives-in TruthtellersRoad) then (says-the-truth X)\<rfloor>"

lemma Question1:
  assumes
   "\<lfloor>Nilda says (Carla lives-in TruthtellersRoad)\<rfloor>\<^sub>c\<^sub>w"
   "\<lfloor>Carla says (Nilda lives-in TruthtellersRoad)\<rfloor>\<^sub>c\<^sub>w"
 shows
   "\<lfloor>((Nilda lives-in S1) and (Carla lives-in S2))\<rfloor>\<^sub>c\<^sub>w"
  nitpick[satisfy]
  oops

(*** Do we run into Paradoxes with the modelling of modalities? ***)

consts It_holds_that_One_plus_One_Equals_Two::\<sigma>
       It_holds_that_Fermats_last_Theorem_is_True::\<sigma>

lemma Question8:
  assumes
   "\<lfloor>It_holds_that_One_plus_One_Equals_Two\<rfloor>\<^sub>c\<^sub>w"
   "\<lfloor>It_holds_that_Fermats_last_Theorem_is_True\<rfloor>\<^sub>c\<^sub>w"
   "\<lfloor>Carla says It_holds_that_One_plus_One_Equals_Two\<rfloor>\<^sub>c\<^sub>w"
  shows
   "\<lfloor>Carla says It_holds_that_Fermats_last_Theorem_is_True\<rfloor>\<^sub>c\<^sub>w"
  unfolding Defs
  sledgehammer [verbose,overlord]
  nitpick[show_all,format=2] oops

end

lemma Question9:
  assumes
   "\<lfloor>It_holds_that_One_plus_One_Equals_Two\<rfloor>\<^sub>c\<^sub>w"
   "\<lfloor>It_holds_that_Fermats_last_Theorem_is_True\<rfloor>\<^sub>c\<^sub>w"
   "\<lfloor>Carla knows It_holds_that_One_plus_One_Equals_Two\<rfloor>\<^sub>c\<^sub>w"
  shows
   "\<lfloor>Carla knows It_holds_that_Fermats_last_Theorem_is_True\<rfloor>\<^sub>c\<^sub>w"
  sledgehammer [verbose](assms)
  nitpick  oops

(*** But! As the remainder shows this is still not a proper modeling
     of "Says" --- See literature on public announcement logic and our
     recent paper at the Dali workshop ***)

lemma Question2:
  assumes
   "\<lfloor>Nilda says (Carla lives-in LiarsStreet)\<rfloor>\<^sub>c\<^sub>w"
   "\<lfloor>Carla says (neither Nilda nor Carla live-in LiarsStreet)\<rfloor>\<^sub>c\<^sub>w"
  shows
   "\<lfloor>((Nilda lives-in S1) and (Carla lives-in S2))\<rfloor>\<^sub>c\<^sub>w"
  nitpick[satisfy] oops

lemma Question3:
  assumes
   "\<lfloor>Nilda says (Carla lives-in LiarsStreet)\<rfloor>\<^sub>c\<^sub>w"
   "\<lfloor>Carla says (Carla lives-in LiarsStreet)\<rfloor>\<^sub>c\<^sub>w"
 shows
   "\<lfloor>((Nilda lives-in S1) and (Carla lives-in S2))\<rfloor>\<^sub>c\<^sub>w"
  nitpick[satisfy,show_all] oops

lemma Question4:
  assumes
   "\<lfloor>Nilda says (Nilda says (Nilda lives-in LiarsStreet))\<rfloor>\<^sub>c\<^sub>w"
 shows
   "\<lfloor>(Nilda lives-in S1)\<rfloor>"
  nitpick[satisfy,show_all] oops

lemma Question5:
  assumes
   "\<lfloor>Nilda says (Nilda says (Nilda lives-not-in LiarsStreet))\<rfloor>\<^sub>c\<^sub>w"
 shows
   "\<lfloor>(Nilda lives-in S1)\<rfloor>\<^sub>c\<^sub>w"
  nitpick[satisfy] oops

lemma Question6:
  assumes
   "\<lfloor>Nilda says (Nilda says ((Nilda lives-in LiarsStreet) and (Nilda lives-in TruthtellersRoad)))\<rfloor>"
 shows
   "\<lfloor>(Nilda lives-in S1)\<rfloor>\<^sub>c\<^sub>w"
  nitpick[satisfy] oops

lemma Question7:
  assumes
   "\<lfloor>Nilda says (Carla says ((Nilda lives-in LiarsStreet) and (Nilda lives-in TruthtellersRoad)))\<rfloor>\<^sub>c\<^sub>w"
 shows
   "\<lfloor>((Nilda lives-in S1) and (Carla lives-in S2))\<rfloor>\<^sub>c\<^sub>w"
  nitpick[satisfy] oops

end


header {* Generic Algorithm to Convert Sets to Lists *}
theory To_List_GA
imports Imp_Set_Spec Imp_List_Spec Hash_Set_Impl Open_List
begin
  text {* This theory demonstrates how to develop a generic to-list
    algorithm, and gives a sample instantiation for hash sets and open lists.
    *}

  subsection {* Algorithm *}
  partial_function (heap) to_list_ga_rec where [code]:
    "to_list_ga_rec
      it_has_next it_next
      l_prepend
      it l
    =
    do {
      b \<leftarrow> it_has_next it;
      if b then do {
        (x,it) \<leftarrow> it_next it;
        l \<leftarrow> l_prepend x l;
        to_list_ga_rec it_has_next it_next
          l_prepend it l
      } else
        return l
    }
    "

  lemma to_list_ga_rec_rule:
    assumes "imp_set_iterate is_set is_it it_init it_has_next it_next"
    assumes "imp_list_prepend is_list l_prepend"
    assumes FIN: "finite it"
    shows "
    < is_it s si it iti * is_list l li >
      to_list_ga_rec it_has_next it_next l_prepend iti li
    < \<lambda>r. \<exists>\<^sub>Al'. is_set s si
      * is_list l' r
      * \<up>(set l' = set l \<union> it) >\<^sub>t"
  proof -
    interpret imp_set_iterate is_set is_it it_init it_has_next it_next
      + imp_list_prepend is_list l_prepend
      by fact+

    from FIN show ?thesis
    proof (induction arbitrary: l li iti rule: finite_psubset_induct)
      case (psubset it)
      show ?case
        apply (subst to_list_ga_rec.simps)
        apply (sep_auto heap: psubset.IH)
        apply (rule ent_frame_fwd[OF quit_iteration])
        apply frame_inference
        apply solve_entails
        done
    qed
  qed

  definition "to_list_ga
    it_init it_has_next it_next
    l_empty l_prepend s
    \<equiv> do {
      it \<leftarrow> it_init s;
      l \<leftarrow> l_empty;
      l \<leftarrow> to_list_ga_rec it_has_next it_next l_prepend it l;
      return l
    }"

  lemma to_list_ga_rule:
    assumes IT: "imp_set_iterate is_set is_it it_init it_has_next it_next"
    assumes EM: "imp_list_empty is_list l_empty"
    assumes PREP: "imp_list_prepend is_list l_prepend"
    assumes FIN: "finite s"
    shows "
    <is_set s si>
    to_list_ga it_init it_has_next it_next
      l_empty l_prepend si
    <\<lambda>r. \<exists>\<^sub>Al. is_set s si * is_list l r * true * \<up>(set l = s)>"
  proof -
    interpret imp_list_empty is_list l_empty +
      imp_set_iterate is_set is_it it_init it_has_next it_next
      by fact+

    note [sep_heap_rules] = to_list_ga_rec_rule[OF IT PREP]
    show ?thesis
      unfolding to_list_ga_def
      by (sep_auto simp: FIN)
  qed

  subsection {* Sample Instantiation for hash set and open list *}
  definition "hs_to_ol
    \<equiv> to_list_ga hs_it_init hs_it_has_next hs_it_next
        os_empty os_prepend"

  lemmas hs_to_ol_rule[sep_heap_rules] =
    to_list_ga_rule[OF hs_iterate_impl os_empty_impl os_prepend_impl,
    folded hs_to_ol_def]

  export_code hs_to_ol checking SML_imp

end


(*  Title:      HOL/Induct/Sexp.thy
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
    Copyright   1992  University of Cambridge

S-expressions, general binary trees for defining recursive data
structures by hand.
*)

theory Sexp
imports "HOL-Library.Old_Datatype"
begin

type_synonym 'a item = "'a Old_Datatype.item"
abbreviation "Leaf == Old_Datatype.Leaf"
abbreviation "Numb == Old_Datatype.Numb"

inductive_set
  sexp      :: "'a item set"
  where
    LeafI:  "Leaf(a) \<in> sexp"
  | NumbI:  "Numb(i) \<in> sexp"
  | SconsI: "[| M \<in> sexp;  N \<in> sexp |] ==> Scons M N \<in> sexp"

definition
  sexp_case :: "['a=>'b, nat=>'b, ['a item, 'a item]=>'b,
                'a item] => 'b" where
  "sexp_case c d e M = (THE z. (\<exists>x.   M=Leaf(x) & z=c(x))
                             | (\<exists>k.   M=Numb(k) & z=d(k))
                             | (\<exists>N1 N2. M = Scons N1 N2  & z=e N1 N2))"

definition
  pred_sexp :: "('a item * 'a item)set" where
     "pred_sexp = (\<Union>M \<in> sexp. \<Union>N \<in> sexp. {(M, Scons M N), (N, Scons M N)})"

definition
  sexp_rec  :: "['a item, 'a=>'b, nat=>'b,
                ['a item, 'a item, 'b, 'b]=>'b] => 'b" where
   "sexp_rec M c d e = wfrec pred_sexp
             (%g. sexp_case c d (%N1 N2. e N1 N2 (g N1) (g N2))) M"

(** sexp_case **)

lemma sexp_case_Leaf [simp]: "sexp_case c d e (Leaf a) = c(a)"
by (simp add: sexp_case_def, blast)

lemma sexp_case_Numb [simp]: "sexp_case c d e (Numb k) = d(k)"
by (simp add: sexp_case_def, blast)

lemma sexp_case_Scons [simp]: "sexp_case c d e (Scons M N) = e M N"
by (simp add: sexp_case_def)

(** Introduction rules for sexp constructors **)

lemma sexp_In0I: "M \<in> sexp ==> In0(M) \<in> sexp"
apply (simp add: In0_def)
apply (erule sexp.NumbI [THEN sexp.SconsI])
done

lemma sexp_In1I: "M \<in> sexp ==> In1(M) \<in> sexp"
apply (simp add: In1_def)
apply (erule sexp.NumbI [THEN sexp.SconsI])
done

declare sexp.intros [intro,simp]

lemma range_Leaf_subset_sexp: "range(Leaf) <= sexp"
by blast

lemma Scons_D: "Scons M N \<in> sexp ==> M \<in> sexp & N \<in> sexp"
  by (induct S == "Scons M N" set: sexp) auto

(** Introduction rules for 'pred_sexp' **)

lemma pred_sexp_subset_Sigma: "pred_sexp <= sexp \<times> sexp"
  by (simp add: pred_sexp_def) blast

(* (a,b) \<in> pred_sexp^+ ==> a \<in> sexp *)
lemmas trancl_pred_sexpD1 =
    pred_sexp_subset_Sigma
         [THEN trancl_subset_Sigma, THEN subsetD, THEN SigmaD1]
and trancl_pred_sexpD2 =
    pred_sexp_subset_Sigma
         [THEN trancl_subset_Sigma, THEN subsetD, THEN SigmaD2]

lemma pred_sexpI1:
    "[| M \<in> sexp;  N \<in> sexp |] ==> (M, Scons M N) \<in> pred_sexp"
by (simp add: pred_sexp_def, blast)

lemma pred_sexpI2:
    "[| M \<in> sexp;  N \<in> sexp |] ==> (N, Scons M N) \<in> pred_sexp"
by (simp add: pred_sexp_def, blast)

(*Combinations involving transitivity and the rules above*)
lemmas pred_sexp_t1 [simp] = pred_sexpI1 [THEN r_into_trancl]
and    pred_sexp_t2 [simp] = pred_sexpI2 [THEN r_into_trancl]

lemmas pred_sexp_trans1 [simp] = trans_trancl [THEN transD, OF _ pred_sexp_t1]
and    pred_sexp_trans2 [simp] = trans_trancl [THEN transD, OF _ pred_sexp_t2]

(*Proves goals of the form (M,N):pred_sexp^+ provided M,N:sexp*)
declare cut_apply [simp]

lemma pred_sexpE:
    "[| p \<in> pred_sexp;
        !!M N. [| p = (M, Scons M N);  M \<in> sexp;  N \<in> sexp |] ==> R;
        !!M N. [| p = (N, Scons M N);  M \<in> sexp;  N \<in> sexp |] ==> R
     |] ==> R"
by (simp add: pred_sexp_def, blast)

lemma wf_pred_sexp: "wf(pred_sexp)"
apply (rule pred_sexp_subset_Sigma [THEN wfI])
apply (erule sexp.induct)
apply (blast elim!: pred_sexpE)+
done

(*** sexp_rec -- by wf recursion on pred_sexp ***)

lemma sexp_rec_unfold_lemma:
     "(%M. sexp_rec M c d e) ==
      wfrec pred_sexp (%g. sexp_case c d (%N1 N2. e N1 N2 (g N1) (g N2)))"
by (simp add: sexp_rec_def)

lemmas sexp_rec_unfold = def_wfrec [OF sexp_rec_unfold_lemma wf_pred_sexp]

(* sexp_rec a c d e =
   sexp_case c d
    (%N1 N2.
        e N1 N2 (cut (%M. sexp_rec M c d e) pred_sexp a N1)
         (cut (%M. sexp_rec M c d e) pred_sexp a N2)) a
*)

(** conversion rules **)

lemma sexp_rec_Leaf: "sexp_rec (Leaf a) c d h = c(a)"
apply (subst sexp_rec_unfold)
apply (rule sexp_case_Leaf)
done

lemma sexp_rec_Numb: "sexp_rec (Numb k) c d h = d(k)"
apply (subst sexp_rec_unfold)
apply (rule sexp_case_Numb)
done

lemma sexp_rec_Scons: "[| M \<in> sexp;  N \<in> sexp |] ==>
     sexp_rec (Scons M N) c d h = h M N (sexp_rec M c d h) (sexp_rec N c d h)"
apply (rule sexp_rec_unfold [THEN trans])
apply (simp add: pred_sexpI1 pred_sexpI2)
done

end


(*  Title:      HOL/Algebra/FiniteProduct.thy
    Author:     Clemens Ballarin, started 19 November 2002

This file is largely based on HOL/Finite_Set.thy.
*)

theory FiniteProduct
imports Group
begin

subsection \<open>Product Operator for Commutative Monoids\<close>

subsubsection \<open>Inductive Definition of a Relation for Products over Sets\<close>

text \<open>Instantiation of locale \<open>LC\<close> of theory \<open>Finite_Set\<close> is not
  possible, because here we have explicit typing rules like
  \<open>x \<in> carrier G\<close>.  We introduce an explicit argument for the domain
  \<open>D\<close>.\<close>

inductive_set
  foldSetD :: "['a set, 'b \<Rightarrow> 'a \<Rightarrow> 'a, 'a] \<Rightarrow> ('b set * 'a) set"
  for D :: "'a set" and f :: "'b \<Rightarrow> 'a \<Rightarrow> 'a" and e :: 'a
  where
    emptyI [intro]: "e \<in> D \<Longrightarrow> ({}, e) \<in> foldSetD D f e"
  | insertI [intro]: "\<lbrakk>x \<notin> A; f x y \<in> D; (A, y) \<in> foldSetD D f e\<rbrakk> \<Longrightarrow>
                      (insert x A, f x y) \<in> foldSetD D f e"

inductive_cases empty_foldSetDE [elim!]: "({}, x) \<in> foldSetD D f e"

definition
  foldD :: "['a set, 'b \<Rightarrow> 'a \<Rightarrow> 'a, 'a, 'b set] \<Rightarrow> 'a"
  where "foldD D f e A = (THE x. (A, x) \<in> foldSetD D f e)"

lemma foldSetD_closed: "(A, z) \<in> foldSetD D f e \<Longrightarrow> z \<in> D"
  by (erule foldSetD.cases) auto

lemma Diff1_foldSetD:
  "\<lbrakk>(A - {x}, y) \<in> foldSetD D f e; x \<in> A; f x y \<in> D\<rbrakk> \<Longrightarrow>
   (A, f x y) \<in> foldSetD D f e"
  by (metis Diff_insert_absorb foldSetD.insertI mk_disjoint_insert)

lemma foldSetD_imp_finite [simp]: "(A, x) \<in> foldSetD D f e \<Longrightarrow> finite A"
  by (induct set: foldSetD) auto

lemma finite_imp_foldSetD:
  "\<lbrakk>finite A; e \<in> D; \<And>x y. \<lbrakk>x \<in> A; y \<in> D\<rbrakk> \<Longrightarrow> f x y \<in> D\<rbrakk>
    \<Longrightarrow> \<exists>x. (A, x) \<in> foldSetD D f e"
proof (induct set: finite)
  case empty then show ?case by auto
next
  case (insert x F)
  then obtain y where y: "(F, y) \<in> foldSetD D f e" by auto
  with insert have "y \<in> D" by (auto dest: foldSetD_closed)
  with y and insert have "(insert x F, f x y) \<in> foldSetD D f e"
    by (intro foldSetD.intros) auto
  then show ?case ..
qed

lemma foldSetD_backwards:
  assumes "A \<noteq> {}" "(A, z) \<in> foldSetD D f e"
  shows "\<exists>x y. x \<in> A \<and> (A - { x }, y) \<in> foldSetD D f e \<and> z = f x y"
  using assms(2) by (cases) (simp add: assms(1), metis Diff_insert_absorb insertI1)

subsubsection \<open>Left-Commutative Operations\<close>

locale LCD =
  fixes B :: "'b set"
  and D :: "'a set"
  and f :: "'b \<Rightarrow> 'a \<Rightarrow> 'a"    (infixl "\<cdot>" 70)
  assumes left_commute:
    "\<lbrakk>x \<in> B; y \<in> B; z \<in> D\<rbrakk> \<Longrightarrow> x \<cdot> (y \<cdot> z) = y \<cdot> (x \<cdot> z)"
  and f_closed [simp, intro!]: "!!x y. \<lbrakk>x \<in> B; y \<in> D\<rbrakk> \<Longrightarrow> f x y \<in> D"

lemma (in LCD) foldSetD_closed [dest]: "(A, z) \<in> foldSetD D f e \<Longrightarrow> z \<in> D"
  by (erule foldSetD.cases) auto

lemma (in LCD) Diff1_foldSetD:
  "\<lbrakk>(A - {x}, y) \<in> foldSetD D f e; x \<in> A; A \<subseteq> B\<rbrakk> \<Longrightarrow>
  (A, f x y) \<in> foldSetD D f e"
  by (meson Diff1_foldSetD f_closed local.foldSetD_closed subsetCE)

lemma (in LCD) finite_imp_foldSetD:
  "\<lbrakk>finite A; A \<subseteq> B; e \<in> D\<rbrakk> \<Longrightarrow> \<exists>x. (A, x) \<in> foldSetD D f e"
proof (induct set: finite)
  case empty then show ?case by auto
next
  case (insert x F)
  then obtain y where y: "(F, y) \<in> foldSetD D f e" by auto
  with insert have "y \<in> D" by auto
  with y and insert have "(insert x F, f x y) \<in> foldSetD D f e"
    by (intro foldSetD.intros) auto
  then show ?case ..
qed

lemma (in LCD) foldSetD_determ_aux:
  assumes "e \<in> D" and A: "card A < n" "A \<subseteq> B" "(A, x) \<in> foldSetD D f e" "(A, y) \<in> foldSetD D f e"
  shows "y = x"
  using A
proof (induction n arbitrary: A x y)
  case 0
  then show ?case
    by auto
next
  case (Suc n)
  then consider "card A = n" | "card A < n"
    by linarith
  then show ?case
  proof cases
    case 1
    show ?thesis
      using foldSetD.cases [OF \<open>(A,x) \<in> foldSetD D (\<cdot>) e\<close>]
    proof cases
      case 1
      then show ?thesis
        using \<open>(A,y) \<in> foldSetD D (\<cdot>) e\<close> by auto
    next
      case (2 x' A' y')
      note A' = this
      show ?thesis
        using foldSetD.cases [OF \<open>(A,y) \<in> foldSetD D (\<cdot>) e\<close>]
      proof cases
        case 1
        then show ?thesis
          using \<open>(A,x) \<in> foldSetD D (\<cdot>) e\<close> by auto
      next
        case (2 x'' A'' y'')
        note A'' = this
        show ?thesis
        proof (cases "x' = x''")
          case True
          show ?thesis
          proof (cases "y' = y''")
            case True
            then show ?thesis
              using A' A'' \<open>x' = x''\<close> by (blast elim!: equalityE)
          next
            case False
            then show ?thesis
              using A' A'' \<open>x' = x''\<close>
              by (metis \<open>card A = n\<close> Suc.IH Suc.prems(2) card_insert_disjoint foldSetD_imp_finite insert_eq_iff insert_subset lessI)
          qed
        next
          case False
          then have *: "A' - {x''} = A'' - {x'}" "x'' \<in> A'" "x' \<in> A''"
            using A' A'' by fastforce+
          then have "A' = insert x'' A'' - {x'}"
            using \<open>x' \<notin> A'\<close> by blast
          then have card: "card A' \<le> card A''"
            using A' A'' * by (metis card_Suc_Diff1 eq_refl foldSetD_imp_finite)
          obtain u where u: "(A' - {x''}, u) \<in> foldSetD D (\<cdot>) e"
            using finite_imp_foldSetD [of "A' - {x''}"] A' Diff_insert \<open>A \<subseteq> B\<close> \<open>e \<in> D\<close> by fastforce
          have "y' = f x'' u"
            using Diff1_foldSetD [OF u] \<open>x'' \<in> A'\<close> \<open>card A = n\<close> A' Suc.IH \<open>A \<subseteq> B\<close> by auto
          then have "(A'' - {x'}, u) \<in> foldSetD D f e"
            using "*"(1) u by auto
          then have "y'' = f x' u"
            using A'' by (metis * \<open>card A = n\<close> A'(1) Diff1_foldSetD Suc.IH \<open>A \<subseteq> B\<close>
                card card_Suc_Diff1 card_insert_disjoint foldSetD_imp_finite insert_subset le_imp_less_Suc)
          then show ?thesis
            using A' A''
            by (metis \<open>A \<subseteq> B\<close> \<open>y' = x'' \<cdot> u\<close> insert_subset left_commute local.foldSetD_closed u)
        qed
      qed
    qed
  next
    case 2 with Suc show ?thesis by blast
  qed
qed

lemma (in LCD) foldSetD_determ:
  "\<lbrakk>(A, x) \<in> foldSetD D f e; (A, y) \<in> foldSetD D f e; e \<in> D; A \<subseteq> B\<rbrakk>
  \<Longrightarrow> y = x"
  by (blast intro: foldSetD_determ_aux [rule_format])

lemma (in LCD) foldD_equality:
  "\<lbrakk>(A, y) \<in> foldSetD D f e; e \<in> D; A \<subseteq> B\<rbrakk> \<Longrightarrow> foldD D f e A = y"
  by (unfold foldD_def) (blast intro: foldSetD_determ)

lemma foldD_empty [simp]:
  "e \<in> D \<Longrightarrow> foldD D f e {} = e"
  by (unfold foldD_def) blast

lemma (in LCD) foldD_insert_aux:
  "\<lbrakk>x \<notin> A; x \<in> B; e \<in> D; A \<subseteq> B\<rbrakk>
    \<Longrightarrow> ((insert x A, v) \<in> foldSetD D f e) \<longleftrightarrow> (\<exists>y. (A, y) \<in> foldSetD D f e \<and> v = f x y)"
  apply auto
  by (metis Diff_insert_absorb f_closed finite_Diff foldSetD.insertI foldSetD_determ foldSetD_imp_finite insert_subset local.finite_imp_foldSetD local.foldSetD_closed)

lemma (in LCD) foldD_insert:
  assumes "finite A" "x \<notin> A" "x \<in> B" "e \<in> D" "A \<subseteq> B"
  shows "foldD D f e (insert x A) = f x (foldD D f e A)"
proof -
  have "(THE v. \<exists>y. (A, y) \<in> foldSetD D (\<cdot>) e \<and> v = x \<cdot> y) = x \<cdot> (THE y. (A, y) \<in> foldSetD D (\<cdot>) e)"
    by (rule the_equality) (use assms foldD_def foldD_equality foldD_def finite_imp_foldSetD in \<open>metis+\<close>)
  then show ?thesis
    unfolding foldD_def using assms by (simp add: foldD_insert_aux)
qed

lemma (in LCD) foldD_closed [simp]:
  "\<lbrakk>finite A; e \<in> D; A \<subseteq> B\<rbrakk> \<Longrightarrow> foldD D f e A \<in> D"
proof (induct set: finite)
  case empty then show ?case by simp
next
  case insert then show ?case by (simp add: foldD_insert)
qed

lemma (in LCD) foldD_commute:
  "\<lbrakk>finite A; x \<in> B; e \<in> D; A \<subseteq> B\<rbrakk> \<Longrightarrow>
   f x (foldD D f e A) = foldD D f (f x e) A"
  by (induct set: finite) (auto simp add: left_commute foldD_insert)

lemma Int_mono2:
  "\<lbrakk>A \<subseteq> C; B \<subseteq> C\<rbrakk> \<Longrightarrow> A Int B \<subseteq> C"
  by blast

lemma (in LCD) foldD_nest_Un_Int:
  "\<lbrakk>finite A; finite C; e \<in> D; A \<subseteq> B; C \<subseteq> B\<rbrakk> \<Longrightarrow>
   foldD D f (foldD D f e C) A = foldD D f (foldD D f e (A Int C)) (A Un C)"
proof (induction set: finite)
  case (insert x F)
  then show ?case
    by (simp add: foldD_insert foldD_commute Int_insert_left insert_absorb Int_mono2)
qed simp

lemma (in LCD) foldD_nest_Un_disjoint:
  "\<lbrakk>finite A; finite B; A Int B = {}; e \<in> D; A \<subseteq> B; C \<subseteq> B\<rbrakk>
    \<Longrightarrow> foldD D f e (A Un B) = foldD D f (foldD D f e B) A"
  by (simp add: foldD_nest_Un_Int)

\<comment> \<open>Delete rules to do with \<open>foldSetD\<close> relation.\<close>

declare foldSetD_imp_finite [simp del]
  empty_foldSetDE [rule del]
  foldSetD.intros [rule del]
declare (in LCD)
  foldSetD_closed [rule del]

text \<open>Commutative Monoids\<close>

text \<open>
  We enter a more restrictive context, with \<open>f :: 'a \<Rightarrow> 'a \<Rightarrow> 'a\<close>
  instead of \<open>'b \<Rightarrow> 'a \<Rightarrow> 'a\<close>.
\<close>

locale ACeD =
  fixes D :: "'a set"
    and f :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"    (infixl "\<cdot>" 70)
    and e :: 'a
  assumes ident [simp]: "x \<in> D \<Longrightarrow> x \<cdot> e = x"
    and commute: "\<lbrakk>x \<in> D; y \<in> D\<rbrakk> \<Longrightarrow> x \<cdot> y = y \<cdot> x"
    and assoc: "\<lbrakk>x \<in> D; y \<in> D; z \<in> D\<rbrakk> \<Longrightarrow> (x \<cdot> y) \<cdot> z = x \<cdot> (y \<cdot> z)"
    and e_closed [simp]: "e \<in> D"
    and f_closed [simp]: "\<lbrakk>x \<in> D; y \<in> D\<rbrakk> \<Longrightarrow> x \<cdot> y \<in> D"

lemma (in ACeD) left_commute:
  "\<lbrakk>x \<in> D; y \<in> D; z \<in> D\<rbrakk> \<Longrightarrow> x \<cdot> (y \<cdot> z) = y \<cdot> (x \<cdot> z)"
proof -
  assume D: "x \<in> D" "y \<in> D" "z \<in> D"
  then have "x \<cdot> (y \<cdot> z) = (y \<cdot> z) \<cdot> x" by (simp add: commute)
  also from D have "... = y \<cdot> (z \<cdot> x)" by (simp add: assoc)
  also from D have "z \<cdot> x = x \<cdot> z" by (simp add: commute)
  finally show ?thesis .
qed

lemmas (in ACeD) AC = assoc commute left_commute

lemma (in ACeD) left_ident [simp]: "x \<in> D \<Longrightarrow> e \<cdot> x = x"
proof -
  assume "x \<in> D"
  then have "x \<cdot> e = x" by (rule ident)
  with \<open>x \<in> D\<close> show ?thesis by (simp add: commute)
qed

lemma (in ACeD) foldD_Un_Int:
  "\<lbrakk>finite A; finite B; A \<subseteq> D; B \<subseteq> D\<rbrakk> \<Longrightarrow>
    foldD D f e A \<cdot> foldD D f e B =
    foldD D f e (A Un B) \<cdot> foldD D f e (A Int B)"
proof (induction set: finite)
  case empty
  then show ?case
    by(simp add: left_commute LCD.foldD_closed [OF LCD.intro [of D]])
next
  case (insert x F)
  then show ?case
    by(simp add: AC insert_absorb Int_insert_left Int_mono2
                 LCD.foldD_insert [OF LCD.intro [of D]]
                 LCD.foldD_closed [OF LCD.intro [of D]])
qed

lemma (in ACeD) foldD_Un_disjoint:
  "\<lbrakk>finite A; finite B; A Int B = {}; A \<subseteq> D; B \<subseteq> D\<rbrakk> \<Longrightarrow>
    foldD D f e (A Un B) = foldD D f e A \<cdot> foldD D f e B"
  by (simp add: foldD_Un_Int
    left_commute LCD.foldD_closed [OF LCD.intro [of D]])

subsubsection \<open>Products over Finite Sets\<close>

definition
  finprod :: "[('b, 'm) monoid_scheme, 'a \<Rightarrow> 'b, 'a set] \<Rightarrow> 'b"
  where "finprod G f A =
   (if finite A
    then foldD (carrier G) (mult G \<circ> f) \<one>\<^bsub>G\<^esub> A
    else \<one>\<^bsub>G\<^esub>)"

syntax
  "_finprod" :: "index \<Rightarrow> idt \<Rightarrow> 'a set \<Rightarrow> 'b \<Rightarrow> 'b"
      ("(3\<Otimes>__\<in>_. _)" [1000, 0, 51, 10] 10)
translations
  "\<Otimes>\<^bsub>G\<^esub>i\<in>A. b" \<rightleftharpoons> "CONST finprod G (%i. b) A"
  \<comment> \<open>Beware of argument permutation!\<close>

lemma (in comm_monoid) finprod_empty [simp]:
  "finprod G f {} = \<one>"
  by (simp add: finprod_def)

lemma (in comm_monoid) finprod_infinite[simp]:
  "\<not> finite A \<Longrightarrow> finprod G f A = \<one>"
  by (simp add: finprod_def)

declare funcsetI [intro]
  funcset_mem [dest]

context comm_monoid begin

lemma finprod_insert [simp]:
  assumes "finite F" "a \<notin> F" "f \<in> F \<rightarrow> carrier G" "f a \<in> carrier G"
  shows "finprod G f (insert a F) = f a \<otimes> finprod G f F"
proof -
  have "finprod G f (insert a F) = foldD (carrier G) ((\<otimes>) \<circ> f) \<one> (insert a F)"
    by (simp add: finprod_def assms)
  also have "... = ((\<otimes>) \<circ> f) a (foldD (carrier G) ((\<otimes>) \<circ> f) \<one> F)"
    by (rule LCD.foldD_insert [OF LCD.intro [of "insert a F"]])
      (use assms in \<open>auto simp: m_lcomm Pi_iff\<close>)
  also have "... = f a \<otimes> finprod G f F"
    using \<open>finite F\<close> by (auto simp add: finprod_def)
  finally show ?thesis .
qed

lemma finprod_one_eqI: "(\<And>x. x \<in> A \<Longrightarrow> f x = \<one>) \<Longrightarrow> finprod G f A = \<one>"
proof (induct A rule: infinite_finite_induct)
  case empty show ?case by simp
next
  case (insert a A)
  have "(\<lambda>i. \<one>) \<in> A \<rightarrow> carrier G" by auto
  with insert show ?case by simp
qed simp

lemma finprod_one [simp]: "(\<Otimes>i\<in>A. \<one>) = \<one>"
  by (simp add: finprod_one_eqI)

lemma finprod_closed [simp]:
  fixes A
  assumes f: "f \<in> A \<rightarrow> carrier G"
  shows "finprod G f A \<in> carrier G"
using f
proof (induct A rule: infinite_finite_induct)
  case empty show ?case by simp
next
  case (insert a A)
  then have a: "f a \<in> carrier G" by fast
  from insert have A: "f \<in> A \<rightarrow> carrier G" by fast
  from insert A a show ?case by simp
qed simp

lemma funcset_Int_left [simp, intro]:
  "\<lbrakk>f \<in> A \<rightarrow> C; f \<in> B \<rightarrow> C\<rbrakk> \<Longrightarrow> f \<in> A Int B \<rightarrow> C"
  by fast

lemma funcset_Un_left [iff]:
  "(f \<in> A Un B \<rightarrow> C) = (f \<in> A \<rightarrow> C \<and> f \<in> B \<rightarrow> C)"
  by fast

lemma finprod_Un_Int:
  "\<lbrakk>finite A; finite B; g \<in> A \<rightarrow> carrier G; g \<in> B \<rightarrow> carrier G\<rbrakk> \<Longrightarrow>
     finprod G g (A Un B) \<otimes> finprod G g (A Int B) =
     finprod G g A \<otimes> finprod G g B"
\<comment> \<open>The reversed orientation looks more natural, but LOOPS as a simprule!\<close>
proof (induct set: finite)
  case empty then show ?case by simp
next
  case (insert a A)
  then have a: "g a \<in> carrier G" by fast
  from insert have A: "g \<in> A \<rightarrow> carrier G" by fast
  from insert A a show ?case
    by (simp add: m_ac Int_insert_left insert_absorb Int_mono2)
qed

lemma finprod_Un_disjoint:
  "\<lbrakk>finite A; finite B; A Int B = {};
      g \<in> A \<rightarrow> carrier G; g \<in> B \<rightarrow> carrier G\<rbrakk>
   \<Longrightarrow> finprod G g (A Un B) = finprod G g A \<otimes> finprod G g B"
  by (metis Pi_split_domain finprod_Un_Int finprod_closed finprod_empty r_one)

lemma finprod_multf [simp]:
  "\<lbrakk>f \<in> A \<rightarrow> carrier G; g \<in> A \<rightarrow> carrier G\<rbrakk> \<Longrightarrow>
   finprod G (\<lambda>x. f x \<otimes> g x) A = (finprod G f A \<otimes> finprod G g A)"
proof (induct A rule: infinite_finite_induct)
  case empty show ?case by simp
next
  case (insert a A) then
  have fA: "f \<in> A \<rightarrow> carrier G" by fast
  from insert have fa: "f a \<in> carrier G" by fast
  from insert have gA: "g \<in> A \<rightarrow> carrier G" by fast
  from insert have ga: "g a \<in> carrier G" by fast
  from insert have fgA: "(%x. f x \<otimes> g x) \<in> A \<rightarrow> carrier G"
    by (simp add: Pi_def)
  show ?case
    by (simp add: insert fA fa gA ga fgA m_ac)
qed simp

lemma finprod_cong':
  "\<lbrakk>A = B; g \<in> B \<rightarrow> carrier G;
      !!i. i \<in> B \<Longrightarrow> f i = g i\<rbrakk> \<Longrightarrow> finprod G f A = finprod G g B"
proof -
  assume prems: "A = B" "g \<in> B \<rightarrow> carrier G"
    "!!i. i \<in> B \<Longrightarrow> f i = g i"
  show ?thesis
  proof (cases "finite B")
    case True
    then have "!!A. \<lbrakk>A = B; g \<in> B \<rightarrow> carrier G;
      !!i. i \<in> B \<Longrightarrow> f i = g i\<rbrakk> \<Longrightarrow> finprod G f A = finprod G g B"
    proof induct
      case empty thus ?case by simp
    next
      case (insert x B)
      then have "finprod G f A = finprod G f (insert x B)" by simp
      also from insert have "... = f x \<otimes> finprod G f B"
      proof (intro finprod_insert)
        show "finite B" by fact
      next
        show "x \<notin> B" by fact
      next
        assume "x \<notin> B" "!!i. i \<in> insert x B \<Longrightarrow> f i = g i"
          "g \<in> insert x B \<rightarrow> carrier G"
        thus "f \<in> B \<rightarrow> carrier G" by fastforce
      next
        assume "x \<notin> B" "!!i. i \<in> insert x B \<Longrightarrow> f i = g i"
          "g \<in> insert x B \<rightarrow> carrier G"
        thus "f x \<in> carrier G" by fastforce
      qed
      also from insert have "... = g x \<otimes> finprod G g B" by fastforce
      also from insert have "... = finprod G g (insert x B)"
      by (intro finprod_insert [THEN sym]) auto
      finally show ?case .
    qed
    with prems show ?thesis by simp
  next
    case False with prems show ?thesis by simp
  qed
qed

lemma finprod_cong:
  "\<lbrakk>A = B; f \<in> B \<rightarrow> carrier G = True;
      \<And>i. i \<in> B =simp=> f i = g i\<rbrakk> \<Longrightarrow> finprod G f A = finprod G g B"
  (* This order of prems is slightly faster (3%) than the last two swapped. *)
  by (rule finprod_cong') (auto simp add: simp_implies_def)

text \<open>Usually, if this rule causes a failed congruence proof error,
  the reason is that the premise \<open>g \<in> B \<rightarrow> carrier G\<close> cannot be shown.
  Adding @{thm [source] Pi_def} to the simpset is often useful.
  For this reason, @{thm [source] finprod_cong}
  is not added to the simpset by default.
\<close>

end

declare funcsetI [rule del]
  funcset_mem [rule del]

context comm_monoid begin

lemma finprod_0 [simp]:
  "f \<in> {0::nat} \<rightarrow> carrier G \<Longrightarrow> finprod G f {..0} = f 0"
  by (simp add: Pi_def)

lemma finprod_0':
  "f \<in> {..n} \<rightarrow> carrier G \<Longrightarrow> (f 0) \<otimes> finprod G f {Suc 0..n} = finprod G f {..n}"
proof -
  assume A: "f \<in> {.. n} \<rightarrow> carrier G"
  hence "(f 0) \<otimes> finprod G f {Suc 0..n} = finprod G f {..0} \<otimes> finprod G f {Suc 0..n}"
    using finprod_0[of f] by (simp add: funcset_mem)
  also have " ... = finprod G f ({..0} \<union> {Suc 0..n})"
    using finprod_Un_disjoint[of "{..0}" "{Suc 0..n}" f] A by (simp add: funcset_mem)
  also have " ... = finprod G f {..n}"
    by (simp add: atLeastAtMost_insertL atMost_atLeast0)
  finally show ?thesis .
qed

lemma finprod_Suc [simp]:
  "f \<in> {..Suc n} \<rightarrow> carrier G \<Longrightarrow>
   finprod G f {..Suc n} = (f (Suc n) \<otimes> finprod G f {..n})"
by (simp add: Pi_def atMost_Suc)

lemma finprod_Suc2:
  "f \<in> {..Suc n} \<rightarrow> carrier G \<Longrightarrow>
   finprod G f {..Suc n} = (finprod G (%i. f (Suc i)) {..n} \<otimes> f 0)"
proof (induct n)
  case 0 thus ?case by (simp add: Pi_def)
next
  case Suc thus ?case by (simp add: m_assoc Pi_def)
qed

lemma finprod_Suc3:
  assumes "f \<in> {..n :: nat} \<rightarrow> carrier G"
  shows "finprod G f {.. n} = (f n) \<otimes> finprod G f {..< n}"
proof (cases "n = 0")
  case True thus ?thesis
   using assms atMost_Suc by simp
next
  case False
  then obtain k where "n = Suc k"
    using not0_implies_Suc by blast
  thus ?thesis
    using finprod_Suc[of f k] assms atMost_Suc lessThan_Suc_atMost by simp
qed

lemma finprod_reindex: \<^marker>\<open>contributor \<open>Jeremy Avigad\<close>\<close>
  "f \<in> (h ` A) \<rightarrow> carrier G \<Longrightarrow>
        inj_on h A \<Longrightarrow> finprod G f (h ` A) = finprod G (\<lambda>x. f (h x)) A"
proof (induct A rule: infinite_finite_induct)
  case (infinite A)
  hence "\<not> finite (h ` A)"
    using finite_imageD by blast
  with \<open>\<not> finite A\<close> show ?case by simp
qed (auto simp add: Pi_def)

lemma finprod_const: \<^marker>\<open>contributor \<open>Jeremy Avigad\<close>\<close>
  assumes a [simp]: "a \<in> carrier G"
    shows "finprod G (\<lambda>x. a) A = a [^] card A"
proof (induct A rule: infinite_finite_induct)
  case (insert b A)
  show ?case
  proof (subst finprod_insert[OF insert(1-2)])
    show "a \<otimes> (\<Otimes>x\<in>A. a) = a [^] card (insert b A)"
      by (insert insert, auto, subst m_comm, auto)
  qed auto
qed auto

lemma finprod_singleton: \<^marker>\<open>contributor \<open>Jesus Aransay\<close>\<close>
  assumes i_in_A: "i \<in> A" and fin_A: "finite A" and f_Pi: "f \<in> A \<rightarrow> carrier G"
  shows "(\<Otimes>j\<in>A. if i = j then f j else \<one>) = f i"
  using i_in_A finprod_insert [of "A - {i}" i "(\<lambda>j. if i = j then f j else \<one>)"]
    fin_A f_Pi finprod_one [of "A - {i}"]
    finprod_cong [of "A - {i}" "A - {i}" "(\<lambda>j. if i = j then f j else \<one>)" "(\<lambda>i. \<one>)"]
  unfolding Pi_def simp_implies_def by (force simp add: insert_absorb)

lemma finprod_singleton_swap:
  assumes i_in_A: "i \<in> A" and fin_A: "finite A" and f_Pi: "f \<in> A \<rightarrow> carrier G"
  shows "(\<Otimes>j\<in>A. if j = i then f j else \<one>) = f i"
  using finprod_singleton [OF assms] by (simp add: eq_commute)

lemma finprod_mono_neutral_cong_left:
  assumes "finite B"
    and "A \<subseteq> B"
    and 1: "\<And>i. i \<in> B - A \<Longrightarrow> h i = \<one>"
    and gh: "\<And>x. x \<in> A \<Longrightarrow> g x = h x"
    and h: "h \<in> B \<rightarrow> carrier G"
  shows "finprod G g A = finprod G h B"
proof-
  have eq: "A \<union> (B - A) = B" using \<open>A \<subseteq> B\<close> by blast
  have d: "A \<inter> (B - A) = {}" using \<open>A \<subseteq> B\<close> by blast
  from \<open>finite B\<close> \<open>A \<subseteq> B\<close> have f: "finite A" "finite (B - A)"
    by (auto intro: finite_subset)
  have "h \<in> A \<rightarrow> carrier G" "h \<in> B - A \<rightarrow> carrier G"
    using assms by (auto simp: image_subset_iff_funcset)
  moreover have "finprod G g A = finprod G h A \<otimes> finprod G h (B - A)"
  proof -
    have "finprod G h (B - A) = \<one>"
      using "1" finprod_one_eqI by blast
    moreover have "finprod G g A = finprod G h A"
      using \<open>h \<in> A \<rightarrow> carrier G\<close> finprod_cong' gh by blast
    ultimately show ?thesis
      by (simp add: \<open>h \<in> A \<rightarrow> carrier G\<close>)
  qed
  ultimately show ?thesis
    by (simp add: finprod_Un_disjoint [OF f d, unfolded eq])
qed

lemma finprod_mono_neutral_cong_right:
  assumes "finite B"
    and "A \<subseteq> B" "\<And>i. i \<in> B - A \<Longrightarrow> g i = \<one>" "\<And>x. x \<in> A \<Longrightarrow> g x = h x" "g \<in> B \<rightarrow> carrier G"
  shows "finprod G g B = finprod G h A"
  using assms  by (auto intro!: finprod_mono_neutral_cong_left [symmetric])

lemma finprod_mono_neutral_cong:
  assumes [simp]: "finite B" "finite A"
    and *: "\<And>i. i \<in> B - A \<Longrightarrow> h i = \<one>" "\<And>i. i \<in> A - B \<Longrightarrow> g i = \<one>"
    and gh: "\<And>x. x \<in> A \<inter> B \<Longrightarrow> g x = h x"
    and g: "g \<in> A \<rightarrow> carrier G"
    and h: "h \<in> B \<rightarrow> carrier G"
 shows "finprod G g A = finprod G h B"
proof-
  have "finprod G g A = finprod G g (A \<inter> B)"
    by (rule finprod_mono_neutral_cong_right) (use assms in auto)
  also have "\<dots> = finprod G h (A \<inter> B)"
    by (rule finprod_cong) (use assms in auto)
  also have "\<dots> = finprod G h B"
    by (rule finprod_mono_neutral_cong_left) (use assms in auto)
  finally show ?thesis .
qed

end

(* Jeremy Avigad. This should be generalized to arbitrary groups, not just commutative
   ones, using Lagrange's theorem. *)

lemma (in comm_group) power_order_eq_one:
  assumes fin [simp]: "finite (carrier G)"
    and a [simp]: "a \<in> carrier G"
  shows "a [^] card(carrier G) = one G"
proof -
  have "(\<Otimes>x\<in>carrier G. x) = (\<Otimes>x\<in>carrier G. a \<otimes> x)"
    by (subst (2) finprod_reindex [symmetric],
      auto simp add: Pi_def inj_on_cmult surj_const_mult)
  also have "\<dots> = (\<Otimes>x\<in>carrier G. a) \<otimes> (\<Otimes>x\<in>carrier G. x)"
    by (auto simp add: finprod_multf Pi_def)
  also have "(\<Otimes>x\<in>carrier G. a) = a [^] card(carrier G)"
    by (auto simp add: finprod_const)
  finally show ?thesis
    by auto
qed

lemma (in comm_monoid) finprod_UN_disjoint:
  assumes
    "finite I" "\<And>i. i \<in> I \<Longrightarrow> finite (A i)" "pairwise (\<lambda>i j. disjnt (A i) (A j)) I"
    "\<And>i x. i \<in> I \<Longrightarrow> x \<in> A i \<Longrightarrow> g x \<in> carrier G"
shows "finprod G g (\<Union>(A ` I)) = finprod G (\<lambda>i. finprod G g (A i)) I"
  using assms
proof (induction set: finite)
  case empty
  then show ?case
    by force
next
  case (insert i I)
  then show ?case
    unfolding pairwise_def disjnt_def
    apply clarsimp
    apply (subst finprod_Un_disjoint)
         apply (fastforce intro!: funcsetI finprod_closed)+
    done
qed

lemma (in comm_monoid) finprod_Union_disjoint:
  "\<lbrakk>finite C; \<And>A. A \<in> C \<Longrightarrow> finite A \<and> (\<forall>x\<in>A. f x \<in> carrier G); pairwise disjnt C\<rbrakk> \<Longrightarrow>
    finprod G f (\<Union>C) = finprod G (finprod G f) C"
  by (frule finprod_UN_disjoint [of C id f]) auto

end


(*  Author:     Tobias Nipkow
    Copyright   2004 TU Muenchen
*)

section \<open>Compiling exception handling\<close>

theory Exceptions
imports Main
begin

subsection\<open>The source language\<close>

datatype expr = Val int | Add expr expr | Throw | Catch expr expr

primrec eval :: "expr \<Rightarrow> int option"
where
  "eval (Val i) = Some i"
| "eval (Add x y) =
   (case eval x of None \<Rightarrow> None
    | Some i \<Rightarrow> (case eval y of None \<Rightarrow> None
                 | Some j \<Rightarrow> Some(i+j)))"
| "eval Throw = None"
| "eval (Catch x h) = (case eval x of None \<Rightarrow> eval h | Some i \<Rightarrow> Some i)"

subsection\<open>The target language\<close>

datatype instr =
  Push int | ADD | THROW | Mark nat | Unmark | Label nat | Jump nat

datatype item = VAL int | HAN nat

type_synonym code = "instr list"
type_synonym stack = "item list"

fun jump where
  "jump l [] = []"
| "jump l (Label l' # cs) = (if l = l' then cs else jump l cs)"
| "jump l (c # cs) = jump l cs"

lemma size_jump1: "size (jump l cs) < Suc (size cs)"
apply(induct cs)
 apply simp
apply(case_tac a)
apply auto
done

lemma size_jump2: "size (jump l cs) < size cs \<or> jump l cs = cs"
apply(induct cs)
 apply simp
apply(case_tac a)
apply auto
done

function (sequential) exec2 :: "bool \<Rightarrow> code \<Rightarrow> stack \<Rightarrow> stack" where
  "exec2 True [] s = s"
| "exec2 True (Push i#cs) s = exec2 True cs (VAL i # s)"
| "exec2 True (ADD#cs) (VAL j # VAL i # s) = exec2 True cs (VAL(i+j) # s)"
| "exec2 True (THROW#cs) s = exec2 False cs s"
| "exec2 True (Mark l#cs) s = exec2 True cs (HAN l # s)"
| "exec2 True (Unmark#cs) (v # HAN l # s) = exec2 True cs (v # s)"
| "exec2 True (Label l#cs) s = exec2 True cs s"
| "exec2 True (Jump l#cs) s = exec2 True (jump l cs) s"

| "exec2 False cs [] = []"
| "exec2 False cs (VAL i # s) = exec2 False cs s"
| "exec2 False cs (HAN l # s) = exec2 True (jump l cs) s"
by pat_completeness auto

termination by (relation
  "inv_image (measure(%cs. size cs) <*lex*> measure(%s. size s)) (%(b,cs,s). (cs,s))")
    (auto simp add: size_jump1 size_jump2)

abbreviation "exec \<equiv> exec2 True"
abbreviation "unwind \<equiv> exec2 False"

subsection\<open>The compiler\<close>

primrec compile :: "nat \<Rightarrow> expr \<Rightarrow> code * nat"
where
  "compile l (Val i) = ([Push i], l)"
| "compile l (Add x y) = (let (xs,m) = compile l x; (ys,n) = compile m y
                       in (xs @ ys @ [ADD], n))"
| "compile l Throw = ([THROW],l)"
| "compile l (Catch x h) =
    (let (xs,m) = compile (l+2) x; (hs,n) = compile m h
     in (Mark l # xs @ [Unmark, Jump (l+1), Label l] @ hs @ [Label(l+1)], n))"

abbreviation
  cmp :: "nat \<Rightarrow> expr \<Rightarrow> code" where
  "cmp l e == fst(compile l e)"

primrec isFresh :: "nat \<Rightarrow> stack \<Rightarrow> bool"
where
  "isFresh l [] = True"
| "isFresh l (it#s) = (case it of VAL i \<Rightarrow> isFresh l s
                       | HAN l' \<Rightarrow> l' < l \<and> isFresh l s)"

definition
  conv :: "code \<Rightarrow> stack \<Rightarrow> int option \<Rightarrow> stack" where
  "conv cs s io = (case io of None \<Rightarrow> unwind cs s
                  | Some i \<Rightarrow> exec cs (VAL i # s))"

subsection\<open>The proofs\<close>

text\<open>Lemma numbers are the same as in the paper.\<close>

declare
  conv_def[simp] option.splits[split] Let_def[simp]

lemma 3:
  "(\<And>l. c = Label l \<Longrightarrow> isFresh l s) \<Longrightarrow> unwind (c#cs) s = unwind cs s"
apply(induct s)
 apply simp
apply(auto)
apply(case_tac a)
apply auto
apply(case_tac c)
apply auto
done

corollary [simp]:
  "(!!l. c \<noteq> Label l) \<Longrightarrow> unwind (c#cs) s = unwind cs s"
by(blast intro: 3)

corollary [simp]:
  "isFresh l s \<Longrightarrow> unwind (Label l#cs) s = unwind cs s"
by(blast intro: 3)

lemma 5: "\<lbrakk> isFresh l s; l \<le> m \<rbrakk> \<Longrightarrow> isFresh m s"
apply(induct s)
 apply simp
apply(auto split:item.split)
done

corollary [simp]: "isFresh l s \<Longrightarrow> isFresh (Suc l) s"
by(auto intro:5)

lemma 6: "\<And>l. l \<le> snd(compile l e)"
proof(induct e)
  case Val thus ?case by simp
next
  case (Add x y)
  from \<open>l \<le> snd (compile l x)\<close>
   and \<open>snd (compile l x) \<le> snd (compile (snd (compile l x)) y)\<close>
  show ?case by(simp_all add:split_def)
next
  case Throw thus ?case by simp
next
  case (Catch x h)
  from \<open>l+2 \<le> snd (compile (l+2) x)\<close>
   and \<open>snd (compile (l+2) x) \<le> snd (compile (snd (compile (l+2) x)) h)\<close>
  show ?case by(simp_all add:split_def)
qed

corollary [simp]: "l < m \<Longrightarrow> l < snd(compile m e)"
using 6[where l = m and e = e] by auto

corollary [simp]: "isFresh l s \<Longrightarrow> isFresh (snd(compile l e)) s"
using 5 6 by blast

text\<open>Contrary to what the paper says, the proof of lemma 4 does not
just need lemma 3 but also the above corollary of 5 and 6. Hence the
strange order of the lemmas in our proof.\<close>

lemma 4 [simp]: "\<And>l cs. isFresh l s \<Longrightarrow> unwind (cmp l e @ cs) s = unwind cs s"
by (induct e) (auto simp add:split_def)

lemma 7 [simp]: "l < m \<Longrightarrow> jump l (cmp m e @ cs) = jump l cs"
by (induct e arbitrary: m cs) (simp_all add:split_def)

text\<open>The compiler correctness theorem:\<close>

theorem comp_corr:
  "\<And>l s cs. isFresh l s \<Longrightarrow> exec (cmp l e @ cs) s = conv cs s (eval e)"
by(induct e)(auto simp add:split_def)

text\<open>The specialized and more readable version (omitted in the paper):\<close>

corollary "exec (cmp l e) [] = (case eval e of None \<Rightarrow> [] | Some n \<Rightarrow> [VAL n])"
by (simp add: comp_corr[where cs = "[]", simplified])

end


(* Missing file in theory import *)

theory IMP_Minus_Common_Funs_Nat
  imports "../../IMP-/IMP_Minus_Nat_Bijection"
begin

subsection \<open>append\<close>

text\<open>Goal of this subsection is *append_tail*, which is defined in terms
  of reverse_nat and append_acc, both of which, in turn, are defined in
  terms of -- or can be related to -- *reverse_nat_acc*.\<close>

lemma revapp: "append_acc acc xs = reverse_nat_acc acc xs"
  by(induction xs arbitrary: acc rule: append_acc.induct) simp+

(*
  append_tail xs ys
= reverse_nat       (append_acc      (reverse_nat       xs) ys)
= reverse_nat       (reverse_nat_acc (reverse_nat       xs) ys)
= reverse_nat_acc 0 (reverse_nat_acc (reverse_nat_acc 0 xs) ys)
*)

(* Registers:
e: xs
f: ys
*)
definition append_tail_IMP_Minus where "append_tail_IMP_Minus \<equiv>
  ''a'' ::= (A (N 0)) ;;
  ''b'' ::= (A (V ''e'')) ;;
  ''append_tail'' ::= (A (V ''f'')) ;;
  reverse_nat_acc_IMP_Minus ;;
  ''a'' ::= (A (V ''reverse_nat_acc'')) ;;
  ''b'' ::= (A (V ''append_tail'')) ;;
  reverse_nat_acc_IMP_Minus ;;
  ''a'' ::= (A (N 0)) ;;
  ''b'' ::= (A (V ''reverse_nat_acc'')) ;;
  reverse_nat_acc_IMP_Minus ;;
  ''append_tail'' ::= (A (V ''reverse_nat_acc'')) ;;
  zero_variables [''a'', ''b'', ''c'', ''d'', ''e'', ''f'', ''fst_nat'', ''snd_nat'', ''cons'',
    ''triangle'', ''prod_encode'', ''reverse_nat_acc'']"

definition append_tail_IMP_Minus_time where
  "append_tail_IMP_Minus_time xs ys \<equiv>
16
+ reverse_nat_acc_IMP_Minus_time 0 xs
+ reverse_nat_acc_IMP_Minus_time (reverse_nat_acc 0 xs) ys
+ reverse_nat_acc_IMP_Minus_time 0 (reverse_nat_acc (reverse_nat_acc 0 xs) ys)
+ zero_variables_time [''a'', ''b'', ''c'', ''d'', ''e'', ''f'', ''fst_nat'', ''snd_nat'', ''cons'',
    ''triangle'', ''prod_encode'', ''reverse_nat_acc'']"

lemma append_tail_IMP_Minus_correct:
  "(append_tail_IMP_Minus, s)
    \<Rightarrow>\<^bsup>append_tail_IMP_Minus_time (s ''e'') (s ''f'')\<^esup>
  s(''a'':=0, ''b'':=0, ''c'':=0, ''d'':=0, ''e'':=0, ''f'':=0,
    ''fst_nat'':=0, ''snd_nat'':=0, ''cons'':=0,
    ''triangle'':=0, ''prod_encode'':=0, ''reverse_nat_acc'':=0,
    ''append_tail'':= append_tail (s ''e'') (s ''f''))"
  unfolding append_tail_IMP_Minus_def append_tail_IMP_Minus_time_def
  by (fastforce simp: ext reverse_nat_def revapp append_tail_def
      simp del: reverse_nat_acc.simps
      intro!: terminates_in_time_state_intro[OF Seq']
      intro: zero_variables_correct reverse_nat_acc_IMP_Minus_correct
      )+

subsection \<open>elemof\<close>

(* Registers:
  e: e
  f: list
  a: "result"
*)
definition elemof_IMP_Minus_iteration where "elemof_IMP_Minus_iteration \<equiv>
  ''a'' ::= ((V ''f'') \<ominus> (N 1)) ;;
  IMP_Minus_fst_nat ;;
  ''a'' ::= ((V ''fst_nat'') \<ominus> (V ''e'')) ;;
  ''b'' ::= ((V ''e'') \<ominus> (V ''fst_nat'')) ;;
  ''a'' ::= ((V ''a'') \<oplus> (V ''b'')) ;;
  IF ''a''\<noteq>0 THEN
    ''a'' ::= ((V ''f'') \<ominus> (N 1)) ;;
    IMP_Minus_snd_nat ;;

    ''f'' ::= (A (V ''snd_nat''))
  ELSE (
    ''a'' ::= (A (N 1));;
    ''f'' ::= (A (N 0))
  ) ;;
  zero_variables [''b'', ''c'', ''fst_nat'', ''snd_nat'']"
(*
WHILE 0/=l DO
  if hd_nat l = e then r = 1; BREAK
  else l = tl_nat l
*)

definition elemof_IMP_Minus_iteration_time where
  "elemof_IMP_Minus_iteration_time e l \<equiv>
  8 + IMP_Minus_fst_nat_time (l - 1) +
  (if e = hd_nat l then 5
  else 5 + IMP_Minus_fst_nat_time (l - 1))
  + zero_variables_time [''b'', ''c'', ''fst_nat'', ''snd_nat'']"

lemma elemof_IMP_Minus_iteration_correct:
  "(elemof_IMP_Minus_iteration, s)
    \<Rightarrow>\<^bsup>elemof_IMP_Minus_iteration_time (s ''e'') (s ''f'')\<^esup>
  s(''a'' := (if (s ''e'') = hd_nat (s ''f'') then 1 else 0),
    ''b'' := 0,
    ''c'' := 0,
    ''f'' := (if (s ''e'') = hd_nat (s ''f'') then 0 else (tl_nat (s ''f''))),
    ''fst_nat'' := 0,
    ''snd_nat'' := 0)"
proof(cases "hd_nat (s ''f'') = s ''e''")
  case True
  then show ?thesis
    unfolding elemof_IMP_Minus_iteration_def
      elemof_IMP_Minus_iteration_time_def
    by (fastforce simp: hd_nat_def
        intro!: terminates_in_time_state_intro[OF Seq']
        intro:zero_variables_correct IMP_Minus_fst_nat_correct
        )+
next
  case False
  then show ?thesis
    unfolding elemof_IMP_Minus_iteration_def
      elemof_IMP_Minus_iteration_time_def
    by (fastforce simp: hd_nat_def tl_nat_def
        intro!: terminates_in_time_state_intro[OF Seq']
        intro: zero_variables_correct
        IMP_Minus_fst_nat_correct
        IMP_Minus_snd_nat_correct
        )+
qed

definition elemof_IMP_Minus_loop where "elemof_IMP_Minus_loop \<equiv>
  (WHILE ''f'' \<noteq>0 DO elemof_IMP_Minus_iteration)"

fun elemof_IMP_Minus_loop_time :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
  "elemof_IMP_Minus_loop_time e 0 = 2"
| "elemof_IMP_Minus_loop_time e l = 1 + elemof_IMP_Minus_iteration_time e l
 + elemof_IMP_Minus_loop_time e (if e = hd_nat l then 0 else (tl_nat l))"

lemma elemof_IMP_Minus_loop_correct:
  assumes "s ''a'' = 0" "s ''b'' = 0" "s ''c'' = 0" "s ''fst_nat'' = 0" "s ''snd_nat'' = 0"
  shows
    "(elemof_IMP_Minus_loop, s)
    \<Rightarrow>\<^bsup>elemof_IMP_Minus_loop_time (s ''e'') (s ''f'')\<^esup>
  s(''a'' := elemof (s ''e'') (s ''f''),
    ''b'' := 0,
    ''c'' := 0,
    ''f'' := 0,
    ''fst_nat'' := 0,
    ''snd_nat'' := 0 )"
  using assms
proof(induction "s ''e''" "s ''f''" arbitrary: s rule: elemof.induct)
  case 1
  then show ?case
  proof(cases "s ''f''")
    case 0 then show ?thesis
      unfolding elemof_IMP_Minus_loop_def
      by(auto simp: numeral_2_eq_2 1
          intro!: terminates_in_state_intro[OF Big_StepT.WhileFalse])
  next
    case (Suc nat)
    show ?thesis
    proof(cases "hd_nat (s ''f'') = s ''e''")
      case True
      then show ?thesis unfolding elemof_IMP_Minus_loop_def
        using Suc
          terminates_in_time_state_intro[OF Big_StepT.WhileTrue[of s], OF _
            elemof_IMP_Minus_iteration_correct Big_StepT.WhileFalse ]
        by simp
    next
      case False
      show ?thesis unfolding elemof_IMP_Minus_loop_def
        apply(rule terminates_in_state_intro[OF Big_StepT.WhileTrue])
            apply(simp add: Suc)
           apply(rule elemof_IMP_Minus_iteration_correct)
          apply(subst elemof_IMP_Minus_loop_def[symmetric])
          apply(rule 1(1))
        using False Suc by auto
    qed
  qed
qed

(* Registers:
  a: e
  b: l
*)
definition elemof_IMP_Minus where "elemof_IMP_Minus \<equiv>
  ''e'' ::= (A (V ''a'')) ;;
  ''f'' ::= (A (V ''b'')) ;;
  zero_variables [''a'', ''b'', ''c'', ''fst_nat'', ''snd_nat''] ;;
  elemof_IMP_Minus_loop ;;
  ''elemof'' ::= (A (V ''a'')) ;;
  zero_variables [''a'', ''b'', ''c'', ''e'', ''f'', ''fst_nat'', ''snd_nat'']"

definition elemof_IMP_Minus_time :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
  "elemof_IMP_Minus_time e l = 2 + 2
 + zero_variables_time [''a'', ''b'', ''c'', ''fst_nat'', ''snd_nat'']
 + elemof_IMP_Minus_loop_time e l + 2
 + zero_variables_time [''a'', ''b'', ''c'', ''e'', ''f'', ''fst_nat'', ''snd_nat'']
"

lemma elemof_IMP_Minus_correct:
  "(elemof_IMP_Minus, s)
    \<Rightarrow>\<^bsup>elemof_IMP_Minus_time (s ''a'') (s ''b'')\<^esup>
  s(''a'' := 0,
    ''b'' := 0,
    ''c'' := 0,
    ''e'' := 0,
    ''f'' := 0,
    ''fst_nat'' := 0,
    ''snd_nat'' := 0,
    ''elemof'' := elemof (s ''a'') (s ''b'')
  )"
  unfolding elemof_IMP_Minus_def elemof_IMP_Minus_time_def
  by(fastforce
      intro!: ext terminates_in_time_state_intro[OF Seq']
      intro: zero_variables_correct elemof_IMP_Minus_loop_correct
      )+

subsection \<open>remdups_tail\<close>

subsection \<open>list_from_acc\<close>

(* Registers:
acc: d
s: e
n: f
*)
definition list_from_acc_IMP_Minus_iteration where
  "list_from_acc_IMP_Minus_iteration \<equiv>
  cons_IMP_Minus (V ''e'') (V ''d'') ;;
  ''d'' ::= (A (V ''cons'')) ;;
  ''e'' ::= ((V ''e'') \<oplus> (N 1)) ;;
  ''f'' ::= ((V ''f'') \<ominus> (N 1))
"

definition list_from_acc_IMP_Minus_iteration_time where
  "list_from_acc_IMP_Minus_iteration_time h t \<equiv>
  cons_IMP_Minus_time h t + 6
"

lemma list_from_acc_IMP_Minus_iteration_correct:
  "(list_from_acc_IMP_Minus_iteration, s)
  \<Rightarrow>\<^bsup>list_from_acc_IMP_Minus_iteration_time (s ''e'') (s ''d'') \<^esup>
    s(''a'' := 0,
      ''b'' := 0,
      ''c'' := 0,
      ''d'' := (s ''e'')##(s ''d''),
      ''e'' := (s ''e'') + 1,
      ''f'' := (s ''f'') - 1,
      ''triangle'' := 0,
      ''prod_encode'' := 0,
      ''cons'' := (s ''e'')##(s ''d'')
    )"
  unfolding list_from_acc_IMP_Minus_iteration_def list_from_acc_IMP_Minus_iteration_time_def
  by(fastforce
      intro!: terminates_in_time_state_intro[OF Seq']
      intro: cons_IMP_Minus_correct)+

fun list_from_acc_IMP_Minus_loop_time where
  "list_from_acc_IMP_Minus_loop_time acc s 0 = 2"
| "list_from_acc_IMP_Minus_loop_time acc s (Suc n) =
  1 + list_from_acc_IMP_Minus_iteration_time s acc
  + list_from_acc_IMP_Minus_loop_time (s##acc) (s+1) n"

lemma list_from_acc_loop_correct:
  assumes "s ''cons'' = s ''d''"
    "s ''a'' = 0" "s ''b'' = 0" "s ''c'' = 0"
    "s ''triangle'' = 0" "s ''prod_encode'' = 0"
  shows "(WHILE ''f''\<noteq>0 DO list_from_acc_IMP_Minus_iteration, s)
  \<Rightarrow>\<^bsup>list_from_acc_IMP_Minus_loop_time (s ''d'') (s ''e'') (s ''f'') \<^esup>
    s(''a'' := 0,
      ''b'' := 0,
      ''c'' := 0,
      ''d'' := list_from_acc (s ''d'') (s ''e'') (s ''f''),
      ''e'' := (s ''e'') + (s ''f''),
      ''f'' := 0,
      ''triangle'' := 0,
      ''prod_encode'' := 0,
      ''cons'' := list_from_acc (s ''d'') (s ''e'') (s ''f'')
    )"
  using assms
proof(induct "s ''d''" "s ''e''" "s ''f''" arbitrary: s rule: list_from_acc.induct)
  case 1
  show ?case
  proof(cases "s ''f''")
    case 0 then show ?thesis
      by(auto simp add: 1 intro!: terminates_in_time_state_intro[OF Big_StepT.WhileFalse])
  next
    case (Suc nat)
    show ?thesis
      apply(rule terminates_in_time_state_intro[OF Big_StepT.WhileTrue])
           apply(fastforce
          simp add: 1 Suc
          intro: 1(1) list_from_acc_IMP_Minus_iteration_correct)+
      done
  qed
qed

subsection \<open>concat_acc\<close>

(*
WHILE n \<noteq> 0
  acc := append_tail (reverse_nat (hd_nat n)) acc ;
  n = tl_nat n ;

WHILE n \<noteq> 0
  $fst = hd_nat n ;             -- $ABC fst
  $rev = reverse_nat $fst ;     -- $ABCDEF fst snd cons triangle prod_encode
  $app = append_tail $rev acc ; -- $ABCDEF fst snd cons triangle prod_encode rev app
  acc := $app ;
  $snd = tl_nat n ;             -- $ABC snd
  n = $snd ;
*)

definition concat_acc_IMP_Minus_iteration where
  "concat_acc_IMP_Minus_iteration \<equiv>
  ''a'' ::= ((V ''n'') \<ominus> (N 1)) ;;
  IMP_Minus_fst_nat ;;
  ''a'' ::= (A (N 0)) ;;
  ''b'' ::= (A (V ''fst_nat'')) ;;
  reverse_nat_acc_IMP_Minus ;;
  ''e'' ::= (A (V ''reverse_nat_acc'')) ;;
  ''f'' ::= (A (V ''acc'')) ;;
  append_tail_IMP_Minus ;;
  ''acc'' ::= (A (V ''append_tail'')) ;;
  ''a'' ::= ((V ''n'') \<ominus> (N 1)) ;;
  IMP_Minus_snd_nat ;;
  ''n'' ::= (A (V ''snd_nat'')) ;;
  zero_variables [''a'', ''b'', ''c'', ''d'', ''e'', ''f'',
    ''fst_nat'', ''snd_nat'', ''cons'', ''triangle'', ''prod_encode'',
    ''reverse_nat_acc'', ''append_tail'']
  "

definition concat_acc_IMP_Minus_iteration_time where
  "concat_acc_IMP_Minus_iteration_time acc n \<equiv>
  16
+ IMP_Minus_fst_nat_time (n - 1)
+ reverse_nat_acc_IMP_Minus_time 0 (hd_nat n)
+ append_tail_IMP_Minus_time (reverse_nat_acc 0 (hd_nat n)) acc
+ IMP_Minus_fst_nat_time (n - 1)
+ zero_variables_time [''a'', ''b'', ''c'', ''d'', ''e'', ''f'',
    ''fst_nat'', ''snd_nat'', ''cons'', ''triangle'', ''prod_encode'',
    ''reverse_nat_acc'', ''append_tail'']
"

lemma concat_acc_IMP_Minus_iteration_correct:
  "(concat_acc_IMP_Minus_iteration, s)
    \<Rightarrow>\<^bsup>concat_acc_IMP_Minus_iteration_time (s ''acc'') (s ''n'')\<^esup>
  s(''a'' := 0, ''b'' := 0, ''c'' := 0, ''d'' := 0, ''e'' := 0, ''f'' := 0,
  ''fst_nat'' := 0, ''snd_nat'' := 0, ''cons'' := 0,
  ''triangle'' := 0, ''prod_encode'' := 0,
  ''reverse_nat_acc'' := 0, ''append_tail'' := 0,
  ''acc'' := append_tail (reverse_nat (hd_nat (s ''n''))) (s ''acc''),
  ''n'' := tl_nat (s ''n'')
)"
  unfolding concat_acc_IMP_Minus_iteration_def
    concat_acc_IMP_Minus_iteration_time_def
  by(fastforce simp: hd_nat_def tl_nat_def reverse_nat_def
      intro!: ext terminates_in_time_state_intro[OF Seq']
      intro: IMP_Minus_fst_nat_correct IMP_Minus_snd_nat_correct
      reverse_nat_acc_IMP_Minus_correct
      append_tail_IMP_Minus_correct
      zero_variables_correct)+

fun concat_acc_IMP_Minus_loop_time where
  "concat_acc_IMP_Minus_loop_time acc 0 = 2"
| "concat_acc_IMP_Minus_loop_time acc n = 1
+ concat_acc_IMP_Minus_iteration_time acc n
+ concat_acc_IMP_Minus_loop_time (append_tail (reverse_nat (hd_nat n)) acc) (tl_nat n)
"

lemma concat_acc_IMP_Minus_correct:
  assumes "s ''a'' = 0" "s ''b'' = 0" "s ''c'' = 0" "s ''d'' = 0" "s ''e'' = 0" "s ''f'' = 0"
    "s ''fst_nat'' = 0" "s ''snd_nat'' = 0" "s ''cons'' = 0"
    "s ''triangle'' = 0" "s ''prod_encode'' = 0"
    "s ''reverse_nat_acc'' = 0" "s ''append_tail'' = 0"
  shows "(WHILE ''n''\<noteq>0 DO concat_acc_IMP_Minus_iteration, s)
    \<Rightarrow>\<^bsup>concat_acc_IMP_Minus_loop_time (s ''acc'') (s ''n'')\<^esup>
s(''a'':=0, ''b'':=0, ''c'':=0, ''d'':=0, ''e'':=0, ''f'':=0,
''fst_nat'' := 0, ''snd_nat'' := 0, ''cons'' := 0,
  ''triangle'' := 0, ''prod_encode'' := 0,
  ''reverse_nat_acc'' := 0, ''append_tail'' := 0,
  ''acc'' := concat_acc (s ''acc'') (s ''n''),
  ''n'' := 0)"
  using assms
proof(induct "s ''acc''" "s ''n''" arbitrary: s rule: concat_acc.induct)
  case 1
  show ?case proof(cases "s ''n''")
    case 0
    then show ?thesis
      by(auto simp add: 1
          intro!: terminates_in_time_state_intro[OF Big_StepT.WhileFalse]
          )
    next
    case (Suc nat)
    show ?thesis
      apply(rule terminates_in_time_state_intro[OF Big_StepT.WhileTrue])
           apply(fastforce simp: Suc intro: 1(1) concat_acc_IMP_Minus_iteration_correct)+
      done
  qed
qed

end


theory BetsAndValidators

imports Main

begin

datatype validator = Validator int

type_synonym weight = "validator \<Rightarrow> int"

definition tie_breaking :: "validator set \<Rightarrow> weight \<Rightarrow> bool"
where
"tie_breaking V w =
 ( \<forall> S0 S1.
    S0 \<subseteq> V \<longrightarrow>
    S1 \<subseteq> V \<longrightarrow>
    S0 \<noteq> S1 \<longrightarrow>
    sum w S0 \<noteq> sum w S1
 )"

definition uniform_weight :: "validator \<Rightarrow> int"
where
"uniform_weight v = 1"

lemma should_be_false: "\<not> tie_breaking {Validator 0, Validator 1} uniform_weight "
apply(simp add: tie_breaking_def)
apply(rule_tac x = "{Validator 1}" in exI)
apply simp
apply(rule_tac x = "{Validator 0}" in exI)
apply (simp add: uniform_weight_def)
done

datatype estimate = Estimate bool

datatype bet =
  Bet "estimate * validator * bet list"

fun sender :: "bet \<Rightarrow> validator"
where
"sender (Bet (_, v, _)) = v"

fun est :: "bet \<Rightarrow> estimate"
where
"est (Bet (e, _, _)) = e"

fun justifies :: "bet \<Rightarrow> (bet \<Rightarrow> bool)"
where
"justifies b (Bet (e, v, js)) = (b \<in> set js)"

inductive tran :: "(bet \<Rightarrow> bet \<Rightarrow> bool) \<Rightarrow> (bet \<Rightarrow> bet \<Rightarrow> bool)"
where
  tran_simple: "R x y \<Longrightarrow> tran R x y"
| tran_composit: "tran R x y \<Longrightarrow> R y z \<Longrightarrow> tran R x z"

lemma tran_cases :
"tran R x z = (R x z \<or> (\<exists> y. R y z \<and> tran R x y))"
by (metis tran.simps)

definition is_dependency :: "bet \<Rightarrow> bet \<Rightarrow> bool"
where
"is_dependency = tran justifies"

(*
lemma justifies_antisymmetric:
  "\<not> justifies b b"
sledgehammer
*)

lemma is_dependency_tail_first :
  "tran R y z \<Longrightarrow> R x y \<Longrightarrow> tran R x z"
apply(induction rule: tran.induct)
  apply (meson tran_cases)
	using tran_composit by blast

(* no cycle *)
lemma dependency_no_cycle :
  "\<forall> a. is_dependency a b \<longrightarrow> \<not> is_dependency b a"
apply(induction b)
apply(simp add: is_dependency_def)
apply(rule allI)
apply(rule impI)
apply(subgoal_tac "tran justifies a (Bet xa)  = (justifies a (Bet xa) \<or> (\<exists> y. justifies y (Bet xa) \<and> tran justifies a y))" )
 defer
 using tran_cases apply blast
apply auto
by (meson is_dependency_tail_first justifies.simps)

lemma dependency_is_transitive :
  "is_dependency y z \<Longrightarrow> \<forall> x. is_dependency x y \<longrightarrow> is_dependency x z"
apply(simp add: is_dependency_def)
apply(induction rule: tran.induct)
 using tran_composit apply blast
using tran_composit by blast

definition equivocation :: "bet \<Rightarrow> bet \<Rightarrow> bool"
where
"equivocation b0 b1 =
   (sender b0 = sender b1 \<and> \<not> is_dependency b0 b1 \<and> \<not> is_dependency b1 b0 \<and> b0 \<noteq> b1 )"

definition is_view :: "bet set \<Rightarrow> bool"
where
"is_view bs = (\<forall> b0 b1. b0 \<in> bs \<longrightarrow> b1 \<in> bs \<longrightarrow> \<not> equivocation b0 b1)"

definition latest_bets :: "bet set \<Rightarrow> validator \<Rightarrow> bet set"
where
" latest_bets bs v = { l . l \<in> bs \<and> sender l = v \<and> (\<not> (\<exists> b'. b' \<in> bs \<and> sender b' = v \<and> is_dependency l b')) } "

definition is_latest_in :: "bet \<Rightarrow> bet set \<Rightarrow> bool"
where
"is_latest_in b bs = (b \<in> bs \<and> (\<not> (\<exists> b'. b' \<in> bs \<and> is_dependency b b')))"

lemma latest_bets_are_latest_in :
"(latest_bets bs v) = {b. (is_latest_in b {b' . b' \<in> bs \<and> sender b' = v})}"
apply(auto simp add: is_latest_in_def latest_bets_def)
done

definition is_non_empty :: "'a set \<Rightarrow> bool"
where
"is_non_empty bs =
  ( \<exists>b. b\<in>bs )"

lemma latest_existence' :
  "finite bs \<Longrightarrow> is_non_empty bs \<longrightarrow> (\<exists> l. is_latest_in l bs)"
apply(rule finite_induct)
  apply simp
 apply (simp add: is_non_empty_def)
apply(case_tac "is_non_empty F")
 defer
 apply(simp add: is_non_empty_def)
 apply(rule_tac x = x in exI)
 using dependency_no_cycle is_latest_in_def apply auto[1]
apply auto
apply(case_tac "is_dependency l x")
 defer
 apply(rule_tac x = l in exI)
 using is_latest_in_def apply auto[1]
apply(rule_tac x = x in exI)
apply(auto simp add: is_latest_in_def)
 using dependency_no_cycle apply blast
using dependency_is_transitive by blast

lemma latest_existence :
  "finite bs \<Longrightarrow> is_non_empty bs \<Longrightarrow> (\<exists> l. is_latest_in l bs)"
using latest_existence' by auto

lemma two_latests_are_equivocation :
  "b0 \<in> latest_bets bs v \<Longrightarrow> b1 \<in> latest_bets bs v \<Longrightarrow> b0 \<noteq> b1 \<Longrightarrow> equivocation b0 b1"
apply(simp add: equivocation_def latest_bets_def)
done

definition at_most_one :: "'a set \<Rightarrow> bool"
where
"at_most_one s = (\<forall> x y. x \<in> s \<longrightarrow> y \<in> s \<longrightarrow> x = y)"

lemma view_has_at_most_one_latest_bet :
  "is_view bs \<Longrightarrow>
   at_most_one (latest_bets bs v)"
apply(auto simp add: at_most_one_def is_view_def)
apply(drule_tac x = x in spec)
apply(subgoal_tac "x \<in> bs")
 apply simp
 apply(drule_tac x = y in spec)
 apply(subgoal_tac "y \<in> bs")
  apply simp
  using two_latests_are_equivocation apply fastforce
 apply(auto simp add: latest_bets_def)
done

(*
by (meson at_most_one_def is_view_def latest_bets_def mem_Collect_eq two_latests_are_equivocation)
*)

lemma should_be_not_be_non_empty :
  "\<not>is_non_empty {}"
by(simp add: is_non_empty_def)

definition observed_validators :: "bet set \<Rightarrow> validator set"
where
  "observed_validators bs =
({v :: validator. \<exists>b. b \<in> bs \<and> v = sender b })"

lemma observed_validators_exist_in_non_empty_bet_set :
  "is_non_empty bs \<Longrightarrow> is_non_empty (observed_validators bs)"
by (simp add: is_non_empty_def observed_validators_def)

lemma observed_validator_has_latest_bet :
  "finite bs \<longrightarrow> v \<in> (observed_validators bs) \<longrightarrow> is_non_empty (latest_bets bs v)"
apply(simp add: is_non_empty_def observed_validators_def)
apply(simp add: latest_bets_are_latest_in)
apply clarify
apply(rule latest_existence)
 apply auto
using is_non_empty_def by blast

lemma latest_bets_exist_in_non_empty_bet_set :
  "finite bs \<Longrightarrow>
   is_non_empty bs \<Longrightarrow>
  \<exists>v::validator.(is_non_empty (latest_bets bs v))
   "
by (meson is_non_empty_def observed_validator_has_latest_bet observed_validators_exist_in_non_empty_bet_set)

definition has_a_latest_bet_on :: "bet set \<Rightarrow> validator \<Rightarrow> estimate \<Rightarrow> bool"
where
"has_a_latest_bet_on bs v e =
 (\<exists> b. b \<in> latest_bets bs v \<and> est b = e)"

lemma validator_in_view_contributes_to_at_most_one_estimates_weight :
  "is_view bs \<Longrightarrow>
   \<forall>v. v\<in>(observed_validators bs) \<longrightarrow> at_most_one {e. (has_a_latest_bet_on bs v e)}
  "
apply(auto simp add: has_a_latest_bet_on_def at_most_one_def)
apply(drule_tac v = v in view_has_at_most_one_latest_bet)
apply(auto simp add: at_most_one_def)
done

definition weight_of_estimate :: "bet set \<Rightarrow> weight \<Rightarrow> estimate \<Rightarrow> int"
where
"weight_of_estimate bs w e =
 sum w { v. has_a_latest_bet_on bs v e }"

definition is_max_weight_estimate :: "bet set \<Rightarrow> weight \<Rightarrow> estimate \<Rightarrow> bool"
where
"is_max_weight_estimate bs w e =
  (\<forall> e'.
   weight_of_estimate bs w e \<ge> weight_of_estimate bs w e')
 "

definition positive_weights :: "validator set \<Rightarrow> weight \<Rightarrow> bool"
where
"positive_weights vs w =
  (\<forall>v. v \<in> vs \<longrightarrow> w v > 0)
"

lemma finite_observed_validators :
  "finite bs \<Longrightarrow> finite (observed_validators bs)"
apply(simp add: observed_validators_def)
done

lemma finite_latest_betters_if_only_finite_bets :
 "finite bs \<Longrightarrow>
  finite {v. has_a_latest_bet_on bs v e}"
apply(simp add: has_a_latest_bet_on_def latest_bets_def)
done

lemma any_latest_bet_witnesses_a_validator:
  "Bet (e, v', js) \<in> latest_bets bs v \<Longrightarrow> {v. has_a_latest_bet_on bs v e} \<noteq> {}"
apply(auto simp add: latest_bets_def has_a_latest_bet_on_def)
done

lemma latest_bets_have_positive_weights :
   "finite bs \<Longrightarrow>
    positive_weights (observed_validators bs) w \<Longrightarrow>
    Bet (e, v', js) \<in> latest_bets bs v \<Longrightarrow>
    weight_of_estimate bs w e > 0"
apply(auto simp add: weight_of_estimate_def)
apply(rule Groups_Big.ordered_comm_monoid_add_class.sum_pos)
  apply(simp add: finite_latest_betters_if_only_finite_bets)
 using any_latest_bet_witnesses_a_validator apply blast
using has_a_latest_bet_on_def latest_bets_def observed_validators_def positive_weights_def by auto

lemma non_empty_bet_set_has_non_zero_weight_for_some_estimate :
  "finite bs \<Longrightarrow>
   is_non_empty bs \<Longrightarrow>
   positive_weights (observed_validators bs) w \<Longrightarrow>
   \<exists>e. weight_of_estimate bs w e > 0"
apply(subgoal_tac "
  \<exists>v::validator.(is_non_empty (latest_bets bs v))")
 defer
 using latest_bets_exist_in_non_empty_bet_set apply auto[1]
apply(auto simp add: is_non_empty_def)
apply(case_tac ba)
apply(case_tac x)
apply simp
using latest_bets_have_positive_weights by blast

lemma tie_breaking_contra :
    "tie_breaking vs w \<Longrightarrow>
     sum w vs0 = sum w vs1 \<Longrightarrow>
     vs0 \<subseteq> vs \<Longrightarrow>
     vs1 \<subseteq> vs \<Longrightarrow>
     vs0 = vs1"
using tie_breaking_def by blast

lemma only_observed_validators_can_bet_latest_bets :
  "{v. has_a_latest_bet_on bs v x} \<subseteq> observed_validators bs"
apply(auto simp add: has_a_latest_bet_on_def latest_bets_def observed_validators_def)
done

lemma latest_bets_are_same :
  "is_view bs \<Longrightarrow> b \<in> latest_bets bs v \<Longrightarrow> ba \<in> latest_bets bs v \<Longrightarrow> b = ba"
by (meson at_most_one_def view_has_at_most_one_latest_bet)

lemma latest_bets_are_on_same_estimate:
   "is_view bs \<Longrightarrow> has_a_latest_bet_on bs v y
   \<Longrightarrow> has_a_latest_bet_on bs v x
   \<Longrightarrow> x = y"
apply(auto simp add: has_a_latest_bet_on_def)
using latest_bets_are_same by auto

lemma tie_breaking_validators_put_same_weight_only_on_same_estimate :
 "is_view bs \<Longrightarrow>
  tie_breaking (observed_validators bs) w \<Longrightarrow>
  0 < weight_of_estimate bs w x \<Longrightarrow>
  weight_of_estimate bs w x = weight_of_estimate bs w y \<Longrightarrow> x = y"
proof (simp add: weight_of_estimate_def)
 assume "tie_breaking (observed_validators bs) w"
 moreover assume " sum w {v. has_a_latest_bet_on bs v x} = sum w {v. has_a_latest_bet_on bs v y}"
 ultimately have "{v. has_a_latest_bet_on bs v x} = {v. has_a_latest_bet_on bs v y}"
  using only_observed_validators_can_bet_latest_bets tie_breaking_contra by blast
 moreover assume "0 < sum w {v. has_a_latest_bet_on bs v y}"
 moreover assume "is_view bs"
 ultimately show "x = y"
  proof -
   assume "0 < sum w {v. has_a_latest_bet_on bs v y}"
   then have "\<exists> v. v \<in> {v. has_a_latest_bet_on bs v y}"
    proof -
    	have "\<not> sum w {v. has_a_latest_bet_on bs v y} \<le> 0"
  	  	using \<open>0 < sum w {v. has_a_latest_bet_on bs v y}\<close> by force
  	  then show ?thesis
  	  	by (meson sum_nonpos)
    qed
   moreover assume "{v. has_a_latest_bet_on bs v x} = {v. has_a_latest_bet_on bs v y}"
   ultimately have "\<exists> v. v \<in> {v. has_a_latest_bet_on bs v y} \<and> v \<in> {v. has_a_latest_bet_on bs v x}"
    by blast
   then have "\<exists> v. has_a_latest_bet_on bs v y \<and> has_a_latest_bet_on bs v x"
    by blast
   moreover assume "is_view bs"
   ultimately show "x = y"
    using latest_bets_are_on_same_estimate by blast
  qed
qed

lemma non_empty_bets_have_positive_weighted_estimate :
  "finite bs \<Longrightarrow>
   is_non_empty bs \<Longrightarrow>
   positive_weights (observed_validators bs) w \<Longrightarrow>
   \<exists> e'. sum w {v. has_a_latest_bet_on bs v e'} > 0"
using non_empty_bet_set_has_non_zero_weight_for_some_estimate weight_of_estimate_def by auto

lemma tmp:
 "\<exists> e'. sum (w :: validator \<Rightarrow> int) {v. has_a_latest_bet_on bs v e'} > 0 \<Longrightarrow>
  \<forall>e'. sum w {v. has_a_latest_bet_on bs v e'} \<le> 0 \<Longrightarrow> False"
apply(erule exE)
apply(drule_tac x = e' in spec)
by auto

lemma max_weight_is_positive :
  "finite bs \<Longrightarrow>
   is_non_empty bs \<Longrightarrow>
   positive_weights (observed_validators bs) w \<Longrightarrow>
   \<forall>e'. weight_of_estimate bs w e' \<le> weight_of_estimate bs w x \<Longrightarrow>
   0 < weight_of_estimate bs w x"
apply(auto simp add: weight_of_estimate_def)
apply(case_tac "sum w {v. has_a_latest_bet_on bs v x} = 0"; simp)
 using non_empty_bets_have_positive_weighted_estimate tmp apply blast
proof -
  assume a1: "positive_weights (observed_validators bs) w"
  assume a2: "sum w {v. has_a_latest_bet_on bs v x} \<noteq> 0"
  have f3: "\<forall>v. v \<notin> observed_validators bs \<or> \<not> w v \<le> 0"
    using a1 positive_weights_def by fastforce
  obtain vv :: "(validator \<Rightarrow> int) \<Rightarrow> validator set \<Rightarrow> validator" where
    "\<forall>x0 x1. (\<exists>v2. v2 \<in> x1 \<and> \<not> 0 \<le> x0 v2) = (vv x0 x1 \<in> x1 \<and> \<not> 0 \<le> x0 (vv x0 x1))"
    by moura
  then have f4: "\<forall>V f. vv f V \<in> V \<and> \<not> 0 \<le> f (vv f V) \<or> 0 \<le> sum f V"
  by (meson sum_nonneg)
  obtain bb :: "estimate \<Rightarrow> validator \<Rightarrow> bet set \<Rightarrow> bet" where
    "\<forall>x0 x1 x2. (\<exists>v3. v3 \<in> latest_bets x2 x1 \<and> est v3 = x0) = (bb x0 x1 x2 \<in> latest_bets x2 x1 \<and> est (bb x0 x1 x2) = x0)"
    by moura
  then have f5: "(\<not> has_a_latest_bet_on bs (vv w {v. has_a_latest_bet_on bs v x}) x \<or> bb x (vv w {v. has_a_latest_bet_on bs v x}) bs \<in> latest_bets bs (vv w {v. has_a_latest_bet_on bs v x}) \<and> est (bb x (vv w {v. has_a_latest_bet_on bs v x}) bs) = x) \<and> (has_a_latest_bet_on bs (vv w {v. has_a_latest_bet_on bs v x}) x \<or> (\<forall>b. b \<notin> latest_bets bs (vv w {v. has_a_latest_bet_on bs v x}) \<or> est b \<noteq> x))"
    using has_a_latest_bet_on_def by auto
  have "(bb x (vv w {v. has_a_latest_bet_on bs v x}) bs \<notin> bs \<or> sender (bb x (vv w {v. has_a_latest_bet_on bs v x}) bs) \<noteq> vv w {v. has_a_latest_bet_on bs v x} \<or> (\<exists>b. b \<in> bs \<and> sender b = vv w {v. has_a_latest_bet_on bs v x} \<and> is_dependency (bb x (vv w {v. has_a_latest_bet_on bs v x}) bs) b)) \<or> (bb x (vv w {v. has_a_latest_bet_on bs v x}) bs \<notin> bs \<or> sender (bb x (vv w {v. has_a_latest_bet_on bs v x}) bs) \<noteq> vv w {v. has_a_latest_bet_on bs v x} \<or> (\<exists>b. b \<in> bs \<and> sender b = vv w {v. has_a_latest_bet_on bs v x} \<and> is_dependency (bb x (vv w {v. has_a_latest_bet_on bs v x}) bs) b)) \<or> (\<exists>b. b \<in> bs \<and> vv w {v. has_a_latest_bet_on bs v x} = sender b)"
    by (metis (no_types))
  moreover
  { assume aa1: "\<exists>b. b \<in> bs \<and> vv w {v. has_a_latest_bet_on bs v x} = sender b"
    have "w (vv w {uu. has_a_latest_bet_on bs uu x}) \<le> 0 \<or> 0 \<le> w (vv w {uu. has_a_latest_bet_on bs uu x})"
      by linarith
    then have "sum w {v. has_a_latest_bet_on bs v x} \<noteq> 0 \<and> 0 \<le> sum w {v. has_a_latest_bet_on bs v x}"
      using aa1 f4 f3 a2 observed_validators_def by auto }
  moreover
  { assume "\<not> (bb x (vv w {v. has_a_latest_bet_on bs v x}) bs \<in> bs \<and> sender (bb x (vv w {v. has_a_latest_bet_on bs v x}) bs) = vv w {v. has_a_latest_bet_on bs v x} \<and> (\<forall>b. b \<notin> bs \<or> sender b \<noteq> vv w {v. has_a_latest_bet_on bs v x} \<or> \<not> is_dependency (bb x (vv w {v. has_a_latest_bet_on bs v x}) bs) b))"
    then have "\<not> has_a_latest_bet_on bs (vv w {v. has_a_latest_bet_on bs v x}) x"
      using f5 latest_bets_def by blast
    then have "sum w {v. has_a_latest_bet_on bs v x} \<noteq> 0 \<and> 0 \<le> sum w {v. has_a_latest_bet_on bs v x}"
      using f4 a2 by (meson mem_Collect_eq) }
  ultimately have "sum w {v. has_a_latest_bet_on bs v x} \<noteq> 0 \<and> 0 \<le> sum w {v. has_a_latest_bet_on bs v x}"
    by blast
  then show "0 < (\<Sum>v | has_a_latest_bet_on bs v x. w v)"
    by linarith
qed

lemma weight_of_estimate_anti_symmetric :
  "\<forall>e'. weight_of_estimate bs w e' \<le> weight_of_estimate bs w x \<Longrightarrow>
   \<forall>e'. weight_of_estimate bs w e' \<le> weight_of_estimate bs w y \<Longrightarrow>
   weight_of_estimate bs w x = weight_of_estimate bs w y"
(* sledgehammer *)
proof -
  assume a1: "\<forall>e'. weight_of_estimate bs w e' \<le> weight_of_estimate bs w y"
  assume a2: "\<forall>e'. weight_of_estimate bs w e' \<le> weight_of_estimate bs w x"
  have "weight_of_estimate bs w x = weight_of_estimate bs w y \<or> \<not> weight_of_estimate bs w x + - 1 * weight_of_estimate bs w y \<le> 0 \<or> \<not> 0 \<le> weight_of_estimate bs w x + - 1 * weight_of_estimate bs w y"
    by auto
  then show ?thesis
    using a2 a1 by simp
qed

(* prove view \<Longrightarrow> tie breaking \<Rightarrow> non empty \<Rightarrow> exists at most one max estimate *)
lemma view_has_at_most_one_max_weight_estimate :
  "is_view bs \<Longrightarrow>
   finite bs \<Longrightarrow>
   is_non_empty bs \<Longrightarrow>
   positive_weights (observed_validators bs) w \<Longrightarrow>
   tie_breaking (observed_validators bs) w \<Longrightarrow>
   at_most_one {e. is_max_weight_estimate bs w e}"
apply(auto simp add: is_max_weight_estimate_def at_most_one_def)
apply(rule_tac bs = bs and w = w in tie_breaking_validators_put_same_weight_only_on_same_estimate)
   apply blast
  apply blast
 apply(simp add: max_weight_is_positive)
using weight_of_estimate_anti_symmetric by blast

declare is_max_weight_estimate_def [simp]

lemma "is_max_weight_estimate {} f e = True"
apply(simp add: weight_of_estimate_def)
apply(simp add: has_a_latest_bet_on_def latest_bets_def)
done

fun is_valid :: "weight \<Rightarrow> bet \<Rightarrow> bool"
where
"is_valid w (Bet (e, v, js)) = is_max_weight_estimate (set js) w e"

definition is_valid_view :: "weight \<Rightarrow> bet set \<Rightarrow> bool"
where
"is_valid_view w bs = (is_view bs \<and> (\<forall> b \<in> bs. is_valid w b))"

definition is_future_view :: "weight \<Rightarrow> bet set \<Rightarrow> bet set \<Rightarrow> bool"
where
"is_future_view w b0 b1 =
 (b0 \<supseteq> b1 \<and> is_valid_view w b0 \<and> is_valid_view w b1)"

definition is_estimate_safe :: "weight \<Rightarrow> bet set \<Rightarrow> estimate \<Rightarrow> bool"
where
"is_estimate_safe w bs e =
 (\<forall> bf. is_future_view w bf bs \<longrightarrow> is_max_weight_estimate bf w e)"

definition consistent_views :: "weight \<Rightarrow> bet set \<Rightarrow> bet set \<Rightarrow> bool"
where
"consistent_views w b0 b1 =
 (is_valid_view w b0 \<and> is_valid_view w b1 \<and> is_valid_view w (b0 \<union> b1))"

lemma union_of_consistent_views_is_future :
  "consistent_views w b0 b1 \<Longrightarrow>
   is_future_view w (b0 \<union> b1) b0"
apply(auto simp add: consistent_views_def is_future_view_def is_valid_view_def)
done

lemma positive_weights_on_union_of_bets :
  "positive_weights (observed_validators b0) w \<Longrightarrow>
   positive_weights (observed_validators b1) w \<Longrightarrow>
   positive_weights (observed_validators (b0 \<union> b1)) w"
apply(auto simp add: positive_weights_def observed_validators_def)
done

lemma consensus_safety :
  "finite b0 \<Longrightarrow>
   finite b1 \<Longrightarrow>
   is_non_empty b1 \<Longrightarrow>
   positive_weights (observed_validators b0) w \<Longrightarrow>
   positive_weights (observed_validators b1) w \<Longrightarrow>
   tie_breaking (observed_validators (b0 \<union> b1)) w \<Longrightarrow>
   is_estimate_safe w b0 e0 \<Longrightarrow>
   is_estimate_safe w b1 e1 \<Longrightarrow>
   consistent_views w b0 b1 \<Longrightarrow>
   e0 = e1
  "
proof -
  assume "consistent_views w b0 b1"
  then have "is_future_view w (b0 \<union> b1) b0"
    using union_of_consistent_views_is_future by blast
  moreover assume "is_estimate_safe w b0 e0"
  ultimately have max0: "is_max_weight_estimate (b0 \<union> b1) w e0"
    by (simp add: is_estimate_safe_def)

  assume "consistent_views w b0 b1"
  then have "consistent_views w b1 b0"
    by (simp add: consistent_views_def sup.commute)
  then have "is_future_view w (b1 \<union> b0) b1"
    using union_of_consistent_views_is_future by blast
  moreover assume "is_estimate_safe w b1 e1"
  ultimately have "is_max_weight_estimate (b1 \<union> b0) w e1"
    by (simp add: is_estimate_safe_def)
  then have max1: "is_max_weight_estimate (b0 \<union> b1) w e1"
    by (simp add: sup_commute)

  assume f0: "finite b0"
  moreover assume f1: "finite b1"
  moreover assume e1: "is_non_empty b1"
  moreover assume p0: "positive_weights (observed_validators b0) w"
  moreover assume p1: "positive_weights (observed_validators b1) w"
  moreover assume t: "tie_breaking (observed_validators (b0 \<union> b1)) w"
  ultimately have
   unique: "at_most_one {e. is_max_weight_estimate (b0 \<union> b1) w e}"
    by (metis \<open>consistent_views w b0 b1\<close> consistent_views_def f0 f1 finite_UnI is_non_empty_def is_valid_view_def p0 p1 positive_weights_on_union_of_bets set_rev_mp sup_ge2 t view_has_at_most_one_max_weight_estimate)
  show "e0 = e1"
by (meson at_most_one_def max0 max1 mem_Collect_eq unique)
qed

(*

compute estimate_safety
by
adversary on the weaker model

*)

end


(*  Title:      CTT/Bool.thy
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
    Copyright   1991  University of Cambridge
*)

section {* The two-element type (booleans and conditionals) *}

theory Bool
imports CTT
begin

definition
  Bool :: "t" where
  "Bool == T+T"

definition
  true :: "i" where
  "true == inl(tt)"

definition
  false :: "i" where
  "false == inr(tt)"

definition
  cond :: "[i,i,i]\<Rightarrow>i" where
  "cond(a,b,c) == when(a, \<lambda>u. b, \<lambda>u. c)"

lemmas bool_defs = Bool_def true_def false_def cond_def

subsection {* Derivation of rules for the type Bool *}

(*formation rule*)
lemma boolF: "Bool type"
apply (unfold bool_defs)
apply typechk
done

(*introduction rules for true, false*)

lemma boolI_true: "true : Bool"
apply (unfold bool_defs)
apply typechk
done

lemma boolI_false: "false : Bool"
apply (unfold bool_defs)
apply typechk
done

(*elimination rule: typing of cond*)
lemma boolE: "\<lbrakk>p:Bool; a : C(true); b : C(false)\<rbrakk> \<Longrightarrow> cond(p,a,b) : C(p)"
apply (unfold bool_defs)
apply typechk
apply (erule_tac [!] TE)
apply typechk
done

lemma boolEL: "\<lbrakk>p = q : Bool; a = c : C(true); b = d : C(false)\<rbrakk>
  \<Longrightarrow> cond(p,a,b) = cond(q,c,d) : C(p)"
apply (unfold bool_defs)
apply (rule PlusEL)
apply (erule asm_rl refl_elem [THEN TEL])+
done

(*computation rules for true, false*)

lemma boolC_true: "\<lbrakk>a : C(true); b : C(false)\<rbrakk> \<Longrightarrow> cond(true,a,b) = a : C(true)"
apply (unfold bool_defs)
apply (rule comp_rls)
apply typechk
apply (erule_tac [!] TE)
apply typechk
done

lemma boolC_false: "\<lbrakk>a : C(true); b : C(false)\<rbrakk> \<Longrightarrow> cond(false,a,b) = b : C(false)"
apply (unfold bool_defs)
apply (rule comp_rls)
apply typechk
apply (erule_tac [!] TE)
apply typechk
done

end


section \<open>\isaheader{Fold-Combinator}\<close>
theory Refine_Fold
imports Collections.Refine_Dflt_Only_ICF
begin
  text \<open>
    In this theory, we explore the usage of the partial-function package, and
    define a function with a higher-order argument. As example, we choose a
    nondeterministic fold-operation on lists.
\<close>

  text \<open>
    Note that the function @{const nfoldli}, which is included in the
    refinement framework by default, is similar to this function.
    Also, the parametricity based proof technique used there should
    be prefered to this example.
\<close>

  partial_function (nrec) rfoldl where
    "rfoldl f s l = (case l of
        [] \<Rightarrow> RETURN s
      | x#ls \<Rightarrow> do { s\<leftarrow>f s x; rfoldl f s ls}
    )"

  text \<open>Currently, we have to manually state the standard simplification
    lemmas:\<close>
  lemma rfoldl_simps[simp]:
    "rfoldl f s [] = RETURN s"
    "rfoldl f s (x#ls) = do { s\<leftarrow>f s x; rfoldl f s ls}"
    apply (subst rfoldl.simps, simp)+
    done

  lemma rfoldl_refines[refine]:
    assumes REFF: "\<And>x x' s s'. \<lbrakk> (s,s')\<in>Rs; (x,x')\<in>Rl \<rbrakk>
      \<Longrightarrow> f s x \<le> \<Down>Rs (f' s' x')"
    assumes REF0: "(s0,s0')\<in>Rs"
    assumes REFL: "(l,l')\<in>\<langle>Rl\<rangle>list_rel"
    shows "rfoldl f s0 l \<le> \<Down>Rs (rfoldl f' s0' l')"
    using REFL[unfolded list_rel_def, simplified] REF0
    apply (induct arbitrary: s0 s0' rule: list_all2_induct)
    apply (simp add: REF0 RETURN_refine)
    apply (simp only: rfoldl_simps)
    apply (refine_rcg)
    apply (rule REFF)
    apply simp_all
    done

  lemma transfer_rfoldl[refine_transfer]:
    assumes "\<And>s x. RETURN (f s x) \<le> F s x"
    shows "RETURN (foldl f s l) \<le> rfoldl F s l"
    using assms
    apply (induct l arbitrary: s)
    apply simp
    apply (simp only: foldl_Nil foldl_append rfoldl_simps)
    apply simp
    apply (rule order_trans[rotated])
    apply (rule refine_transfer)
    apply assumption
    apply assumption
    apply simp
    done

  subsection \<open>Example\<close>
  text \<open>
    As example application, we define a program that takes as input a list
    of non-empty sets of natural numbers, picks some number of each list,
    and adds up the picked numbers.
\<close>
  definition "pick_sum (s0::nat) l \<equiv>
    rfoldl (\<lambda>s x. do {
      ASSERT (x\<noteq>{});
      y\<leftarrow>SPEC (\<lambda>y. y\<in>x);
      RETURN (s+y)
    }) s0 l
    "

  lemma foldl_mono:
    assumes "\<And>x. mono (\<lambda>s. f s x)"
    shows "mono (\<lambda>s. foldl f s l)"
    apply (rule monoI)
    using assms
    apply (induct l)
    apply (auto dest: monoD)
    done

  lemma pick_sum_correct:
    assumes NE: "{}\<notin>set l"
    assumes FIN: "\<forall>x\<in>set l. finite x"
    shows "pick_sum s0 l \<le> SPEC (\<lambda>s. s \<le> foldl (\<lambda>s x. s+Max x) s0 l)"
    using NE FIN
    apply (induction l arbitrary: s0)
    apply (simp)
    apply (simp)
    apply (intro refine_vcg)
    apply blast
    apply simp
    apply (rule order_trans)
    apply assumption
    apply (rule SPEC_rule)
    apply (erule order_trans)
    apply (rule monoD[OF foldl_mono])
    apply (auto intro: monoI)
    done

  definition "pick_sum_impl s0 l \<equiv>
    rfoldl (\<lambda>s x. do {
      y\<leftarrow>RETURN (the (ls.sel x (\<lambda>_. True)));
      RETURN (s+y)
    }) (s0::nat) l"

  lemma pick_sum_impl_refine:
    assumes A: "(l,l')\<in>\<langle>br ls.\<alpha> ls.invar\<rangle>list_rel"
    shows "pick_sum_impl s0 l \<le> \<Down>Id (pick_sum s0 l')"
    unfolding pick_sum_def pick_sum_impl_def
    using A
    apply (refine_rcg)
    apply (refine_dref_type)
    apply (simp_all add: refine_hsimp refine_rel_defs)
    done

  schematic_goal pick_sum_code_aux: "RETURN ?f \<le> pick_sum_impl s0 l"
    unfolding pick_sum_impl_def
    apply refine_transfer
    done

  concrete_definition pick_sum_code for ?s0.0 l uses pick_sum_code_aux

  lemma pick_sum_code_refines:
    "RETURN (pick_sum_code s l) \<le> pick_sum_impl s l"
    by (rule pick_sum_code.refine)

  value
    "pick_sum_code 0 [list_to_ls [3,2,1], list_to_ls [1,2,3], list_to_ls[2,1]]"

end