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

section \<open>Cartesian products\<close>

theory Product_Type
  imports Typedef Inductive Fun
  keywords "inductive_set" "coinductive_set" :: thy_defn
begin

subsection \<open>\<^typ>\<open>bool\<close> is a datatype\<close>

free_constructors (discs_sels) case_bool for True | False
  by auto

text \<open>Avoid name clashes by prefixing the output of \<open>old_rep_datatype\<close> with \<open>old\<close>.\<close>

setup \<open>Sign.mandatory_path "old"\<close>

old_rep_datatype True False by (auto intro: bool_induct)

setup \<open>Sign.parent_path\<close>

text \<open>But erase the prefix for properties that are not generated by \<open>free_constructors\<close>.\<close>

setup \<open>Sign.mandatory_path "bool"\<close>

lemmas induct = old.bool.induct
lemmas inducts = old.bool.inducts
lemmas rec = old.bool.rec
lemmas simps = bool.distinct bool.case bool.rec

setup \<open>Sign.parent_path\<close>

declare case_split [cases type: bool]
  \<comment> \<open>prefer plain propositional version\<close>

lemma If_case_cert:
  assumes "CASE \<equiv> (\<lambda>b. If b f g)"
  shows "(CASE True \<equiv> f) &&& (CASE False \<equiv> g)"
  using assms by simp_all

setup \<open>Code.declare_case_global @{thm If_case_cert}\<close>

code_printing
  constant "HOL.equal :: bool \<Rightarrow> bool \<Rightarrow> bool" \<rightharpoonup> (Haskell) infix 4 "=="
| class_instance "bool" :: "equal" \<rightharpoonup> (Haskell) -

subsection \<open>The \<open>unit\<close> type\<close>

typedef unit = "{True}"
  by auto

definition Unity :: unit  ("'(')")
  where "() = Abs_unit True"

lemma unit_eq [no_atp]: "u = ()"
  by (induct u) (simp add: Unity_def)

text \<open>
  Simplification procedure for @{thm [source] unit_eq}.  Cannot use
  this rule directly --- it loops!
\<close>

simproc_setup unit_eq ("x::unit") = \<open>
  fn _ => fn _ => fn ct =>
    if HOLogic.is_unit (Thm.term_of ct) then NONE
    else SOME (mk_meta_eq @{thm unit_eq})
\<close>

free_constructors case_unit for "()"
  by auto

text \<open>Avoid name clashes by prefixing the output of \<open>old_rep_datatype\<close> with \<open>old\<close>.\<close>

setup \<open>Sign.mandatory_path "old"\<close>

old_rep_datatype "()" by simp

setup \<open>Sign.parent_path\<close>

text \<open>But erase the prefix for properties that are not generated by \<open>free_constructors\<close>.\<close>

setup \<open>Sign.mandatory_path "unit"\<close>

lemmas induct = old.unit.induct
lemmas inducts = old.unit.inducts
lemmas rec = old.unit.rec
lemmas simps = unit.case unit.rec

setup \<open>Sign.parent_path\<close>

lemma unit_all_eq1: "(\<And>x::unit. PROP P x) \<equiv> PROP P ()"
  by simp

lemma unit_all_eq2: "(\<And>x::unit. PROP P) \<equiv> PROP P"
  by (rule triv_forall_equality)

text \<open>
  This rewrite counters the effect of simproc \<open>unit_eq\<close> on @{term
  [source] "\<lambda>u::unit. f u"}, replacing it by @{term [source]
  f} rather than by @{term [source] "\<lambda>u. f ()"}.
\<close>

lemma unit_abs_eta_conv [simp]: "(\<lambda>u::unit. f ()) = f"
  by (rule ext) simp

lemma UNIV_unit: "UNIV = {()}"
  by auto

instantiation unit :: default
begin

definition "default = ()"

instance ..

end

instantiation unit :: "{complete_boolean_algebra,complete_linorder,wellorder}"
begin

definition less_eq_unit :: "unit \<Rightarrow> unit \<Rightarrow> bool"
  where "(_::unit) \<le> _ \<longleftrightarrow> True"

lemma less_eq_unit [iff]: "u \<le> v" for u v :: unit
  by (simp add: less_eq_unit_def)

definition less_unit :: "unit \<Rightarrow> unit \<Rightarrow> bool"
  where "(_::unit) < _ \<longleftrightarrow> False"

lemma less_unit [iff]: "\<not> u < v" for u v :: unit
  by (simp_all add: less_eq_unit_def less_unit_def)

definition bot_unit :: unit
  where [code_unfold]: "\<bottom> = ()"

definition top_unit :: unit
  where [code_unfold]: "\<top> = ()"

definition inf_unit :: "unit \<Rightarrow> unit \<Rightarrow> unit"
  where [simp]: "_ \<sqinter> _ = ()"

definition sup_unit :: "unit \<Rightarrow> unit \<Rightarrow> unit"
  where [simp]: "_ \<squnion> _ = ()"

definition Inf_unit :: "unit set \<Rightarrow> unit"
  where [simp]: "\<Sqinter>_ = ()"

definition Sup_unit :: "unit set \<Rightarrow> unit"
  where [simp]: "\<Squnion>_ = ()"

definition uminus_unit :: "unit \<Rightarrow> unit"
  where [simp]: "- _ = ()"

declare less_eq_unit_def [abs_def, code_unfold]
  less_unit_def [abs_def, code_unfold]
  inf_unit_def [abs_def, code_unfold]
  sup_unit_def [abs_def, code_unfold]
  Inf_unit_def [abs_def, code_unfold]
  Sup_unit_def [abs_def, code_unfold]
  uminus_unit_def [abs_def, code_unfold]

instance
  by intro_classes auto

end

lemma [code]: "HOL.equal u v \<longleftrightarrow> True" for u v :: unit
  unfolding equal unit_eq [of u] unit_eq [of v] by (rule iffI TrueI refl)+

code_printing
  type_constructor unit \<rightharpoonup>
    (SML) "unit"
    and (OCaml) "unit"
    and (Haskell) "()"
    and (Scala) "Unit"
| constant Unity \<rightharpoonup>
    (SML) "()"
    and (OCaml) "()"
    and (Haskell) "()"
    and (Scala) "()"
| class_instance unit :: equal \<rightharpoonup>
    (Haskell) -
| constant "HOL.equal :: unit \<Rightarrow> unit \<Rightarrow> bool" \<rightharpoonup>
    (Haskell) infix 4 "=="

code_reserved SML
  unit

code_reserved OCaml
  unit

code_reserved Scala
  Unit

subsection \<open>The product type\<close>

subsubsection \<open>Type definition\<close>

definition Pair_Rep :: "'a \<Rightarrow> 'b \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> bool"
  where "Pair_Rep a b = (\<lambda>x y. x = a \<and> y = b)"

definition "prod = {f. \<exists>a b. f = Pair_Rep (a::'a) (b::'b)}"

typedef ('a, 'b) prod ("(_ \<times>/ _)" [21, 20] 20) = "prod :: ('a \<Rightarrow> 'b \<Rightarrow> bool) set"
  unfolding prod_def by auto

type_notation (ASCII)
  prod  (infixr "*" 20)

definition Pair :: "'a \<Rightarrow> 'b \<Rightarrow> 'a \<times> 'b"
  where "Pair a b = Abs_prod (Pair_Rep a b)"

lemma prod_cases: "(\<And>a b. P (Pair a b)) \<Longrightarrow> P p"
  by (cases p) (auto simp add: prod_def Pair_def Pair_Rep_def)

free_constructors case_prod for Pair fst snd
proof -
  fix P :: bool and p :: "'a \<times> 'b"
  show "(\<And>x1 x2. p = Pair x1 x2 \<Longrightarrow> P) \<Longrightarrow> P"
    by (cases p) (auto simp add: prod_def Pair_def Pair_Rep_def)
next
  fix a c :: 'a and b d :: 'b
  have "Pair_Rep a b = Pair_Rep c d \<longleftrightarrow> a = c \<and> b = d"
    by (auto simp add: Pair_Rep_def fun_eq_iff)
  moreover have "Pair_Rep a b \<in> prod" and "Pair_Rep c d \<in> prod"
    by (auto simp add: prod_def)
  ultimately show "Pair a b = Pair c d \<longleftrightarrow> a = c \<and> b = d"
    by (simp add: Pair_def Abs_prod_inject)
qed

text \<open>Avoid name clashes by prefixing the output of \<open>old_rep_datatype\<close> with \<open>old\<close>.\<close>

setup \<open>Sign.mandatory_path "old"\<close>

old_rep_datatype Pair
  by (erule prod_cases) (rule prod.inject)

setup \<open>Sign.parent_path\<close>

text \<open>But erase the prefix for properties that are not generated by \<open>free_constructors\<close>.\<close>

setup \<open>Sign.mandatory_path "prod"\<close>

declare old.prod.inject [iff del]

lemmas induct = old.prod.induct
lemmas inducts = old.prod.inducts
lemmas rec = old.prod.rec
lemmas simps = prod.inject prod.case prod.rec

setup \<open>Sign.parent_path\<close>

declare prod.case [nitpick_simp del]
declare old.prod.case_cong_weak [cong del]
declare prod.case_eq_if [mono]
declare prod.split [no_atp]
declare prod.split_asm [no_atp]

text \<open>
  @{thm [source] prod.split} could be declared as \<open>[split]\<close>
  done after the Splitter has been speeded up significantly;
  precompute the constants involved and don't do anything unless the
  current goal contains one of those constants.
\<close>

subsubsection \<open>Tuple syntax\<close>

text \<open>
  Patterns -- extends pre-defined type \<^typ>\<open>pttrn\<close> used in
  abstractions.
\<close>

nonterminal tuple_args and patterns
syntax
  "_tuple"      :: "'a \<Rightarrow> tuple_args \<Rightarrow> 'a \<times> 'b"        ("(1'(_,/ _'))")
  "_tuple_arg"  :: "'a \<Rightarrow> tuple_args"                   ("_")
  "_tuple_args" :: "'a \<Rightarrow> tuple_args \<Rightarrow> tuple_args"     ("_,/ _")
  "_pattern"    :: "pttrn \<Rightarrow> patterns \<Rightarrow> pttrn"         ("'(_,/ _')")
  ""            :: "pttrn \<Rightarrow> patterns"                  ("_")
  "_patterns"   :: "pttrn \<Rightarrow> patterns \<Rightarrow> patterns"      ("_,/ _")
  "_unit"       :: pttrn                                ("'(')")
translations
  "(x, y)" \<rightleftharpoons> "CONST Pair x y"
  "_pattern x y" \<rightleftharpoons> "CONST Pair x y"
  "_patterns x y" \<rightleftharpoons> "CONST Pair x y"
  "_tuple x (_tuple_args y z)" \<rightleftharpoons> "_tuple x (_tuple_arg (_tuple y z))"
  "\<lambda>(x, y, zs). b" \<rightleftharpoons> "CONST case_prod (\<lambda>x (y, zs). b)"
  "\<lambda>(x, y). b" \<rightleftharpoons> "CONST case_prod (\<lambda>x y. b)"
  "_abs (CONST Pair x y) t" \<rightharpoonup> "\<lambda>(x, y). t"
  \<comment> \<open>This rule accommodates tuples in \<open>case C \<dots> (x, y) \<dots> \<Rightarrow> \<dots>\<close>:
     The \<open>(x, y)\<close> is parsed as \<open>Pair x y\<close> because it is \<open>logic\<close>,
     not \<open>pttrn\<close>.\<close>
  "\<lambda>(). b" \<rightleftharpoons> "CONST case_unit b"
  "_abs (CONST Unity) t" \<rightharpoonup> "\<lambda>(). t"

text \<open>print \<^term>\<open>case_prod f\<close> as \<^term>\<open>\<lambda>(x, y). f x y\<close> and
  \<^term>\<open>case_prod (\<lambda>x. f x)\<close> as \<^term>\<open>\<lambda>(x, y). f x y\<close>\<close>

