theory Lambda
imports
  "../Nominal2"
  "~~/src/HOL/Library/Monad_Syntax"
begin

lemma perm_commute:
  "a \<sharp> p \<Longrightarrow> a' \<sharp> p \<Longrightarrow> (a \<rightleftharpoons> a') + p = p + (a \<rightleftharpoons> a')"
apply(rule plus_perm_eq)
apply(simp add: supp_swap fresh_def)
done

atom_decl name

thm obtain_atom

ML {* trace := true *}

nominal_datatype lam =
  Var "name"
| App "lam" "lam"
| Lam x::"name" l::"lam"  binds x in l ("Lam [_]. _" [100, 100] 100)

nominal_datatype environment =
   Ni
 | En name closure environment
and closure =
   Clos "lam" "environment"

thm environment_closure.exhaust(1)

nominal_function
  env_lookup :: "environment => name => closure"
where
  "env_lookup Ni x = Clos (Var x) Ni"
| "env_lookup (En v clos rest) x = (if (v = x) then clos else env_lookup rest x)"
   apply (auto)
   apply (simp add: env_lookup_graph_aux_def eqvt_def)
   by (metis environment_closure.strong_exhaust(1))

lemma
  "Lam [x]. Var x = Lam [y]. Var y"
proof -
  obtain c::name where fresh: "atom c \<sharp> (Lam [x]. Var x, Lam [y]. Var y)"
    by (metis obtain_fresh)
  have "Lam [x]. Var x = (c \<leftrightarrow> x) \<bullet> Lam [x]. Var x"
    using fresh by (rule_tac flip_fresh_fresh[symmetric]) (simp_all add: fresh_Pair)
  also have "... = Lam [c].Var c" by simp
  also have "... = (c \<leftrightarrow> y) \<bullet> Lam [c]. Var c"
    using fresh by (rule_tac flip_fresh_fresh[symmetric]) (auto simp add: fresh_Pair)
  also have "... = Lam [y]. Var y" by simp
  finally show "Lam [x]. Var x = Lam [y]. Var y" .
qed

definition
  Name :: "nat \<Rightarrow> name"
where
  "Name n = Abs_name (Atom (Sort ''name'' []) n)"

definition
   "Ident2 = Lam [Name 1].(Var (Name 1))"

definition
   "Ident x = Lam [x].(Var x)"

lemma "Ident2 = Ident x"
unfolding Ident_def Ident2_def
by simp

lemma "Ident x = Ident y"
unfolding Ident_def
by simp

section {* Simple examples from Norrish 2004 *}

nominal_function
  is_app :: "lam \<Rightarrow> bool"
where
  "is_app (Var x) = False"
| "is_app (App t1 t2) = True"
| "is_app (Lam [x]. t) = False"
thm is_app_graph_def is_app_graph_aux_def
apply(simp add: eqvt_def is_app_graph_aux_def)
apply(rule TrueI)
apply(rule_tac y="x" in lam.exhaust)
apply(auto)[3]
apply(all_trivials)
done

nominal_termination (eqvt) by lexicographic_order

thm is_app_def
thm is_app.eqvt

thm eqvts

nominal_function
  rator :: "lam \<Rightarrow> lam option"
where
  "rator (Var x) = None"
| "rator (App t1 t2) = Some t1"
| "rator (Lam [x]. t) = None"
apply(simp add: eqvt_def rator_graph_aux_def)
apply(rule TrueI)
apply(rule_tac y="x" in lam.exhaust)
apply(auto)[3]
apply(simp_all)
done

nominal_termination (eqvt) by lexicographic_order

nominal_function
  rand :: "lam \<Rightarrow> lam option"
where
  "rand (Var x) = None"
| "rand (App t1 t2) = Some t2"
| "rand (Lam [x]. t) = None"
apply(simp add: eqvt_def rand_graph_aux_def)
apply(rule TrueI)
apply(rule_tac y="x" in lam.exhaust)
apply(auto)[3]
apply(simp_all)
done

nominal_termination (eqvt) by lexicographic_order

nominal_function
  is_eta_nf :: "lam \<Rightarrow> bool"
where
  "is_eta_nf (Var x) = True"
| "is_eta_nf (App t1 t2) = (is_eta_nf t1 \<and> is_eta_nf t2)"
| "is_eta_nf (Lam [x]. t) = (is_eta_nf t \<and>
                             ((is_app t \<and> rand t = Some (Var x)) \<longrightarrow> atom x \<in> supp (rator t)))"
