theory Lambda
imports "../NewParser" Quotient_Option
begin

atom_decl name

nominal_datatype lam =
  Var "name"
| App "lam" "lam"
| Lam x::"name" l::"lam"  bind_set x in l

thm lam.fv
thm lam.supp
lemmas supp_fn' = lam.fv[simplified lam.supp]

declare lam.perm[eqvt]


section {* Strong Induction Principles*}

(*
  Old way of establishing strong induction
  principles by chosing a fresh name.
*)
lemma
  fixes c::"'a::fs"
  assumes a1: "\<And>name c. P c (Var name)"
  and     a2: "\<And>lam1 lam2 c. \<lbrakk>\<And>d. P d lam1; \<And>d. P d lam2\<rbrakk> \<Longrightarrow> P c (App lam1 lam2)"
  and     a3: "\<And>name lam c. \<lbrakk>atom name \<sharp> c; \<And>d. P d lam\<rbrakk> \<Longrightarrow> P c (Lam name lam)"
  shows "P c lam"
proof -
  have "\<And>p. P c (p \<bullet> lam)"
    apply(induct lam arbitrary: c rule: lam.induct)
    apply(perm_simp)
    apply(rule a1)
    apply(perm_simp)
    apply(rule a2)
    apply(assumption)
    apply(assumption)
    apply(subgoal_tac "\<exists>new::name. (atom new) \<sharp> (c, Lam (p \<bullet> name) (p \<bullet> lam))")
    defer
    apply(simp add: fresh_def)
    apply(rule_tac X="supp (c, Lam (p \<bullet> name) (p \<bullet> lam))" in obtain_at_base)
    apply(simp add: supp_Pair finite_supp)
    apply(blast)
    apply(erule exE)
    apply(rule_tac t="p \<bullet> Lam name lam" and 
                   s="(((p \<bullet> name) \<leftrightarrow> new) + p) \<bullet> Lam name lam" in subst)
    apply(simp del: lam.perm)
    apply(subst lam.perm)
    apply(subst (2) lam.perm)
    apply(rule flip_fresh_fresh)
    apply(simp add: fresh_def)
    apply(simp only: supp_fn')
    apply(simp)
    apply(simp add: fresh_Pair)
    apply(simp)
    apply(rule a3)
    apply(simp add: fresh_Pair)
    apply(drule_tac x="((p \<bullet> name) \<leftrightarrow> new) + p" in meta_spec)
    apply(simp)
    done
  then have "P c (0 \<bullet> lam)" by blast
  then show "P c lam" by simp
qed

(* 
  New way of establishing strong induction
  principles by using a appropriate permutation.
*)
lemma
  fixes c::"'a::fs"
  assumes a1: "\<And>name c. P c (Var name)"
  and     a2: "\<And>lam1 lam2 c. \<lbrakk>\<And>d. P d lam1; \<And>d. P d lam2\<rbrakk> \<Longrightarrow> P c (App lam1 lam2)"
  and     a3: "\<And>name lam c. \<lbrakk>atom name \<sharp> c; \<And>d. P d lam\<rbrakk> \<Longrightarrow> P c (Lam name lam)"
  shows "P c lam"
proof -
  have "\<And>p. P c (p \<bullet> lam)"
    apply(induct lam arbitrary: c rule: lam.induct)
    apply(perm_simp)
    apply(rule a1)
    apply(perm_simp)
    apply(rule a2)
    apply(assumption)
    apply(assumption)
    apply(subgoal_tac "\<exists>q. (q \<bullet> {p \<bullet> atom name}) \<sharp>* c \<and> supp (p \<bullet> Lam name lam) \<sharp>* q")
    apply(erule exE)
    apply(rule_tac t="p \<bullet> Lam name lam" and 
                   s="q \<bullet> p \<bullet> Lam name lam" in subst)
    defer
    apply(simp)
    apply(rule a3)
    apply(simp add: eqvts fresh_star_def)
    apply(drule_tac x="q + p" in meta_spec)
    apply(simp)
    apply(rule at_set_avoiding2)
    apply(simp add: finite_supp)
    apply(simp add: finite_supp)
    apply(simp add: finite_supp)
    apply(perm_simp)
    apply(simp add: fresh_star_def fresh_def supp_fn')
    apply(rule supp_perm_eq)
    apply(simp)
    done
  then have "P c (0 \<bullet> lam)" by blast
  then show "P c lam" by simp
qed

section {* Typing *}

nominal_datatype ty =
  TVar string
| TFun ty ty

notation
 TFun ("_ \<rightarrow> _") 

declare ty.perm[eqvt]

inductive
  valid :: "(name \<times> ty) list \<Rightarrow> bool"
where
  "valid []"
| "\<lbrakk>atom x \<sharp> Gamma; valid Gamma\<rbrakk> \<Longrightarrow> valid ((x, T)#Gamma)"

inductive
  typing :: "(name\<times>ty) list \<Rightarrow> lam \<Rightarrow> ty \<Rightarrow> bool" ("_ \<turnstile> _ : _" [60,60,60] 60) 
where
    t_Var[intro]: "\<lbrakk>valid \<Gamma>; (x, T) \<in> set \<Gamma>\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> Var x : T"
  | t_App[intro]: "\<lbrakk>\<Gamma> \<turnstile> t1 : T1 \<rightarrow> T2; \<Gamma> \<turnstile> t2 : T1\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> App t1 t2 : T2"
  | t_Lam[intro]: "\<lbrakk>atom x \<sharp> \<Gamma>; (x, T1) # \<Gamma> \<turnstile> t : T2\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> Lam x t : T1 \<rightarrow> T2"

equivariance valid
equivariance typing

thm valid.eqvt
thm typing.eqvt
thm eqvts
thm eqvts_raw

thm typing.induct[of "\<Gamma>" "t" "T", no_vars]

lemma
  fixes c::"'a::fs"
  assumes a: "\<Gamma> \<turnstile> t : T" 
  and a1: "\<And>\<Gamma> x T c. \<lbrakk>valid \<Gamma>; (x, T) \<in> set \<Gamma>\<rbrakk> \<Longrightarrow> P c \<Gamma> (Var x) T"
  and a2: "\<And>\<Gamma> t1 T1 T2 t2 c. \<lbrakk>\<Gamma> \<turnstile> t1 : T1 \<rightarrow> T2; \<And>d. P d \<Gamma> t1 T1 \<rightarrow> T2; \<Gamma> \<turnstile> t2 : T1; \<And>d. P d \<Gamma> t2 T1\<rbrakk> 
           \<Longrightarrow> P c \<Gamma> (App t1 t2) T2"
  and a3: "\<And>x \<Gamma> T1 t T2 c. \<lbrakk>atom x \<sharp> c; atom x \<sharp> \<Gamma>; (x, T1) # \<Gamma> \<turnstile> t : T2; \<And>d. P d ((x, T1) # \<Gamma>) t T2\<rbrakk> 
           \<Longrightarrow> P c \<Gamma> (Lam x t) T1 \<rightarrow> T2"
  shows "P c \<Gamma> t T"
proof -
  from a have "\<And>p c. P c (p \<bullet> \<Gamma>) (p \<bullet> t) (p \<bullet> T)"
  proof (induct)
    case (t_Var \<Gamma> x T p c)
    then show ?case
      apply -
      apply(perm_strict_simp)
      apply(rule a1)
      apply(drule_tac p="p" in permute_boolI)
      apply(perm_strict_simp add: permute_minus_cancel)
      apply(assumption)
      apply(rotate_tac 1)
      apply(drule_tac p="p" in permute_boolI)
      apply(perm_strict_simp add: permute_minus_cancel)
      apply(assumption)
      done
  next
    case (t_App \<Gamma> t1 T1 T2 t2 p c)
    then show ?case
      apply -
      apply(perm_strict_simp)
      apply(rule a2)
      apply(drule_tac p="p" in permute_boolI)
      apply(perm_strict_simp add: permute_minus_cancel)
      apply(assumption)
      apply(assumption)
      apply(rotate_tac 2)
      apply(drule_tac p="p" in permute_boolI)
      apply(perm_strict_simp add: permute_minus_cancel)
      apply(assumption)
      apply(assumption)
      done
  next
    case (t_Lam x \<Gamma> T1 t T2 p c)
    then show ?case
      apply -
      apply(subgoal_tac "\<exists>q. (q \<bullet> {p \<bullet> atom x}) \<sharp>* c \<and> 
        supp (p \<bullet> \<Gamma>, p \<bullet> Lam x t, p \<bullet> (T1 \<rightarrow> T2)) \<sharp>* q")
      apply(erule exE)
      apply(rule_tac t="p \<bullet> \<Gamma>" and  s="(q + p) \<bullet> \<Gamma>" in subst)
      apply(simp only: permute_plus)
      apply(rule supp_perm_eq)
      apply(simp add: supp_Pair fresh_star_union)
      apply(rule_tac t="p \<bullet> Lam x t" and  s="(q + p) \<bullet> Lam x t" in subst)
      apply(simp only: permute_plus)
      apply(rule supp_perm_eq)
      apply(simp add: supp_Pair fresh_star_union)
      apply(rule_tac t="p \<bullet> (T1 \<rightarrow> T2)" and  s="(q + p) \<bullet> (T1 \<rightarrow> T2)" in subst)
      apply(simp only: permute_plus)
      apply(rule supp_perm_eq)
      apply(simp add: supp_Pair fresh_star_union)
      apply(simp (no_asm) only: eqvts)
      apply(rule a3)
      apply(simp only: eqvts permute_plus)
      apply(simp add: fresh_star_def)
      apply(drule_tac p="q + p" in permute_boolI)
      apply(perm_strict_simp add: permute_minus_cancel)
      apply(assumption)
      apply(rotate_tac 1)
      apply(drule_tac p="q + p" in permute_boolI)
      apply(perm_strict_simp add: permute_minus_cancel)
      apply(assumption)
      apply(drule_tac x="d" in meta_spec)
      apply(drule_tac x="q + p" in meta_spec)
      apply(perm_strict_simp add: permute_minus_cancel)
      apply(assumption)
      apply(rule at_set_avoiding2)
      apply(simp add: finite_supp)
      apply(simp add: finite_supp)
      apply(simp add: finite_supp)
      apply(rule_tac p="-p" in permute_boolE)
      apply(perm_strict_simp add: permute_minus_cancel)
	(* supplied by the user *)
      apply(simp add: fresh_star_prod)
      apply(simp add: fresh_star_def)
      sorry
  qed
  then have "P c (0 \<bullet> \<Gamma>) (0 \<bullet> t) (0 \<bullet> T)" .
  then show "P c \<Gamma> t T" by simp
qed







inductive
  tt :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool)"  
  for r :: "('a \<Rightarrow> 'a \<Rightarrow> bool)"
where
    aa: "tt r a a"
  | bb: "tt r a b ==> tt r a c"

(* PROBLEM: derived eqvt-theorem does not conform with [eqvt]
equivariance tt
*)


inductive
 alpha_lam_raw'
where
  a1: "name = namea \<Longrightarrow> alpha_lam_raw' (Var_raw name) (Var_raw namea)"
| a2: "\<lbrakk>alpha_lam_raw' lam_raw1 lam_raw1a; alpha_lam_raw' lam_raw2 lam_raw2a\<rbrakk> \<Longrightarrow>
   alpha_lam_raw' (App_raw lam_raw1 lam_raw2) (App_raw lam_raw1a lam_raw2a)"
| a3: "\<exists>pi. ({atom name}, lam_raw) \<approx>gen alpha_lam_raw' fv_lam_raw pi ({atom namea}, lam_rawa) \<Longrightarrow>
   alpha_lam_raw' (Lam_raw name lam_raw) (Lam_raw namea lam_rawa)"

equivariance alpha_lam_raw'

thm eqvts_raw

section {* size function *}

lemma size_eqvt_raw:
  fixes t::"lam_raw"
  shows "size (pi \<bullet> t)  = size t"
  apply (induct rule: lam_raw.inducts)
  apply simp_all
  done

instantiation lam :: size 
begin

quotient_definition
  "size_lam :: lam \<Rightarrow> nat"
is
  "size :: lam_raw \<Rightarrow> nat"

lemma size_rsp:
  "alpha_lam_raw x y \<Longrightarrow> size x = size y"
  apply (induct rule: alpha_lam_raw.inducts)
  apply (simp_all only: lam_raw.size)
  apply (simp_all only: alphas)
  apply clarify
  apply (simp_all only: size_eqvt_raw)
  done

lemma [quot_respect]:
  "(alpha_lam_raw ===> op =) size size"
  by (simp_all add: size_rsp)

lemma [quot_preserve]:
  "(rep_lam ---> id) size = size"
  by (simp_all add: size_lam_def)

instance
  by default

end

lemmas size_lam[simp] = 
  lam_raw.size(4)[quot_lifted]
  lam_raw.size(5)[quot_lifted]
  lam_raw.size(6)[quot_lifted]

(* is this needed? *)
lemma [measure_function]: 
  "is_measure (size::lam\<Rightarrow>nat)" 
  by (rule is_measure_trivial)

section {* Matching *}

definition
  MATCH :: "('c::pt \<Rightarrow> (bool * 'a::pt * 'b::pt)) \<Rightarrow> 'b \<Rightarrow> 'a \<Rightarrow> 'b"
where
  "MATCH M d x \<equiv> if (\<exists>!r. \<exists>q. M q = (True, x, r)) then (THE r. \<exists>q. M q = (True, x, r)) else d"

(*
lemma MATCH_eqvt:
  shows "p \<bullet> (MATCH M d x) = MATCH (p \<bullet> M) (p \<bullet> d) (p \<bullet> x)"
unfolding MATCH_def
apply(perm_simp the_eqvt)
apply (tactic {* Nominal_Permeq.eqvt_tac @{context} 1 *})
apply(simp)
thm eqvts_raw 
apply(subst if_eqvt)
apply(subst ex1_eqvt)
apply(subst permute_fun_def)
apply(subst ex_eqvt)
apply(subst permute_fun_def)
apply(subst eq_eqvt)
apply(subst permute_fun_app_eq[where f="M"])
apply(simp only: permute_minus_cancel)
apply(subst permute_prod.simps)
apply(subst permute_prod.simps)
apply(simp only: permute_minus_cancel)
apply(simp only: permute_bool_def)
apply(simp)
apply(subst ex1_eqvt)
apply(subst permute_fun_def)
apply(subst ex_eqvt)
apply(subst permute_fun_def)
apply(subst eq_eqvt)

apply(simp only: eqvts)
apply(simp)
apply(subgoal_tac "(p \<bullet> (\<exists>!r. \<exists>q. M q = (True, x, r))) = (\<exists>!r. \<exists>q. (p \<bullet> M) q = (True, p \<bullet> x, r))")
apply(drule sym)
apply(simp)
apply(rule impI)
apply(simp add: perm_bool)
apply(rule trans)
apply(rule pt_the_eqvt[OF pta at])
apply(assumption)
apply(simp add: pt_ex_eqvt[OF pt at])
apply(simp add: pt_eq_eqvt[OF ptb at])
apply(rule cheat)
apply(rule trans)
apply(rule pt_ex1_eqvt)
apply(rule pta)
apply(rule at)
apply(simp add: pt_ex_eqvt[OF pt at])
apply(simp add: pt_eq_eqvt[OF ptb at])
apply(subst pt_pi_rev[OF pta at])
apply(subst pt_fun_app_eq[OF pt at])
apply(subst pt_pi_rev[OF pt at])
apply(simp)
done

lemma MATCH_cng:
  assumes a: "M1 = M2" "d1 = d2"
  shows "MATCH M1 d1 x = MATCH M2 d2 x"
using a by simp

lemma MATCH_eq:
  assumes a: "t = l x" "G x" "\<And>x'. t = l x' \<Longrightarrow> G x' \<Longrightarrow> r x' = r x"
  shows "MATCH (\<lambda>x. (G x, l x, r x)) d t = r x"
using a
unfolding MATCH_def
apply(subst if_P)
apply(rule_tac a="r x" in ex1I)
apply(rule_tac x="x" in exI)
apply(blast)
apply(erule exE)
apply(drule_tac x="q" in meta_spec)
apply(auto)[1]
apply(rule the_equality)
apply(blast)
apply(erule exE)
apply(drule_tac x="q" in meta_spec)
apply(auto)[1]
done

lemma MATCH_eq2:
  assumes a: "t = l x1 x2" "G x1 x2" "\<And>x1' x2'. t = l x1' x2' \<Longrightarrow> G x1' x2' \<Longrightarrow> r x1' x2' = r x1 x2"
  shows "MATCH (\<lambda>(x1,x2). (G x1 x2, l x1 x2, r x1 x2)) d t = r x1 x2"
sorry

lemma MATCH_neq:
  assumes a: "\<And>x. t = l x \<Longrightarrow> G x \<Longrightarrow> False"
  shows "MATCH (\<lambda>x. (G x, l x, r x)) d t = d"
using a
unfolding MATCH_def
apply(subst if_not_P)
apply(blast)
apply(rule refl)
done

lemma MATCH_neq2:
  assumes a: "\<And>x1 x2. t = l x1 x2 \<Longrightarrow> G x1 x2 \<Longrightarrow> False"
  shows "MATCH (\<lambda>(x1,x2). (G x1 x2, l x1 x2, r x1 x2)) d t = d"
using a
unfolding MATCH_def
apply(subst if_not_P)
apply(auto)
done
*)

ML {*
fun mk_avoids ctxt params name set =
  let
    val (_, ctxt') = ProofContext.add_fixes
      (map (fn (s, T) => (Binding.name s, SOME T, NoSyn)) params) ctxt;
    fun mk s =
      let
        val t = Syntax.read_term ctxt' s;
        val t' = list_abs_free (params, t) |>
          funpow (length params) (fn Abs (_, _, t) => t)
      in (t', HOLogic.dest_setT (fastype_of t)) end
      handle TERM _ =>
        error ("Expression " ^ quote s ^ " to be avoided in case " ^
          quote name ^ " is not a set type");
    fun add_set p [] = [p]
      | add_set (t, T) ((u, U) :: ps) =
          if T = U then
            let val S = HOLogic.mk_setT T
            in (Const (@{const_name sup}, S --> S --> S) $ u $ t, T) :: ps
            end
          else (u, U) :: add_set (t, T) ps
  in
    (mk #> add_set) set 
  end;
*}


ML {* 
  writeln (commas (map (Syntax.string_of_term @{context} o fst) 
    (mk_avoids @{context} [] "t_Var" "{x}" []))) 
*}


ML {*

fun prove_strong_ind (pred_name, avoids) ctxt = 
  Proof.theorem NONE (K I) [] ctxt

local structure P = Parse and K = Keyword in

val _ =
  Outer_Syntax.local_theory_to_proof "nominal_inductive"
    "proves strong induction theorem for inductive predicate involving nominal datatypes" K.thy_goal
      (P.xname -- (Scan.optional (P.$$$ "avoids" |-- P.enum1 "|" (P.name --
        (P.$$$ ":" |-- P.and_list1 P.term))) []) >>  prove_strong_ind)

end;

*}

(*
nominal_inductive typing
*)

(* Substitution *)

primrec match_Var_raw where
  "match_Var_raw (Var_raw x) = Some x"
| "match_Var_raw (App_raw x y) = None"
| "match_Var_raw (Lam_raw n t) = None"

quotient_definition
  "match_Var :: lam \<Rightarrow> name option"
is match_Var_raw

lemma [quot_respect]: "(alpha_lam_raw ===> op =) match_Var_raw match_Var_raw"
  apply rule
  apply (induct_tac a b rule: alpha_lam_raw.induct)
  apply simp_all
  done

lemmas match_Var_simps = match_Var_raw.simps[quot_lifted]

primrec match_App_raw where
  "match_App_raw (Var_raw x) = None"
| "match_App_raw (App_raw x y) = Some (x, y)"
| "match_App_raw (Lam_raw n t) = None"

quotient_definition
  "match_App :: lam \<Rightarrow> (lam \<times> lam) option"
is match_App_raw

lemma [quot_respect]:
  "(alpha_lam_raw ===> option_rel (prod_rel alpha_lam_raw alpha_lam_raw)) match_App_raw match_App_raw"
  apply (intro fun_relI)
  apply (induct_tac a b rule: alpha_lam_raw.induct)
  apply simp_all
  done

lemmas match_App_simps = match_App_raw.simps[quot_lifted]

definition new where
  "new (s :: 'a :: fs) = (THE x. \<forall>a \<in> supp s. atom x \<noteq> a)"

definition
  "match_Lam (S :: 'a :: fs) t = (if (\<exists>n s. (t = Lam n s)) then
    (let z = new (S, t) in Some (z, THE s. t = Lam z s)) else None)"

lemma lam_half_inj: "(Lam z s = Lam z sa) = (s = sa)"
  apply auto
  apply (simp only: lam.eq_iff alphas)
  apply clarify
  apply (simp add: eqvts)
  sorry

lemma match_Lam_simps:
  "match_Lam S (Var n) = None"
  "match_Lam S (App l r) = None"
  "z = new (S, (Lam z s)) \<Longrightarrow> match_Lam S (Lam z s) = Some (z, s)"
  apply (simp_all add: match_Lam_def)
  apply (simp add: lam_half_inj)
  apply auto
  done

(*
lemma match_Lam_simps2:
  "atom n \<sharp> ((S :: 'a :: fs), Lam n s) \<Longrightarrow> match_Lam S (Lam n s) = Some (n, s)"
  apply (rule_tac t="Lam n s"
              and s="Lam (new (S, (Lam n s))) ((n \<leftrightarrow> (new (S, (Lam n s)))) \<bullet> s)" in subst)
  defer
  apply (subst match_Lam_simps(3))
  defer
  apply simp
*)

(*primrec match_Lam_raw where
  "match_Lam_raw (S :: atom set) (Var_raw x) = None"
| "match_Lam_raw S (App_raw x y) = None"
| "match_Lam_raw S (Lam_raw n t) = (let z = new (S \<union> (fv_lam_raw t - {atom n})) in Some (z, (n \<leftrightarrow> z) \<bullet> t))"

quotient_definition
  "match_Lam :: (atom set) \<Rightarrow> lam \<Rightarrow> (name \<times> lam) option"
is match_Lam_raw

lemma swap_fresh:
  assumes a: "fv_lam_raw t \<sharp>* p"
  shows "alpha_lam_raw (p \<bullet> t) t"
  using a apply (induct t)
  apply (simp add: supp_at_base fresh_star_def)
  apply (rule alpha_lam_raw.intros)
  apply (metis Rep_name_inverse atom_eqvt atom_name_def fresh_perm)
  apply (simp)
  apply (simp only: fresh_star_union)
  apply clarify
  apply (rule alpha_lam_raw.intros)
  apply simp
  apply simp
  apply simp
  apply (rule alpha_lam_raw.intros)
  sorry

lemma [quot_respect]:
  "(op = ===> alpha_lam_raw ===> option_rel (prod_rel op = alpha_lam_raw)) match_Lam_raw match_Lam_raw"
  proof (intro fun_relI, clarify)
    fix S t s
    assume a: "alpha_lam_raw t s"
    show "option_rel (prod_rel op = alpha_lam_raw) (match_Lam_raw S t) (match_Lam_raw S s)"
      using a proof (induct t s rule: alpha_lam_raw.induct)
      case goal1 show ?case by simp
    next
      case goal2 show ?case by simp
    next
      case (goal3 x t y s)
      then obtain p where "({atom x}, t) \<approx>gen (\<lambda>x1 x2. alpha_lam_raw x1 x2 \<and>
                              option_rel (prod_rel op = alpha_lam_raw) (match_Lam_raw S x1)
                               (match_Lam_raw S x2)) fv_lam_raw p ({atom y}, s)" ..
      then have
        c: "fv_lam_raw t - {atom x} = fv_lam_raw s - {atom y}" and
        d: "(fv_lam_raw t - {atom x}) \<sharp>* p" and
        e: "alpha_lam_raw (p \<bullet> t) s" and
        f: "option_rel (prod_rel op = alpha_lam_raw) (match_Lam_raw S (p \<bullet> t)) (match_Lam_raw S s)" and
        g: "p \<bullet> {atom x} = {atom y}" unfolding alphas(1) by - (elim conjE, assumption)+
      let ?z = "new (S \<union> (fv_lam_raw t - {atom x}))"
      have h: "?z = new (S \<union> (fv_lam_raw s - {atom y}))" using c by simp
      show ?case
        unfolding match_Lam_raw.simps Let_def option_rel.simps prod_rel.simps split_conv
      proof
        show "?z = new (S \<union> (fv_lam_raw s - {atom y}))" by (fact h)
      next
        have "atom y \<sharp> p" sorry
        have "fv_lam_raw t \<sharp>* ((x \<leftrightarrow> y) \<bullet> p)" sorry
        then have "alpha_lam_raw (((x \<leftrightarrow> y) \<bullet> p) \<bullet> t) t" using swap_fresh by auto
        then have "alpha_lam_raw (p \<bullet> t) ((x \<leftrightarrow> y) \<bullet> t)" sorry
        have "alpha_lam_raw t ((x \<leftrightarrow> y) \<bullet> s)" sorry
        then have "alpha_lam_raw ((x \<leftrightarrow> ?z) \<bullet> t) ((y \<leftrightarrow> ?z) \<bullet> s)" using eqvts(15) sorry
        then show "alpha_lam_raw ((x \<leftrightarrow> new (S \<union> (fv_lam_raw t - {atom x}))) \<bullet> t)
                  ((y \<leftrightarrow> new (S \<union> (fv_lam_raw s - {atom y}))) \<bullet> s)" unfolding h .
      qed
    qed
  qed

lemmas match_Lam_simps = match_Lam_raw.simps[quot_lifted]
*)

lemma app_some: "match_App x = Some (a, b) \<Longrightarrow> x = App a b"
by (induct x rule: lam.induct) (simp_all add: match_App_simps)

lemma lam_some: "match_Lam S x = Some (z, s) \<Longrightarrow> x = Lam z s \<and> atom z \<sharp> S"
  apply (induct x rule: lam.induct)
  apply (simp_all add: match_Lam_simps)
  apply (thin_tac "match_Lam S lam = Some (z, s) \<Longrightarrow> lam = Lam z s \<and> atom z \<sharp> S")
  apply (simp add: match_Lam_def)
  apply (subgoal_tac "\<exists>n s. Lam name lam = Lam n s")
  prefer 2
  apply auto[1]
  apply (simp add: Let_def)
  apply (thin_tac "\<exists>n s. Lam name lam = Lam n s")
  apply clarify
  apply (rule conjI)
  apply (rule_tac t="THE s. Lam name lam = Lam (new (S, Lam name lam)) s" and
                  s="(name \<leftrightarrow> (new (S, Lam name lam))) \<bullet> lam" in subst)
  defer
  apply (simp add: lam.eq_iff)
  apply (rule_tac x="(name \<leftrightarrow> (new (S, Lam name lam)))" in exI)
  apply (simp add: alphas)
  apply (simp add: eqvts)
  apply (rule conjI)
  sorry

function subst where
"subst v s t = (
  case match_Var t of Some n \<Rightarrow> if n = v then s else Var n | None \<Rightarrow>
  case match_App t of Some (l, r) \<Rightarrow> App (subst v s l) (subst v s r) | None \<Rightarrow>
  case match_Lam (v,s) t of Some (n, t) \<Rightarrow> Lam n (subst v s t) | None \<Rightarrow> undefined)"
by pat_completeness auto

termination apply (relation "measure (\<lambda>(_, _, t). size t)")
  apply auto[1]
  apply (case_tac a) apply simp
  apply (frule lam_some) apply simp
  apply (case_tac a) apply simp
  apply (frule app_some) apply simp
  apply (case_tac a) apply simp
  apply (frule app_some) apply simp
done

lemmas lam_exhaust = lam_raw.exhaust[quot_lifted]

lemma subst_eqvt:
  "p \<bullet> (subst v s t) = subst (p \<bullet> v) (p \<bullet> s) (p \<bullet> t)"
  proof (induct v s t rule: subst.induct)
    case (1 v s t)
    show ?case proof (cases t rule: lam_exhaust)
      fix n
      assume "t = Var n"
      then show ?thesis by (simp add: match_Var_simps)
    next
      fix l r
      assume "t = App l r"
      then show ?thesis
        apply (simp only:)
        apply (subst subst.simps)
        apply (subst match_Var_simps)
        apply (simp only: option.cases)
        apply (subst match_App_simps)
        apply (simp only: option.cases)
        apply (simp only: prod.cases)
        apply (simp only: lam.perm)
        apply (subst (3) subst.simps)
        apply (subst match_Var_simps)
        apply (simp only: option.cases)
        apply (subst match_App_simps)
        apply (simp only: option.cases)
        apply (simp only: prod.cases)
        apply (subst 1(2)[of "(l, r)" "l" "r"])
        apply (simp add: match_Var_simps)
        apply (simp add: match_App_simps)
        apply (rule refl)
        apply (subst 1(3)[of "(l, r)" "l" "r"])
        apply (simp add: match_Var_simps)
        apply (simp add: match_App_simps)
        apply (rule refl)
        apply (rule refl)
        done
    next
      fix n t'
      assume "t = Lam n t'"
      then show ?thesis
        apply (simp only: )
        apply (simp only: lam.perm)
        apply (subst subst.simps)
        apply (subst match_Var_simps)
        apply (simp only: option.cases)
        apply (subst match_App_simps)
        apply (simp only: option.cases)
        apply (rule_tac t="Lam n t'" and s="Lam (new ((v, s), Lam n t')) ((n \<leftrightarrow> new ((v, s), Lam n t')) \<bullet> t')" in subst)
        defer
        apply (subst match_Lam_simps)
        defer
        apply (simp only: option.cases)
        apply (simp only: prod.cases)
        apply (subst (2) subst.simps)
        apply (subst match_Var_simps)
        apply (simp only: option.cases)
        apply (subst match_App_simps)
        apply (simp only: option.cases)
        apply (rule_tac t="Lam (p \<bullet> n) (p \<bullet> t')" and s="Lam (new ((p \<bullet> v, p \<bullet> s), Lam (p \<bullet> n) (p \<bullet> t'))) (((p \<bullet> n) \<leftrightarrow> new ((p \<bullet> v, p \<bullet> s), Lam (p \<bullet> n) (p \<bullet> t'))) \<bullet> t')" in subst)
        defer
        apply (subst match_Lam_simps)
        defer
        apply (simp only: option.cases)
        apply (simp only: prod.cases)
        apply (simp only: lam.perm)
        thm 1(1)
        sorry
    qed
  qed

lemma subst_proper_eqs:
  "subst y s (Var x) = (if x = y then s else (Var x))"
  "subst y s (App l r) = App (subst y s l) (subst y s r)"
  "atom x \<sharp> (t, s) \<Longrightarrow> subst y s (Lam x t) = Lam x (subst y s t)"
  apply (subst subst.simps)
  apply (simp only: match_Var_simps)
  apply (simp only: option.simps)
  apply (subst subst.simps)
  apply (simp only: match_App_simps)
  apply (simp only: option.simps)
  apply (simp only: prod.simps)
  apply (simp only: match_Var_simps)
  apply (simp only: option.simps)
  apply (subst subst.simps)
  apply (simp only: match_Var_simps)
  apply (simp only: option.simps)
  apply (simp only: match_App_simps)
  apply (simp only: option.simps)
  apply (rule_tac t="Lam x t" and s="Lam (new ((y, s), Lam x t)) ((x \<leftrightarrow> new ((y, s), Lam x t)) \<bullet> t)" in subst)
  defer
  apply (subst match_Lam_simps)
  defer
  apply (simp only: option.simps)
  apply (simp only: prod.simps)
  sorry

end