typed_print_translation \<open>
  let
    fun case_prod_guess_names_tr' T [Abs (x, _, Abs _)] = raise Match
      | case_prod_guess_names_tr' T [Abs (x, xT, t)] =
          (case (head_of t) of
            Const (\<^const_syntax>\<open>case_prod\<close>, _) => raise Match
          | _ =>
            let
              val (_ :: yT :: _) = binder_types (domain_type T) handle Bind => raise Match;
              val (y, t') = Syntax_Trans.atomic_abs_tr' ("y", yT, incr_boundvars 1 t $ Bound 0);
              val (x', t'') = Syntax_Trans.atomic_abs_tr' (x, xT, t');
            in
              Syntax.const \<^syntax_const>\<open>_abs\<close> $
                (Syntax.const \<^syntax_const>\<open>_pattern\<close> $ x' $ y) $ t''
            end)
      | case_prod_guess_names_tr' T [t] =
          (case head_of t of
            Const (\<^const_syntax>\<open>case_prod\<close>, _) => raise Match
          | _ =>
            let
              val (xT :: yT :: _) = binder_types (domain_type T) handle Bind => raise Match;
              val (y, t') =
                Syntax_Trans.atomic_abs_tr' ("y", yT, incr_boundvars 2 t $ Bound 1 $ Bound 0);
              val (x', t'') = Syntax_Trans.atomic_abs_tr' ("x", xT, t');
            in
              Syntax.const \<^syntax_const>\<open>_abs\<close> $
                (Syntax.const \<^syntax_const>\<open>_pattern\<close> $ x' $ y) $ t''
            end)
      | case_prod_guess_names_tr' _ _ = raise Match;
  in [(\<^const_syntax>\<open>case_prod\<close>, K case_prod_guess_names_tr')] end
\<close>

text \<open>Reconstruct pattern from (nested) \<^const>\<open>case_prod\<close>s,
  avoiding eta-contraction of body; required for enclosing "let",
  if "let" does not avoid eta-contraction, which has been observed to occur.\<close>

print_translation \<open>
  let
    fun case_prod_tr' [Abs (x, T, t as (Abs abs))] =
          (* case_prod (\<lambda>x y. t) \<Rightarrow> \<lambda>(x, y) t *)
          let
            val (y, t') = Syntax_Trans.atomic_abs_tr' abs;
            val (x', t'') = Syntax_Trans.atomic_abs_tr' (x, T, t');
          in
            Syntax.const \<^syntax_const>\<open>_abs\<close> $
              (Syntax.const \<^syntax_const>\<open>_pattern\<close> $ x' $ y) $ t''
          end
      | case_prod_tr' [Abs (x, T, (s as Const (\<^const_syntax>\<open>case_prod\<close>, _) $ t))] =
          (* case_prod (\<lambda>x. (case_prod (\<lambda>y z. t))) \<Rightarrow> \<lambda>(x, y, z). t *)
          let
            val Const (\<^syntax_const>\<open>_abs\<close>, _) $
              (Const (\<^syntax_const>\<open>_pattern\<close>, _) $ y $ z) $ t' =
                case_prod_tr' [t];
            val (x', t'') = Syntax_Trans.atomic_abs_tr' (x, T, t');
          in
            Syntax.const \<^syntax_const>\<open>_abs\<close> $
              (Syntax.const \<^syntax_const>\<open>_pattern\<close> $ x' $
                (Syntax.const \<^syntax_const>\<open>_patterns\<close> $ y $ z)) $ t''
          end
      | case_prod_tr' [Const (\<^const_syntax>\<open>case_prod\<close>, _) $ t] =
          (* case_prod (case_prod (\<lambda>x y z. t)) \<Rightarrow> \<lambda>((x, y), z). t *)
          case_prod_tr' [(case_prod_tr' [t])]
            (* inner case_prod_tr' creates next pattern *)
      | case_prod_tr' [Const (\<^syntax_const>\<open>_abs\<close>, _) $ x_y $ Abs abs] =
          (* case_prod (\<lambda>pttrn z. t) \<Rightarrow> \<lambda>(pttrn, z). t *)
          let val (z, t) = Syntax_Trans.atomic_abs_tr' abs in
            Syntax.const \<^syntax_const>\<open>_abs\<close> $
              (Syntax.const \<^syntax_const>\<open>_pattern\<close> $ x_y $ z) $ t
          end
      | case_prod_tr' _ = raise Match;
  in [(\<^const_syntax>\<open>case_prod\<close>, K case_prod_tr')] end
\<close>

subsubsection \<open>Code generator setup\<close>

code_printing
  type_constructor prod \<rightharpoonup>
    (SML) infix 2 "*"
    and (OCaml) infix 2 "*"
    and (Haskell) "!((_),/ (_))"
    and (Scala) "((_),/ (_))"
| constant Pair \<rightharpoonup>
    (SML) "!((_),/ (_))"
    and (OCaml) "!((_),/ (_))"
    and (Haskell) "!((_),/ (_))"
    and (Scala) "!((_),/ (_))"
| class_instance  prod :: equal \<rightharpoonup>
    (Haskell) -
| constant "HOL.equal :: 'a \<times> 'b \<Rightarrow> 'a \<times> 'b \<Rightarrow> bool" \<rightharpoonup>
    (Haskell) infix 4 "=="
| constant fst \<rightharpoonup> (Haskell) "fst"
| constant snd \<rightharpoonup> (Haskell) "snd"

subsubsection \<open>Fundamental operations and properties\<close>

lemma Pair_inject: "(a, b) = (a', b') \<Longrightarrow> (a = a' \<Longrightarrow> b = b' \<Longrightarrow> R) \<Longrightarrow> R"
  by simp

lemma surj_pair [simp]: "\<exists>x y. p = (x, y)"
  by (cases p) simp

lemma fst_eqD: "fst (x, y) = a \<Longrightarrow> x = a"
  by simp

lemma snd_eqD: "snd (x, y) = a \<Longrightarrow> y = a"
  by simp

lemma case_prod_unfold [nitpick_unfold]: "case_prod = (\<lambda>c p. c (fst p) (snd p))"
  by (simp add: fun_eq_iff split: prod.split)

lemma case_prod_conv [simp, code]: "(case (a, b) of (c, d) \<Rightarrow> f c d) = f a b"
  by (fact prod.case)

lemmas surjective_pairing = prod.collapse [symmetric]

lemma prod_eq_iff: "s = t \<longleftrightarrow> fst s = fst t \<and> snd s = snd t"
  by (cases s, cases t) simp

lemma prod_eqI [intro?]: "fst p = fst q \<Longrightarrow> snd p = snd q \<Longrightarrow> p = q"
  by (simp add: prod_eq_iff)

lemma case_prodI: "f a b \<Longrightarrow> case (a, b) of (c, d) \<Rightarrow> f c d"
  by (rule prod.case [THEN iffD2])

lemma case_prodD: "(case (a, b) of (c, d) \<Rightarrow> f c d) \<Longrightarrow> f a b"
  by (rule prod.case [THEN iffD1])

lemma case_prod_Pair [simp]: "case_prod Pair = id"
  by (simp add: fun_eq_iff split: prod.split)

lemma case_prod_eta: "(\<lambda>(x, y). f (x, y)) = f"
  \<comment> \<open>Subsumes the old \<open>split_Pair\<close> when \<^term>\<open>f\<close> is the identity function.\<close>
  by (simp add: fun_eq_iff split: prod.split)

(* This looks like a sensible simp-rule but appears to do more harm than good:
lemma case_prod_const [simp]: "(\<lambda>(_,_). c) = (\<lambda>_. c)"
by(rule case_prod_eta)
*)

lemma case_prod_comp: "(case x of (a, b) \<Rightarrow> (f \<circ> g) a b) = f (g (fst x)) (snd x)"
  by (cases x) simp

lemma The_case_prod: "The (case_prod P) = (THE xy. P (fst xy) (snd xy))"
  by (simp add: case_prod_unfold)

lemma cond_case_prod_eta: "(\<And>x y. f x y = g (x, y)) \<Longrightarrow> (\<lambda>(x, y). f x y) = g"
  by (simp add: case_prod_eta)

lemma split_paired_all [no_atp]: "(\<And>x. PROP P x) \<equiv> (\<And>a b. PROP P (a, b))"
proof
  fix a b
  assume "\<And>x. PROP P x"
  then show "PROP P (a, b)" .
next
  fix x
  assume "\<And>a b. PROP P (a, b)"
  from \<open>PROP P (fst x, snd x)\<close> show "PROP P x" by simp
qed

text \<open>
  The rule @{thm [source] split_paired_all} does not work with the
  Simplifier because it also affects premises in congrence rules,
  where this can lead to premises of the form \<open>\<And>a b. \<dots> = ?P(a, b)\<close>
  which cannot be solved by reflexivity.
\<close>

lemmas split_tupled_all = split_paired_all unit_all_eq2

ML \<open>
  (* replace parameters of product type by individual component parameters *)
  local (* filtering with exists_paired_all is an essential optimization *)
    fun exists_paired_all (Const (\<^const_name>\<open>Pure.all\<close>, _) $ Abs (_, T, t)) =
          can HOLogic.dest_prodT T orelse exists_paired_all t
      | exists_paired_all (t $ u) = exists_paired_all t orelse exists_paired_all u
      | exists_paired_all (Abs (_, _, t)) = exists_paired_all t
      | exists_paired_all _ = false;
    val ss =
      simpset_of
       (put_simpset HOL_basic_ss \<^context>
        addsimps [@{thm split_paired_all}, @{thm unit_all_eq2}, @{thm unit_abs_eta_conv}]
        addsimprocs [\<^simproc>\<open>unit_eq\<close>]);
  in
    fun split_all_tac ctxt = SUBGOAL (fn (t, i) =>
      if exists_paired_all t then safe_full_simp_tac (put_simpset ss ctxt) i else no_tac);

    fun unsafe_split_all_tac ctxt = SUBGOAL (fn (t, i) =>
      if exists_paired_all t then full_simp_tac (put_simpset ss ctxt) i else no_tac);

    fun split_all ctxt th =
      if exists_paired_all (Thm.prop_of th)
      then full_simplify (put_simpset ss ctxt) th else th;
  end;
\<close>

setup \<open>map_theory_claset (fn ctxt => ctxt addSbefore ("split_all_tac", split_all_tac))\<close>

lemma split_paired_All [simp, no_atp]: "(\<forall>x. P x) \<longleftrightarrow> (\<forall>a b. P (a, b))"
  \<comment> \<open>\<open>[iff]\<close> is not a good idea because it makes \<open>blast\<close> loop\<close>
  by fast

lemma split_paired_Ex [simp, no_atp]: "(\<exists>x. P x) \<longleftrightarrow> (\<exists>a b. P (a, b))"
  by fast

lemma split_paired_The [no_atp]: "(THE x. P x) = (THE (a, b). P (a, b))"
  \<comment> \<open>Can't be added to simpset: loops!\<close>
  by (simp add: case_prod_eta)

text \<open>
  Simplification procedure for @{thm [source] cond_case_prod_eta}.  Using
  @{thm [source] case_prod_eta} as a rewrite rule is not general enough,
  and using @{thm [source] cond_case_prod_eta} directly would render some
  existing proofs very inefficient; similarly for \<open>prod.case_eq_if\<close>.
\<close>

ML \<open>
local
  val cond_case_prod_eta_ss =
    simpset_of (put_simpset HOL_basic_ss \<^context> addsimps @{thms cond_case_prod_eta});
  fun Pair_pat k 0 (Bound m) = (m = k)
    | Pair_pat k i (Const (\<^const_name>\<open>Pair\<close>,  _) $ Bound m $ t) =
        i > 0 andalso m = k + i andalso Pair_pat k (i - 1) t
    | Pair_pat _ _ _ = false;
  fun no_args k i (Abs (_, _, t)) = no_args (k + 1) i t
    | no_args k i (t $ u) = no_args k i t andalso no_args k i u
    | no_args k i (Bound m) = m < k orelse m > k + i
    | no_args _ _ _ = true;
  fun split_pat tp i (Abs  (_, _, t)) = if tp 0 i t then SOME (i, t) else NONE
    | split_pat tp i (Const (\<^const_name>\<open>case_prod\<close>, _) $ Abs (_, _, t)) = split_pat tp (i + 1) t
    | split_pat tp i _ = NONE;
  fun metaeq ctxt lhs rhs = mk_meta_eq (Goal.prove ctxt [] []
        (HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs)))
        (K (simp_tac (put_simpset cond_case_prod_eta_ss ctxt) 1)));

  fun beta_term_pat k i (Abs (_, _, t)) = beta_term_pat (k + 1) i t
    | beta_term_pat k i (t $ u) =
        Pair_pat k i (t $ u) orelse (beta_term_pat k i t andalso beta_term_pat k i u)
    | beta_term_pat k i t = no_args k i t;
  fun eta_term_pat k i (f $ arg) = no_args k i f andalso Pair_pat k i arg
    | eta_term_pat _ _ _ = false;
  fun subst arg k i (Abs (x, T, t)) = Abs (x, T, subst arg (k+1) i t)
    | subst arg k i (t $ u) =
        if Pair_pat k i (t $ u) then incr_boundvars k arg
        else (subst arg k i t $ subst arg k i u)
    | subst arg k i t = t;
in
  fun beta_proc ctxt (s as Const (\<^const_name>\<open>case_prod\<close>, _) $ Abs (_, _, t) $ arg) =
        (case split_pat beta_term_pat 1 t of
          SOME (i, f) => SOME (metaeq ctxt s (subst arg 0 i f))
        | NONE => NONE)
    | beta_proc _ _ = NONE;
  fun eta_proc ctxt (s as Const (\<^const_name>\<open>case_prod\<close>, _) $ Abs (_, _, t)) =
        (case split_pat eta_term_pat 1 t of
          SOME (_, ft) => SOME (metaeq ctxt s (let val f $ _ = ft in f end))
        | NONE => NONE)
    | eta_proc _ _ = NONE;
end;
\<close>
simproc_setup case_prod_beta ("case_prod f z") =
  \<open>fn _ => fn ctxt => fn ct => beta_proc ctxt (Thm.term_of ct)\<close>
simproc_setup case_prod_eta ("case_prod f") =
  \<open>fn _ => fn ctxt => fn ct => eta_proc ctxt (Thm.term_of ct)\<close>

lemma case_prod_beta': "(\<lambda>(x,y). f x y) = (\<lambda>x. f (fst x) (snd x))"
  by (auto simp: fun_eq_iff)

text \<open>
  \<^medskip> \<^const>\<open>case_prod\<close> used as a logical connective or set former.

  \<^medskip> These rules are for use with \<open>blast\<close>; could instead
  call \<open>simp\<close> using @{thm [source] prod.split} as rewrite.\<close>

lemma case_prodI2:
  "\<And>p. (\<And>a b. p = (a, b) \<Longrightarrow> c a b) \<Longrightarrow> case p of (a, b) \<Rightarrow> c a b"
  by (simp add: split_tupled_all)

lemma case_prodI2':
  "\<And>p. (\<And>a b. (a, b) = p \<Longrightarrow> c a b x) \<Longrightarrow> (case p of (a, b) \<Rightarrow> c a b) x"
  by (simp add: split_tupled_all)

lemma case_prodE [elim!]:
  "(case p of (a, b) \<Rightarrow> c a b) \<Longrightarrow> (\<And>x y. p = (x, y) \<Longrightarrow> c x y \<Longrightarrow> Q) \<Longrightarrow> Q"
  by (induct p) simp

lemma case_prodE' [elim!]:
  "(case p of (a, b) \<Rightarrow> c a b) z \<Longrightarrow> (\<And>x y. p = (x, y) \<Longrightarrow> c x y z \<Longrightarrow> Q) \<Longrightarrow> Q"
  by (induct p) simp

lemma case_prodE2:
  assumes q: "Q (case z of (a, b) \<Rightarrow> P a b)"
    and r: "\<And>x y. z = (x, y) \<Longrightarrow> Q (P x y) \<Longrightarrow> R"
  shows R
proof (rule r)
  show "z = (fst z, snd z)" by simp
  then show "Q (P (fst z) (snd z))"
    using q by (simp add: case_prod_unfold)
qed

lemma case_prodD': "(case (a, b) of (c, d) \<Rightarrow> R c d) c \<Longrightarrow> R a b c"
  by simp

lemma mem_case_prodI: "z \<in> c a b \<Longrightarrow> z \<in> (case (a, b) of (d, e) \<Rightarrow> c d e)"
  by simp

lemma mem_case_prodI2 [intro!]:
  "\<And>p. (\<And>a b. p = (a, b) \<Longrightarrow> z \<in> c a b) \<Longrightarrow> z \<in> (case p of (a, b) \<Rightarrow> c a b)"
  by (simp only: split_tupled_all) simp

declare mem_case_prodI [intro!] \<comment> \<open>postponed to maintain traditional declaration order!\<close>
declare case_prodI2' [intro!] \<comment> \<open>postponed to maintain traditional declaration order!\<close>
declare case_prodI2 [intro!] \<comment> \<open>postponed to maintain traditional declaration order!\<close>
declare case_prodI [intro!] \<comment> \<open>postponed to maintain traditional declaration order!\<close>

lemma mem_case_prodE [elim!]:
  assumes "z \<in> case_prod c p"
  obtains x y where "p = (x, y)" and "z \<in> c x y"
  using assms by (rule case_prodE2)

ML \<open>
local (* filtering with exists_p_split is an essential optimization *)
  fun exists_p_split (Const (\<^const_name>\<open>case_prod\<close>,_) $ _ $ (Const (\<^const_name>\<open>Pair\<close>,_)$_$_)) = true
    | exists_p_split (t $ u) = exists_p_split t orelse exists_p_split u
    | exists_p_split (Abs (_, _, t)) = exists_p_split t
    | exists_p_split _ = false;
in
  fun split_conv_tac ctxt = SUBGOAL (fn (t, i) =>
    if exists_p_split t
    then safe_full_simp_tac (put_simpset HOL_basic_ss ctxt addsimps @{thms case_prod_conv}) i
    else no_tac);
end;
\<close>

(* This prevents applications of splitE for already splitted arguments leading
   to quite time-consuming computations (in particular for nested tuples) *)
setup \<open>map_theory_claset (fn ctxt => ctxt addSbefore ("split_conv_tac", split_conv_tac))\<close>

lemma split_eta_SetCompr [simp, no_atp]: "(\<lambda>u. \<exists>x y. u = (x, y) \<and> P (x, y)) = P"
  by (rule ext) fast

lemma split_eta_SetCompr2 [simp, no_atp]: "(\<lambda>u. \<exists>x y. u = (x, y) \<and> P x y) = case_prod P"
  by (rule ext) fast

lemma split_part [simp]: "(\<lambda>(a,b). P \<and> Q a b) = (\<lambda>ab. P \<and> case_prod Q ab)"
  \<comment> \<open>Allows simplifications of nested splits in case of independent predicates.\<close>
  by (rule ext) blast

(* Do NOT make this a simp rule as it
   a) only helps in special situations
   b) can lead to nontermination in the presence of split_def
*)
lemma split_comp_eq:
  fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c"
    and g :: "'d \<Rightarrow> 'a"
  shows "(\<lambda>u. f (g (fst u)) (snd u)) = case_prod (\<lambda>x. f (g x))"
  by (rule ext) auto

lemma pair_imageI [intro]: "(a, b) \<in> A \<Longrightarrow> f a b \<in> (\<lambda>(a, b). f a b) ` A"
  by (rule image_eqI [where x = "(a, b)"]) auto

lemma Collect_const_case_prod[simp]: "{(a,b). P} = (if P then UNIV else {})"
by auto

lemma The_split_eq [simp]: "(THE (x',y'). x = x' \<and> y = y') = (x, y)"
  by blast

(*
the following  would be slightly more general,
but cannot be used as rewrite rule:
### Cannot add premise as rewrite rule because it contains (type) unknowns:
### ?y = .x
Goal "[| P y; !!x. P x ==> x = y |] ==> (@(x',y). x = x' & P y) = (x,y)"
by (rtac some_equality 1)
by ( Simp_tac 1)
by (split_all_tac 1)
by (Asm_full_simp_tac 1)
qed "The_split_eq";
*)

lemma case_prod_beta: "case_prod f p = f (fst p) (snd p)"
  by (fact prod.case_eq_if)

lemma prod_cases3 [cases type]:
  obtains (fields) a b c where "y = (a, b, c)"
proof (cases y)
  case (Pair a b)
  with that show ?thesis
    by (cases b) blast
qed

lemma prod_induct3 [case_names fields, induct type]:
  "(\<And>a b c. P (a, b, c)) \<Longrightarrow> P x"
  by (cases x) blast

lemma prod_cases4 [cases type]:
  obtains (fields) a b c d where "y = (a, b, c, d)"
proof (cases y)
  case (fields a b c)
  with that show ?thesis
    by (cases c) blast
qed

lemma prod_induct4 [case_names fields, induct type]:
  "(\<And>a b c d. P (a, b, c, d)) \<Longrightarrow> P x"
  by (cases x) blast

lemma prod_cases5 [cases type]:
  obtains (fields) a b c d e where "y = (a, b, c, d, e)"
proof (cases y)
  case (fields a b c d)
  with that show ?thesis
    by (cases d) blast
qed

lemma prod_induct5 [case_names fields, induct type]:
  "(\<And>a b c d e. P (a, b, c, d, e)) \<Longrightarrow> P x"
  by (cases x) blast

lemma prod_cases6 [cases type]:
  obtains (fields) a b c d e f where "y = (a, b, c, d, e, f)"
proof (cases y)
  case (fields a b c d e)
  with that show ?thesis
    by (cases e) blast
qed

lemma prod_induct6 [case_names fields, induct type]:
  "(\<And>a b c d e f. P (a, b, c, d, e, f)) \<Longrightarrow> P x"
  by (cases x) blast

lemma prod_cases7 [cases type]:
  obtains (fields) a b c d e f g where "y = (a, b, c, d, e, f, g)"
proof (cases y)
  case (fields a b c d e f)
  with that show ?thesis
    by (cases f) blast
qed

lemma prod_induct7 [case_names fields, induct type]:
  "(\<And>a b c d e f g. P (a, b, c, d, e, f, g)) \<Longrightarrow> P x"
  by (cases x) blast

definition internal_case_prod :: "('a \<Rightarrow> 'b \<Rightarrow> 'c) \<Rightarrow> 'a \<times> 'b \<Rightarrow> 'c"
  where "internal_case_prod \<equiv> case_prod"

lemma internal_case_prod_conv: "internal_case_prod c (a, b) = c a b"
  by (simp only: internal_case_prod_def case_prod_conv)

ML_file \<open>Tools/split_rule.ML\<close>

hide_const internal_case_prod

subsubsection \<open>Derived operations\<close>

definition curry :: "('a \<times> 'b \<Rightarrow> 'c) \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> 'c"
  where "curry = (\<lambda>c x y. c (x, y))"

lemma curry_conv [simp, code]: "curry f a b = f (a, b)"
  by (simp add: curry_def)

lemma curryI [intro!]: "f (a, b) \<Longrightarrow> curry f a b"
  by (simp add: curry_def)

lemma curryD [dest!]: "curry f a b \<Longrightarrow> f (a, b)"
  by (simp add: curry_def)

lemma curryE: "curry f a b \<Longrightarrow> (f (a, b) \<Longrightarrow> Q) \<Longrightarrow> Q"
  by (simp add: curry_def)

lemma curry_case_prod [simp]: "curry (case_prod f) = f"
  by (simp add: curry_def case_prod_unfold)

lemma case_prod_curry [simp]: "case_prod (curry f) = f"
  by (simp add: curry_def case_prod_unfold)

lemma curry_K: "curry (\<lambda>x. c) = (\<lambda>x y. c)"
  by (simp add: fun_eq_iff)

text \<open>The composition-uncurry combinator.\<close>

definition scomp :: "('a \<Rightarrow> 'b \<times> 'c) \<Rightarrow> ('b \<Rightarrow> 'c \<Rightarrow> 'd) \<Rightarrow> 'a \<Rightarrow> 'd"  (infixl "\<circ>\<rightarrow>" 60)
  where "f \<circ>\<rightarrow> g = (\<lambda>x. case_prod g (f x))"

no_notation scomp (infixl "\<circ>\<rightarrow>" 60)

bundle state_combinator_syntax
begin

notation fcomp (infixl "\<circ>>" 60)
notation scomp (infixl "\<circ>\<rightarrow>" 60)

end

context
  includes state_combinator_syntax
begin

lemma scomp_unfold: "(\<circ>\<rightarrow>) = (\<lambda>f g x. g (fst (f x)) (snd (f x)))"
  by (simp add: fun_eq_iff scomp_def case_prod_unfold)

lemma scomp_apply [simp]: "(f \<circ>\<rightarrow> g) x = case_prod g (f x)"
  by (simp add: scomp_unfold case_prod_unfold)

lemma Pair_scomp: "Pair x \<circ>\<rightarrow> f = f x"
  by (simp add: fun_eq_iff)

lemma scomp_Pair: "x \<circ>\<rightarrow> Pair = x"
  by (simp add: fun_eq_iff)

lemma scomp_scomp: "(f \<circ>\<rightarrow> g) \<circ>\<rightarrow> h = f \<circ>\<rightarrow> (\<lambda>x. g x \<circ>\<rightarrow> h)"
  by (simp add: fun_eq_iff scomp_unfold)

lemma scomp_fcomp: "(f \<circ>\<rightarrow> g) \<circ>> h = f \<circ>\<rightarrow> (\<lambda>x. g x \<circ>> h)"
  by (simp add: fun_eq_iff scomp_unfold fcomp_def)

lemma fcomp_scomp: "(f \<circ>> g) \<circ>\<rightarrow> h = f \<circ>> (g \<circ>\<rightarrow> h)"
  by (simp add: fun_eq_iff scomp_unfold)

end

code_printing
  constant scomp \<rightharpoonup> (Eval) infixl 3 "#->"

text \<open>
  \<^term>\<open>map_prod\<close> --- action of the product functor upon functions.
\<close>

definition map_prod :: "('a \<Rightarrow> 'c) \<Rightarrow> ('b \<Rightarrow> 'd) \<Rightarrow> 'a \<times> 'b \<Rightarrow> 'c \<times> 'd"
  where "map_prod f g = (\<lambda>(x, y). (f x, g y))"

lemma map_prod_simp [simp, code]: "map_prod f g (a, b) = (f a, g b)"
  by (simp add: map_prod_def)

functor map_prod: map_prod
  by (auto simp add: split_paired_all)

lemma fst_map_prod [simp]: "fst (map_prod f g x) = f (fst x)"
  by (cases x) simp_all

lemma snd_map_prod [simp]: "snd (map_prod f g x) = g (snd x)"
  by (cases x) simp_all

lemma fst_comp_map_prod [simp]: "fst \<circ> map_prod f g = f \<circ> fst"
  by (rule ext) simp_all

lemma snd_comp_map_prod [simp]: "snd \<circ> map_prod f g = g \<circ> snd"
  by (rule ext) simp_all

lemma map_prod_compose: "map_prod (f1 \<circ> f2) (g1 \<circ> g2) = (map_prod f1 g1 \<circ> map_prod f2 g2)"
  by (rule ext) (simp add: map_prod.compositionality comp_def)

lemma map_prod_ident [simp]: "map_prod (\<lambda>x. x) (\<lambda>y. y) = (\<lambda>z. z)"
  by (rule ext) (simp add: map_prod.identity)

lemma map_prod_imageI [intro]: "(a, b) \<in> R \<Longrightarrow> (f a, g b) \<in> map_prod f g ` R"
  by (rule image_eqI) simp_all

lemma prod_fun_imageE [elim!]:
  assumes major: "c \<in> map_prod f g ` R"
    and cases: "\<And>x y. c = (f x, g y) \<Longrightarrow> (x, y) \<in> R \<Longrightarrow> P"
  shows P
proof (rule major [THEN imageE])
  fix x
  assume "c = map_prod f g x" "x \<in> R"
  then show P
    using cases by (cases x) simp
qed

definition apfst :: "('a \<Rightarrow> 'c) \<Rightarrow> 'a \<times> 'b \<Rightarrow> 'c \<times> 'b"
  where "apfst f = map_prod f id"

definition apsnd :: "('b \<Rightarrow> 'c) \<Rightarrow> 'a \<times> 'b \<Rightarrow> 'a \<times> 'c"
  where "apsnd f = map_prod id f"

lemma apfst_conv [simp, code]: "apfst f (x, y) = (f x, y)"
  by (simp add: apfst_def)

lemma apsnd_conv [simp, code]: "apsnd f (x, y) = (x, f y)"
  by (simp add: apsnd_def)

lemma fst_apfst [simp]: "fst (apfst f x) = f (fst x)"
  by (cases x) simp

lemma fst_comp_apfst [simp]: "fst \<circ> apfst f = f \<circ> fst"
  by (simp add: fun_eq_iff)

lemma fst_apsnd [simp]: "fst (apsnd f x) = fst x"
  by (cases x) simp

lemma fst_comp_apsnd [simp]: "fst \<circ> apsnd f = fst"
  by (simp add: fun_eq_iff)

lemma snd_apfst [simp]: "snd (apfst f x) = snd x"
  by (cases x) simp

lemma snd_comp_apfst [simp]: "snd \<circ> apfst f = snd"
  by (simp add: fun_eq_iff)

lemma snd_apsnd [simp]: "snd (apsnd f x) = f (snd x)"
  by (cases x) simp

lemma snd_comp_apsnd [simp]: "snd \<circ> apsnd f = f \<circ> snd"
  by (simp add: fun_eq_iff)

lemma apfst_compose: "apfst f (apfst g x) = apfst (f \<circ> g) x"
  by (cases x) simp

lemma apsnd_compose: "apsnd f (apsnd g x) = apsnd (f \<circ> g) x"
  by (cases x) simp

lemma apfst_apsnd [simp]: "apfst f (apsnd g x) = (f (fst x), g (snd x))"
  by (cases x) simp

lemma apsnd_apfst [simp]: "apsnd f (apfst g x) = (g (fst x), f (snd x))"
  by (cases x) simp

lemma apfst_id [simp]: "apfst id = id"
  by (simp add: fun_eq_iff)

lemma apsnd_id [simp]: "apsnd id = id"
  by (simp add: fun_eq_iff)

lemma apfst_eq_conv [simp]: "apfst f x = apfst g x \<longleftrightarrow> f (fst x) = g (fst x)"
  by (cases x) simp

lemma apsnd_eq_conv [simp]: "apsnd f x = apsnd g x \<longleftrightarrow> f (snd x) = g (snd x)"
  by (cases x) simp

lemma apsnd_apfst_commute: "apsnd f (apfst g p) = apfst g (apsnd f p)"
  by simp

context
begin

local_setup \<open>Local_Theory.map_background_naming (Name_Space.mandatory_path "prod")\<close>

definition swap :: "'a \<times> 'b \<Rightarrow> 'b \<times> 'a"
  where "swap p = (snd p, fst p)"

end

lemma swap_simp [simp]: "prod.swap (x, y) = (y, x)"
  by (simp add: prod.swap_def)

lemma swap_swap [simp]: "prod.swap (prod.swap p) = p"
  by (cases p) simp

lemma swap_comp_swap [simp]: "prod.swap \<circ> prod.swap = id"
  by (simp add: fun_eq_iff)

lemma pair_in_swap_image [simp]: "(y, x) \<in> prod.swap ` A \<longleftrightarrow> (x, y) \<in> A"
  by (auto intro!: image_eqI)

lemma inj_swap [simp]: "inj_on prod.swap A"
  by (rule inj_onI) auto

lemma swap_inj_on: "inj_on (\<lambda>(i, j). (j, i)) A"
  by (rule inj_onI) auto

lemma surj_swap [simp]: "surj prod.swap"
  by (rule surjI [of _ prod.swap]) simp

lemma bij_swap [simp]: "bij prod.swap"
  by (simp add: bij_def)

lemma case_swap [simp]: "(case prod.swap p of (y, x) \<Rightarrow> f x y) = (case p of (x, y) \<Rightarrow> f x y)"
  by (cases p) simp

lemma fst_swap [simp]: "fst (prod.swap x) = snd x"
  by (cases x) simp

lemma snd_swap [simp]: "snd (prod.swap x) = fst x"
  by (cases x) simp

text \<open>Disjoint union of a family of sets -- Sigma.\<close>

definition Sigma :: "'a set \<Rightarrow> ('a \<Rightarrow> 'b set) \<Rightarrow> ('a \<times> 'b) set"
  where "Sigma A B \<equiv> \<Union>x\<in>A. \<Union>y\<in>B x. {Pair x y}"

abbreviation Times :: "'a set \<Rightarrow> 'b set \<Rightarrow> ('a \<times> 'b) set"  (infixr "\<times>" 80)
  where "A \<times> B \<equiv> Sigma A (\<lambda>_. B)"

hide_const (open) Times

bundle no_Set_Product_syntax begin
no_notation Product_Type.Times (infixr "\<times>" 80)
end
bundle Set_Product_syntax begin
notation Product_Type.Times (infixr "\<times>" 80)
end

syntax
  "_Sigma" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> 'b set \<Rightarrow> ('a \<times> 'b) set"  ("(3SIGMA _:_./ _)" [0, 0, 10] 10)
translations
  "SIGMA x:A. B" \<rightleftharpoons> "CONST Sigma A (\<lambda>x. B)"

lemma SigmaI [intro!]: "a \<in> A \<Longrightarrow> b \<in> B a \<Longrightarrow> (a, b) \<in> Sigma A B"
  unfolding Sigma_def by blast

lemma SigmaE [elim!]: "c \<in> Sigma A B \<Longrightarrow> (\<And>x y. x \<in> A \<Longrightarrow> y \<in> B x \<Longrightarrow> c = (x, y) \<Longrightarrow> P) \<Longrightarrow> P"
  \<comment> \<open>The general elimination rule.\<close>
  unfolding Sigma_def by blast

text \<open>
  Elimination of \<^term>\<open>(a, b) \<in> A \<times> B\<close> -- introduces no
  eigenvariables.
\<close>

lemma SigmaD1: "(a, b) \<in> Sigma A B \<Longrightarrow> a \<in> A"
  by blast

lemma SigmaD2: "(a, b) \<in> Sigma A B \<Longrightarrow> b \<in> B a"
  by blast

lemma SigmaE2: "(a, b) \<in> Sigma A B \<Longrightarrow> (a \<in> A \<Longrightarrow> b \<in> B a \<Longrightarrow> P) \<Longrightarrow> P"
  by blast

lemma Sigma_cong: "A = B \<Longrightarrow> (\<And>x. x \<in> B \<Longrightarrow> C x = D x) \<Longrightarrow> (SIGMA x:A. C x) = (SIGMA x:B. D x)"
  by auto

lemma Sigma_mono: "A \<subseteq> C \<Longrightarrow> (\<And>x. x \<in> A \<Longrightarrow> B x \<subseteq> D x) \<Longrightarrow> Sigma A B \<subseteq> Sigma C D"
  by blast

lemma Sigma_empty1 [simp]: "Sigma {} B = {}"
  by blast

lemma Sigma_empty2 [simp]: "A \<times> {} = {}"
  by blast

lemma UNIV_Times_UNIV [simp]: "UNIV \<times> UNIV = UNIV"
  by auto

lemma Compl_Times_UNIV1 [simp]: "- (UNIV \<times> A) = UNIV \<times> (-A)"
  by auto

lemma Compl_Times_UNIV2 [simp]: "- (A \<times> UNIV) = (-A) \<times> UNIV"
  by auto

lemma mem_Sigma_iff [iff]: "(a, b) \<in> Sigma A B \<longleftrightarrow> a \<in> A \<and> b \<in> B a"
  by blast

lemma mem_Times_iff: "x \<in> A \<times> B \<longleftrightarrow> fst x \<in> A \<and> snd x \<in> B"
  by (induct x) simp

lemma Sigma_empty_iff: "(SIGMA i:I. X i) = {} \<longleftrightarrow> (\<forall>i\<in>I. X i = {})"
  by auto

lemma Times_subset_cancel2: "x \<in> C \<Longrightarrow> A \<times> C \<subseteq> B \<times> C \<longleftrightarrow> A \<subseteq> B"
  by blast

lemma Times_eq_cancel2: "x \<in> C \<Longrightarrow> A \<times> C = B \<times> C \<longleftrightarrow> A = B"
  by (blast elim: equalityE)

lemma Collect_case_prod_Sigma: "{(x, y). P x \<and> Q x y} = (SIGMA x:Collect P. Collect (Q x))"
  by blast

lemma Collect_case_prod [simp]: "{(a, b). P a \<and> Q b} = Collect P \<times> Collect Q "
  by (fact Collect_case_prod_Sigma)

lemma Collect_case_prodD: "x \<in> Collect (case_prod A) \<Longrightarrow> A (fst x) (snd x)"
  by auto

lemma Collect_case_prod_mono: "A \<le> B \<Longrightarrow> Collect (case_prod A) \<subseteq> Collect (case_prod B)"
  by auto (auto elim!: le_funE)

lemma Collect_split_mono_strong:
  "X = fst ` A \<Longrightarrow> Y = snd ` A \<Longrightarrow> \<forall>a\<in>X. \<forall>b \<in> Y. P a b \<longrightarrow> Q a b
    \<Longrightarrow> A \<subseteq> Collect (case_prod P) \<Longrightarrow> A \<subseteq> Collect (case_prod Q)"
  by fastforce

lemma UN_Times_distrib: "(\<Union>(a, b)\<in>A \<times> B. E a \<times> F b) = \<Union>(E ` A) \<times> \<Union>(F ` B)"
  \<comment> \<open>Suggested by Pierre Chartier\<close>
  by blast

lemma split_paired_Ball_Sigma [simp, no_atp]: "(\<forall>z\<in>Sigma A B. P z) \<longleftrightarrow> (\<forall>x\<in>A. \<forall>y\<in>B x. P (x, y))"
  by blast

lemma split_paired_Bex_Sigma [simp, no_atp]: "(\<exists>z\<in>Sigma A B. P z) \<longleftrightarrow> (\<exists>x\<in>A. \<exists>y\<in>B x. P (x, y))"
  by blast

lemma Sigma_Un_distrib1: "Sigma (I \<union> J) C = Sigma I C \<union> Sigma J C"
  by blast

lemma Sigma_Un_distrib2: "(SIGMA i:I. A i \<union> B i) = Sigma I A \<union> Sigma I B"
  by blast

lemma Sigma_Int_distrib1: "Sigma (I \<inter> J) C = Sigma I C \<inter> Sigma J C"
  by blast

lemma Sigma_Int_distrib2: "(SIGMA i:I. A i \<inter> B i) = Sigma I A \<inter> Sigma I B"
  by blast

lemma Sigma_Diff_distrib1: "Sigma (I - J) C = Sigma I C - Sigma J C"
  by blast

lemma Sigma_Diff_distrib2: "(SIGMA i:I. A i - B i) = Sigma I A - Sigma I B"
  by blast

lemma Sigma_Union: "Sigma (\<Union>X) B = (\<Union>A\<in>X. Sigma A B)"
  by blast

lemma Pair_vimage_Sigma: "Pair x -` Sigma A f = (if x \<in> A then f x else {})"
  by auto

text \<open>
  Non-dependent versions are needed to avoid the need for higher-order
  matching, especially when the rules are re-oriented.
\<close>

lemma Times_Un_distrib1: "(A \<union> B) \<times> C = A \<times> C \<union> B \<times> C "
  by (fact Sigma_Un_distrib1)

lemma Times_Int_distrib1: "(A \<inter> B) \<times> C = A \<times> C \<inter> B \<times> C "
  by (fact Sigma_Int_distrib1)

lemma Times_Diff_distrib1: "(A - B) \<times> C = A \<times> C - B \<times> C "
  by (fact Sigma_Diff_distrib1)

lemma Times_empty [simp]: "A \<times> B = {} \<longleftrightarrow> A = {} \<or> B = {}"
  by auto

lemma times_subset_iff: "A \<times> C \<subseteq> B \<times> D \<longleftrightarrow> A={} \<or> C={} \<or> A \<subseteq> B \<and> C \<subseteq> D"
  by blast

lemma times_eq_iff: "A \<times> B = C \<times> D \<longleftrightarrow> A = C \<and> B = D \<or> (A = {} \<or> B = {}) \<and> (C = {} \<or> D = {})"
  by auto

lemma fst_image_times [simp]: "fst ` (A \<times> B) = (if B = {} then {} else A)"
  by force

lemma snd_image_times [simp]: "snd ` (A \<times> B) = (if A = {} then {} else B)"
  by force

lemma fst_image_Sigma: "fst ` (Sigma A B) = {x \<in> A. B(x) \<noteq> {}}"
  by force

lemma snd_image_Sigma: "snd ` (Sigma A B) = (\<Union> x \<in> A. B x)"
  by force

lemma vimage_fst: "fst -` A = A \<times> UNIV"
  by auto

lemma vimage_snd: "snd -` A = UNIV \<times> A"
  by auto

lemma insert_Times_insert [simp]:
  "insert a A \<times> insert b B = insert (a,b) (A \<times> insert b B \<union> insert a A \<times> B)"
  by blast

lemma vimage_Times: "f -` (A \<times> B) = (fst \<circ> f) -` A \<inter> (snd \<circ> f) -` B"
proof (rule set_eqI)
  show "x \<in> f -` (A \<times> B) \<longleftrightarrow> x \<in> (fst \<circ> f) -` A \<inter> (snd \<circ> f) -` B" for x
    by (cases "f x") (auto split: prod.split)
qed

lemma Times_Int_Times: "A \<times> B \<inter> C \<times> D = (A \<inter> C) \<times> (B \<inter> D)"
  by auto

lemma image_paired_Times:
   "(\<lambda>(x,y). (f x, g y)) ` (A \<times> B) = (f ` A) \<times> (g ` B)"
  by auto

lemma product_swap: "prod.swap ` (A \<times> B) = B \<times> A"
  by (auto simp add: set_eq_iff)

lemma swap_product: "(\<lambda>(i, j). (j, i)) ` (A \<times> B) = B \<times> A"
  by (auto simp add: set_eq_iff)

lemma image_split_eq_Sigma: "(\<lambda>x. (f x, g x)) ` A = Sigma (f ` A) (\<lambda>x. g ` (f -` {x} \<inter> A))"
proof (safe intro!: imageI)
  fix a b
  assume *: "a \<in> A" "b \<in> A" and eq: "f a = f b"
  show "(f b, g a) \<in> (\<lambda>x. (f x, g x)) ` A"
    using * eq[symmetric] by auto
qed simp_all

lemma subset_fst_snd: "A \<subseteq> (fst ` A \<times> snd ` A)"
  by force

lemma inj_on_apfst [simp]: "inj_on (apfst f) (A \<times> UNIV) \<longleftrightarrow> inj_on f A"
  by (auto simp add: inj_on_def)

lemma inj_apfst [simp]: "inj (apfst f) \<longleftrightarrow> inj f"
  using inj_on_apfst[of f UNIV] by simp

lemma inj_on_apsnd [simp]: "inj_on (apsnd f) (UNIV \<times> A) \<longleftrightarrow> inj_on f A"
  by (auto simp add: inj_on_def)

lemma inj_apsnd [simp]: "inj (apsnd f) \<longleftrightarrow> inj f"
  using inj_on_apsnd[of f UNIV] by simp

context
begin

qualified definition product :: "'a set \<Rightarrow> 'b set \<Rightarrow> ('a \<times> 'b) set"
  where [code_abbrev]: "product A B = A \<times> B"

lemma member_product: "x \<in> Product_Type.product A B \<longleftrightarrow> x \<in> A \<times> B"
  by (simp add: product_def)

end

text \<open>The following \<^const>\<open>map_prod\<close> lemmas are due to Joachim Breitner:\<close>

lemma map_prod_inj_on:
  assumes "inj_on f A"
    and "inj_on g B"
  shows "inj_on (map_prod f g) (A \<times> B)"
proof (rule inj_onI)
  fix x :: "'a \<times> 'c"
  fix y :: "'a \<times> 'c"
  assume "x \<in> A \<times> B"
  then have "fst x \<in> A" and "snd x \<in> B" by auto
  assume "y \<in> A \<times> B"
  then have "fst y \<in> A" and "snd y \<in> B" by auto
  assume "map_prod f g x = map_prod f g y"
  then have "fst (map_prod f g x) = fst (map_prod f g y)" by auto
  then have "f (fst x) = f (fst y)" by (cases x, cases y) auto
  with \<open>inj_on f A\<close> and \<open>fst x \<in> A\<close> and \<open>fst y \<in> A\<close> have "fst x = fst y"
    by (auto dest: inj_onD)
  moreover from \<open>map_prod f g x = map_prod f g y\<close>
  have "snd (map_prod f g x) = snd (map_prod f g y)" by auto
  then have "g (snd x) = g (snd y)" by (cases x, cases y) auto
  with \<open>inj_on g B\<close> and \<open>snd x \<in> B\<close> and \<open>snd y \<in> B\<close> have "snd x = snd y"
    by (auto dest: inj_onD)
  ultimately show "x = y" by (rule prod_eqI)
qed

lemma map_prod_surj:
  fixes f :: "'a \<Rightarrow> 'b"
    and g :: "'c \<Rightarrow> 'd"
  assumes "surj f" and "surj g"
  shows "surj (map_prod f g)"
  unfolding surj_def
proof
  fix y :: "'b \<times> 'd"
  from \<open>surj f\<close> obtain a where "fst y = f a"
    by (auto elim: surjE)
  moreover
  from \<open>surj g\<close> obtain b where "snd y = g b"
    by (auto elim: surjE)
  ultimately have "(fst y, snd y) = map_prod f g (a,b)"
    by auto
  then show "\<exists>x. y = map_prod f g x"
    by auto
qed

lemma map_prod_surj_on:
  assumes "f ` A = A'" and "g ` B = B'"
  shows "map_prod f g ` (A \<times> B) = A' \<times> B'"
  unfolding image_def
proof (rule set_eqI, rule iffI)
  fix x :: "'a \<times> 'c"
  assume "x \<in> {y::'a \<times> 'c. \<exists>x::'b \<times> 'd\<in>A \<times> B. y = map_prod f g x}"
  then obtain y where "y \<in> A \<times> B" and "x = map_prod f g y"
    by blast
  from \<open>image f A = A'\<close> and \<open>y \<in> A \<times> B\<close> have "f (fst y) \<in> A'"
    by auto
  moreover from \<open>image g B = B'\<close> and \<open>y \<in> A \<times> B\<close> have "g (snd y) \<in> B'"
    by auto
  ultimately have "(f (fst y), g (snd y)) \<in> (A' \<times> B')"
    by auto
  with \<open>x = map_prod f g y\<close> show "x \<in> A' \<times> B'"
    by (cases y) auto
next
  fix x :: "'a \<times> 'c"
  assume "x \<in> A' \<times> B'"
  then have "fst x \<in> A'" and "snd x \<in> B'"
    by auto
  from \<open>image f A = A'\<close> and \<open>fst x \<in> A'\<close> have "fst x \<in> image f A"
    by auto
  then obtain a where "a \<in> A" and "fst x = f a"
    by (rule imageE)
  moreover from \<open>image g B = B'\<close> and \<open>snd x \<in> B'\<close> obtain b where "b \<in> B" and "snd x = g b"
    by auto
  ultimately have "(fst x, snd x) = map_prod f g (a, b)"
    by auto
  moreover from \<open>a \<in> A\<close> and  \<open>b \<in> B\<close> have "(a , b) \<in> A \<times> B"
    by auto
  ultimately have "\<exists>y \<in> A \<times> B. x = map_prod f g y"
    by auto
  then show "x \<in> {x. \<exists>y \<in> A \<times> B. x = map_prod f g y}"
    by auto
qed

subsection \<open>Simproc for rewriting a set comprehension into a pointfree expression\<close>

ML_file \<open>Tools/set_comprehension_pointfree.ML\<close>

setup \<open>
  Code_Preproc.map_pre (fn ctxt => ctxt addsimprocs
    [Simplifier.make_simproc \<^context> "set comprehension"
      {lhss = [\<^term>\<open>Collect P\<close>],
       proc = K Set_Comprehension_Pointfree.code_simproc}])
\<close>

subsection \<open>Lemmas about disjointness\<close>

lemma disjnt_Times1_iff [simp]: "disjnt (C \<times> A) (C \<times> B) \<longleftrightarrow> C = {} \<or> disjnt A B"
  by (auto simp: disjnt_def)

lemma disjnt_Times2_iff [simp]: "disjnt (A \<times> C) (B \<times> C) \<longleftrightarrow> C = {} \<or> disjnt A B"
  by (auto simp: disjnt_def)

lemma disjnt_Sigma_iff: "disjnt (Sigma A C) (Sigma B C) \<longleftrightarrow> (\<forall>i \<in> A\<inter>B. C i = {}) \<or> disjnt A B"
  by (auto simp: disjnt_def)

subsection \<open>Inductively defined sets\<close>

(* simplify {(x1, ..., xn). (x1, ..., xn) : S} to S *)
simproc_setup Collect_mem ("Collect t") = \<open>
  fn _ => fn ctxt => fn ct =>
    (case Thm.term_of ct of
      S as Const (\<^const_name>\<open>Collect\<close>, Type (\<^type_name>\<open>fun\<close>, [_, T])) $ t =>
        let val (u, _, ps) = HOLogic.strip_ptupleabs t in
          (case u of
            (c as Const (\<^const_name>\<open>Set.member\<close>, _)) $ q $ S' =>
              (case try (HOLogic.strip_ptuple ps) q of
                NONE => NONE
              | SOME ts =>
                  if not (Term.is_open S') andalso
                    ts = map Bound (length ps downto 0)
                  then
                    let val simp =
                      full_simp_tac (put_simpset HOL_basic_ss ctxt
                        addsimps [@{thm split_paired_all}, @{thm case_prod_conv}]) 1
                    in
                      SOME (Goal.prove ctxt [] []
                        (Const (\<^const_name>\<open>Pure.eq\<close>, T --> T --> propT) $ S $ S')
                        (K (EVERY
                          [resolve_tac ctxt [eq_reflection] 1,
                           resolve_tac ctxt @{thms subset_antisym} 1,
                           resolve_tac ctxt @{thms subsetI} 1,
                           dresolve_tac ctxt @{thms CollectD} 1, simp,
                           resolve_tac ctxt @{thms subsetI} 1,
                           resolve_tac ctxt @{thms CollectI} 1, simp])))
                    end
                  else NONE)
          | _ => NONE)
        end
    | _ => NONE)
\<close>

ML_file \<open>Tools/inductive_set.ML\<close>

subsection \<open>Legacy theorem bindings and duplicates\<close>

lemmas fst_conv = prod.sel(1)
lemmas snd_conv = prod.sel(2)
lemmas split_def = case_prod_unfold
lemmas split_beta' = case_prod_beta'
lemmas split_beta = prod.case_eq_if
lemmas split_conv = case_prod_conv
lemmas split = case_prod_conv

hide_const (open) prod

end

repo: isabelle


text:
(*  Title:      PKCS_Model07.thy
    Author:     Andreas Viktor Hess, DTU
    Author:     Sebastian A. Mödersheim, DTU
    Author:     Achim D. Brucker, University of Exeter
    Author:     Anders Schlichtkrull, DTU
    SPDX-License-Identifier: BSD-3-Clause
*)

section\<open>The PKCS Protocol, Scenario 7\<close>
theory PKCS_Model07
  imports "../../PSPSP"

begin

declare [[code_timing]]

trac\<open>
Protocol: RE_IMPORT_ATT

Enumerations:
token   = {token1}

Sets:
extract/1 wrap/1 unwrap/1 decrypt/1 sensitive/1

Functions:
Public  senc/2 h/2 bind/2
Private inv/1

Analysis:
senc(M1,K2) ? K2 -> M1  #This analysis rule corresponds to the decrypt2 rule in the AIF-omega specification.
                        #M1 was type untyped

Transactions:
iik1()
  new K1
  new N1
  insert N1 sensitive(token1)
  insert N1 extract(token1)
  insert K1 sensitive(token1)
  send h(N1,K1).

iik2()
  new K2
  new N2
  insert N2 wrap(token1)
  insert N2 extract(token1)
  send h(N2,K2).

# =====set wrap=====
setwrap(N2:value,K2:value)
  receive h(N2,K2)
  N2 notin sensitive(token1)
  N2 notin decrypt(token1)
  insert N2 wrap(token1).

# =====set unwrap===
setunwrap(N2:value,K2:value)
  receive h(N2,K2)
  N2 notin sensitive(token1)
  insert N2 unwrap(token1).

# =====unwrap, generate new handler======
#-----------the senstive attr copy-------------
unwrapsensitive(M2:value, K2:value, N1:value, N2:value) #M2 was untyped in the AIF-omega specification.
  receive senc(M2,K2)
  receive bind(N1,M2)
  receive h(N2,K2)
  N1 in sensitive(token1)
  N2 in unwrap(token1)
  new Nnew
  insert Nnew sensitive(token1)
  send h(Nnew,M2).

#-----------the wrap attr copy-------------
wrapattr(M2:value, K2:value, N1:value, N2:value) #M2 was untyped in the AIF-omega specification.
  receive senc(M2,K2)
  receive bind(N1,M2)
  receive h(N2,K2)
  N1 in wrap(token1)
  N2 in unwrap(token1)
  new Nnew
  insert Nnew wrap(token1)
  send h(Nnew,M2).

#-----------the decrypt attr copy-------------
decrypt1attr(M2:value,K2:value,N1:value,N2:value) #M2 was untyped in the AIF-omega specification.
  receive senc(M2,K2)
  receive bind(N1,M2)
  receive h(N2,K2)
  N1 in decrypt(token1)
  N2 in unwrap(token1)
  new Nnew
  insert Nnew decrypt(token1)
  send h(Nnew,M2).

decrypt2attr(M2:value,K2:value,N1:value,N2:value) #M2 was untyped in the AIF-omega specification.
  receive senc(M2,K2)
  receive bind(N1,M2)
  receive h(N2,K2)
  N1 notin sensitive(token1)
  N1 notin wrap(token1)
  N1 notin decrypt(token1)
  N2 in unwrap(token1)
  new Nnew
  send h(Nnew,M2).

# ======================wrap================
wrap(N1:value,K1:value,N2:value,K2:value)
  receive h(N1,K1)
  receive h(N2,K2)
  N1 in extract(token1)
  N2 in wrap(token1)
  send senc(K1,K2)
  send bind(N1,K1).

# =====set decrypt===
setdecrypt(Nnew:value, K2:value)
  receive h(Nnew,K2)
  Nnew notin wrap(token1)
  insert Nnew decrypt(token1).

# ======================decrypt================
decrypt1(Nnew:value, K2:value,M1:value) #M1 was untyped in the AIF-omega specification.
  receive h(Nnew,K2)
  receive senc(M1,K2)
  Nnew in decrypt(token1)
  delete Nnew decrypt(token1)
  send M1.

# ======================attacks================
attack1(K1:value)
  receive K1
  K1 in sensitive(token1)
  attack.
\<close>

subsection \<open>Protocol model setup\<close>
protocol_model_setup spm: RE_IMPORT_ATT

subsection \<open>Fixpoint computation\<close>
compute_fixpoint RE_IMPORT_ATT_protocol RE_IMPORT_ATT_fixpoint attack_trace

text \<open>The fixpoint contains an attack signal\<close>
lemma "attack\<langle>ln 0\<rangle> \<in> set (fst RE_IMPORT_ATT_fixpoint)"
by code_simp

text \<open>The attack trace can be inspected as follows\<close>
print_attack_trace RE_IMPORT_ATT RE_IMPORT_ATT_protocol attack_trace

(* subsection \<open>Proof of security\<close>
compute_SMP [optimized] RE_IMPORT_ATT_protocol RE_IMPORT_ATT_SMP
protocol_security_proof [unsafe] ssp: RE_IMPORT_ATT
  for RE_IMPORT_ATT_protocol RE_IMPORT_ATT_fixpoint RE_IMPORT_ATT_SMP *)

subsection \<open>The generated theorems and definitions\<close>
(* thm ssp.protocol_secure *)

thm RE_IMPORT_ATT_enum_consts.nchotomy
thm RE_IMPORT_ATT_sets.nchotomy
thm RE_IMPORT_ATT_fun.nchotomy
thm RE_IMPORT_ATT_atom.nchotomy
thm RE_IMPORT_ATT_arity.simps
thm RE_IMPORT_ATT_public.simps
thm RE_IMPORT_ATT_\<Gamma>.simps
thm RE_IMPORT_ATT_Ana.simps

thm RE_IMPORT_ATT_transaction_iik1_def
thm RE_IMPORT_ATT_transaction_iik2_def
thm RE_IMPORT_ATT_transaction_setwrap_def
thm RE_IMPORT_ATT_transaction_setunwrap_def
thm RE_IMPORT_ATT_transaction_unwrapsensitive_def
thm RE_IMPORT_ATT_transaction_wrapattr_def
thm RE_IMPORT_ATT_transaction_decrypt1attr_def
thm RE_IMPORT_ATT_transaction_decrypt2attr_def
thm RE_IMPORT_ATT_transaction_wrap_def
thm RE_IMPORT_ATT_transaction_setdecrypt_def
thm RE_IMPORT_ATT_transaction_decrypt1_def
thm RE_IMPORT_ATT_transaction_attack1_def

thm RE_IMPORT_ATT_protocol_def

thm RE_IMPORT_ATT_fixpoint_def

end

author: isabelle-prover

repo: mirror-afp-devel


text:
theory ZIOS
  imports "Z_Toolkit.Z_Toolkit_Pretty" "../utp"
begin

unbundle UTP_Syntax

definition [lens_defs]: "pfun_collection_lens = pfun_lens"

adhoc_overloading collection_lens pfun_collection_lens

lemma pfun_collection_lens_mwb [simp]: "mwb_lens (pfun_collection_lens e)"
  by (simp add: pfun_collection_lens_def)

lemma source_pfun_collection_lens: "\<S>\<^bsub>pfun_collection_lens i\<^esub> = {f. i \<in> pdom(f)}"
  by (auto simp add: lens_defs lens_source_def, metis pfun_upd_ext)

lemma defined_pfun_collection_lens [simp]:
  "\<lbrakk> vwb_lens x; $x \<sharp> (@e)\<^sub>e \<rbrakk> \<Longrightarrow> \<^bold>D(x[e]) = (e \<in> pdom($x))\<^sub>e"
  by (simp add: lens_defined_def src_dyn_lens unrest source_ns_alpha source_pfun_collection_lens)
     (simp add: lens_defs wb_lens.source_UNIV)

text \<open> The meaning of scene equivalence outside of a partial function selection. \<close>

lemma scene_equiv_outside_pfun:
  assumes "vwb_lens x" "$x \<sharp> (@e)\<^sub>e" "e s\<^sub>1 \<in> pdom (get\<^bsub>x\<^esub> s\<^sub>1)"
  shows "s\<^sub>1 \<approx>\<^sub>S s\<^sub>2 on - \<lbrakk>(x[@e])\<^sub>v\<rbrakk>\<^sub>\<sim>
        \<longleftrightarrow>
        (s\<^sub>1 \<approx>\<^sub>S s\<^sub>2 on - \<lbrakk>x\<rbrakk>\<^sub>\<sim> \<and> {e s\<^sub>1} \<Zndres> get\<^bsub>x\<^esub> s\<^sub>1 = {e s\<^sub>1} \<Zndres> get\<^bsub>x\<^esub> s\<^sub>2)"
  using assms
  apply (auto simp add: scene_equiv_def scene_override_commute unrest)
    apply (simp_all add: unrest_lens)
    apply (simp_all add: lens_defs)
    apply (metis vwb_lens.put_eq)
   apply (metis Compl_iff Partial_Fun.pdom_res_upd_out all_not_in_conv insert_not_empty mwb_lens_weak singletonD vwb_lens_mwb weak_lens.put_get)
  apply (metis Diff_insert_absorb compl_bot_eq empty_iff pdom_res_UNIV pfun_pdom_antires_upd pfun_upd_ext singletonI)
  done

alphabet ('i, 'o, 's) ios =
  inp :: "'i"
  out :: "'o"
  st :: "'s"

definition ZDelta :: "('s \<Rightarrow> \<bool>) \<Rightarrow> _" ("\<Delta>[_]") where
[expr_defs]: "ZDelta P = (P\<^sup>< \<and> P\<^sup>>)\<^sub>e \<up> (st \<times> st)"

definition ZXi ("\<Xi>[_]") where
[expr_defs]: "ZXi P = (P\<^sup>< \<and> (\<^bold>v\<^sup>< = \<^bold>v\<^sup>>))\<^sub>e \<up> (st \<times> st)"

definition ZBefore ("[_]\<^sup><") where
[expr_defs]: "ZBefore P = P\<^sup>< \<up> (st \<times> st)"

definition ZAfter ("[_]\<^sup>>") where
[expr_defs]: "ZAfter P = P\<^sup>> \<up> (st \<times> st)"

definition ZedSchema :: "('s \<Rightarrow> \<bool>) \<Rightarrow> ('s \<Rightarrow> \<bool>) \<Rightarrow> _" ("[_ | _]") where
[expr_defs]: "ZedSchema P Q \<equiv> (P \<and> Q)\<^sub>e"

expr_ctr ZDelta (0)
expr_ctr ZXi (0)
expr_ctr ZBefore (0)
expr_ctr ZAfter (0)

expr_ctr ZedSchema (0 1)

no_notation Set.member ("(_/ : _)" [51, 51] 50)

syntax
  "_zed_input"  :: "id \<Rightarrow> logic" ("(_)?" [1000] 1000)
  "_zed_output" :: "id \<Rightarrow> logic" ("(_)!" [1000] 1000)

translations
  "_zed_input x"  == "(_sexp_var (_svid_fst (_svid_dot (_svid (CONST inp)) (_svid x))))"
  "_zed_output x" == "(_sexp_var (_svid_snd (_svid_dot (_svid (CONST out)) (_svid x))))"

end

author: isabelle-utp

repo: UTP

save_path: github-repos/isabelle/isabelle-utp-UTP


text:
subsection {* Relational Hoare calculus *}

theory utp_hoare
imports "../../AlgebraicLaws/Rel&Des/Algebraic_Laws"
begin

named_theorems hoare

subsection {*Hoare triple definition*}

text {*A Hoare triple is represented by a pre-condition @{text P} a post-condition @{text Q}
       and a program @{text C}. It says whenever the pre-condition @{text P} holds on the initial state
       then the post-condition @{text Q} must hold on the final state and this
       after the execution of the program @{text C}.*}

definition hoare_r :: "'\<alpha> cond \<Rightarrow> '\<alpha> hrel \<Rightarrow> '\<alpha> cond \<Rightarrow> bool" ("\<lbrace>_\<rbrace>_\<lbrace>_\<rbrace>\<^sub>u") where
"\<lbrace>p\<rbrace>Q\<lbrace>r\<rbrace>\<^sub>u = ((\<lceil>p\<rceil>\<^sub>< \<Rightarrow> \<lceil>r\<rceil>\<^sub>>) \<sqsubseteq> Q)"

declare hoare_r_def [upred_defs]

lemma hoare_true [hoare]: "\<lbrace>p\<rbrace>C\<lbrace>true\<rbrace>\<^sub>u"
  by rel_auto

lemma hoare_false [hoare]: "\<lbrace>false\<rbrace>C\<lbrace>q\<rbrace>\<^sub>u"
  by rel_auto

subsection {*Hoare for Consequence*}

lemma hoare_r_conseq [hoare]:
  assumes "`p\<^sub>1 \<Rightarrow> p\<^sub>2`" and "\<lbrace>p\<^sub>2\<rbrace>C\<lbrace>q\<^sub>2\<rbrace>\<^sub>u" and "`q\<^sub>2 \<Rightarrow> q\<^sub>1`"
  shows   "\<lbrace>p\<^sub>1\<rbrace>C\<lbrace>q\<^sub>1\<rbrace>\<^sub>u"
  by (insert assms) rel_auto

subsection {*Precondition strengthening*}

lemma hoare_pre_str[hoare]:
  assumes "`p\<^sub>1 \<Rightarrow> p\<^sub>2`" and "\<lbrace>p\<^sub>2\<rbrace>C\<lbrace>q\<rbrace>\<^sub>u"
  shows "\<lbrace>p\<^sub>1\<rbrace>C\<lbrace>q\<rbrace>\<^sub>u"
  by (insert assms) rel_auto

subsection {*Post-condition weakening*}

lemma hoare_post_weak[hoare]:
  assumes "\<lbrace>p\<rbrace>C\<lbrace>q\<^sub>2\<rbrace>\<^sub>u" and "`q\<^sub>2 \<Rightarrow> q\<^sub>1`"
  shows "\<lbrace>p\<rbrace>C\<lbrace>q\<^sub>1\<rbrace>\<^sub>u"
 by (insert assms) rel_auto

subsection {*Hoare and assertion logic*}

lemma hoare_r_conj [hoare]:
  assumes"\<lbrace>p\<rbrace>C\<lbrace>r\<rbrace>\<^sub>u" and "\<lbrace>p\<rbrace>C\<lbrace>s\<rbrace>\<^sub>u"
  shows "\<lbrace>p\<rbrace>C\<lbrace>r \<and> s\<rbrace>\<^sub>u"
  by (insert assms) rel_auto

subsection {*Hoare SKIP*}

lemma skip_hoare_r [hoare]: "\<lbrace>p\<rbrace>II\<lbrace>p\<rbrace>\<^sub>u"
  by rel_auto

subsection {*Hoare for assignment*}

lemma assigns_hoare_r [hoare]:
  assumes"`p \<Rightarrow> \<sigma> \<dagger> q`"
  shows  "\<lbrace>p\<rbrace>\<langle>\<sigma>\<rangle>\<^sub>a\<lbrace>q\<rbrace>\<^sub>u"
  by (insert assms) rel_auto

lemma assigns_hoare_r' [hoare]: "\<lbrace>\<sigma> \<dagger> p\<rbrace>\<langle>\<sigma>\<rangle>\<^sub>a\<lbrace>p\<rbrace>\<^sub>u"
  by rel_auto

subsection {*Hoare for Sequential Composition*}

lemma seq_hoare_r [hoare]:
  assumes"\<lbrace>p\<rbrace>C\<^sub>1\<lbrace>s\<rbrace>\<^sub>u" and "\<lbrace>s\<rbrace>C\<^sub>2\<lbrace>r\<rbrace>\<^sub>u"
  shows"\<lbrace>p\<rbrace>C\<^sub>1 ;; C\<^sub>2\<lbrace>r\<rbrace>\<^sub>u"
  by (insert assms) rel_auto

subsection {*Hoare for Conditional*}

lemma cond_hoare_r [hoare]:
  assumes "\<lbrace>b \<and> p\<rbrace>C\<^sub>1\<lbrace>q\<rbrace>\<^sub>u" and "\<lbrace>\<not>b \<and> p\<rbrace>C\<^sub>2\<lbrace>q\<rbrace>\<^sub>u"
  shows "\<lbrace>p\<rbrace>C\<^sub>1 \<triangleleft> b \<triangleright>\<^sub>r C\<^sub>2\<lbrace>q\<rbrace>\<^sub>u"
  by (insert assms) rel_auto

subsection {*Hoare for assert*}

lemma assert_hoare_r [hoare]:
  assumes "\<lbrace>c \<and> p\<rbrace>II\<lbrace>q\<rbrace>\<^sub>u" and "\<lbrace>\<not>c \<and> p\<rbrace>true\<lbrace>q\<rbrace>\<^sub>u"
  shows "\<lbrace>p\<rbrace>c\<^sub>\<bottom>\<lbrace>q\<rbrace>\<^sub>u"
  unfolding rassert_def using assms cond_hoare_r [of c p _ q ]
  by auto

subsection {*Hoare for assume*}

lemma assume_hoare_r [hoare]:
  assumes "\<lbrace>c \<and> p\<rbrace>II\<lbrace>q\<rbrace>\<^sub>u" and "\<lbrace>\<not>c \<and> p\<rbrace>false\<lbrace>q\<rbrace>\<^sub>u"
  shows "\<lbrace>p\<rbrace>c\<^sup>\<top>\<lbrace>q\<rbrace>\<^sub>u"
  unfolding rassume_def using assms cond_hoare_r [of c p _ q ]
  by auto

subsection {*Hoare for While-loop*}

lemma while_hoare_r [hoare]:
  assumes "\<lbrace>p \<and> b\<rbrace>C\<lbrace>p\<rbrace>\<^sub>u"
  shows "\<lbrace>p\<rbrace>while b do C od\<lbrace>\<not>b \<and> p\<rbrace>\<^sub>u"
  using assms
  apply (simp add: while_def hoare_r_def)apply ( rule_tac lfp_lowerbound) apply(rel_auto)
  done
lemma while_hoare_r' [hoare]:
  assumes "\<lbrace>p \<and> b\<rbrace>C\<lbrace>p\<rbrace>\<^sub>u" and "`p \<and> \<not>b \<Rightarrow> q`"
  shows "\<lbrace>p\<rbrace>while b do C od\<lbrace>q\<rbrace>\<^sub>u"
  using assms
  by (metis conj_comm hoare_r_conseq p_imp_p taut_true while_hoare_r)

lemma while_invr_hoare_r [hoare]:
  assumes "\<lbrace>p \<and> b\<rbrace>C\<lbrace>p\<rbrace>\<^sub>u" and "`pre \<Rightarrow> p`" and "`(\<not>b \<and> p) \<Rightarrow> post`"
  shows "\<lbrace>pre\<rbrace>while b invr p do C od\<lbrace>post\<rbrace>\<^sub>u"
  by (metis assms hoare_r_conseq while_hoare_r while_inv_def)

end

author: git-vt

repo: orca

save_path: github-repos/isabelle/git-vt-orca


text:
(*
    Author:   Salomon Sickert
    License:  BSD
*)

section \<open>Size Bounds\<close>

text \<open>We prove an exponential upper bound for the normalisation procedure. Moreover, we show that
  the number of proper subformulas, which correspond to states very-weak alternating automata
  (A1W), is only linear for each disjunct.\<close>

theory Normal_Form_Complexity imports
  Normal_Form
begin

subsection \<open>Inequalities and Identities\<close>

lemma inequality_1:
  "y > 0 \<Longrightarrow> y + 3 \<le> (2 :: nat) ^ (y + 1)"
  by (induction y) (simp, fastforce)

lemma inequality_2:
  "x > 0 \<Longrightarrow> y > 0 \<Longrightarrow> ((2 :: nat) ^ (x + 1)) + (2 ^ (y + 1)) \<le> (2 ^ (x + y + 1))"
  by (induction x; simp; induction y; simp; fastforce)

lemma size_gr_0:
  "size (\<phi> :: 'a ltln) > 0"
  by (cases \<phi>) simp_all

lemma sum_associative:
  "finite X \<Longrightarrow> (\<Sum>x \<in> X. f x + c) = (\<Sum>x \<in> X. f x) + card X * c"
  by (induction rule: finite_induct) simp_all

subsection \<open>Length\<close>

text \<open>We prove that the length (size) of the resulting formula in normal form is at most exponential.\<close>

lemma flatten_sigma_1_length:
  "size (\<phi>[N]\<^sub>\<Sigma>\<^sub>1) \<le> size \<phi>"
  by (induction \<phi>) simp_all

lemma flatten_pi_1_length:
  "size (\<phi>[M]\<^sub>\<Pi>\<^sub>1) \<le> size \<phi>"
  by (induction \<phi>) simp_all

lemma flatten_sigma_2_length:
  "size (\<phi>[M]\<^sub>\<Sigma>\<^sub>2) \<le> 2 ^ (size \<phi> + 1)"
proof (induction \<phi>)
  case (And_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 and\<^sub>n \<phi>2)[M]\<^sub>\<Sigma>\<^sub>2  \<le> (2 ^ (size \<phi>1 + 1)) + (2 ^ (size \<phi>2 + 1)) + 1"
    by simp
  also
  have "\<dots> \<le> 2 ^ (size \<phi>1 + size \<phi>2 + 1) + 1 "
    using inequality_2[OF size_gr_0 size_gr_0] by simp
  also
  have "\<dots> \<le> 2 ^ (size (\<phi>1 and\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case.
next
  case (Or_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 or\<^sub>n \<phi>2)[M]\<^sub>\<Sigma>\<^sub>2  \<le> (2 ^ (size \<phi>1 + 1)) + (2 ^ (size \<phi>2 + 1)) + 1"
    by simp
  also
  have "\<dots> \<le> 2 ^ (size \<phi>1 + size \<phi>2 + 1) + 1 "
    using inequality_2[OF size_gr_0 size_gr_0] by simp
  also
  have "\<dots> \<le> 2 ^ (size (\<phi>1 or\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case.
next
  case (Next_ltln \<phi>)
  then show ?case
    using le_Suc_eq by fastforce
next
  case (WeakUntil_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 W\<^sub>n \<phi>2)[M]\<^sub>\<Sigma>\<^sub>2 \<le> 2 ^ (size \<phi>1 + 1) + 2 ^ (size \<phi>2 + 1) + size \<phi>1 + 4"
    by (simp, simp add: add.commute add_mono flatten_pi_1_length)
  also
  have "\<dots> \<le> 2 ^ (size \<phi>2 + 1) + 2 * 2 ^ (size \<phi>1 + 1) + 1"
    using inequality_1[OF size_gr_0, of \<phi>1] by simp
  also
  have "\<dots> \<le> 2 * (2 ^ (size \<phi>1 + 1) + 2 ^ (size \<phi>2 + 1))"
    by simp
  also
  have "\<dots> \<le> 2 * 2 ^ (size \<phi>1 + size \<phi>2 + 1)"
    using inequality_2[OF size_gr_0 size_gr_0] mult_le_mono2 by blast
  also
  have "\<dots> = 2 ^ (size (\<phi>1 W\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case.
next
  case (StrongRelease_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 M\<^sub>n \<phi>2)[M]\<^sub>\<Sigma>\<^sub>2  \<le> (2 ^ (size \<phi>1 + 1)) + (2 ^ (size \<phi>2 + 1)) + 1"
    by simp
  also
  have "\<dots> \<le> 2 ^ (size \<phi>1 + size \<phi>2 + 1) + 1 "
    using inequality_2[OF size_gr_0 size_gr_0] by simp
  also
  have "\<dots> \<le> 2 ^ (size (\<phi>1 M\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case.
next
  case (Until_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 U\<^sub>n \<phi>2)[M]\<^sub>\<Sigma>\<^sub>2  \<le> (2 ^ (size \<phi>1 + 1)) + (2 ^ (size \<phi>2 + 1)) + 1"
    by simp
  also
  have "\<dots> \<le> 2 ^ (size \<phi>1 + size \<phi>2 + 1) + 1 "
    using inequality_2[OF size_gr_0 size_gr_0] by simp
  also
  have "\<dots> \<le> 2 ^ (size (\<phi>1 U\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case.
next
  case (Release_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 R\<^sub>n \<phi>2)[M]\<^sub>\<Sigma>\<^sub>2 \<le> 2 ^ (size \<phi>1 + 1) + 2 ^ (size \<phi>2 + 1) + size \<phi>2 + 4"
    by (simp, simp add: add.commute add_mono flatten_pi_1_length)
  also
  have "\<dots> \<le> 2 ^ (size \<phi>1 + 1) + 2 * 2 ^ (size \<phi>2 + 1) + 1"
    using inequality_1[OF size_gr_0, of \<phi>2] by simp
  also
  have "\<dots> \<le> 2 * (2 ^ (size \<phi>1 + 1) + 2 ^ (size \<phi>2 + 1))"
    by simp
  also
  have "\<dots> \<le> 2 * 2 ^ (size \<phi>1 + size \<phi>2 + 1)"
    using inequality_2[OF size_gr_0 size_gr_0] mult_le_mono2 by blast
  also
  have "\<dots> = 2 ^ (size (\<phi>1 R\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case .
qed auto

lemma flatten_pi_2_length:
  "size (\<phi>[N]\<^sub>\<Pi>\<^sub>2) \<le> 2 ^ (size \<phi> + 1)"
proof (induction \<phi>)
  case (And_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 and\<^sub>n \<phi>2)[N]\<^sub>\<Pi>\<^sub>2  \<le> (2 ^ (size \<phi>1 + 1)) + (2 ^ (size \<phi>2 + 1)) + 1"
    by simp
  also
  have "\<dots> \<le> 2 ^ (size \<phi>1 + size \<phi>2 + 1) + 1 "
    using inequality_2[OF size_gr_0 size_gr_0] by simp
  also
  have "\<dots> \<le> 2 ^ (size (\<phi>1 and\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case.
next
  case (Or_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 or\<^sub>n \<phi>2)[N]\<^sub>\<Pi>\<^sub>2  \<le> (2 ^ (size \<phi>1 + 1)) + (2 ^ (size \<phi>2 + 1)) + 1"
    by simp
  also
  have "\<dots> \<le> 2 ^ (size \<phi>1 + size \<phi>2 + 1) + 1 "
    using inequality_2[OF size_gr_0 size_gr_0] by simp
  also
  have "\<dots> \<le> 2 ^ (size (\<phi>1 or\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case.
next
  case (Next_ltln \<phi>)
  then show ?case
    using le_Suc_eq by fastforce
next
  case (Until_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 U\<^sub>n \<phi>2)[N]\<^sub>\<Pi>\<^sub>2 \<le> 2 ^ (size \<phi>1 + 1) + 2 ^ (size \<phi>2 + 1) + size \<phi>2 + 4"
    by (simp, simp add: add.commute add_mono flatten_sigma_1_length)
  also
  have "\<dots> \<le> 2 ^ (size \<phi>1 + 1) + 2 * 2 ^ (size \<phi>2 + 1) + 1"
    using inequality_1[OF size_gr_0, of \<phi>2] by simp
  also
  have "\<dots> \<le> 2 * (2 ^ (size \<phi>1 + 1) + 2 ^ (size \<phi>2 + 1))"
    by simp
  also
  have "\<dots> \<le> 2 * 2 ^ (size \<phi>1 + size \<phi>2 + 1)"
    using inequality_2[OF size_gr_0 size_gr_0] mult_le_mono2 by blast
  also
  have "\<dots> = 2 ^ (size (\<phi>1 U\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case.
next
  case (Release_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 R\<^sub>n \<phi>2)[N]\<^sub>\<Pi>\<^sub>2  \<le> (2 ^ (size \<phi>1 + 1)) + (2 ^ (size \<phi>2 + 1)) + 1"
    by simp
  also
  have "\<dots> \<le> 2 ^ (size \<phi>1 + size \<phi>2 + 1) + 1 "
    using inequality_2[OF size_gr_0 size_gr_0] by simp
  also
  have "\<dots> \<le> 2 ^ (size (\<phi>1 R\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case.
next
  case (WeakUntil_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 W\<^sub>n \<phi>2)[N]\<^sub>\<Pi>\<^sub>2  \<le> (2 ^ (size \<phi>1 + 1)) + (2 ^ (size \<phi>2 + 1)) + 1"
    by simp
  also
  have "\<dots> \<le> 2 ^ (size \<phi>1 + size \<phi>2 + 1) + 1 "
    using inequality_2[OF size_gr_0 size_gr_0] by simp
  also
  have "\<dots> \<le> 2 ^ (size (\<phi>1 W\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case.
next
  case (StrongRelease_ltln \<phi>1 \<phi>2)
  hence "size (\<phi>1 M\<^sub>n \<phi>2)[N]\<^sub>\<Pi>\<^sub>2 \<le> 2 ^ (size \<phi>1 + 1) + 2 ^ (size \<phi>2 + 1) + size \<phi>1 + 4"
    by (simp, simp add: add.commute add_mono flatten_sigma_1_length)
  also
  have "\<dots> \<le> 2 ^ (size \<phi>2 + 1) + 2 * 2 ^ (size \<phi>1 + 1) + 1"
    using inequality_1[OF size_gr_0, of \<phi>1] by simp
  also
  have "\<dots> \<le> 2 * (2 ^ (size \<phi>1 + 1) + 2 ^ (size \<phi>2 + 1))"
    by simp
  also
  have "\<dots> \<le> 2 * 2 ^ (size \<phi>1 + size \<phi>2 + 1)"
    using inequality_2[OF size_gr_0 size_gr_0] mult_le_mono2 by blast
  also
  have "\<dots> = 2 ^ (size (\<phi>1 M\<^sub>n \<phi>2) + 1)"
    by simp
  finally
  show ?case .
qed auto

definition "normal_form_length_upper_bound"
  where "normal_form_length_upper_bound \<phi>
    \<equiv> (2 :: nat) ^ (size \<phi>) * (2 ^ (size \<phi> + 1) + 2 * (size \<phi> + 2) ^ 2)"

definition "normal_form_disjunct_with_flatten_pi_2_length"
  where "normal_form_disjunct_with_flatten_pi_2_length \<phi> M N
    \<equiv> size (\<phi>[N]\<^sub>\<Pi>\<^sub>2) + (\<Sum>\<psi> \<in> M. size (\<psi>[N]\<^sub>\<Sigma>\<^sub>1) + 2) + (\<Sum>\<psi> \<in> N. size (\<psi>[M]\<^sub>\<Pi>\<^sub>1) + 2)"

definition "normal_form_with_flatten_pi_2_length"
  where "normal_form_with_flatten_pi_2_length \<phi>
    \<equiv> \<Sum>(M, N) \<in> {(M, N) | M N. M \<subseteq> subformulas\<^sub>\<mu> \<phi> \<and> N \<subseteq> subformulas\<^sub>\<nu> \<phi>}. normal_form_disjunct_with_flatten_pi_2_length \<phi> M N"

definition "normal_form_disjunct_with_flatten_sigma_2_length"
  where "normal_form_disjunct_with_flatten_sigma_2_length \<phi> M N
    \<equiv> size (\<phi>[M]\<^sub>\<Sigma>\<^sub>2) + (\<Sum>\<psi> \<in> M. size (\<psi>[N]\<^sub>\<Sigma>\<^sub>1) + 2) + (\<Sum>\<psi> \<in> N. size (\<psi>[M]\<^sub>\<Pi>\<^sub>1) + 2)"

definition "normal_form_with_flatten_sigma_2_length"
  where "normal_form_with_flatten_sigma_2_length \<phi>
    \<equiv> \<Sum>(M, N) \<in> {(M, N) | M N. M \<subseteq> subformulas\<^sub>\<mu> \<phi> \<and> N \<subseteq> subformulas\<^sub>\<nu> \<phi>}. normal_form_disjunct_with_flatten_sigma_2_length \<phi> M N"

lemma normal_form_disjunct_length_upper_bound:
  assumes
    "M \<subseteq> subformulas\<^sub>\<mu> \<phi>"
    "N \<subseteq> subformulas\<^sub>\<nu> \<phi>"
  shows
    "normal_form_disjunct_with_flatten_sigma_2_length \<phi> M N \<le> 2 ^ (size \<phi> + 1) + 2 * (size \<phi> + 2) ^ 2" (is "?thesis1")
    "normal_form_disjunct_with_flatten_pi_2_length \<phi> M N \<le> 2 ^ (size \<phi> + 1) + 2 * (size \<phi> + 2) ^ 2" (is "?thesis2")
proof -
  let ?n = "size \<phi>"
  let ?b = "2 ^ (?n + 1) + ?n * (?n + 2) + ?n * (?n + 2)"

  have finite_M: "finite M" and card_M: "card M \<le> ?n"
    by (metis assms(1) finite_subset subformulas\<^sub>\<mu>_finite)
       (meson assms(1) card_mono order_trans subformulas\<^sub>\<mu>_subfrmlsn subfrmlsn_card subfrmlsn_finite)

  have finite_N: "finite N" and card_N: "card N \<le> ?n"
    by (metis assms(2) finite_subset subformulas\<^sub>\<nu>_finite)
       (meson assms(2) card_mono order_trans subformulas\<^sub>\<nu>_subfrmlsn subfrmlsn_card subfrmlsn_finite)

  have size_M: "\<And>\<psi>. \<psi> \<in> M \<Longrightarrow> size \<psi> \<le> size \<phi>"
    and size_N: "\<And>\<psi>. \<psi> \<in> N \<Longrightarrow> size \<psi> \<le> size \<phi>"
    by (metis assms(1) eq_iff in_mono less_imp_le subformulas\<^sub>\<mu>_subfrmlsn subfrmlsn_size)
       (metis assms(2) eq_iff in_mono less_imp_le subformulas\<^sub>\<nu>_subfrmlsn subfrmlsn_size)

  hence size_M': "\<And>\<psi>. \<psi> \<in> M \<Longrightarrow> size (\<psi>[N]\<^sub>\<Sigma>\<^sub>1) \<le> size \<phi>"
    and size_N': "\<And>\<psi>. \<psi> \<in> N \<Longrightarrow> size (\<psi>[M]\<^sub>\<Pi>\<^sub>1) \<le> size \<phi>"
    using flatten_sigma_1_length flatten_pi_1_length order_trans by blast+

  have "(\<Sum>\<psi> \<in> M. size (\<psi>[N]\<^sub>\<Sigma>\<^sub>1)) \<le> ?n * ?n"
    and "(\<Sum>\<psi> \<in> N. size (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<le> ?n * ?n"
    using sum_bounded_above[of M, OF size_M'] sum_bounded_above[of N, OF size_N']
    using mult_le_mono[OF card_M] mult_le_mono[OF card_N] by fastforce+

  hence "(\<Sum>\<psi> \<in> M. (size (\<psi>[N]\<^sub>\<Sigma>\<^sub>1) + 2)) \<le> ?n * (?n + 2)"
    and "(\<Sum>\<psi> \<in> N. (size (\<psi>[M]\<^sub>\<Pi>\<^sub>1) + 2)) \<le> ?n * (?n + 2)"
    unfolding sum_associative[OF finite_M] sum_associative[OF finite_N]
    using card_M card_N by simp_all

  hence "normal_form_disjunct_with_flatten_sigma_2_length \<phi> M N \<le> ?b"
    and "normal_form_disjunct_with_flatten_pi_2_length \<phi> M N \<le> ?b"
    unfolding normal_form_disjunct_with_flatten_sigma_2_length_def normal_form_disjunct_with_flatten_pi_2_length_def
    by (metis (no_types, lifting) flatten_sigma_2_length flatten_pi_2_length add_le_mono)+

  thus ?thesis1 and ?thesis2
    by (simp_all add: power2_eq_square)
qed

theorem normal_form_length_upper_bound:
  "normal_form_with_flatten_sigma_2_length \<phi> \<le> normal_form_length_upper_bound \<phi>" (is "?thesis1")
  "normal_form_with_flatten_pi_2_length \<phi> \<le> normal_form_length_upper_bound \<phi>" (is "?thesis2")
proof -
  let ?n = "size \<phi>"
  let ?b = "2 ^ (size \<phi> + 1) + 2 * (size \<phi> + 2) ^ 2"

  have "{(M, N) | M N. M \<subseteq> subformulas\<^sub>\<mu> \<phi> \<and> N \<subseteq> subformulas\<^sub>\<nu> \<phi>} = {M. M \<subseteq> subformulas\<^sub>\<mu> \<phi>} \<times> {N. N \<subseteq> subformulas\<^sub>\<nu> \<phi>}" (is "?choices = _")
    by simp

  moreover

  have "card {M. M \<subseteq> subformulas\<^sub>\<mu> \<phi>} = (2 :: nat) ^ (card (subformulas\<^sub>\<mu> \<phi>))"
    and "card {N. N \<subseteq> subformulas\<^sub>\<nu> \<phi>} = (2 :: nat) ^ (card (subformulas\<^sub>\<nu> \<phi>))"
    using card_Pow unfolding Pow_def using subformulas\<^sub>\<mu>_finite subformulas\<^sub>\<nu>_finite by auto

  ultimately

  have "card ?choices \<le> 2 ^ (card (subfrmlsn \<phi>))" (is "?f \<le> _")
    by (metis subformulas\<^sub>\<mu>\<^sub>\<nu>_card card_cartesian_product subformulas\<^sub>\<mu>\<^sub>\<nu>_subfrmlsn subfrmlsn_finite Suc_1 card_mono lessI power_add power_increasing_iff)

  moreover

  have "(2 :: nat) ^ (card (subfrmlsn \<phi>)) \<le> 2 ^ ?n"
    using power_increasing[of _ _ "2 :: nat"] by (simp add: subfrmlsn_card)

  ultimately

  have bar: "of_nat (card ?choices) \<le> (2 :: nat) ^ ?n"
    using of_nat_id by presburger

  moreover

  have "normal_form_with_flatten_sigma_2_length \<phi> \<le> of_nat (card ?choices) * ?b"
    unfolding normal_form_with_flatten_sigma_2_length_def
    by (rule sum_bounded_above) (insert normal_form_disjunct_length_upper_bound, auto)

  moreover

  have "normal_form_with_flatten_pi_2_length \<phi> \<le> of_nat (card ?choices) * ?b"
    unfolding normal_form_with_flatten_pi_2_length_def
    by (rule sum_bounded_above) (insert normal_form_disjunct_length_upper_bound, auto)

  ultimately

  show ?thesis1 and ?thesis2
    unfolding normal_form_length_upper_bound_def
    using mult_le_mono1 order_trans by blast+
qed

subsection \<open>Proper Subformulas\<close>

text \<open>We prove that the number of (proper) subformulas (sf) in a disjunct is linear and not exponential.\<close>

fun sf :: "'a ltln \<Rightarrow> 'a ltln set"
where
  "sf (\<phi> and\<^sub>n \<psi>) = sf \<phi> \<union> sf \<psi>"
| "sf (\<phi> or\<^sub>n \<psi>) = sf \<phi> \<union> sf \<psi>"
| "sf (X\<^sub>n \<phi>) = {X\<^sub>n \<phi>} \<union> sf \<phi>"
| "sf (\<phi> U\<^sub>n \<psi>) = {\<phi> U\<^sub>n \<psi>} \<union> sf \<phi> \<union> sf \<psi>"
| "sf (\<phi> R\<^sub>n \<psi>) = {\<phi> R\<^sub>n \<psi>} \<union> sf \<phi> \<union> sf \<psi>"
| "sf (\<phi> W\<^sub>n \<psi>) = {\<phi> W\<^sub>n \<psi>} \<union> sf \<phi> \<union> sf \<psi>"
| "sf (\<phi> M\<^sub>n \<psi>) = {\<phi> M\<^sub>n \<psi>} \<union> sf \<phi> \<union> sf \<psi>"
| "sf \<phi> = {}"

lemma sf_finite:
  "finite (sf \<phi>)"
  by (induction \<phi>) auto

lemma sf_subset_subfrmlsn:
  "sf \<phi> \<subseteq> subfrmlsn \<phi>"
  by (induction \<phi>) auto

lemma sf_size:
  "\<psi> \<in> sf \<phi> \<Longrightarrow> size \<psi> \<le> size \<phi>"
  by (induction \<phi>) auto

lemma sf_sf_subset:
  "\<psi> \<in> sf \<phi> \<Longrightarrow> sf \<psi> \<subseteq> sf \<phi>"
  by (induction \<phi>) auto

lemma subfrmlsn_sf_subset:
  "\<psi> \<in> subfrmlsn \<phi> \<Longrightarrow> sf \<psi> \<subseteq> sf \<phi>"
  by (induction \<phi>) auto

lemma sf_subset_insert:
  assumes "sf \<phi> \<subseteq> insert \<phi> X"
  assumes "\<psi> \<in> subfrmlsn \<phi>"
  assumes "\<phi> \<noteq> \<psi>"
  shows "sf \<psi> \<subseteq> X"
proof -
  have "sf \<psi> \<subseteq> sf \<phi> - {\<phi>}"
    using assms(2,3) subfrmlsn_sf_subset sf_size subfrmlsn_size by fastforce
  thus "?thesis"
    using assms(1) by auto
qed

lemma flatten_pi_1_sf_subset:
  "sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1) \<subseteq> (\<Union>\<phi>\<in>sf \<phi>. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1))"
  by (induction \<phi>) auto

lemma flatten_sigma_1_sf_subset:
  "sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>1) \<subseteq> (\<Union>\<phi>\<in>sf \<phi>. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>1))"
  by (induction \<phi>) auto

lemma flatten_sigma_2_sf_subset:
  "sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2) \<subseteq> (\<Union>\<psi>\<in>sf \<phi>. sf (\<psi>[M]\<^sub>\<Sigma>\<^sub>2))"
  by (induction \<phi>) auto

lemma sf_set1:
  "sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2) \<union> sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1) \<subseteq> (\<Union>\<psi> \<in> (sf \<phi>). (sf (\<psi>[M]\<^sub>\<Sigma>\<^sub>2) \<union> sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)))"
  by (induction \<phi>) auto

(* TODO: could be moved *)
lemma ltln_not_idempotent [simp]:
  "\<phi> and\<^sub>n \<psi> \<noteq> \<phi>" "\<psi> and\<^sub>n \<phi> \<noteq> \<phi>" "\<phi> \<noteq> \<phi> and\<^sub>n \<psi>" "\<phi> \<noteq> \<psi> and\<^sub>n \<phi>"
  "\<phi> or\<^sub>n \<psi> \<noteq> \<phi>" "\<psi> or\<^sub>n \<phi> \<noteq> \<phi>" "\<phi> \<noteq> \<phi> or\<^sub>n \<psi>" "\<phi> \<noteq> \<psi> or\<^sub>n \<phi>"
  "X\<^sub>n \<phi> \<noteq> \<phi>" "\<phi> \<noteq> X\<^sub>n \<phi>"
  "\<phi> U\<^sub>n \<psi> \<noteq> \<phi>" "\<phi> \<noteq> \<phi> U\<^sub>n \<psi>" "\<psi> U\<^sub>n \<phi> \<noteq> \<phi>" "\<phi> \<noteq> \<psi> U\<^sub>n \<phi>"
  "\<phi> R\<^sub>n \<psi> \<noteq> \<phi>" "\<phi> \<noteq> \<phi> R\<^sub>n \<psi>" "\<psi> R\<^sub>n \<phi> \<noteq> \<phi>" "\<phi> \<noteq> \<psi> R\<^sub>n \<phi>"
  "\<phi> W\<^sub>n \<psi> \<noteq> \<phi>" "\<phi> \<noteq> \<phi> W\<^sub>n \<psi>" "\<psi> W\<^sub>n \<phi> \<noteq> \<phi>" "\<phi> \<noteq> \<psi> W\<^sub>n \<phi>"
  "\<phi> M\<^sub>n \<psi> \<noteq> \<phi>" "\<phi> \<noteq> \<phi> M\<^sub>n \<psi>" "\<psi> M\<^sub>n \<phi> \<noteq> \<phi>" "\<phi> \<noteq> \<psi> M\<^sub>n \<phi>"
  by (induction \<phi>; force)+

lemma flatten_card_sf_induct:
  assumes "finite X"
  assumes "\<And>x. x \<in> X \<Longrightarrow> sf x \<subseteq> X"
  shows "card (\<Union>\<phi>\<in>X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1)) \<le> card X
   \<and> card (\<Union>\<phi>\<in>X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<le> card X
   \<and> card (\<Union>\<phi>\<in>X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2) \<union> sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<le> 3 * card X"
  using assms(2)
proof (induction rule: finite_ranking_induct[where f = size, OF \<open>finite X\<close>])
  case (2 \<psi> X)
    {
      assume "\<psi> \<notin> X"
      hence "\<And>\<chi>. \<chi> \<in> X \<Longrightarrow> sf \<chi> \<subseteq> X"
        using 2(2,4) sf_subset_subfrmlsn subfrmlsn_size by fastforce
      hence "card (\<Union>\<phi>\<in>X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1)) \<le> card X"
        and "card (\<Union>\<phi>\<in>X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<le> card X"
        and "card (\<Union>\<phi>\<in>X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2) \<union> sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<le> 3 * card X"
        using 2(3) by simp+

      moreover

      let ?lower1 = "\<Union>\<phi> \<in> insert \<psi> X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1)"
      let ?upper1 = "(\<Union>\<phi> \<in> X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1)) \<union> {\<psi>[N]\<^sub>\<Sigma>\<^sub>1}"

      let ?lower2 = "\<Union>\<phi> \<in> insert \<psi> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)"
      let ?upper2 = "(\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> {\<psi>[M]\<^sub>\<Pi>\<^sub>1}"

      let ?lower3 = "\<Union>\<phi> \<in> insert \<psi> X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2) \<union> sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)"
      let ?upper3_cases = "{\<psi>[M]\<^sub>\<Sigma>\<^sub>2, \<psi>[M]\<^sub>\<Pi>\<^sub>1} \<union> (case \<psi> of (\<phi>1 W\<^sub>n \<phi>2) \<Rightarrow> {G\<^sub>n (\<phi>1[M]\<^sub>\<Pi>\<^sub>1)} | (\<phi>1 R\<^sub>n \<phi>2) \<Rightarrow> {G\<^sub>n (\<phi>2[M]\<^sub>\<Pi>\<^sub>1)} | _ \<Rightarrow> {})"
      let ?upper3 = "(\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2) \<union> sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> ?upper3_cases"

      have finite_upper1: "finite (?upper1)"
        and finite_upper2: "finite (?upper2)"
        and finite_upper3: "finite (?upper3)"
        using 2(1) sf_finite by auto (cases \<psi>, auto)

      have "\<And>x y. card {x, y} \<le> 3"
        and "\<And>x y z. card {x, y, z} \<le> 3"
        by (simp add: card_insert_if le_less)+
      hence card_leq_3: "card (?upper3_cases) \<le> 3"
        by (cases \<psi>) (simp_all, fast)

      note card_subset_split_rule = le_trans[OF card_mono card_Un_le]

      have sf_in_X: "sf \<psi> \<subseteq> insert \<psi> X"
        using 2 by blast

      have "?lower1 \<subseteq> ?upper1 \<and> ?lower2 \<subseteq> ?upper2 \<and> ?lower3 \<subseteq> ?upper3"
      proof (cases \<psi>)
        case (And_ltln \<psi>\<^sub>1 \<psi>\<^sub>2)
        have *: "sf \<psi>\<^sub>1 \<subseteq> X" "sf \<psi>\<^sub>2 \<subseteq> X"
          by (rule sf_subset_insert[OF sf_in_X, unfolded And_ltln]; simp)+

        have "(sf (\<psi>[M]\<^sub>\<Sigma>\<^sub>2)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2))"
          and "(sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1))"
          and "(sf (\<psi>[N]\<^sub>\<Sigma>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1))"
          subgoal
            using flatten_sigma_2_sf_subset[of _ M] * by (force simp: And_ltln)
          subgoal
            using flatten_pi_1_sf_subset[of _ M] * by (force simp: And_ltln)
          subgoal
            using flatten_sigma_1_sf_subset * by (force simp: And_ltln)
          done

        thus ?thesis
          by blast
      next
        case (Or_ltln \<psi>\<^sub>1 \<psi>\<^sub>2)
        have *: "sf \<psi>\<^sub>1 \<subseteq> X" "sf \<psi>\<^sub>2 \<subseteq> X"
          by (rule sf_subset_insert[OF sf_in_X, unfolded Or_ltln]; simp)+

        have "(sf (\<psi>[M]\<^sub>\<Sigma>\<^sub>2)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2))"
          and "(sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1))"
          and "(sf (\<psi>[N]\<^sub>\<Sigma>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1))"
          subgoal
            using flatten_sigma_2_sf_subset[of _ M] * by (force simp: Or_ltln)
          subgoal
            using flatten_pi_1_sf_subset[of _ M] * by (force simp: Or_ltln)
          subgoal
            using flatten_sigma_1_sf_subset * by (force simp: Or_ltln)
          done

        thus ?thesis
          by blast
      next
        case (Next_ltln \<psi>\<^sub>1)
        have *: "sf \<psi>\<^sub>1 \<subseteq> X"
          by (rule sf_subset_insert[OF sf_in_X, unfolded Next_ltln]) simp_all

        have "(sf (\<psi>[M]\<^sub>\<Sigma>\<^sub>2)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2)) \<union> {\<psi>[M]\<^sub>\<Sigma>\<^sub>2}"
          and "(sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> {\<psi>[M]\<^sub>\<Pi>\<^sub>1}"
          and "(sf (\<psi>[N]\<^sub>\<Sigma>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1)) \<union> {\<psi>[N]\<^sub>\<Sigma>\<^sub>1}"
          subgoal
            using flatten_sigma_2_sf_subset[of _ M] * by (force simp: Next_ltln)
          subgoal
            using flatten_pi_1_sf_subset[of _ M] * by (force simp: Next_ltln)
          subgoal
            using flatten_sigma_1_sf_subset * by (force simp: Next_ltln)
          done

        thus ?thesis
          by blast
      next
        case (Until_ltln \<psi>\<^sub>1 \<psi>\<^sub>2)
        have *: "sf \<psi>\<^sub>1 \<subseteq> X" "sf \<psi>\<^sub>2 \<subseteq> X"
          by (rule sf_subset_insert[OF sf_in_X, unfolded Until_ltln]; simp)+

        hence "(sf (\<psi>[M]\<^sub>\<Sigma>\<^sub>2)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2)) \<union> {\<psi>[M]\<^sub>\<Sigma>\<^sub>2}"
          and "(sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> {\<psi>[M]\<^sub>\<Pi>\<^sub>1}"
          and "(sf (\<psi>[N]\<^sub>\<Sigma>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1)) \<union> {\<psi>[N]\<^sub>\<Sigma>\<^sub>1}"
          subgoal
            using flatten_sigma_2_sf_subset[of _ M] * by (force simp: Until_ltln)
          subgoal
            using flatten_pi_1_sf_subset[of _ M] * by (force simp: Until_ltln)
          subgoal
            using flatten_sigma_1_sf_subset * by (force simp: Until_ltln)
          done

        thus ?thesis
          by blast
      next
        case (Release_ltln \<psi>\<^sub>1 \<psi>\<^sub>2)
        have *: "sf \<psi>\<^sub>1 \<subseteq> X" "sf \<psi>\<^sub>2 \<subseteq> X"
          by (rule sf_subset_insert[OF sf_in_X, unfolded Release_ltln]; simp)+

        have "(sf (\<psi>[M]\<^sub>\<Sigma>\<^sub>2)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2)) \<union> {\<psi>[M]\<^sub>\<Sigma>\<^sub>2, G\<^sub>n \<psi>\<^sub>2[M]\<^sub>\<Pi>\<^sub>1} \<union> sf (\<psi>\<^sub>2[M]\<^sub>\<Pi>\<^sub>1)"
          and "(sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> {\<psi>[M]\<^sub>\<Pi>\<^sub>1}"
          and "(sf (\<psi>[N]\<^sub>\<Sigma>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1)) \<union> {\<psi>[N]\<^sub>\<Sigma>\<^sub>1}"
          subgoal
            using flatten_sigma_2_sf_subset[of _ M] * by (force simp: Release_ltln)
          subgoal
            using flatten_pi_1_sf_subset[of _ M] * by (force simp: Release_ltln)
          subgoal
            using flatten_sigma_1_sf_subset * by (force simp: Release_ltln)
          done

        moreover
        have "sf (\<psi>\<^sub>2[M]\<^sub>\<Pi>\<^sub>1) \<subseteq> (\<Union>\<phi>\<in>X. sf \<phi>[M]\<^sub>\<Sigma>\<^sub>2 \<union> sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> {\<psi>[M]\<^sub>\<Pi>\<^sub>1}"
          using \<open>(sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> {\<psi>[M]\<^sub>\<Pi>\<^sub>1}\<close>
          by (auto simp: Release_ltln)

        ultimately
        show ?thesis
          by (simp add: Release_ltln) blast
      next
        case (WeakUntil_ltln \<psi>\<^sub>1 \<psi>\<^sub>2)
        have *: "sf \<psi>\<^sub>1 \<subseteq> X" "sf \<psi>\<^sub>2 \<subseteq> X"
          by (rule sf_subset_insert[OF sf_in_X, unfolded WeakUntil_ltln]; simp)+

        have "(sf (\<psi>[M]\<^sub>\<Sigma>\<^sub>2)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2)) \<union> {\<psi>[M]\<^sub>\<Sigma>\<^sub>2, G\<^sub>n \<psi>\<^sub>1[M]\<^sub>\<Pi>\<^sub>1} \<union> sf (\<psi>\<^sub>1[M]\<^sub>\<Pi>\<^sub>1)"
          and "(sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> {\<psi>[M]\<^sub>\<Pi>\<^sub>1}"
          and "(sf (\<psi>[N]\<^sub>\<Sigma>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1)) \<union> {\<psi>[N]\<^sub>\<Sigma>\<^sub>1}"
          subgoal
            using flatten_sigma_2_sf_subset[of _ M] * by (force simp: WeakUntil_ltln)
          subgoal
            using flatten_pi_1_sf_subset[of _ M] * by (force simp: WeakUntil_ltln)
          subgoal
            using flatten_sigma_1_sf_subset * by (force simp: WeakUntil_ltln)
          done

        moreover
        have "sf (\<psi>\<^sub>1[M]\<^sub>\<Pi>\<^sub>1) \<subseteq> (\<Union>\<phi>\<in>X. sf \<phi>[M]\<^sub>\<Sigma>\<^sub>2 \<union> sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> {\<psi>[M]\<^sub>\<Pi>\<^sub>1}"
          using \<open>(sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> {\<psi>[M]\<^sub>\<Pi>\<^sub>1}\<close>
          by (auto simp: WeakUntil_ltln)

        ultimately
        show ?thesis
          by (simp add: WeakUntil_ltln) blast
      next
        case (StrongRelease_ltln \<psi>\<^sub>1 \<psi>\<^sub>2)
        have *: "sf \<psi>\<^sub>1 \<subseteq> X" "sf \<psi>\<^sub>2 \<subseteq> X"
          by (rule sf_subset_insert[OF sf_in_X, unfolded StrongRelease_ltln]; simp)+

        hence "(sf (\<psi>[M]\<^sub>\<Sigma>\<^sub>2)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2)) \<union> {\<psi>[M]\<^sub>\<Sigma>\<^sub>2}"
          and "(sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<union> {\<psi>[M]\<^sub>\<Pi>\<^sub>1}"
          and "(sf (\<psi>[N]\<^sub>\<Sigma>\<^sub>1)) \<subseteq> (\<Union>\<phi> \<in> X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1)) \<union> {\<psi>[N]\<^sub>\<Sigma>\<^sub>1}"
          subgoal
            using flatten_sigma_2_sf_subset[of _ M] * by (force simp: StrongRelease_ltln)
          subgoal
            using flatten_pi_1_sf_subset[of _ M] * by (force simp: StrongRelease_ltln)
          subgoal
            using flatten_sigma_1_sf_subset * by (force simp: StrongRelease_ltln)
          done

        thus ?thesis
          by blast
      qed auto

      hence "card ?lower1 \<le> card (\<Union>\<phi> \<in> X. sf (\<phi>[N]\<^sub>\<Sigma>\<^sub>1)) + 1"
        and "card ?lower2 \<le> card (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) + 1"
        and "card ?lower3 \<le> card (\<Union>\<phi> \<in> X. sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2) \<union> sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) + 3"
        using card_subset_split_rule[OF finite_upper1, of ?lower1]
        using card_subset_split_rule[OF finite_upper2, of ?lower2]
        using card_subset_split_rule[OF finite_upper3, of ?lower3]
        using card_leq_3 by simp+

      moreover
      have "card (insert \<psi> X) = card X + 1"
        using \<open>\<psi> \<notin> X\<close> \<open>finite X\<close> by simp
      ultimately
      have ?case
        by linarith
    }
  moreover
  have "\<psi> \<in> X \<Longrightarrow> ?case"
    using 2 by (simp add: insert_absorb)
  ultimately
  show ?case
    by meson
qed simp

theorem flatten_card_sf:
  "card (\<Union>\<psi> \<in> sf \<phi>. sf (\<psi>[M]\<^sub>\<Sigma>\<^sub>1)) \<le> card (sf \<phi>)" (is "?t1")
  "card (\<Union>\<psi> \<in> sf \<phi>. sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<le> card (sf \<phi>)" (is "?t2")
  "card (sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2) \<union> sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<le> 3 * card (sf \<phi>)" (is "?t3")
proof -
  have "card (\<Union>\<psi> \<in> sf \<phi>. sf \<psi>[M]\<^sub>\<Sigma>\<^sub>2 \<union> sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1)) \<le> 3 * card (sf \<phi>)"
    using flatten_card_sf_induct[OF sf_finite sf_sf_subset] by auto
  moreover
  have "card (sf \<phi>[M]\<^sub>\<Sigma>\<^sub>2 \<union> sf (\<phi>[M]\<^sub>\<Pi>\<^sub>1)) \<le> card (\<Union>\<psi> \<in> sf \<phi>. sf \<psi>[M]\<^sub>\<Sigma>\<^sub>2 \<union> sf (\<psi>[M]\<^sub>\<Pi>\<^sub>1))"
    using card_mono[OF _ sf_set1] sf_finite by blast
  ultimately
  show ?t1 ?t2 ?t3
    using flatten_card_sf_induct[OF sf_finite sf_sf_subset] by auto
qed

corollary flatten_sigma_2_card_sf:
  "card (sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2)) \<le> 3 * (card (sf \<phi>))"
  by (metis sf_finite order.trans[OF _ flatten_card_sf(3), of "card (sf (\<phi>[M]\<^sub>\<Sigma>\<^sub>2))", OF card_mono] finite_UnI Un_upper1)

end

repo: PSL