apply(simp add: eqvt_def is_eta_nf_graph_aux_def)
apply(rule TrueI)
apply(rule_tac y="x" in lam.exhaust)
apply(auto)[3]
using [[simproc del: alpha_lst]]
apply(simp_all)
apply(erule_tac c="()" in Abs_lst1_fcb2')
apply(simp_all add: pure_fresh fresh_star_def)[3]
apply(simp add: eqvt_at_def conj_eqvt)
apply(simp add: eqvt_at_def conj_eqvt)
done

nominal_termination (eqvt) by lexicographic_order

nominal_datatype path = Left | Right | In

section {* Paths to a free variables *}

instance path :: pure
apply(standard)
apply(induct_tac "x::path" rule: path.induct)
apply(simp_all)
done

nominal_function
  var_pos :: "name \<Rightarrow> lam \<Rightarrow> (path list) set"
where
  "var_pos y (Var x) = (if y = x then {[]} else {})"
| "var_pos y (App t1 t2) = (Cons Left ` (var_pos y t1)) \<union> (Cons Right ` (var_pos y t2))"
| "atom x \<sharp> y \<Longrightarrow> var_pos y (Lam [x]. t) = (Cons In ` (var_pos y t))"
apply(simp add: eqvt_def var_pos_graph_aux_def)
apply(rule TrueI)
apply(case_tac x)
apply(rule_tac y="b" and c="a" in lam.strong_exhaust)
apply(auto simp add: fresh_star_def)[3]
using [[simproc del: alpha_lst]]
apply(simp_all)
apply(erule conjE)+
apply(erule_tac Abs_lst1_fcb2)
apply(simp add: pure_fresh)
apply(simp add: fresh_star_def)
apply(simp only: eqvt_at_def)
apply(perm_simp)
apply(simp)
apply(simp add: perm_supp_eq)
apply(simp only: eqvt_at_def)
apply(perm_simp)
apply(simp)
apply(simp add: perm_supp_eq)
done

nominal_termination (eqvt) by lexicographic_order

lemma var_pos1:
  assumes "atom y \<notin> supp t"
  shows "var_pos y t = {}"
using assms
apply(induct t rule: var_pos.induct)
apply(simp_all add: lam.supp supp_at_base fresh_at_base)
done

lemma var_pos2:
  shows "var_pos y (Lam [y].t) = {}"
apply(rule var_pos1)
apply(simp add: lam.supp)
done

text {* strange substitution operation *}

nominal_function
  subst' :: "lam \<Rightarrow> name \<Rightarrow> lam \<Rightarrow> lam"  ("_ [_ ::== _]" [90, 90, 90] 90)
where
  "(Var x)[y ::== s] = (if x = y then s else (Var x))"
| "(App t1 t2)[y ::== s] = App (t1[y ::== s]) (t2[y ::== s])"
| "atom x \<sharp> (y, s) \<Longrightarrow> (Lam [x]. t)[y ::== s] = Lam [x].(t[y ::== (App (Var y) s)])"
  apply(simp add: eqvt_def subst'_graph_aux_def)
  apply(rule TrueI)
  apply(case_tac x)
  apply(rule_tac y="a" and c="(b, c)" in lam.strong_exhaust)
  apply(auto simp add: fresh_star_def)[3]
  using [[simproc del: alpha_lst]]
  apply(simp_all)
  apply(erule conjE)+
  apply (erule_tac c="(ya,sa)" in Abs_lst1_fcb2)
  apply(simp_all add: Abs_fresh_iff)
  apply(simp add: fresh_star_def fresh_Pair)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
done

nominal_termination (eqvt) by lexicographic_order

section {* free name function *}

lemma fresh_removeAll_name:
  fixes x::"name"
    and xs:: "name list"
  shows "atom x \<sharp> (removeAll y xs) \<longleftrightarrow> (atom x \<sharp> xs \<or> x = y)"
  apply (induct xs)
  apply(auto simp add: fresh_def supp_Nil supp_Cons supp_at_base)
  done

text {* first returns an atom list *}

nominal_function
  frees_lst :: "lam \<Rightarrow> atom list"
where
  "frees_lst (Var x) = [atom x]"
| "frees_lst (App t1 t2) = frees_lst t1 @ frees_lst t2"
| "frees_lst (Lam [x]. t) = removeAll (atom x) (frees_lst t)"
apply(simp add: eqvt_def frees_lst_graph_aux_def)
apply(rule TrueI)
apply(rule_tac y="x" in lam.exhaust)
using [[simproc del: alpha_lst]]
apply(auto)
apply (erule_tac c="()" in Abs_lst1_fcb2)
apply(simp add: supp_removeAll fresh_def)
apply(simp add: fresh_star_def fresh_Unit)
apply(simp add: eqvt_at_def removeAll_eqvt atom_eqvt)
apply(simp add: eqvt_at_def removeAll_eqvt atom_eqvt)
done

nominal_termination (eqvt) by lexicographic_order

text {* a small test lemma *}
lemma shows "supp t = set (frees_lst t)"
  by (induct t rule: frees_lst.induct) (simp_all add: lam.supp supp_at_base)

text {* second returns an atom set - therefore needs an invariant *}

nominal_function (invariant "\<lambda>x (y::atom set). finite y")
  frees_set :: "lam \<Rightarrow> atom set"
where
  "frees_set (Var x) = {atom x}"
| "frees_set (App t1 t2) = frees_set t1 \<union> frees_set t2"
| "frees_set (Lam [x]. t) = (frees_set t) - {atom x}"
  apply(simp add: eqvt_def frees_set_graph_aux_def)
  apply(erule frees_set_graph.induct)
  apply(auto)[9]
  apply(rule_tac y="x" in lam.exhaust)
  apply(auto)[3]
  using [[simproc del: alpha_lst]]
  apply(simp)
  apply(erule_tac c="()" in Abs_lst1_fcb2)
  apply(simp add: fresh_minus_atom_set)
  apply(simp add: fresh_star_def fresh_Unit)
  apply(simp add: Diff_eqvt eqvt_at_def)
  apply(simp add: Diff_eqvt eqvt_at_def)
  done

nominal_termination (eqvt)
  by lexicographic_order

lemma "frees_set t = supp t"
  by (induct rule: frees_set.induct) (simp_all add: lam.supp supp_at_base)

section {* height function *}

nominal_function
  height :: "lam \<Rightarrow> int"
where
  "height (Var x) = 1"
| "height (App t1 t2) = max (height t1) (height t2) + 1"
| "height (Lam [x].t) = height t + 1"
  apply(simp add: eqvt_def height_graph_aux_def)
  apply(rule TrueI)
  apply(rule_tac y="x" in lam.exhaust)
  using [[simproc del: alpha_lst]]
  apply(auto)
  apply (erule_tac c="()" in Abs_lst1_fcb2)
  apply(simp_all add: fresh_def pure_supp eqvt_at_def fresh_star_def)
  done

nominal_termination (eqvt)
  by lexicographic_order

thm height.simps

section {* capture-avoiding substitution *}

nominal_function
  subst :: "lam \<Rightarrow> name \<Rightarrow> lam \<Rightarrow> lam"  ("_ [_ ::= _]" [90, 90, 90] 90)
where
  "(Var x)[y ::= s] = (if x = y then s else (Var x))"
| "(App t1 t2)[y ::= s] = App (t1[y ::= s]) (t2[y ::= s])"
| "atom x \<sharp> (y, s) \<Longrightarrow> (Lam [x]. t)[y ::= s] = Lam [x].(t[y ::= s])"
  apply(simp add: eqvt_def subst_graph_aux_def)
  apply(rule TrueI)
  using [[simproc del: alpha_lst]]
  apply(auto)
  apply(rule_tac y="a" and c="(aa, b)" in lam.strong_exhaust)
  apply(blast)+
  using [[simproc del: alpha_lst]]
  apply(simp_all add: fresh_star_def fresh_Pair_elim)
  apply (erule_tac c="(ya,sa)" in Abs_lst1_fcb2)
  apply(simp_all add: Abs_fresh_iff)
  apply(simp add: fresh_star_def fresh_Pair)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
done

nominal_termination (eqvt)
  by lexicographic_order

thm subst.eqvt

lemma forget:
  shows "atom x \<sharp> t \<Longrightarrow> t[x ::= s] = t"
  by (nominal_induct t avoiding: x s rule: lam.strong_induct)
     (auto simp add: fresh_at_base)

text {* same lemma but with subst.induction *}
lemma forget2:
  shows "atom x \<sharp> t \<Longrightarrow> t[x ::= s] = t"
  apply(induct t x s rule: subst.induct)
  using [[simproc del: alpha_lst]]
  apply(auto simp add:  flip_fresh_fresh fresh_Pair fresh_at_base)
  done

lemma fresh_fact:
  fixes z::"name"
  assumes a: "atom z \<sharp> s"
      and b: "z = y \<or> atom z \<sharp> t"
  shows "atom z \<sharp> t[y ::= s]"
  using a b
  by (nominal_induct t avoiding: z y s rule: lam.strong_induct)
      (auto simp add:  fresh_at_base)

lemma substitution_lemma:
  assumes a: "x \<noteq> y" "atom x \<sharp> u"
  shows "t[x ::= s][y ::= u] = t[y ::= u][x ::= s[y ::= u]]"
using a
by (nominal_induct t avoiding: x y s u rule: lam.strong_induct)
   (auto simp add: fresh_fact forget)

lemma subst_rename:
  assumes a: "atom y \<sharp> t"
  shows "t[x ::= s] = ((y \<leftrightarrow> x) \<bullet>t)[y ::= s]"
using a
apply (nominal_induct t avoiding: x y s rule: lam.strong_induct)
apply (auto simp add:  fresh_at_base)
done

lemma height_ge_one:
  shows "1 \<le> (height e)"
by (induct e rule: lam.induct) (simp_all)

theorem height_subst:
  shows "height (e[x::=e']) \<le> ((height e) - 1) + (height e')"
proof (nominal_induct e avoiding: x e' rule: lam.strong_induct)
  case (Var y)
  have "1 \<le> height e'" by (rule height_ge_one)
  then show "height (Var y[x::=e']) \<le> height (Var y) - 1 + height e'" by simp
next
  case (Lam y e1)
  hence ih: "height (e1[x::=e']) \<le> ((height e1) - 1) + (height e')" by simp
  moreover
  have vc: "atom y\<sharp>x" "atom y\<sharp>e'" by fact+ (* usual variable convention *)
  ultimately show "height ((Lam [y]. e1)[x::=e']) \<le> height (Lam [y]. e1) - 1 + height e'" by simp
next
  case (App e1 e2)
  hence ih1: "height (e1[x::=e']) \<le> ((height e1) - 1) + (height e')"
    and ih2: "height (e2[x::=e']) \<le> ((height e2) - 1) + (height e')" by simp_all
  then show "height ((App e1 e2)[x::=e']) \<le> height (App e1 e2) - 1 + height e'"  by simp
qed

subsection {* single-step beta-reduction *}

inductive
  beta :: "lam \<Rightarrow> lam \<Rightarrow> bool" (" _ \<longrightarrow>b _" [80,80] 80)
where
  b1[intro]: "t1 \<longrightarrow>b t2 \<Longrightarrow> App t1 s \<longrightarrow>b App t2 s"
| b2[intro]: "s1 \<longrightarrow>b s2 \<Longrightarrow> App t s1 \<longrightarrow>b App t s2"
| b3[intro]: "t1 \<longrightarrow>b t2 \<Longrightarrow> Lam [x]. t1 \<longrightarrow>b Lam [x]. t2"
| b4[intro]: "atom x \<sharp> s \<Longrightarrow> App (Lam [x]. t) s \<longrightarrow>b t[x ::= s]"

equivariance beta

nominal_inductive beta
  avoids b4: "x"
  by (simp_all add: fresh_star_def fresh_Pair  fresh_fact)

thm beta.strong_induct

text {* One-Reduction *}

inductive
  One :: "lam \<Rightarrow> lam \<Rightarrow> bool" (" _ \<longrightarrow>1 _" [80,80] 80)
where
  o1[intro]: "Var x \<longrightarrow>1 Var x"
| o2[intro]: "\<lbrakk>t1 \<longrightarrow>1 t2; s1 \<longrightarrow>1 s2\<rbrakk> \<Longrightarrow> App t1 s1 \<longrightarrow>1 App t2 s2"
| o3[intro]: "t1 \<longrightarrow>1 t2 \<Longrightarrow> Lam [x].t1 \<longrightarrow>1 Lam [x].t2"
| o4[intro]: "\<lbrakk>atom x \<sharp> (s1, s2); t1 \<longrightarrow>1 t2; s1 \<longrightarrow>1 s2\<rbrakk> \<Longrightarrow> App (Lam [x].t1) s1 \<longrightarrow>1 t2[x ::= s2]"

equivariance One

nominal_inductive One
  avoids o3: "x"
      |  o4: "x"
  by (simp_all add: fresh_star_def fresh_Pair  fresh_fact)

lemma One_refl:
  shows "t \<longrightarrow>1 t"
by (nominal_induct t rule: lam.strong_induct) (auto)

lemma One_subst:
  assumes a: "t1 \<longrightarrow>1 t2" "s1 \<longrightarrow>1 s2"
  shows "t1[x ::= s1] \<longrightarrow>1 t2[x ::= s2]"
using a
apply(nominal_induct t1 t2 avoiding: s1 s2 x rule: One.strong_induct)
apply(auto simp add: substitution_lemma fresh_at_base fresh_fact fresh_Pair)
done

lemma better_o4_intro:
  assumes a: "t1 \<longrightarrow>1 t2" "s1 \<longrightarrow>1 s2"
  shows "App (Lam [x]. t1) s1 \<longrightarrow>1 t2[ x ::= s2]"
proof -
  obtain y::"name" where fs: "atom y \<sharp> (x, t1, s1, t2, s2)" by (rule obtain_fresh)
  have "App (Lam [x]. t1) s1 = App (Lam [y]. ((y \<leftrightarrow> x) \<bullet> t1)) s1" using fs
    by (auto simp add: Abs1_eq_iff' flip_def fresh_Pair fresh_at_base)
  also have "\<dots> \<longrightarrow>1 ((y \<leftrightarrow> x) \<bullet> t2)[y ::= s2]" using fs a by (auto simp add: One.eqvt)
  also have "\<dots> = t2[x ::= s2]" using fs by (simp add: subst_rename[symmetric])
  finally show "App (Lam [x].t1) s1 \<longrightarrow>1 t2[x ::= s2]" by simp
qed

section {* Locally Nameless Terms *}

nominal_datatype ln =
  LNBnd nat
| LNVar name
| LNApp ln ln
| LNLam ln

fun
  lookup :: "name list \<Rightarrow> nat \<Rightarrow> name \<Rightarrow> ln"
where
  "lookup [] n x = LNVar x"
| "lookup (y # ys) n x = (if x = y then LNBnd n else (lookup ys (n + 1) x))"

lemma supp_lookup:
  shows "supp (lookup xs n x) \<subseteq> {atom x}"
  apply(induct arbitrary: n rule: lookup.induct)
  apply(simp add: ln.supp supp_at_base)
  apply(simp add: ln.supp pure_supp)
  done

lemma supp_lookup_in:
  shows "x \<in> set xs \<Longrightarrow> supp (lookup xs n x) = {}"
  by (induct arbitrary: n rule: lookup.induct)(auto simp add: ln.supp pure_supp)

lemma supp_lookup_notin:
  shows "x \<notin> set xs \<Longrightarrow> supp (lookup xs n x) = {atom x}"
  by (induct arbitrary: n rule: lookup.induct) (auto simp add: ln.supp pure_supp supp_at_base)

lemma supp_lookup_fresh:
  shows "atom ` set xs \<sharp>* lookup xs n x"
  by (case_tac "x \<in> set xs") (auto simp add: fresh_star_def fresh_def supp_lookup_in supp_lookup_notin)

lemma lookup_eqvt[eqvt]:
  shows "(p \<bullet> lookup xs n x) = lookup (p \<bullet> xs) (p \<bullet> n) (p \<bullet> x)"
  by (induct xs arbitrary: n) (simp_all add: permute_pure)

text {* Function that translates lambda-terms into locally nameless terms *}

nominal_function (invariant "\<lambda>(_, xs) y. atom ` set xs \<sharp>* y")
  trans :: "lam \<Rightarrow> name list \<Rightarrow> ln"
where
  "trans (Var x) xs = lookup xs 0 x"
| "trans (App t1 t2) xs = LNApp (trans t1 xs) (trans t2 xs)"
| "atom x \<sharp> xs \<Longrightarrow> trans (Lam [x]. t) xs = LNLam (trans t (x # xs))"
  apply (simp add: eqvt_def trans_graph_aux_def)
  apply (erule trans_graph.induct)
  apply (auto simp add: ln.fresh)[3]
  apply (simp add: supp_lookup_fresh)
  apply (simp add: fresh_star_def ln.fresh)
  apply (simp add: ln.fresh fresh_star_def)
  apply(auto)[1]
  apply (rule_tac y="a" and c="b" in lam.strong_exhaust)
  apply (auto simp add: fresh_star_def)[3]
  using [[simproc del: alpha_lst]]
  apply(simp_all)
  apply(erule conjE)+
  apply (erule_tac c="xsa" in Abs_lst1_fcb2')
  apply (simp add: fresh_star_def)
  apply (simp add: fresh_star_def)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
  done

nominal_termination (eqvt)
  by lexicographic_order

text {* count the occurences of lambdas in a term *}

nominal_function
  cntlams :: "lam  \<Rightarrow> nat"
where
  "cntlams (Var x) = 0"
| "cntlams (App t1 t2) = (cntlams t1) + (cntlams t2)"
| "cntlams (Lam [x]. t) = Suc (cntlams t)"
  apply(simp add: eqvt_def cntlams_graph_aux_def)
  apply(rule TrueI)
  apply(rule_tac y="x" in lam.exhaust)
  apply(auto)[3]
  apply(all_trivials)
  apply(simp)
  using [[simproc del: alpha_lst]]
  apply(simp)
  apply(erule_tac c="()" in Abs_lst1_fcb2')
  apply(simp add: pure_fresh)
  apply(simp add: fresh_star_def pure_fresh)
  apply(simp add: eqvt_at_def atom_eqvt fresh_star_Pair perm_supp_eq)
  apply(simp add: eqvt_at_def atom_eqvt fresh_star_Pair perm_supp_eq)
  done

nominal_termination (eqvt)
  by lexicographic_order

text {* count the bound-variable occurences in a lambda-term *}

nominal_function
  cntbvs :: "lam \<Rightarrow> name list \<Rightarrow> nat"
where
  "cntbvs (Var x) xs = (if x \<in> set xs then 1 else 0)"
| "cntbvs (App t1 t2) xs = (cntbvs t1 xs) + (cntbvs t2 xs)"
| "atom x \<sharp> xs \<Longrightarrow> cntbvs (Lam [x]. t) xs = cntbvs t (x # xs)"
  apply(simp add: eqvt_def cntbvs_graph_aux_def)
  apply(rule TrueI)
  apply(case_tac x)
  apply(rule_tac y="a" and c="b" in lam.strong_exhaust)
  apply(auto simp add: fresh_star_def)[3]
  apply(all_trivials)
  apply(simp)
  apply(simp)
  using [[simproc del: alpha_lst]]
  apply(simp)
  apply(erule conjE)
  apply(erule Abs_lst1_fcb2')
  apply(simp add: pure_fresh fresh_star_def)
  apply(simp add: fresh_star_def)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
  done

nominal_termination (eqvt)
  by lexicographic_order

section {* De Bruijn Terms *}

nominal_datatype db =
  DBVar nat
| DBApp db db
| DBLam db

instance db :: pure
  apply standard
  apply (induct_tac x rule: db.induct)
  apply (simp_all add: permute_pure)
  done

lemma fresh_at_list: "atom x \<sharp> xs \<longleftrightarrow> x \<notin> set xs"
  unfolding fresh_def supp_set[symmetric]
  by (induct xs) (auto simp add: supp_of_finite_insert supp_at_base supp_set_empty)

fun
  vindex :: "name list \<Rightarrow> name \<Rightarrow> nat \<Rightarrow> db option"
where
  "vindex [] v n = None"
| "vindex (h # t) v n = (if v = h then (Some (DBVar n)) else (vindex t v (Suc n)))"

lemma vindex_eqvt[eqvt]:
  "(p \<bullet> vindex l v n) = vindex (p \<bullet> l) (p \<bullet> v) (p \<bullet> n)"
  by (induct l arbitrary: n) (simp_all add: permute_pure)

nominal_function
  transdb :: "lam \<Rightarrow> name list \<Rightarrow> db option"
where
  "transdb (Var x) l = vindex l x 0"
| "transdb (App t1 t2) xs =
      Option.bind (transdb t1 xs) (\<lambda>d1. Option.bind (transdb t2 xs) (\<lambda>d2. Some (DBApp d1 d2)))"
| "x \<notin> set xs \<Longrightarrow> transdb (Lam [x].t) xs = Option.map_option DBLam (transdb t (x # xs))"
  apply(simp add: eqvt_def transdb_graph_aux_def)
  apply(rule TrueI)
  apply (case_tac x)
  apply (rule_tac y="a" and c="b" in lam.strong_exhaust)
  apply (auto simp add: fresh_star_def fresh_at_list)[3]
  using [[simproc del: alpha_lst]]
  apply(simp_all)
  apply(elim conjE)
  apply (erule_tac c="xsa" in Abs_lst1_fcb2')
  apply (simp add: pure_fresh)
  apply(simp add: fresh_star_def fresh_at_list)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
  done

nominal_termination (eqvt)
  by lexicographic_order

lemma transdb_eqvt[eqvt]:
  "p \<bullet> transdb t l = transdb (p \<bullet>t) (p \<bullet>l)"
  apply (nominal_induct t avoiding: l rule: lam.strong_induct)
  apply (simp add: vindex_eqvt)
  apply (simp_all add: permute_pure)
  apply (simp add: fresh_at_list)
  apply (subst transdb.simps)
  apply (simp add: fresh_at_list[symmetric])
  apply (drule_tac x="name # l" in meta_spec)
  apply auto
  done

lemma db_trans_test:
  assumes a: "y \<noteq> x"
  shows "transdb (Lam [x]. Lam [y]. App (Var x) (Var y)) [] =
  Some (DBLam (DBLam (DBApp (DBVar 1) (DBVar 0))))"
  using a by simp

lemma supp_subst:
  shows "supp (t[x ::= s]) \<subseteq> (supp t - {atom x}) \<union> supp s"
  by (induct t x s rule: subst.induct) (auto simp add: lam.supp supp_at_base)

lemma var_fresh_subst:
  "atom x \<sharp> s \<Longrightarrow> atom x \<sharp> (t[x ::= s])"
  by (induct t x s rule: subst.induct) (auto simp add: lam.supp  fresh_at_base)

(* function that evaluates a lambda term *)
nominal_function
   eval :: "lam \<Rightarrow> lam" and
   apply_subst :: "lam \<Rightarrow> lam \<Rightarrow> lam"
where
  "eval (Var x) = Var x"
| "eval (Lam [x].t) = Lam [x].(eval t)"
| "eval (App t1 t2) = apply_subst (eval t1) (eval t2)"
| "apply_subst (Var x) t2 = App (Var x) t2"
| "apply_subst (App t0 t1) t2 = App (App t0 t1) t2"
| "atom x \<sharp> t2 \<Longrightarrow> apply_subst (Lam [x].t1) t2 = eval (t1[x::= t2])"
  apply(simp add: eval_apply_subst_graph_aux_def eqvt_def)
  apply(rule TrueI)
  apply (case_tac x)
  apply (case_tac a rule: lam.exhaust)
  using [[simproc del: alpha_lst]]
  apply simp_all[3]
  apply (case_tac b)
  apply (rule_tac y="a" and c="ba" in lam.strong_exhaust)
  apply simp_all[3]
  apply (simp add: Abs1_eq_iff fresh_star_def)
  using [[simproc del: alpha_lst]]
  apply(simp_all)
  apply(erule_tac c="()" in Abs_lst1_fcb2)
  apply (simp add: Abs_fresh_iff)
  apply(simp add: fresh_star_def fresh_Unit)
  apply(simp add: eqvt_at_def atom_eqvt fresh_star_Pair perm_supp_eq)
  apply(simp add: eqvt_at_def atom_eqvt fresh_star_Pair perm_supp_eq)
  apply(erule conjE)
  apply(erule_tac c="t2a" in Abs_lst1_fcb2')
  apply (erule fresh_eqvt_at)
  apply (simp add: finite_supp)
  apply (simp add: fresh_Inl var_fresh_subst)
  apply(simp add: fresh_star_def)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
  apply(simp only: eqvt_at_def)
  apply(perm_simp)
  apply(simp add: fresh_star_Pair perm_supp_eq)
done

(* a small test
nominal_termination (eqvt) sorry

lemma
  assumes "x \<noteq> y"
  shows "eval (App (Lam [x].App (Var x) (Var x)) (Var y)) = App (Var y) (Var y)"
using assms
apply(simp add: lam.supp fresh_def supp_at_base)
done
*)

text {* TODO: eqvt_at for the other side *}
nominal_function q where
  "atom c \<sharp> (x, M) \<Longrightarrow> q (Lam [x]. M) (N :: lam) = Lam [x]. (Lam [c]. (App M (q (Var c) N)))"
| "q (Var x) N = Var x"
| "q (App l r) N = App l r"
apply(simp add: eqvt_def q_graph_aux_def)
apply (rule TrueI)
apply (case_tac x)
apply (rule_tac y="a" in lam.exhaust)
using [[simproc del: alpha_lst]]
apply simp_all
apply (rule_tac x="(name, lam)" and ?'a="name" in obtain_fresh)
apply blast
apply clarify
apply (rule_tac x="(x, xa, M, Ma, c, ca, Na)" and ?'a="name" in obtain_fresh)
apply (subgoal_tac "eqvt_at q_sumC (Var ca, Na)") --"Could come from nominal_function?"
apply (subgoal_tac "Lam [c]. App M (q_sumC (Var c, Na)) = Lam [a]. App M (q_sumC (Var a, Na))")
apply (subgoal_tac "Lam [ca]. App Ma (q_sumC (Var ca, Na)) = Lam [a]. App Ma (q_sumC (Var a, Na))")
apply (simp only:)
apply (erule Abs_lst1_fcb)
oops

text {* Working Examples *}

nominal_function
  map_term :: "(lam \<Rightarrow> lam) \<Rightarrow> lam \<Rightarrow> lam"
where
  "eqvt f \<Longrightarrow> map_term f (Var x) = f (Var x)"
| "eqvt f \<Longrightarrow> map_term f (App t1 t2) = App (f t1) (f t2)"
| "eqvt f \<Longrightarrow> map_term f (Lam [x].t) = Lam [x].(f t)"
| "\<not>eqvt f \<Longrightarrow> map_term f t = t"
  apply (simp add: eqvt_def map_term_graph_aux_def)
  apply(rule TrueI)
  apply (case_tac x, case_tac "eqvt a", case_tac b rule: lam.exhaust)
  using [[simproc del: alpha_lst]]
  apply auto
  apply (erule Abs_lst1_fcb)
  apply (simp_all add: Abs_fresh_iff fresh_fun_eqvt_app)
  apply (simp add: eqvt_def permute_fun_app_eq)
  done

nominal_termination (eqvt)
  by lexicographic_order

(*
abbreviation
  mbind :: "'a option => ('a => 'b option) => 'b option"  ("_ \<guillemotright>= _" [65,65] 65)
where
  "c \<guillemotright>= f \<equiv> case c of None => None | (Some v) => f v"

lemma mbind_eqvt:
  fixes c::"'a::pt option"
  shows "(p \<bullet> (c \<guillemotright>= f)) = ((p \<bullet> c) \<guillemotright>= (p \<bullet> f))"
apply(cases c)
apply(simp_all)
apply(perm_simp)
apply(rule refl)
done

lemma mbind_eqvt_raw[eqvt_raw]:
  shows "(p \<bullet> option_case) \<equiv> option_case"
apply(rule eq_reflection)
apply(rule ext)+
apply(case_tac xb)
apply(simp_all)
apply(rule_tac p="-p" in permute_boolE)
apply(perm_simp add: permute_minus_cancel)
apply(simp)
apply(rule_tac p="-p" in permute_boolE)
apply(perm_simp add: permute_minus_cancel)
apply(simp)
done

fun
  index :: "atom list \<Rightarrow> nat \<Rightarrow> atom \<Rightarrow> nat option"
where
  "index [] n x = None"
| "index (y # ys) n x = (if x = y then (Some n) else (index ys (n + 1) x))"

lemma [eqvt]:
  shows "(p \<bullet> index xs n x) = index (p \<bullet> xs) (p \<bullet> n) (p \<bullet> x)"
apply(induct xs arbitrary: n)
apply(simp_all add: permute_pure)
done
*)

(*
nominal_function
  trans2 :: "lam \<Rightarrow> atom list \<Rightarrow> db option"
where
  "trans2 (Var x) xs = (index xs 0 (atom x) \<guillemotright>= (\<lambda>n::nat. Some (DBVar n)))"
| "trans2 (App t1 t2) xs =
     ((trans2 t1 xs) \<guillemotright>= (\<lambda>db1::db. (trans2 t2 xs) \<guillemotright>= (\<lambda>db2::db. Some (DBApp db1 db2))))"
| "trans2 (Lam [x].t) xs = (trans2 t (atom x # xs) \<guillemotright>= (\<lambda>db::db. Some (DBLam db)))"
oops
*)

nominal_function
  CPS :: "lam \<Rightarrow> (lam \<Rightarrow> lam) \<Rightarrow> lam"
where
  "CPS (Var x) k = Var x"
| "CPS (App M N) k = CPS M (\<lambda>m. CPS N (\<lambda>n. n))"
oops

consts b :: name
nominal_function
  Z :: "lam \<Rightarrow> (lam \<Rightarrow> lam) \<Rightarrow> lam"
where
  "Z (App M N) k = Z M (%m. (Z N (%n.(App m n))))"
| "Z (App M N) k = Z M (%m. (Z N (%n.(App (App m n) (Abs b (k (Var b)))))))"
apply(simp add: eqvt_def Z_graph_aux_def)
apply (rule, perm_simp, rule)
oops

lemma test:
  assumes "t = s"
  and "supp p \<sharp>* t" "supp p \<sharp>* x"
  and "(p \<bullet> t) = s \<Longrightarrow> (p \<bullet> x) = y"
  shows "x = y"
using assms by (simp add: perm_supp_eq)

lemma test2:
  assumes "cs \<subseteq> as \<union> bs"
  and "as \<sharp>* x" "bs \<sharp>* x"
  shows "cs \<sharp>* x"
using assms
by (auto simp add: fresh_star_def)

lemma test3:
  assumes "cs \<subseteq> as"
  and "as \<sharp>* x"
  shows "cs \<sharp>* x"
using assms
by (auto simp add: fresh_star_def)

nominal_function  (invariant "\<lambda>(_, _, xs) y. atom ` fst ` set xs \<sharp>* y \<and> atom ` snd ` set xs \<sharp>* y")
  aux :: "lam \<Rightarrow> lam \<Rightarrow> (name \<times> name) list \<Rightarrow> bool"
where
  "aux (Var x) (Var y) xs = ((x, y) \<in> set xs)"
| "aux (App t1 t2) (App s1 s2) xs = (aux t1 s1 xs \<and> aux t2 s2 xs)"
| "aux (Var x) (App t1 t2) xs = False"
| "aux (Var x) (Lam [y].t) xs = False"
| "aux (App t1 t2) (Var x) xs = False"
| "aux (App t1 t2) (Lam [x].t) xs = False"
| "aux (Lam [x].t) (Var y) xs = False"
| "aux (Lam [x].t) (App t1 t2) xs = False"
| "\<lbrakk>{atom x} \<sharp>* (s, xs); {atom y} \<sharp>* (t, xs); x \<noteq> y\<rbrakk> \<Longrightarrow>
       aux (Lam [x].t) (Lam [y].s) xs = aux t s ((x, y) # xs)"
  apply (simp add: eqvt_def aux_graph_aux_def)
  apply(erule aux_graph.induct)
  apply(simp_all add: fresh_star_def pure_fresh)[9]
  apply(case_tac x)
  apply(simp)
  apply(rule_tac y="a" and c="(b, c)" in lam.strong_exhaust)
  apply(simp)
  apply(rule_tac y="b" and c="c" in lam.strong_exhaust)
  apply(metis)+
  apply(simp)
  apply(rule_tac y="b" and c="c" in lam.strong_exhaust)
  apply(metis)+
  apply(simp)
  apply(rule_tac y="b" and c="(lam, c, name)" in lam.strong_exhaust)
  apply(metis)+
  apply(simp)
  apply(drule_tac x="name" in meta_spec)
  apply(drule_tac x="lama" in meta_spec)
  apply(drule_tac x="c" in meta_spec)
  apply(drule_tac x="namea" in meta_spec)
  apply(drule_tac x="lam" in meta_spec)
  apply(simp add: fresh_star_Pair)
  apply(simp add: fresh_star_def fresh_at_base )
  apply(auto)[1]
  apply(simp_all)[44]
  apply(simp del: Product_Type.prod.inject)
  oops

lemma abs_same_binder:
  fixes t ta s sa :: "_ :: fs"
  and x y::"'a::at"
  shows "[[atom x]]lst. t = [[atom y]]lst. ta \<and> [[atom x]]lst. s = [[atom y]]lst. sa
     \<longleftrightarrow> [[atom x]]lst. (t, s) = [[atom y]]lst. (ta, sa)"
  by (cases "atom x = atom y") (auto simp add: Abs1_eq_iff fresh_Pair)

nominal_function
  aux2 :: "lam \<Rightarrow> lam \<Rightarrow> bool"
where
  "aux2 (Var x) (Var y) = (x = y)"
| "aux2 (App t1 t2) (App s1 s2) = (aux2 t1 s1 \<and> aux2 t2 s2)"
| "aux2 (Var x) (App t1 t2) = False"
| "aux2 (Var x) (Lam [y].t) = False"
| "aux2 (App t1 t2) (Var x) = False"
| "aux2 (App t1 t2) (Lam [x].t) = False"
| "aux2 (Lam [x].t) (Var y) = False"
| "aux2 (Lam [x].t) (App t1 t2) = False"
| "x = y \<Longrightarrow> aux2 (Lam [x].t) (Lam [y].s) = aux2 t s"
  apply(simp add: eqvt_def aux2_graph_aux_def)
  apply(rule TrueI)
  apply(case_tac x)
  apply(rule_tac y="a" and c="b" in lam.strong_exhaust)
  apply(rule_tac y="b" in lam.exhaust)
  apply(auto)[3]
  apply(rule_tac y="b" in lam.exhaust)
  apply(auto)[3]
  apply(rule_tac y="b" and c="(name, lam)" in lam.strong_exhaust)
  using [[simproc del: alpha_lst]]
  apply(auto)[3]
  apply(drule_tac x="name" in meta_spec)
  apply(drule_tac x="name" in meta_spec)
  apply(drule_tac x="lam" in meta_spec)
  apply(drule_tac x="(name \<leftrightarrow> namea) \<bullet> lama" in meta_spec)
  using [[simproc del: alpha_lst]]
  apply(simp add: Abs1_eq_iff fresh_star_def fresh_Pair_elim fresh_at_base flip_def)
  apply (metis Nominal2_Base.swap_commute fresh_permute_iff sort_of_atom_eq swap_atom_simps(2))
  using [[simproc del: alpha_lst]]
  apply simp_all
  apply (simp add: abs_same_binder)
  apply (erule_tac c="()" in Abs_lst1_fcb2)
  apply (simp_all add: pure_fresh fresh_star_def eqvt_at_def)
  done

text {* tests of functions containing if and case *}

(*
nominal_function
  A :: "lam => lam"
where
  "A (App M N) = (if (True \<or> P M) then (A M) else (A N))"
| "A (Var x) = (Var x)"
| "A (App M N) = (if True then M else A N)"
oops

nominal_function
  C :: "lam => lam"
where
  "C (App M N) = (case (True \<or> P M) of True \<Rightarrow> (A M) | False \<Rightarrow> (A N))"
| "C (Var x) = (Var x)"
| "C (App M N) = (if True then M else C N)"
oops

nominal_function
  A :: "lam => lam"
where
  "A (Lam [x].M) = (Lam [x].M)"
| "A (Var x) = (Var x)"
| "A (App M N) = (if True then M else A N)"
oops

nominal_function
  B :: "lam => lam"
where
  "B (Lam [x].M) = (Lam [x].M)"
| "B (Var x) = (Var x)"
| "B (App M N) = (if True then M else (B N))"
unfolding eqvt_def
unfolding B_graph_def
apply(perm_simp)
apply(rule allI)
apply(rule refl)
oops
*)
end


theory Exercise_2_4
imports Main
begin
fun snoc :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a list" where
  "snoc [] x = [x]" |
  "snoc (x#xs) y = (x#(snoc xs y))"

value "snoc [1::int,2,3,4] 5"

fun reverse :: "'a list \<Rightarrow> 'a list" where
  "reverse [] = []" |
  "reverse (x#xs) = snoc (reverse xs) x"

lemma reverse_snoc[simp] : "reverse (snoc xs a) = a#(reverse xs)"
  apply(induction xs)
  apply(auto)
  done

lemma double_reverse: "reverse(reverse xs) = xs"
  apply(induction xs)
  apply(auto)
  done


theory "model-generation"
  imports "extensions-simpl"  "labellings-simpl"
begin
nitpick_params [box=false]

(* Example set-up from [BG2011], Figure 4 *)
locale ExFig4 begin
datatype Arg = A | B | C | D
  fun att :: \<open>Arg Rel\<close> where
    "att A B = True" |
    "att B C = True" |
    "att C D = True" |
    "att D C = True" |
    "att _ _ = False"

(****************************************************)
(* Flexible Generation of Extensions and Labellings *)
(****************************************************)

abbreviation surjective where  "surjective f \<equiv> \<forall>y. \<exists>x. f x = y"

(* Admissible labelling where A is In *)
lemma \<open>admissibleLab att Lab \<and> (Lab a) = In\<close> nitpick[satisfy]                                                 oops

(* Admissible labelling where Lab is surjective *)
lemma \<open>admissibleLab att Lab \<and> (surjective Lab)\<close> nitpick[satisfy]                                          oops

(* Admissible labelling where there are more than two arguments labelled In *)
lemma \<open>admissibleLab att Lab \<and> (card({x. in(Lab) x}) > 2)\<close> nitpick[satisfy]                                  oops

(****************************************************)
(* Standard Generation of Extensions and Labellings *)
(****************************************************)

(**** conflict-free sets ****)
lemma \<open>findFor' att conflictfreeExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
(* This gives us exactly the 8 conflict-free sets (7 non-empty) mentioned in [BG2011] p. 8:
     {}, {A}, {B}, {C}, {D}, {A, C}, {A, D}, {B, D} *)

(**** admissible semantics ****)
(* ask nitpick for all admissible extensions/labellings *)
lemma \<open>findFor' att admissibleExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
(* This gives us exactly the 5 sets (4 non-empty) predicted in [BG2011] p. 8:
  {}, {A}, {D}, {A, C}, {A, D} *)
lemma \<open>findFor' att admissibleLab Labs\<close> nitpick[satisfy, eval = "card Labs"] oops
(* This gives us exactly the 7 labellings (7 non-empty) predicted in [BG2011] p. 7:
      {(A := In,    B := Out,   C := In,    D := Out),
       (A := In,    B := Out,   C := Out,   D := In),
       (A := In,    B := Out,   C := Undec, D := Undec),
       (A := In,    B := Undec, C := Out,   D := In),
       (A := In,    B := Undec, C := Undec, D := Undec),
       (A := Undec, B := Undec, C := Out,   D := In),
       (A := Undec, B := Undec, C := Undec, D := Undec)} *)

(* complete semantics *)
lemma \<open>findFor' att completeExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
(* This gives us exactly the 3 sets predicted in [BG2011] p. 10: {A}, {A, C}, {A, D} *)
lemma \<open>findFor' att completeLab Labs\<close> nitpick[satisfy, eval = "card Labs"] oops
(* This gives us exactly the 3 labellings predicted in [BG2011] p. 10:
  {(   (A := In, B := Out, C := In,    D := Out),
       (A := In, B := Out, C := Out,   D := In),
       (A := In, B := Out, C := Undec, D := Undec)} *)

(* grounded semantics *)
lemma \<open>findFor' att groundedExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
(* This gives exactly the one extension given in [BG2011] p. 10:  {A} *)
lemma \<open>findFor' att groundedLab Labs\<close> nitpick[satisfy,box=false, eval = "card Labs"] oops
(* This gives exactly the one labelling given in [BG2011] p. 10:
      {(A := In, B := Out, C := Undec, D := Undec)} *)
(* comment: we have to disable boxing for nitpick to find the model.*)

(* preferred semantics *)
(* This gives us exactly the 2 sets predicted in [BCG2011] p. 12: {A, C}, {A, D} *)
lemma \<open>findFor' att preferredExt Exts\<close> nitpick[satisfy, eval = "card Exts"]                          oops
(* This gives us exactly the two labellings predicted in [BCG2011] p. 12
  {(A := In, B := Out, C := In,  D := Out),
   (A := In, B := Out, C := Out, D := In)} *)
lemma \<open>findFor' att preferredLab Labs\<close> nitpick[satisfy,box=false, eval = "card Labs"]                    oops
(* comment: we have to disable boxing for nitpick to find the model *)

(* ideal semantics *)
lemma \<open>findFor' att idealExt Exts\<close> nitpick[satisfy,box=false,timeout=60] oops (*don't use eval*)
(* This gives us exactly the same (grounded) set predicted in [BG2011] p. 18: {A}*)
lemma \<open>findFor' att idealLab Labs\<close> (*nitpick[satisfy,box=false, timeout=100]*) oops
(* TODO above not working - definition too complex? *)

(* stable labellings *)
lemma \<open>findFor' att stableExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
lemma \<open>findFor' att stableLab Labs\<close> nitpick[satisfy, eval = "card Labs"] oops
(* checked: these are exactly the two (preferred) extensions/labellings given in [BG2011] *)

(* semi-stable labellings *)
lemma \<open>findFor' att semistableExt Exts\<close> nitpick[satisfy,box=false, eval = "card Exts"] oops
lemma \<open>findFor' att semistableLab Labs\<close> nitpick[satisfy,box=false, eval = "card Labs"] oops
(* checked: these are exactly the two (preferred) extensions/labellings given in [BG2011] *)
(* comment: we have to disable boxing for nitpick to find the model *)

end

(* Example set-up from [BG2011], Figure 5 *)
locale ExFig5 begin
datatype Arg = A | B | C | D
  fun att :: \<open>Arg Rel\<close> where
    "att A B = True" |
    "att B A = True" |
    "att A C = True" |
    "att B C = True" |
    "att C D = True" |
    "att _ _ = False"

(*** admissible semantics ***)
lemma \<open>findFor' att admissibleExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
(* This gives us exactly the 5 sets (4 non-empty) predicted in [BG2011] p. 8:
  {}, {A}, {B}, {A, D}, {B, D} *)
lemma \<open>findFor' att admissibleLab Labs\<close> nitpick[satisfy, eval = "card Labs"] oops
(* This gives us 7 labellings. Note that their In-sets coincide with the corresponding
   admissible extensions (note that we can assign more than one labelling to each extension)
    Labs =
      {(A := In, B := Out, C := Out, D := In),
       (A := In, B := Out, C := Out, D := Undec),
       (A := In, B := Out, C := Undec, D := Undec),
       (A := Out, B := In, C := Out, D := In),
       (A := Out, B := In, C := Out, D := Undec),
       (A := Out, B := In, C := Undec, D := Undec),
       (A := Undec, B := Undec, C := Undec, D := Undec)} *)

(*** complete semantics ***)
lemma \<open>findFor' att completeExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
(* This gives us exactly the 3 sets predicted in [BG2011] p. 10: {}, {A, D}, {B, D} *)
lemma \<open>findFor' att complete Labs\<close> nitpick[satisfy, eval = "card Labs"] oops
(* This gives us exactly the 3 labellings indicated in [BG2011] p. 10
   Labs =  {(A := In, B := Out, C := Out, D := In),
            (A := Out, B := In, C := Out, D := In),
            (A := Undec, B := Undec, C := Undec, D := Undec)} *)

(*** grounded semantics ***)
lemma \<open>findFor' att groundedExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
(* We verify that the grounded extension is the trivial one (i.e. empty) as indicated in [BG2011]*)
lemma \<open>findFor' att groundedLab Labs\<close> nitpick[satisfy, box=false, eval = "card Labs"] oops
(* Similarly we verify that the grounded labelling is the trivial one (i.e. empty) *)
(* (comment: we have to disable boxing for nitpick to find the model) *)

(*** preferred semantics ***)
lemma \<open>findFor' att preferredExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
(* This gives us exactly the 2 sets predicted in [BG2011] p. 12: {A, D}, {B, D} *)
lemma \<open>findFor' att preferredLab Labs\<close> nitpick[satisfy, box=false, eval = "card Labs"] oops
(* checked: these are exactly the two labellings given in [BG2011] p. 12
  Labs = {(A := In, B := Out, C := Out, D := In), (A := Out, B := In, C := Out, D := In)}*)
(* comment: we have to disable boxing for nitpick to find the model *)

(*** ideal semantics ***)
lemma \<open>findFor' att idealExt Exts\<close> nitpick[satisfy] oops (*don't use eval*)
(* coincides with the grounded extension (empty) as predicted.*)
lemma \<open>findFor' att idealLab Labs\<close> (*nitpick[satisfy,box=false, timeout=100]*) oops
(* TODO above not working - definition too complex? *)

(* stable labellings *)
lemma \<open>findFor' att stableExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
lemma \<open>findFor' att stableLab Labs\<close> nitpick[satisfy, eval = "card Labs"] oops
(* checked: these are exactly the sets o two extensions & labellings given in [BG2011] *)

(* semi-stable labellings *)
lemma \<open>findFor' att semistableExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
lemma \<open>findFor' att semistableLab Labs\<close> nitpick[satisfy,box=false, eval = "card Labs"] oops
(* checked: these are exactly the two given in [BG2011] *)
(* comment: we have to disable boxing for nitpick to find the model *)
end

(* Example set-up from [BG2011], Figure 6 *)
locale ExFig6 begin
datatype Arg = A | B | C
  fun att :: \<open>Arg Rel\<close> where
    "att A B = True" |
    "att B C = True" |
    "att C A = True" |
    "att _ _ = False"

(*Similarly to the two examples above, we verify that the expected results obtain,
 namely, there exists only one admissible extension/labelling: the empty set*)

(*** admissible semantics ***)
lemma \<open>findFor' att admissibleExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
(* We verify the expected result: only the empty set is admissible*)
lemma \<open>findFor' att admissibleLab Labs\<close> nitpick[satisfy, eval = "card Labs"] oops
(* this gives us: Labs = {(\<lambda>x. _)(A := Undec, B := Undec, C := Undec)} *)
(* this is the one trivial labelling, as mentioned in [BG2011]. *)

(*** complete semantics ***)
lemma \<open>findFor' att completeExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
lemma \<open>findFor' att completeLab Labs\<close> nitpick[satisfy, eval = "card Labs"] oops
(* checked: this is the one trivial extension/labelling, as mentioned in [BG2011].*)

(*** grounded semantics ***)
lemma \<open>findFor' att groundedExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
lemma \<open>findFor' att groundedLab Labs\<close> nitpick[satisfy,box=false, eval = "card Labs"] oops
(* checked: this is the one trivial extension/labelling, as mentioned in [BG2011].*)

(*** preferred semantics ***)
lemma \<open>findFor' att preferredExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
lemma \<open>findFor' att preferredLab Labs\<close> nitpick[satisfy,box=false, eval = "card Labs"] oops
(* checked: this is the one trivial extension/labelling, as mentioned in [BG2011].*)
(* comment: we have to disable boxing for nitpick to find the model *)

(*** ideal semantics ***)
lemma \<open>findFor' att idealExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
lemma \<open>findFor' att idealLab Labs\<close>  (*nitpick[satisfy,box=false, timeout=100]*) oops
(* TODO above not working - definition too complex? *)

(* stable labellings *)
lemma \<open>findFor' att stableExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
lemma \<open>findFor' att stableLab Labs\<close> nitpick[satisfy, eval = "card Labs"] oops
(* checked: there are no stable extensionslabellings, see [BG2011] *)

(* semi-stable labellings *)
lemma \<open>findFor' att semistableExt Exts\<close> nitpick[satisfy, eval = "card Exts"] oops
lemma \<open>findFor' att semistableLab Labs\<close> nitpick[satisfy,box=false, eval = "card Labs"] oops
(* checked: this is the one trivial extension/labelling, as mentioned in [BG2011].*)
(* comment: we have to disable boxing for nitpick to find the model *)
end

end


(*
   Title: The Calculus of Communicating Systems
   Author/Maintainer: Jesper Bengtson (jebe@itu.dk), 2012
*)
theory Weak_Cong_Sim_Pres
  imports Weak_Cong_Sim
begin

lemma actPres:
  fixes P    :: ccs
  and   Q    :: ccs
  and   Rel  :: "(ccs \<times> ccs) set"
  and   a    :: name
  and   Rel' :: "(ccs \<times> ccs) set"

  assumes "(P, Q) \<in> Rel"

  shows "\<alpha>.(P) \<leadsto><Rel> \<alpha>.(Q)"
using assms
by(fastforce simp add: weakCongSimulation_def elim: actCases intro: weakCongAction)

lemma sumPres:
  fixes P   :: ccs
  and   Q   :: ccs
  and   Rel :: "(ccs \<times> ccs) set"

  assumes "P \<leadsto><Rel> Q"
  and     "Rel \<subseteq> Rel'"
  and     "Id \<subseteq> Rel'"

  shows "P \<oplus> R \<leadsto><Rel'> Q \<oplus> R"
using assms
by(force simp add: weakCongSimulation_def elim: sumCases intro: weakCongSum1 weakCongSum2 transitionWeakCongTransition)

lemma parPres:
  fixes P   :: ccs
  and   Q   :: ccs
  and   Rel :: "(ccs \<times> ccs) set"

  assumes "P \<leadsto><Rel> Q"
  and     "(P, Q) \<in> Rel"
  and     C1: "\<And>S T U. (S, T) \<in> Rel \<Longrightarrow> (S \<parallel> U, T \<parallel> U) \<in> Rel'"

  shows "P \<parallel> R \<leadsto><Rel'> Q \<parallel> R"
proof(induct rule: weakSimI)
  case(Sim \<alpha> QR)
  from \<open>Q \<parallel> R \<longmapsto>\<alpha> \<prec> QR\<close>
  show ?case
  proof(induct rule: parCases)
    case(cPar1 Q')
    from \<open>P \<leadsto><Rel> Q\<close> \<open>Q \<longmapsto>\<alpha> \<prec> Q'\<close> obtain P' where "P \<Longrightarrow>\<alpha> \<prec> P'" and "(P', Q') \<in> Rel"
      by(rule weakSimE)
    from \<open>P \<Longrightarrow>\<alpha> \<prec> P'\<close> have "P \<parallel> R \<Longrightarrow>\<alpha> \<prec> P' \<parallel> R" by(rule weakCongPar1)
    moreover from \<open>(P', Q') \<in> Rel\<close> have "(P' \<parallel> R, Q' \<parallel> R) \<in> Rel'" by(rule C1)
    ultimately show ?case by blast
  next
    case(cPar2 R')
    from \<open>R \<longmapsto>\<alpha> \<prec> R'\<close> have "R \<Longrightarrow>\<alpha> \<prec> R'" by(rule transitionWeakCongTransition)
    hence "P \<parallel> R \<Longrightarrow>\<alpha> \<prec> P \<parallel> R'" by(rule weakCongPar2)
    moreover from \<open>(P, Q) \<in> Rel\<close> have "(P \<parallel> R', Q \<parallel> R') \<in> Rel'" by(rule C1)
    ultimately show ?case by blast
  next
    case(cComm Q' R' \<alpha>)
    from \<open>P \<leadsto><Rel> Q\<close> \<open>Q \<longmapsto>\<alpha> \<prec> Q'\<close> obtain P' where "P \<Longrightarrow>\<alpha> \<prec> P'" and "(P', Q') \<in> Rel"
      by(rule weakSimE)
    from \<open>R \<longmapsto>(coAction \<alpha>) \<prec> R'\<close> have "R \<Longrightarrow>(coAction \<alpha>) \<prec> R'"
      by(rule transitionWeakCongTransition)
    with \<open>P \<Longrightarrow>\<alpha> \<prec> P'\<close> have "P \<parallel> R \<Longrightarrow>\<tau> \<prec> P' \<parallel> R'" using \<open>\<alpha> \<noteq> \<tau>\<close>
      by(rule weakCongSync)
    moreover from \<open>(P', Q') \<in> Rel\<close> have "(P' \<parallel> R', Q' \<parallel> R') \<in> Rel'" by(rule C1)
    ultimately show ?case by blast
  qed
qed

  assumes "P \<leadsto><Rel> Q"
  and     "\<And>R S y. (R, S) \<in> Rel \<Longrightarrow> (\<lparr>\<nu>y\<rparr>R, \<lparr>\<nu>y\<rparr>S) \<in> Rel'"

  shows "\<lparr>\<nu>x\<rparr>P \<leadsto><Rel'> \<lparr>\<nu>x\<rparr>Q"
using assms
by(fastforce simp add: weakCongSimulation_def elim: resCases intro: weakCongRes)

  assumes "(P, Q) \<in> Rel"
  and     C1: "\<And>R S. (R, S) \<in> Rel \<Longrightarrow> R \<leadsto><Rel'> S"
  and     C2: "Rel \<subseteq> Rel'"

  shows "!P \<leadsto><bangRel Rel'> !Q"
proof(induct rule: weakSimI)
  case(Sim \<alpha> Q')
  {
    fix Pa \<alpha> Q'
    assume "!Q \<longmapsto>\<alpha> \<prec> Q'" and "(Pa, !Q) \<in> bangRel Rel"
    hence "\<exists>P'. Pa \<Longrightarrow>\<alpha> \<prec> P' \<and> (P', Q') \<in> bangRel Rel'"
    proof(nominal_induct arbitrary: Pa rule: bangInduct)
      case(cPar1 \<alpha> Q')
      from \<open>(Pa, Q \<parallel> !Q) \<in> bangRel Rel\<close>
      show ?case
      proof(induct rule: BRParCases)
        case(BRPar P R)
        from \<open>(P, Q) \<in> Rel\<close> have "P \<leadsto><Rel'> Q" by(rule C1)
        with \<open>Q \<longmapsto>\<alpha> \<prec> Q'\<close> obtain P' where "P \<Longrightarrow>\<alpha> \<prec> P'" and "(P', Q') \<in> Rel'"
          by(blast dest: weakSimE)
        from \<open>P \<Longrightarrow>\<alpha> \<prec> P'\<close> have "P \<parallel> R \<Longrightarrow>\<alpha> \<prec> P' \<parallel> R" by(rule weakCongPar1)
        moreover from \<open>(R, !Q) \<in> bangRel Rel\<close> C2 have "(R, !Q) \<in> bangRel Rel'"
          by induct (auto intro: bangRel.BRPar bangRel.BRBang)
        with \<open>(P', Q') \<in> Rel'\<close> have "(P' \<parallel> R, Q' \<parallel> !Q) \<in> bangRel Rel'"
          by(rule bangRel.BRPar)
        ultimately show ?case by blast
      qed
    next
      case(cPar2 \<alpha> Q')
      from \<open>(Pa, Q \<parallel> !Q) \<in> bangRel Rel\<close>
      show ?case
      proof(induct rule: BRParCases)
        case(BRPar P R)
        from \<open>(R, !Q) \<in> bangRel Rel\<close> obtain R' where "R \<Longrightarrow>\<alpha> \<prec> R'" and "(R', Q') \<in> bangRel Rel'" using cPar2
          by blast
        from \<open>R \<Longrightarrow>\<alpha> \<prec> R'\<close> have "P \<parallel> R \<Longrightarrow>\<alpha> \<prec> P \<parallel> R'" by(rule weakCongPar2)
        moreover from \<open>(P, Q) \<in> Rel\<close> \<open>(R', Q') \<in> bangRel Rel'\<close> C2 have "(P \<parallel> R', Q \<parallel> Q') \<in> bangRel Rel'"
          by(blast intro: bangRel.BRPar)
        ultimately show ?case by blast
      qed
    next
      case(cComm a Q' Q'' Pa)
      from \<open>(Pa, Q \<parallel> !Q) \<in> bangRel Rel\<close>
      show ?case
      proof(induct rule: BRParCases)
        case(BRPar P R)
        from \<open>(P, Q) \<in> Rel\<close> have "P \<leadsto><Rel'> Q" by(rule C1)
        with \<open>Q \<longmapsto>a \<prec> Q'\<close> obtain P' where "P \<Longrightarrow>a \<prec> P'" and "(P', Q') \<in> Rel'"
          by(blast dest: weakSimE)
        from \<open>(R, !Q) \<in> bangRel Rel\<close> obtain R' where "R \<Longrightarrow>(coAction a) \<prec> R'" and "(R', Q'') \<in> bangRel Rel'" using cComm
          by blast
        from \<open>P \<Longrightarrow>a \<prec> P'\<close> \<open>R \<Longrightarrow>(coAction a) \<prec> R'\<close> \<open>a \<noteq> \<tau>\<close> have "P \<parallel> R \<Longrightarrow>\<tau> \<prec> P' \<parallel> R'" by(rule weakCongSync)
        moreover from \<open>(P', Q') \<in> Rel'\<close> \<open>(R', Q'') \<in> bangRel Rel'\<close> have "(P' \<parallel> R', Q' \<parallel> Q'') \<in> bangRel Rel'"
          by(rule bangRel.BRPar)
        ultimately show ?case by blast
      qed
    next
      case(cBang \<alpha> Q' Pa)
      from \<open>(Pa, !Q) \<in> bangRel Rel\<close>
      show ?case
      proof(induct rule: BRBangCases)
        case(BRBang P)
        from \<open>(P, Q) \<in> Rel\<close> have "(!P, !Q) \<in> bangRel Rel" by(rule bangRel.BRBang)
        with \<open>(P, Q) \<in> Rel\<close> have "(P \<parallel> !P, Q \<parallel> !Q) \<in> bangRel Rel" by(rule bangRel.BRPar)
        then obtain P' where "P \<parallel> !P \<Longrightarrow>\<alpha> \<prec> P'" and "(P', Q') \<in> bangRel Rel'" using cBang
          by blast
        from \<open>P \<parallel> !P \<Longrightarrow>\<alpha> \<prec> P'\<close> have "!P \<Longrightarrow>\<alpha> \<prec> P'" by(rule weakCongRepl)
        thus ?case using \<open>(P', Q') \<in> bangRel Rel'\<close> by blast
      qed
    qed
  }

  moreover from \<open>(P, Q) \<in> Rel\<close> have "(!P, !Q) \<in> bangRel Rel" by(rule BRBang)
  ultimately show ?case using \<open>!Q \<longmapsto> \<alpha> \<prec> Q'\<close> by blast
qed

end


subsubsection \<open>Example instantiation\<close>

theory Simple_RM_Example
imports Simple_RM
begin

text \<open>As a concrete example, we consider a monitor with two domains and six variables.\<close>

datatype domain = D1 | D2

datatype var = A | B | C | X | Y | Z

text \<open>Information is allowed to flow from @{text D1} to @{text D2} (and from each domain to itself),
but not from @{text D2} to @{text D1}.\<close>

definition [simp]: "FP \<equiv> {(D1, D1), (D1, D2), (D2, D2)}"

text \<open>The variables are assigned as follows:\<close>

fun observe :: "domain \<Rightarrow> var set" where
  "observe D1 = {A, B, C}"
| "observe D2 = {A, B, C, X, Y, Z}"

fun alter :: "domain \<Rightarrow> var set" where
  "alter D1 = {A, B, C, X, Y, Z}"
| "alter D2 = {X, Y, Z}"

definition s0 :: "var state" where "s0 v = 0"

text \<open>In order to instantiate the simple reference monitor, we just have to show that the
concrete flow policy and the definitions of @{text alter} and @{text observe} fit together ---
which is automatic.\<close>

global_interpretation Simple_RM s0 observe alter FP
defines ex_check = "check" and ex_step = "step" and ex_out = "out"
proof
  show "refl FP" and "trans FP" by (auto simp add: refl_on_def trans_def)
next
  fix u v
  assume "(u, v) \<in> FP"
  then show "observe u \<subseteq> observe v" by auto
next
  fix n u v
  assume "n \<in> alter u" and "n \<in> observe v"
  then show "(u, v) \<in> FP" by auto
qed

text \<open>The fact that this instance is secure is then directly inherited from the general case.\<close>

theorem "NI_secure"
using monitor_secure .

text \<open>We can also export our definitions as executable code (in SML, OCaml, Haskell, or Scala),
and we can evaluate some example assignments.\<close>

export_code s0 step out in Scala
notation Assign ("_ :=\<^bsub>_\<^esub> _")

value "out s0 (X :=\<^bsub>D2\<^esub> (Minus (Plus (Var Y) (Var Z)) (Const 5)))"
  \<comment> \<open>outputs ``- 5''\<close>
value "out s0 (A :=\<^bsub>D2\<^esub> (Minus (Plus (Var Y) (Var Z)) (Const 5)))"
  \<comment> \<open>outputs ``0'', because the check fails\<close>
value "out s0 (A :=\<^bsub>D1\<^esub> (Minus (Plus (Var Y) (Var Z)) (Const 5)))"
  \<comment> \<open>outputs ``0'', because the check fails\<close>
value "out s0 (A :=\<^bsub>D1\<^esub> (Minus (Plus (Var B) (Var C)) (Const 5)))"
  \<comment> \<open>outputs ``- 5''\<close>

end


theory nonlinear
  imports HOL.NthRoot HHL_SL invGen
begin

definition x :: exp where
  "x == RVar ''parx''"

definition y :: exp where
  "y == RVar ''pary''"

definition z :: exp where
  "z == RVar ''parz''"

definition a :: exp where
  "a == RVar ''para''"

consts Inv :: fform

definition cons11 :: fform where "cons11 \<equiv> (x[**]2 [\<le>] Real (1/2) [&] y[**]2 [\<le>] Real (1/3)) [\<longrightarrow>] Inv"
definition cons12 :: fform where "cons12 \<equiv> Inv [\<longrightarrow>] (x[-]Real 4[*]y [<] Real 8)"
definition cons13 :: fform where "cons13 \<equiv> exeFlow(<[''parx'',''pary'']: [(Real 0 [-] x [-](Real 1117[*]y)[div]Real 500 [+] (Real 439[*]y[**]3)[div]Real 200 [-] (Real 333[*]y[**]5)[div]Real 500),(x [+](Real 617[*]y)[div]Real 500 [-] (Real 439[*]y[**]3)[div]Real 200 [+] (Real 333[*]y[**]5)[div]Real 500)] && Inv & fTrue>) Inv [\<longrightarrow>] Inv"
lemma allcons1: "\<forall>s. (cons11 [&] cons12 [&] cons13) s"
  apply (simp only: cons11_def cons12_def cons13_def x_def y_def)
  by (inv_check_oracle "parx^2 + parx*pary + pary^2 - 111/59 <=0")

lemma N1:"{(x[**]2 [\<le>] Real (1/2) [&] y[**]2 [\<le>] Real (1/3))}
         <[''parx'',''pary'']: [(Real 0 [-] x [-](Real 1117[*]y)[div]Real 500 [+] (Real 439[*]y[**]3)[div]Real 200 [-] (Real 333[*]y[**]5)[div]Real 500),(x [+](Real 617[*]y)[div]Real 500 [-] (Real 439[*]y[**]3)[div]Real 200 [+] (Real 333[*]y[**]5)[div]Real 500)] && Inv & fTrue>
          {(x[-]Real 4[*]y [<] Real 8);elE 0 [[|]] almost(x[-]Real 4[*]y [<] Real 8)}"
apply (rule ContinuousRuleGT )
  apply auto
      apply (cut_tac allcons1)
      apply (simp add:fAnd_def fImp_def cons11_def)
     apply (cut_tac allcons1)
     apply (simp add:fAnd_def fImp_def cons12_def)
apply (cut_tac allcons1)
    apply (simp add:fAnd_def fImp_def cons13_def)
   apply (simp add:dOr_def)
  apply(cut_tac allcons1)
  apply (simp add:fAnd_def fImp_def dOr_def almost_def cons12_def)
  done

definition cons21 :: fform where "cons21 \<equiv> (x[**]2 [\<le>] Real (1/2) [&] (y[+]Real 2)[**]2 [\<le>] Real (1/3)) [\<longrightarrow>] Inv"
definition cons22 :: fform where "cons22 \<equiv> Inv [\<longrightarrow>] ((x[-]Real 1)[**]2[+](y[-]Real (3/2))[**]2 [>] Real (1/4))"
definition cons23 :: fform where "cons23 \<equiv> exeFlow(<[''parx'',''pary'']: [(Real 0 [-] x [+] y [-]x[**]3),(Real 0 [-] x [-] y [+] y[**]2)] && Inv & fTrue>) Inv [\<longrightarrow>] Inv"
lemma allcons2: "\<forall>s. (cons21 [&] cons22 [&] cons23) s"
  apply (simp only: cons21_def cons22_def cons23_def x_def y_def)
  by (inv_check_oracle"2*parx^2 + (pary + 3/2)^2 - 4<= 0")
lemma N2:"{ (x[**]2 [\<le>] Real (1/2) [&] (y[+]Real 2)[**]2 [\<le>] Real (1/3))}
         <[''parx'',''pary'']: [(Real 0 [-] x [+] y [-]x[**]3),(Real 0 [-] x [-] y [+] y[**]2)] && Inv & fTrue>
          { ((x[-]Real 1)[**]2[+](y[-]Real (3/2))[**]2 [>] Real (1/4));elE 0 [[|]] almost ((x[-]Real 1)[**]2[+](y[-]Real (3/2))[**]2 [>] Real (1/4))}"
apply (rule ContinuousRuleGT )
  apply auto
      apply (cut_tac allcons2)
      apply (simp add:fAnd_def fImp_def cons21_def)
     apply (cut_tac allcons2)
     apply (simp add:fAnd_def fImp_def cons22_def)
apply (cut_tac allcons2)
    apply (simp add:fAnd_def fImp_def cons23_def)
   apply (simp add:dOr_def)
  apply(cut_tac allcons2)
  apply (simp add:fAnd_def fImp_def dOr_def almost_def cons22_def)
  done

definition cons31 :: fform where "cons31 \<equiv> (x[**]2 [\<le>] Real (1/2) [&] y[**]2 [\<le>] Real (1/3)) [\<longrightarrow>] Inv"
definition cons32 :: fform where "cons32 \<equiv> Inv [\<longrightarrow>] ((x[-]Real 2)[**]2[+](y[-]Real 3)[**]2 [>] Real (1/4))"
definition cons33 :: fform where "cons33 \<equiv> exeFlow(<[''parx'',''pary'']: [(y [-](x[**]7)[*](x[**]4[+]Real 2[*]y[**]2[-]Real 10)),(Real 0 [-] x[**]3 [-]Real 3[*] y[**]5[*](x[**]4[+]Real 2[*]y[**]2[-]Real 10))] && Inv & fTrue>) Inv [\<longrightarrow>] Inv"
lemma allcons3: "\<forall>s. (cons31 [&] cons32 [&] cons33) s"
  apply (simp only: cons31_def cons32_def cons33_def x_def y_def)
by (inv_check_oracle"parx^4 + 2*pary^2 - 19 <= 0")
lemma N3:"{ (x[**]2 [\<le>] Real (1/2) [&] y[**]2 [\<le>] Real (1/3))}
         <[''parx'',''pary'']: [(y [-](x[**]7)[*](x[**]4[+]Real 2[*]y[**]2[-]Real 10)),(Real 0 [-] x[**]3 [-]Real 3[*] y[**]5[*](x[**]4[+]Real 2[*]y[**]2[-]Real 10))] && Inv & fTrue>
          { ((x[-]Real 2)[**]2[+](y[-]Real 3)[**]2 [>] Real (1/4));elE 0 [[|]] almost ((x[-]Real 2)[**]2[+](y[-]Real 3)[**]2 [>] Real (1/4))}"
apply (rule ContinuousRuleGT )
  apply auto
      apply (cut_tac allcons3)
      apply (simp add:fAnd_def fImp_def cons31_def)
     apply (cut_tac allcons3)
     apply (simp add:fAnd_def fImp_def cons32_def)
apply (cut_tac allcons3)
    apply (simp add:fAnd_def fImp_def cons33_def)
   apply (simp add:dOr_def)
  apply(cut_tac allcons3)
  apply (simp add:fAnd_def fImp_def dOr_def almost_def cons32_def)
  done

definition cons41 :: fform where "cons41 \<equiv> (x [=] Real 1 [&] y [=] Real 0 [&] z [=] Real 0) [\<longrightarrow>] Inv"
definition cons42 :: fform where "cons42 \<equiv> Inv [&] close(x[**]2[+]y[**]2[+]z[**]2[=] Real 1)[\<longrightarrow>] (x [\<le>] Real 1 [&] z[\<le>] Real 0)"
definition cons43 :: fform where "cons43 \<equiv> exeFlow(<[''parx'',''pary'',''parz'']: [x[*]z,y[*]z,Real 0[-]x[**]2[-]y[**]2] && Inv & (x[**]2[+]y[**]2[+]z[**]2[=] Real 1)>) Inv [\<longrightarrow>] Inv"
lemma allcons4: "\<forall>s. (cons41 [&] cons42 [&] cons43) s"
  apply (simp add: cons41_def cons42_def cons43_def x_def y_def z_def)
 by (inv_check_oracle "parz <= 0")
lemma N4:"{(x [=] Real 1 [&] y [=] Real 0 [&] z [=] Real 0)}
         <[''parx'',''pary'',''parz'']: [x[*]z,y[*]z,Real 0[-]x[**]2[-]y[**]2] && Inv & (x[**]2[+]y[**]2[+]z[**]2[=] Real 1)>
          {x [\<le>] Real 1 [&] z[\<le>] Real 0;elE 0 [[|]] almost (x [\<le>] Real 1 [&] z[\<le>] Real 0)}"
  apply (rule ContinuousRuleGT )
apply auto
  apply(simp add:fAnd_def fImp_def fEqual_def)
      apply (cut_tac allcons4)
      apply (simp add:fAnd_def fImp_def cons41_def)
     apply (cut_tac allcons4)
     apply (simp add:fAnd_def fImp_def cons42_def)
apply (cut_tac allcons4)
    apply (simp add:fAnd_def fImp_def cons43_def)
   apply (simp add:dOr_def)
  apply(cut_tac allcons4)
  apply (simp add:fAnd_def fImp_def dOr_def almost_def cons42_def)
  done

definition cons51 :: fform where "cons51 \<equiv> (x [=] Real 0 [&] y [=] Real (0-1) [&] y[*]a[**]2[=]Real -1) [\<longrightarrow>] Inv"
definition cons52 :: fform where "cons52 \<equiv> Inv [\<longrightarrow>] ( y[\<le>] Real 0 )"
definition cons53 :: fform where "cons53 \<equiv> exeFlow(<[''parx'',''pary'',''para'']: [x,y[**]2,Real (1/2)[div]a] && Inv & fTrue>) Inv [\<longrightarrow>] Inv"
lemma allcons5: "\<forall>s. (cons51 [&] cons52 [&] cons53) s"
apply (simp only: cons51_def cons52_def cons53_def x_def y_def a_def)
 by (inv_check_oracle "pary*para^2+1=0")

lemma N5le:"{(x [=] Real 0 [&] y [=] Real (0-1) [&] y[*]a[**]2[=]Real -1)}
         <[''parx'',''pary'',''para'']: [x,y[**]2,Real (1/2)[div]a] && Inv & fTrue>
          {( y[\<le>] Real 0 );elE 0 [[|]] almost ( y[\<le>] Real 0 )}"
  apply (rule ContinuousRuleGT )
apply auto
      apply (cut_tac allcons5)
      apply (simp add:fAnd_def fImp_def cons51_def)
     apply (cut_tac allcons5)
     apply (simp add:fAnd_def fImp_def cons52_def)
apply (cut_tac allcons5)
    apply (simp add:fAnd_def fImp_def cons53_def)
   apply (simp add:dOr_def)
  apply(cut_tac allcons5)
  apply (simp add:fAnd_def fImp_def dOr_def almost_def cons52_def)
  done
lemma N5:"{(x [=] Real 0 [&] y [=] Real (0-1) )}
         <[''parx'',''pary'']: [x,y[**]2] && Inv & fTrue>
          {( y[\<le>] Real 0);elE 0 [[|]] almost ( y[\<le>] Real 0)}"
apply (rule GhostRule[where w="''para''"
                          and F="Real (1/2)[div]a"
                          and pre="x [=] Real 0 [&] y [=] Real (0-1) [&] y[*]a[**]2[=]Real -1"
                          and post="( y[\<le>] Real 0 )"
                          and HF="(elE 0)[[|]]almost (( y[\<le>] Real 0 ))"])
         apply auto
apply(simp add: fAnd_def  fEqual_def  not_in_fform_def x_def y_def )
   apply(simp add: fLessEqual_def fOr_def fEqual_def fLess_def fGreater_def fNot_def not_in_fform_def x_def y_def )
  apply(simp add:dOr_def   fGreaterEqual_def fLessEqual_def fOr_def fImp_def fEqual_def fLess_def fGreater_def fNot_def not_in_dform_def x_def y_def  almost_def)
  apply(subgoal_tac "{(x [=] Real 0 [&] y [=] Real (0-1) [&] y[*]a[**]2[=]Real -1)}
         <[''parx'',''pary'',''para'']: [x,y[**]2,Real (1/2)[div]a] && Inv & fTrue>
          {( y[\<le>] Real 0 );elE 0 [[|]] almost ( y[\<le>] Real 0 )}")
  apply(simp add: dOr_def)
     apply (rule N5le)
  subgoal for s
  proof -
    have not_a: "not_in_fform ''para'' (x [=] Real 0 [&] y [=] Real - 1)"
      by (simp add: fAnd_def fGreaterEqual_def fLessEqual_def fOr_def fImp_def fEqual_def fLess_def fGreater_def fNot_def not_in_fform_def x_def y_def )
    have eq: "(x [=] Real 0 [&] y [=] Real - 1) (\<lambda>y. if y \<noteq> ''para'' then s y else  sqrt ( -1/s ''pary'')) \<longleftrightarrow> (x [=] Real 0 [&] y [=] Real - 1) s"
      by (simp add: not_in_fform_update[OF not_a])
    show ?thesis
      apply (rule exI[where x="sqrt ( -1/s ''pary'')"] )
      apply (auto simp add: eq fAnd_def   fEqual_def fLess_def   x_def y_def  a_def)
      done
  qed
 subgoal for s
   proof -
     have not_a: "not_in_fform ''para'' (y [\<le>] Real 0)"
       by(simp add:  fLessEqual_def fOr_def fImp_def fEqual_def fLess_def fGreater_def fNot_def not_in_fform_def x_def y_def )
     have eq: "(y [\<le>] Real 0) (\<lambda>y. if y \<noteq> ''para'' then s y else sqrt ( -s ''pary'')) \<longleftrightarrow> (y [\<le>] Real 0) s"
      by (simp add: not_in_fform_update[OF not_a])
    show ?thesis
      apply (rule exI[where x="sqrt ( -s ''pary'')"])
      apply ( simp add: eq fAnd_def  fLessEqual_def fOr_def fImp_def fEqual_def fLess_def fGreater_def fNot_def  x_def y_def  a_def)
      done
  qed
  subgoal for h n d
    apply(simp add:dOr_def almost_def fAnd_def a_def )
    apply (case_tac "n=d")
    apply auto
    apply (case_tac "n>d")
     apply auto
    apply (case_tac "n<d")
     apply auto
    apply (rule exI[where x="\<lambda>t y. sqrt(- (h t  ''pary''))"])
    apply auto
      apply (subgoal_tac "not_in_fform ''para'' (y [\<le>] Real 0)")
       apply(simp add:not_in_fform_def)
       apply smt
    apply(simp add:  fLessEqual_def fOr_def fImp_def fEqual_def fLess_def fGreater_def fNot_def not_in_fform_def x_def y_def )
    apply(simp add:  fLessEqual_def fOr_def fImp_def fEqual_def fLess_def fGreater_def fNot_def  x_def y_def )
    done
  done

end