QuotMain.thy
author Cezary Kaliszyk <kaliszyk@in.tum.de>
Thu, 22 Oct 2009 15:44:16 +0200
changeset 155 8b3d4806ad79
parent 154 1610de61c44b
child 156 9c74171ff78b
permissions -rw-r--r--
Removed an assumption

theory QuotMain
imports QuotScript QuotList Prove
uses ("quotient.ML")
begin

ML {* Pretty.writeln *}
ML {*  LocalTheory.theory_result *}

locale QUOT_TYPE =
  fixes R :: "'a \<Rightarrow> 'a \<Rightarrow> bool"
  and   Abs :: "('a \<Rightarrow> bool) \<Rightarrow> 'b"
  and   Rep :: "'b \<Rightarrow> ('a \<Rightarrow> bool)"
  assumes equiv: "EQUIV R"
  and     rep_prop: "\<And>y. \<exists>x. Rep y = R x"
  and     rep_inverse: "\<And>x. Abs (Rep x) = x"
  and     abs_inverse: "\<And>x. (Rep (Abs (R x))) = (R x)"
  and     rep_inject: "\<And>x y. (Rep x = Rep y) = (x = y)"
begin

definition
  "ABS x \<equiv> Abs (R x)"

definition
  "REP a = Eps (Rep a)"

lemma lem9:
  shows "R (Eps (R x)) = R x"
proof -
  have a: "R x x" using equiv by (simp add: EQUIV_REFL_SYM_TRANS REFL_def)
  then have "R x (Eps (R x))" by (rule someI)
  then show "R (Eps (R x)) = R x"
    using equiv unfolding EQUIV_def by simp
qed

theorem thm10:
  shows "ABS (REP a) \<equiv> a"
  apply  (rule eq_reflection)
  unfolding ABS_def REP_def
proof -
  from rep_prop
  obtain x where eq: "Rep a = R x" by auto
  have "Abs (R (Eps (Rep a))) = Abs (R (Eps (R x)))" using eq by simp
  also have "\<dots> = Abs (R x)" using lem9 by simp
  also have "\<dots> = Abs (Rep a)" using eq by simp
  also have "\<dots> = a" using rep_inverse by simp
  finally
  show "Abs (R (Eps (Rep a))) = a" by simp
qed

lemma REP_refl:
  shows "R (REP a) (REP a)"
unfolding REP_def
by (simp add: equiv[simplified EQUIV_def])

lemma lem7:
  shows "(R x = R y) = (Abs (R x) = Abs (R y))"
apply(rule iffI)
apply(simp)
apply(drule rep_inject[THEN iffD2])
apply(simp add: abs_inverse)
done

theorem thm11:
  shows "R r r' = (ABS r = ABS r')"
unfolding ABS_def
by (simp only: equiv[simplified EQUIV_def] lem7)


lemma REP_ABS_rsp:
  shows "R f (REP (ABS g)) = R f g"
  and   "R (REP (ABS g)) f = R g f"
by (simp_all add: thm10 thm11)

lemma QUOTIENT:
  "QUOTIENT R ABS REP"
apply(unfold QUOTIENT_def)
apply(simp add: thm10)
apply(simp add: REP_refl)
apply(subst thm11[symmetric])
apply(simp add: equiv[simplified EQUIV_def])
done

lemma R_trans:
  assumes ab: "R a b"
  and     bc: "R b c"
  shows "R a c"
proof -
  have tr: "TRANS R" using equiv EQUIV_REFL_SYM_TRANS[of R] by simp
  moreover have ab: "R a b" by fact
  moreover have bc: "R b c" by fact
  ultimately show "R a c" unfolding TRANS_def by blast
qed

lemma R_sym:
  assumes ab: "R a b"
  shows "R b a"
proof -
  have re: "SYM R" using equiv EQUIV_REFL_SYM_TRANS[of R] by simp
  then show "R b a" using ab unfolding SYM_def by blast
qed

lemma R_trans2:
  assumes ac: "R a c"
  and     bd: "R b d"
  shows "R a b = R c d"
proof
  assume "R a b"
  then have "R b a" using R_sym by blast
  then have "R b c" using ac R_trans by blast
  then have "R c b" using R_sym by blast
  then show "R c d" using bd R_trans by blast
next
  assume "R c d"
  then have "R a d" using ac R_trans by blast
  then have "R d a" using R_sym by blast
  then have "R b a" using bd R_trans by blast
  then show "R a b" using R_sym by blast
qed

lemma REPS_same:
  shows "R (REP a) (REP b) \<equiv> (a = b)"
proof -
  have "R (REP a) (REP b) = (a = b)"
  proof
    assume as: "R (REP a) (REP b)"
    from rep_prop
    obtain x y
      where eqs: "Rep a = R x" "Rep b = R y" by blast
    from eqs have "R (Eps (R x)) (Eps (R y))" using as unfolding REP_def by simp
    then have "R x (Eps (R y))" using lem9 by simp
    then have "R (Eps (R y)) x" using R_sym by blast
    then have "R y x" using lem9 by simp
    then have "R x y" using R_sym by blast
    then have "ABS x = ABS y" using thm11 by simp
    then have "Abs (Rep a) = Abs (Rep b)" using eqs unfolding ABS_def by simp
    then show "a = b" using rep_inverse by simp
  next
    assume ab: "a = b"
    have "REFL R" using equiv EQUIV_REFL_SYM_TRANS[of R] by simp
    then show "R (REP a) (REP b)" unfolding REFL_def using ab by auto
  qed
  then show "R (REP a) (REP b) \<equiv> (a = b)" by simp
qed

end


section {* type definition for the quotient type *}

use "quotient.ML"

(* mapfuns for some standard types *)
setup {*
  maps_update @{type_name "list"} {mapfun = @{const_name "map"},      relfun = @{const_name "LIST_REL"}} #>
  maps_update @{type_name "*"}    {mapfun = @{const_name "prod_fun"}, relfun = @{const_name "prod_rel"}} #>
  maps_update @{type_name "fun"}  {mapfun = @{const_name "fun_map"},  relfun = @{const_name "FUN_REL"}}
*}


ML {* maps_lookup @{theory} @{type_name list} *}

ML {*
val no_vars = Thm.rule_attribute (fn context => fn th =>
  let
    val ctxt = Variable.set_body false (Context.proof_of context);
    val ((_, [th']), _) = Variable.import true [th] ctxt;
  in th' end);
*}

section {* various tests for quotient types*}
datatype trm =
  var  "nat"
| app  "trm" "trm"
| lam  "nat" "trm"

axiomatization
  RR :: "trm \<Rightarrow> trm \<Rightarrow> bool"
where
  r_eq: "EQUIV RR"

ML {* print_quotdata @{context} *}

quotient qtrm = trm / "RR"
  apply(rule r_eq)
  done

ML {* print_quotdata @{context} *}

typ qtrm
term Rep_qtrm
term REP_qtrm
term Abs_qtrm
term ABS_qtrm
thm QUOT_TYPE_qtrm
thm QUOTIENT_qtrm
thm REP_qtrm_def

(* Test interpretation *)
thm QUOT_TYPE_I_qtrm.thm11
thm QUOT_TYPE.thm11

print_theorems

thm Rep_qtrm

text {* another test *}
datatype 'a trm' =
  var'  "'a"
| app'  "'a trm'" "'a trm'"
| lam'  "'a" "'a trm'"

consts R' :: "'a trm' \<Rightarrow> 'a trm' \<Rightarrow> bool"
axioms r_eq': "EQUIV R'"

quotient qtrm' = "'a trm'" / "R'"
  apply(rule r_eq')
  done

print_theorems

term ABS_qtrm'
term REP_qtrm'
thm QUOT_TYPE_qtrm'
thm QUOTIENT_qtrm'
thm Rep_qtrm'


text {* a test with lists of terms *}
datatype t =
  vr "string"
| ap "t list"
| lm "string" "t"

consts Rt :: "t \<Rightarrow> t \<Rightarrow> bool"
axioms t_eq: "EQUIV Rt"

quotient qt = "t" / "Rt"
  by (rule t_eq)

section {* lifting of constants *}

ML {*
(* calculates the aggregate abs and rep functions for a given type; 
   repF is for constants' arguments; absF is for constants;
   function types need to be treated specially, since repF and absF
   change   
*)
datatype flag = absF | repF

fun negF absF = repF
  | negF repF = absF

fun get_fun flag rty qty lthy ty =
let
  val qty_name = Long_Name.base_name (fst (dest_Type qty))

  fun get_fun_aux s fs_tys =
  let
    val (fs, tys) = split_list fs_tys
    val (otys, ntys) = split_list tys
    val oty = Type (s, otys)
    val nty = Type (s, ntys)
    val ftys = map (op -->) tys
  in
   (case (maps_lookup (ProofContext.theory_of lthy) s) of
      SOME info => (list_comb (Const (#mapfun info, ftys ---> (oty --> nty)), fs), (oty, nty))
    | NONE      => raise ERROR ("no map association for type " ^ s))
  end

  fun get_fun_fun fs_tys =
  let
    val (fs, tys) = split_list fs_tys
    val ([oty1, oty2], [nty1, nty2]) = split_list tys
    val oty = nty1 --> oty2
    val nty = oty1 --> nty2
    val ftys = map (op -->) tys
  in
    (list_comb (Const (@{const_name "fun_map"}, ftys ---> oty --> nty), fs), (oty, nty))
  end

  fun get_const absF = (Const ("QuotMain.ABS_" ^ qty_name, rty --> qty), (rty, qty))
    | get_const repF = (Const ("QuotMain.REP_" ^ qty_name, qty --> rty), (qty, rty))

  fun mk_identity ty = Abs ("", ty, Bound 0)

in
  if ty = qty
  then (get_const flag)
  else (case ty of
          TFree _ => (mk_identity ty, (ty, ty))
        | Type (_, []) => (mk_identity ty, (ty, ty)) 
        | Type ("fun" , [ty1, ty2]) => 
                 get_fun_fun [get_fun (negF flag) rty qty lthy ty1, get_fun flag rty qty lthy ty2]
        | Type (s, tys) => get_fun_aux s (map (get_fun flag rty qty lthy) tys)
        | _ => raise ERROR ("no type variables")
       )
end
*}

ML {*
  get_fun repF @{typ t} @{typ qt} @{context} @{typ "((((qt \<Rightarrow> qt) \<Rightarrow> qt) \<Rightarrow> qt) list) * nat"}
  |> fst
  |> Syntax.string_of_term @{context}
  |> writeln
*}

ML {*
  get_fun absF @{typ t} @{typ qt} @{context} @{typ "qt * nat"}
  |> fst
  |> Syntax.string_of_term @{context}
  |> writeln
*}

ML {*
  get_fun absF @{typ t} @{typ qt} @{context} @{typ "(qt \<Rightarrow> qt) \<Rightarrow> qt"}
  |> fst
  |> Syntax.pretty_term @{context}
  |> Pretty.string_of
  |> writeln
*}

text {* produces the definition for a lifted constant *}

ML {*
fun get_const_def nconst oconst rty qty lthy =
let
  val ty = fastype_of nconst
  val (arg_tys, res_ty) = strip_type ty

  val fresh_args = arg_tys |> map (pair "x")
                           |> Variable.variant_frees lthy [nconst, oconst]
                           |> map Free

  val rep_fns = map (fst o get_fun repF rty qty lthy) arg_tys
  val abs_fn  = (fst o get_fun absF rty qty lthy) res_ty

in
  map (op $) (rep_fns ~~ fresh_args)
  |> curry list_comb oconst
  |> curry (op $) abs_fn
  |> fold_rev lambda fresh_args
end
*}

ML {*
fun exchange_ty rty qty ty =
  if ty = rty
  then qty
  else
    (case ty of
       Type (s, tys) => Type (s, map (exchange_ty rty qty) tys)
      | _ => ty
    )
*}

ML {*
fun make_const_def nconst_bname oconst mx rty qty lthy =
let
  val oconst_ty = fastype_of oconst
  val nconst_ty = exchange_ty rty qty oconst_ty
  val nconst = Const (Binding.name_of nconst_bname, nconst_ty)
  val def_trm = get_const_def nconst oconst rty qty lthy
in
  define (nconst_bname, mx, def_trm) lthy
end
*}

(* A test whether get_fun works properly
consts bla :: "(t \<Rightarrow> t) \<Rightarrow> t"
local_setup {*
  fn lthy => (Toplevel.program (fn () =>
    make_const_def @{binding bla'} @{term "bla"} NoSyn @{typ "t"} @{typ "qt"} lthy
  )) |> snd
*}
*)

local_setup {*
  make_const_def @{binding VR} @{term "vr"} NoSyn @{typ "t"} @{typ "qt"} #> snd #>
  make_const_def @{binding AP} @{term "ap"} NoSyn @{typ "t"} @{typ "qt"} #> snd #>
  make_const_def @{binding LM} @{term "lm"} NoSyn @{typ "t"} @{typ "qt"} #> snd
*}

term vr
term ap
term lm
thm VR_def AP_def LM_def
term LM
term VR
term AP

text {* a test with functions *}
datatype 'a t' =
  vr' "string"
| ap' "('a t') * ('a t')"
| lm' "'a" "string \<Rightarrow> ('a t')"

consts Rt' :: "('a t') \<Rightarrow> ('a t') \<Rightarrow> bool"
axioms t_eq': "EQUIV Rt'"

quotient qt' = "'a t'" / "Rt'"
  apply(rule t_eq')
  done

print_theorems

local_setup {*
  make_const_def @{binding VR'} @{term "vr'"} NoSyn @{typ "'a t'"} @{typ "'a qt'"} #> snd #>
  make_const_def @{binding AP'} @{term "ap'"} NoSyn @{typ "'a t'"} @{typ "'a qt'"} #> snd #>
  make_const_def @{binding LM'} @{term "lm'"} NoSyn @{typ "'a t'"} @{typ "'a qt'"} #> snd
*}

term vr'
term ap'
term ap'
thm VR'_def AP'_def LM'_def
term LM'
term VR'
term AP'

section {* ATOMIZE *}

text {*
  Unabs_def converts a definition given as

    c \<equiv> %x. %y. f x y

  to a theorem of the form

    c x y \<equiv> f x y

  This function is needed to rewrite the right-hand
  side to the left-hand side.
*}

ML {*
fun unabs_def ctxt def =
let
  val (lhs, rhs) = Thm.dest_equals (cprop_of def)
  val xs = strip_abs_vars (term_of rhs)
  val (_, ctxt') = Variable.add_fixes (map fst xs) ctxt

  val thy = ProofContext.theory_of ctxt'
  val cxs = map (cterm_of thy o Free) xs
  val new_lhs = Drule.list_comb (lhs, cxs)

  fun get_conv [] = Conv.rewr_conv def
    | get_conv (x::xs) = Conv.fun_conv (get_conv xs)
in
  get_conv xs new_lhs |>
  singleton (ProofContext.export ctxt' ctxt)
end
*}

lemma atomize_eqv[atomize]: 
  shows "(Trueprop A \<equiv> Trueprop B) \<equiv> (A \<equiv> B)" 
proof
  assume "A \<equiv> B" 
  then show "Trueprop A \<equiv> Trueprop B" by unfold
next
  assume *: "Trueprop A \<equiv> Trueprop B"
  have "A = B"
  proof (cases A)
    case True
    have "A" by fact
    then show "A = B" using * by simp
  next
    case False
    have "\<not>A" by fact
    then show "A = B" using * by auto
  qed
  then show "A \<equiv> B" by (rule eq_reflection)
qed

ML {*
fun atomize_thm thm =
let
  val thm' = forall_intr_vars thm
  val thm'' = ObjectLogic.atomize (cprop_of thm')
in
  Thm.freezeT (Simplifier.rewrite_rule [thm''] thm')
end
*}

ML {* atomize_thm @{thm list.induct} *}

section {* REGULARIZE *}

text {* tyRel takes a type and builds a relation that a quantifier over this
  type needs to respect. *}
ML {*
fun tyRel ty rty rel lthy =
  if ty = rty 
  then rel
  else (case ty of
          Type (s, tys) =>
            let
              val tys_rel = map (fn ty => ty --> ty --> @{typ bool}) tys;
              val ty_out = ty --> ty --> @{typ bool};
              val tys_out = tys_rel ---> ty_out;
            in
            (case (maps_lookup (ProofContext.theory_of lthy) s) of
               SOME (info) => list_comb (Const (#relfun info, tys_out), map (fn ty => tyRel ty rty rel lthy) tys)
             | NONE  => HOLogic.eq_const ty
            )
            end
        | _ => HOLogic.eq_const ty)
*}

ML {*
  cterm_of @{theory} (tyRel @{typ "trm \<Rightarrow> bool"} @{typ "trm"} @{term "RR"} @{context})
*}

definition
  Babs :: "('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b"
where
  "(x \<in> p) \<Longrightarrow> (Babs p m x = m x)"
(* TODO: Consider defining it with an "if"; sth like:
   Babs p m = \<lambda>x. if x \<in> p then m x else undefined
*)

ML {*
fun needs_lift (rty as Type (rty_s, _)) ty =
  case ty of
    Type (s, tys) =>
      (s = rty_s) orelse (exists (needs_lift rty) tys)
  | _ => false

*}

ML {*
(* trm \<Rightarrow> new_trm *)
fun regularise trm rty rel lthy =
  case trm of
    Abs (x, T, t) =>
      if (needs_lift rty T) then let
        val ([x'], lthy2) = Variable.variant_fixes [x] lthy;
        val v = Free (x', T);
        val t' = subst_bound (v, t);
        val rec_term = regularise t' rty rel lthy2;
        val lam_term = Term.lambda_name (x, v) rec_term;
        val sub_res_term = tyRel T rty rel lthy;
        val respects = Const (@{const_name Respects}, (fastype_of sub_res_term) --> T --> @{typ bool});
        val res_term = respects $ sub_res_term;
        val ty = fastype_of trm;
        val rabs = Const (@{const_name Babs}, (fastype_of res_term) --> ty --> ty);
        val rabs_term = (rabs $ res_term) $ lam_term;
      in
        rabs_term
      end else let
        val ([x'], lthy2) = Variable.variant_fixes [x] lthy;
        val v = Free (x', T);
        val t' = subst_bound (v, t);
        val rec_term = regularise t' rty rel lthy2;
      in
        Term.lambda_name (x, v) rec_term
      end
  | ((Const (@{const_name "All"}, at)) $ (Abs (x, T, t))) =>
      if (needs_lift rty T) then let
        val ([x'], lthy2) = Variable.variant_fixes [x] lthy;
        val v = Free (x', T);
        val t' = subst_bound (v, t);
        val rec_term = regularise t' rty rel lthy2;
        val lam_term = Term.lambda_name (x, v) rec_term;
        val sub_res_term = tyRel T rty rel lthy;
        val respects = Const (@{const_name Respects}, (fastype_of sub_res_term) --> T --> @{typ bool});
        val res_term = respects $ sub_res_term;
        val ty = fastype_of lam_term;
        val rall = Const (@{const_name Ball}, (fastype_of res_term) --> ty --> @{typ bool});
        val rall_term = (rall $ res_term) $ lam_term;
      in
        rall_term
      end else let
        val ([x'], lthy2) = Variable.variant_fixes [x] lthy;
        val v = Free (x', T);
        val t' = subst_bound (v, t);
        val rec_term = regularise t' rty rel lthy2;
        val lam_term = Term.lambda_name (x, v) rec_term
      in
        Const(@{const_name "All"}, at) $ lam_term
      end
  | ((Const (@{const_name "All"}, at)) $ P) =>
      let
        val (_, [al, _]) = dest_Type (fastype_of P);
        val ([x], lthy2) = Variable.variant_fixes [""] lthy;
        val v = (Free (x, al));
        val abs = Term.lambda_name (x, v) (P $ v);
      in regularise ((Const (@{const_name "All"}, at)) $ abs) rty rel lthy2 end
  | ((Const (@{const_name "Ex"}, at)) $ (Abs (x, T, t))) =>
      if (needs_lift rty T) then let
        val ([x'], lthy2) = Variable.variant_fixes [x] lthy;
        val v = Free (x', T);
        val t' = subst_bound (v, t);
        val rec_term = regularise t' rty rel lthy2;
        val lam_term = Term.lambda_name (x, v) rec_term;
        val sub_res_term = tyRel T rty rel lthy;
        val respects = Const (@{const_name Respects}, (fastype_of sub_res_term) --> T --> @{typ bool});
        val res_term = respects $ sub_res_term;
        val ty = fastype_of lam_term;
        val rall = Const (@{const_name Bex}, (fastype_of res_term) --> ty --> @{typ bool});
        val rall_term = (rall $ res_term) $ lam_term;
      in
        rall_term
      end else let
        val ([x'], lthy2) = Variable.variant_fixes [x] lthy;
        val v = Free (x', T);
        val t' = subst_bound (v, t);
        val rec_term = regularise t' rty rel lthy2;
        val lam_term = Term.lambda_name (x, v) rec_term
      in
        Const(@{const_name "Ex"}, at) $ lam_term
      end
  | ((Const (@{const_name "Ex"}, at)) $ P) =>
      let
        val (_, [al, _]) = dest_Type (fastype_of P);
        val ([x], lthy2) = Variable.variant_fixes [""] lthy;
        val v = (Free (x, al));
        val abs = Term.lambda_name (x, v) (P $ v);
      in regularise ((Const (@{const_name "Ex"}, at)) $ abs) rty rel lthy2 end
  | a $ b => (regularise a rty rel lthy) $ (regularise b rty rel lthy)
  | _ => trm

*}

ML {*
  cterm_of @{theory} (regularise @{term "\<lambda>x :: int. x"} @{typ "trm"} @{term "RR"} @{context});
  cterm_of @{theory} (regularise @{term "\<lambda>x :: trm. x"} @{typ "trm"} @{term "RR"} @{context});
  cterm_of @{theory} (regularise @{term "\<forall>x :: trm. P x"} @{typ "trm"} @{term "RR"} @{context});
  cterm_of @{theory} (regularise @{term "\<exists>x :: trm. P x"} @{typ "trm"} @{term "RR"} @{context});
  cterm_of @{theory} (regularise @{term "All (P :: trm \<Rightarrow> bool)"} @{typ "trm"} @{term "RR"} @{context});
*}

(* my version of regularise *)
(****************************)

(* some helper functions *)


ML {*
fun mk_babs ty ty' = Const (@{const_name "Babs"}, [ty' --> @{typ bool}, ty] ---> ty)
fun mk_ball ty = Const (@{const_name "Ball"}, [ty, ty] ---> @{typ bool})
fun mk_bex ty = Const (@{const_name "Bex"}, [ty, ty] ---> @{typ bool})
fun mk_resp ty = Const (@{const_name Respects}, [[ty, ty] ---> @{typ bool}, ty] ---> @{typ bool})
*}

(* applies f to the subterm of an abstractions, otherwise to the given term *)
ML {*
fun apply_subt f trm =
  case trm of
    Abs (x, T, t) => 
       let 
         val (x', t') = Term.dest_abs (x, T, t)
       in
         Term.absfree (x', T, f t') 
       end
  | _ => f trm
*}


(* FIXME: assumes always the typ is qty! *)
(* FIXME: if there are more than one quotient, then you have to look up the relation *)
ML {*
fun my_reg rel trm =
  case trm of
    Abs (x, T, t) =>
       let 
          val ty1 = fastype_of trm
       in
         (mk_babs ty1 T) $ (mk_resp T $ rel) $ (apply_subt (my_reg rel) trm)    
       end
  | Const (@{const_name "All"}, ty) $ t =>
       let 
          val ty1 = domain_type ty
          val ty2 = domain_type ty1
       in
         (mk_ball ty1) $ (mk_resp ty2 $ rel) $ (apply_subt (my_reg rel) t)      
       end
  | Const (@{const_name "Ex"}, ty) $ t =>
       let 
          val ty1 = domain_type ty
          val ty2 = domain_type ty1
       in
         (mk_bex ty1) $ (mk_resp ty2 $ rel) $ (apply_subt (my_reg rel) t)    
       end
  | t1 $ t2 => (my_reg rel t1) $ (my_reg rel t2)
  | _ => trm
*}

ML {*  
  cterm_of @{theory} (regularise @{term "\<exists>(y::trm). P (\<lambda>(x::trm). y)"} @{typ "trm"} 
     @{term "RR"} @{context});
  cterm_of @{theory} (my_reg @{term "RR"} @{term "\<exists>(y::trm). P (\<lambda>(x::trm). y)"})
*}

ML {*  
  cterm_of @{theory} (regularise @{term "\<lambda>x::trm. x"} @{typ "trm"} @{term "RR"} @{context});
  cterm_of @{theory} (my_reg @{term "RR"} @{term "\<lambda>x::trm. x"})
*}

ML {*  
  cterm_of @{theory} (regularise @{term "\<forall>(x::trm) (y::trm). P x y"} @{typ "trm"} @{term "RR"} @{context});
  cterm_of @{theory} (my_reg @{term "RR"} @{term "\<forall>(x::trm) (y::trm). P x y"})
*}

ML {*  
  cterm_of @{theory} (regularise @{term "\<forall>x::trm. P x"} @{typ "trm"} @{term "RR"} @{context});
  cterm_of @{theory} (my_reg @{term "RR"} @{term "\<forall>x::trm. P x"})
*}

ML {*  
  cterm_of @{theory} (regularise @{term "\<exists>x::trm. P x"} @{typ "trm"} @{term "RR"} @{context});
  cterm_of @{theory} (my_reg @{term "RR"} @{term "\<exists>x::trm. P x"})
*}

(* my version is not eta-expanded, but that should be OK *)
ML {*  
  cterm_of @{theory} (regularise @{term "All (P::trm \<Rightarrow> bool)"} @{typ "trm"} @{term "RR"} @{context});
  cterm_of @{theory} (my_reg @{term "RR"} @{term "All (P::trm \<Rightarrow> bool)"})
*}

(*fun prove_reg trm \<Rightarrow> thm (we might need some facts to do this)
  trm == new_trm
*)

text {* Assumes that the given theorem is atomized *}
ML {*
  fun build_regularize_goal thm rty rel lthy =
     Logic.mk_implies
       ((prop_of thm),
       (regularise (prop_of thm) rty rel lthy))
*}

section {* RepAbs injection *}

ML {*
fun build_repabs_term lthy thm constructors rty qty =
  let
    fun mk_rep tm =
      let
        val ty = exchange_ty rty qty (fastype_of tm)
      in fst (get_fun repF rty qty lthy ty) $ tm end

    fun mk_abs tm =
      let
        val ty = exchange_ty rty qty (fastype_of tm) in
      fst (get_fun absF rty qty lthy ty) $ tm end

    fun is_constructor (Const (x, _)) = member (op =) constructors x
      | is_constructor _ = false;

    fun build_aux lthy tm =
      case tm of
      Abs (a as (_, vty, _)) =>
      let
        val (vs, t) = Term.dest_abs a;
        val v = Free(vs, vty);
        val t' = lambda v (build_aux lthy t)
      in
      if (not (needs_lift rty (fastype_of tm))) then t'
      else mk_rep (mk_abs (
        if not (needs_lift rty vty) then t'
        else
          let
            val v' = mk_rep (mk_abs v);
            val t1 = Envir.beta_norm (t' $ v')
          in
            lambda v t1
          end
      ))
      end
    | x =>
      let
        val (opp, tms0) = Term.strip_comb tm
        val tms = map (build_aux lthy) tms0
        val ty = fastype_of tm
      in
        if (((fst (Term.dest_Const opp)) = @{const_name Respects}) handle _ => false)
          then (list_comb (opp, (hd tms0) :: (tl tms)))
      else if (is_constructor opp andalso needs_lift rty ty) then
          mk_rep (mk_abs (list_comb (opp,tms)))
        else if ((Term.is_Free opp) andalso (length tms > 0) andalso (needs_lift rty ty)) then
          mk_rep(mk_abs(list_comb(opp,tms)))
        else if tms = [] then opp
        else list_comb(opp, tms)
      end
  in
    build_aux lthy (Thm.prop_of thm)
  end
*}

text {* Assumes that it is given a regularized theorem *}
ML {*
fun build_repabs_goal ctxt thm cons rty qty =
  Logic.mk_equals ((Thm.prop_of thm), (build_repabs_term ctxt thm cons rty qty))
*}


section {* finite set example *}

inductive
  list_eq (infix "\<approx>" 50)
where
  "a#b#xs \<approx> b#a#xs"
| "[] \<approx> []"
| "xs \<approx> ys \<Longrightarrow> ys \<approx> xs"
| "a#a#xs \<approx> a#xs"
| "xs \<approx> ys \<Longrightarrow> a#xs \<approx> a#ys"
| "\<lbrakk>xs1 \<approx> xs2; xs2 \<approx> xs3\<rbrakk> \<Longrightarrow> xs1 \<approx> xs3"

lemma list_eq_refl:
  shows "xs \<approx> xs"
  apply (induct xs)
   apply (auto intro: list_eq.intros)
  done

lemma equiv_list_eq:
  shows "EQUIV list_eq"
  unfolding EQUIV_REFL_SYM_TRANS REFL_def SYM_def TRANS_def
  apply(auto intro: list_eq.intros list_eq_refl)
  done

quotient fset = "'a list" / "list_eq"
  apply(rule equiv_list_eq)
  done

print_theorems

typ "'a fset"
thm "Rep_fset"

local_setup {*
  make_const_def @{binding EMPTY} @{term "[]"} NoSyn @{typ "'a list"} @{typ "'a fset"} #> snd
*}

term Nil
term EMPTY
thm EMPTY_def


local_setup {*
  make_const_def @{binding INSERT} @{term "op #"} NoSyn @{typ "'a list"} @{typ "'a fset"} #> snd
*}

term Cons
term INSERT
thm INSERT_def

local_setup {*
  make_const_def @{binding UNION} @{term "op @"} NoSyn @{typ "'a list"} @{typ "'a fset"} #> snd
*}

term append
term UNION
thm UNION_def


thm QUOTIENT_fset

thm QUOT_TYPE_I_fset.thm11


fun
  membship :: "'a \<Rightarrow> 'a list \<Rightarrow> bool" (infix "memb" 100)
where
  m1: "(x memb []) = False"
| m2: "(x memb (y#xs)) = ((x=y) \<or> (x memb xs))"

fun
  card1 :: "'a list \<Rightarrow> nat"
where
  card1_nil: "(card1 []) = 0"
| card1_cons: "(card1 (x # xs)) = (if (x memb xs) then (card1 xs) else (Suc (card1 xs)))"

local_setup {*
  make_const_def @{binding card} @{term "card1"} NoSyn @{typ "'a list"} @{typ "'a fset"} #> snd
*}

term card1
term card
thm card_def

(* text {*
 Maybe make_const_def should require a theorem that says that the particular lifted function
 respects the relation. With it such a definition would be impossible:
 make_const_def @{binding CARD} @{term "length"} NoSyn @{typ "'a list"} @{typ "'a fset"} #> snd
*}*)

lemma card1_0:
  fixes a :: "'a list"
  shows "(card1 a = 0) = (a = [])"
  apply (induct a)
   apply (simp)
  apply (simp_all)
   apply meson
  apply (simp_all)
  done

lemma not_mem_card1:
  fixes x :: "'a"
  fixes xs :: "'a list"
  shows "~(x memb xs) \<Longrightarrow> card1 (x # xs) = Suc (card1 xs)"
  by simp


lemma mem_cons:
  fixes x :: "'a"
  fixes xs :: "'a list"
  assumes a : "x memb xs"
  shows "x # xs \<approx> xs"
  using a
  apply (induct xs)
  apply (auto intro: list_eq.intros)
  done

lemma card1_suc:
  fixes xs :: "'a list"
  fixes n :: "nat"
  assumes c: "card1 xs = Suc n"
  shows "\<exists>a ys. ~(a memb ys) \<and> xs \<approx> (a # ys)"
  using c
apply(induct xs)
apply (metis Suc_neq_Zero card1_0)
apply (metis QUOT_TYPE_I_fset.R_trans QuotMain.card1_cons list_eq_refl mem_cons)
done

primrec
  fold1
where
  "fold1 f (g :: 'a \<Rightarrow> 'b) (z :: 'b) [] = z"
| "fold1 f g z (a # A) =
     (if ((!u v. (f u v = f v u))
      \<and> (!u v w. ((f u (f v w) = f (f u v) w))))
     then (
       if (a memb A) then (fold1 f g z A) else (f (g a) (fold1 f g z A))
     ) else z)"

(* fold1_def is not usable, but: *)
thm fold1.simps

lemma fs1_strong_cases:
  fixes X :: "'a list"
  shows "(X = []) \<or> (\<exists>a. \<exists> Y. (~(a memb Y) \<and> (X \<approx> a # Y)))"
  apply (induct X)
  apply (simp)
  apply (metis QUOT_TYPE_I_fset.thm11 list_eq_refl mem_cons QuotMain.m1)
  done

local_setup {*
  make_const_def @{binding IN} @{term "membship"} NoSyn @{typ "'a list"} @{typ "'a fset"} #> snd
*}

term membship
term IN
thm IN_def

ML {*
  val consts = [@{const_name "Nil"}, @{const_name "Cons"},
                @{const_name "membship"}, @{const_name "card1"},
                @{const_name "append"}, @{const_name "fold1"}];
*}

ML {* val fset_defs = @{thms EMPTY_def IN_def UNION_def card_def INSERT_def} *}
ML {* val fset_defs_sym = map (fn t => symmetric (unabs_def @{context} t)) fset_defs *}

text {* Respectfullness *}

lemma mem_respects:
  fixes z
  assumes a: "list_eq x y"
  shows "(z memb x) = (z memb y)"
  using a by induct auto

lemma card1_rsp:
  fixes a b :: "'a list"
  assumes e: "a \<approx> b"
  shows "card1 a = card1 b"
  using e apply induct
  apply (simp_all add:mem_respects)
  done

lemma cons_preserves:
  fixes z
  assumes a: "xs \<approx> ys"
  shows "(z # xs) \<approx> (z # ys)"
  using a by (rule QuotMain.list_eq.intros(5))

lemma append_respects_fst:
  assumes a : "list_eq l1 l2"
  shows "list_eq (l1 @ s) (l2 @ s)"
  using a
  apply(induct)
  apply(auto intro: list_eq.intros)
  apply(simp add: list_eq_refl)
done

thm list.induct
lemma list_induct_hol4:
  fixes P :: "'a list \<Rightarrow> bool"
  assumes "((P []) \<and> (\<forall>t. (P t) \<longrightarrow> (\<forall>h. (P (h # t)))))"
  shows "(\<forall>l. (P l))"
  sorry

ML {* atomize_thm @{thm list_induct_hol4} *}

prove list_induct_r: {*
   build_regularize_goal (atomize_thm @{thm list_induct_hol4}) @{typ "'a List.list"} @{term "op \<approx>"} @{context} *}
  apply (simp only: equiv_res_forall[OF equiv_list_eq])
  thm RIGHT_RES_FORALL_REGULAR
  apply (rule RIGHT_RES_FORALL_REGULAR)
  prefer 2
  apply (assumption)
  apply (metis)
  done

ML {*
fun instantiate_tac thm = Subgoal.FOCUS (fn {concl, ...} =>
let
  val pat = Drule.strip_imp_concl (cprop_of thm)
  val insts = Thm.match (pat, concl)
in
  rtac (Drule.instantiate insts thm) 1
end
handle _ => no_tac
)
*}

ML {*
fun r_mk_comb_tac ctxt quot_thm reflex_thm trans_thm =
  (FIRST' [
    rtac @{thm FUN_QUOTIENT},
    rtac quot_thm,
    rtac @{thm IDENTITY_QUOTIENT},
    rtac @{thm card1_rsp},
      rtac @{thm ext},
      rtac trans_thm,
      instantiate_tac @{thm REP_ABS_RSP(1)} ctxt,
      instantiate_tac @{thm APPLY_RSP} ctxt,
      rtac reflex_thm,
      Cong_Tac.cong_tac @{thm cong},
      atac
    ])
*}

ML {*
fun r_mk_comb_tac_fset ctxt =
  r_mk_comb_tac ctxt @{thm QUOTIENT_fset} @{thm list_eq_refl} @{thm QUOT_TYPE_I_fset.R_trans2}
*}


ML {* val thm = @{thm list_induct_r} OF [atomize_thm @{thm list_induct_hol4}] *}
ML {* val trm_r = build_repabs_goal @{context} thm consts @{typ "'a list"} @{typ "'a fset"} *}
ML {* val trm = build_repabs_term @{context} thm consts @{typ "'a list"} @{typ "'a fset"} *}

prove list_induct_tr: trm_r
apply (atomize(full))
apply (simp only: id_def[symmetric])
(* APPLY_RSP_TAC *)
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
prefer 2
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
(* LAMBDA_RES_TAC *)
apply (simp only: FUN_REL.simps)
apply (rule allI)
apply (rule allI)
apply (rule impI)
(* MK_COMB_TAC *)
apply (tactic {* Cong_Tac.cong_tac @{thm cong} 1 *})
(* MK_COMB_TAC *)
apply (tactic {* Cong_Tac.cong_tac @{thm cong} 1 *})
(* REFL_TAC *)
apply (simp)
(* MK_COMB_TAC *)
apply (tactic {* Cong_Tac.cong_tac @{thm cong} 1 *})
(* MK_COMB_TAC *)
apply (tactic {* Cong_Tac.cong_tac @{thm cong} 1 *})
(* REFL_TAC *)
apply (simp)
(* APPLY_RSP_TAC *)
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (simp only: FUN_REL.simps)
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
(* TODO don't know how to handle ho_respects *)
apply (simp only: FUN_REL.simps)
apply (rule allI)
apply (rule allI)
apply (rule impI)
apply (tactic {* instantiate_tac @{thm RES_FORALL_RSP} @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (simp only: FUN_REL.simps)
(* ABS_REP_RSP *)
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
(* LAMBDA_RSP *)
apply (simp only: FUN_REL.simps)
apply (rule allI)
apply (rule allI)
apply (rule impI)
(* MK_COMB_TAC *)
apply (tactic {* Cong_Tac.cong_tac @{thm cong} 1 *})
(* MK_COMB_TAC *)
apply (tactic {* Cong_Tac.cong_tac @{thm cong} 1 *})
(* REFL_TAC *)
apply (simp)
(* APPLY_RSP *)
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
(* MINE *)
apply (simp only: FUN_REL.simps)
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
(* MK_COMB_TAC *)
apply (tactic {* Cong_Tac.cong_tac @{thm cong} 1 *})
(* REFL_TAC *)
apply (simp)
(* W(C (curry op THEN) (G... *)
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (simp only: FUN_REL.simps)
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
(* CONS respects *)
apply (simp add: FUN_REL.simps)
apply (rule allI)
apply (rule allI)
apply (rule allI)
apply (rule impI)
apply (rule cons_preserves)
apply (assumption)
apply (simp)
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (simp only: FUN_REL.simps)
apply (rule allI)
apply (rule allI)
apply (rule impI)
apply (tactic {* instantiate_tac @{thm RES_FORALL_RSP} @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (simp only: FUN_REL.simps)
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (simp only: FUN_REL.simps)
apply (rule allI)
apply (rule allI)
apply (rule impI)
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (tactic {* r_mk_comb_tac_fset @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (simp add: FUN_REL.simps)
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (simp only: FUN_REL.simps)
apply (rule allI)
apply (rule allI)
apply (rule impI)
apply (tactic {* instantiate_tac @{thm RES_FORALL_RSP} @{context} 1 *})
apply (tactic {* REPEAT_ALL_NEW (r_mk_comb_tac_fset @{context}) 1 *})
apply (simp only: FUN_REL.simps)
done

prove list_induct_t: trm
apply (simp only: list_induct_tr[symmetric])
apply (tactic {* rtac thm 1 *})
done

ML {* val nthm = MetaSimplifier.rewrite_rule fset_defs_sym (snd (no_vars (Context.Theory @{theory}, @{thm list_induct_t}))) *}

thm list.recs(2)


ML {* val card1_suc_f = Thm.freezeT (atomize_thm @{thm card1_suc}) *}

prove card1_suc_r: {*
 Logic.mk_implies
   ((prop_of card1_suc_f),
   (regularise (prop_of card1_suc_f) @{typ "'a List.list"} @{term "op \<approx>"} @{context})) *}
  apply (simp add: equiv_res_forall[OF equiv_list_eq] equiv_res_exists[OF equiv_list_eq])
  done

ML {* @{thm card1_suc_r} OF [card1_suc_f] *}

ML {* val li = Thm.freezeT (atomize_thm @{thm fold1.simps(2)}) *}
prove fold1_def_2_r: {*
 Logic.mk_implies
   ((prop_of li),
   (regularise (prop_of li) @{typ "'a List.list"} @{term "op \<approx>"} @{context})) *}
  apply (simp add: equiv_res_forall[OF equiv_list_eq])
  done

ML {* @{thm fold1_def_2_r} OF [li] *}


lemma yy:
  shows "(False = x memb []) = (False = IN (x::nat) EMPTY)"
unfolding IN_def EMPTY_def
apply(rule_tac f="(op =) False" in arg_cong)
apply(rule mem_respects)
apply(simp only: QUOT_TYPE_I_fset.REP_ABS_rsp)
apply(rule list_eq.intros)
done

lemma
  shows "IN (x::nat) EMPTY = False"
using m1
apply -
apply(rule yy[THEN iffD1, symmetric])
apply(simp)
done

lemma
  shows "((x=y) \<or> (IN x xs) = (IN (x::nat) (INSERT y xs))) =
         ((x=y) \<or> x memb REP_fset xs = x memb (y # REP_fset xs))"
unfolding IN_def INSERT_def
apply(rule_tac f="(op \<or>) (x=y)" in arg_cong)
apply(rule_tac f="(op =) (x memb REP_fset xs)" in arg_cong)
apply(rule mem_respects)
apply(rule list_eq.intros(3))
apply(unfold REP_fset_def ABS_fset_def)
apply(simp only: QUOT_TYPE.REP_ABS_rsp[OF QUOT_TYPE_fset])
apply(rule list_eq_refl)
done

lemma yyy:
  shows "
    (
     (UNION EMPTY s = s) &
     ((UNION (INSERT e s1) s2) = (INSERT e (UNION s1 s2)))
    ) = (
     ((ABS_fset ([] @ REP_fset s)) = s) &
     ((ABS_fset ((e # (REP_fset s1)) @ REP_fset s2)) = ABS_fset (e # (REP_fset s1 @ REP_fset s2)))
    )"
  unfolding UNION_def EMPTY_def INSERT_def
  apply(rule_tac f="(op &)" in arg_cong2)
  apply(rule_tac f="(op =)" in arg_cong2)
  apply(simp only: QUOT_TYPE_I_fset.thm11[symmetric])
  apply(rule append_respects_fst)
  apply(simp only: QUOT_TYPE_I_fset.REP_ABS_rsp)
  apply(rule list_eq_refl)
  apply(simp)
  apply(rule_tac f="(op =)" in arg_cong2)
  apply(simp only: QUOT_TYPE_I_fset.thm11[symmetric])
  apply(rule append_respects_fst)
  apply(simp only: QUOT_TYPE_I_fset.REP_ABS_rsp)
  apply(rule list_eq_refl)
  apply(simp only: QUOT_TYPE_I_fset.thm11[symmetric])
  apply(rule list_eq.intros(5))
  apply(simp only: QUOT_TYPE_I_fset.REP_ABS_rsp)
  apply(rule list_eq_refl)
done

lemma
  shows "
     (UNION EMPTY s = s) &
     ((UNION (INSERT e s1) s2) = (INSERT e (UNION s1 s2)))"
  apply (simp add: yyy)
  apply (simp add: QUOT_TYPE_I_fset.thm10)
  done

ML {*
  val m1_novars = snd(no_vars ((Context.Theory @{theory}), @{thm m2}))
*}

ML {*
cterm_of @{theory} (prop_of m1_novars);
cterm_of @{theory} (build_repabs_term @{context} m1_novars consts @{typ "'a list"} @{typ "'a fset"});
*}


(* Has all the theorems about fset plugged in. These should be parameters to the tactic *)
ML {*
  fun transconv_fset_tac' ctxt =
    (LocalDefs.unfold_tac @{context} fset_defs) THEN
    ObjectLogic.full_atomize_tac 1 THEN
    REPEAT_ALL_NEW (FIRST' [
      rtac @{thm list_eq_refl},
      rtac @{thm cons_preserves},
      rtac @{thm mem_respects},
      rtac @{thm card1_rsp},
      rtac @{thm QUOT_TYPE_I_fset.R_trans2},
      CHANGED o (simp_tac ((Simplifier.context ctxt HOL_ss) addsimps @{thms QUOT_TYPE_I_fset.REP_ABS_rsp})),
      Cong_Tac.cong_tac @{thm cong},
      rtac @{thm ext}
    ]) 1
*}

ML {*
  val m1_novars = snd(no_vars ((Context.Theory @{theory}), @{thm m1}))
  val goal = build_repabs_goal @{context} m1_novars consts @{typ "'a list"} @{typ "'a fset"}
  val cgoal = cterm_of @{theory} goal
  val cgoal2 = Thm.rhs_of (MetaSimplifier.rewrite false fset_defs_sym cgoal)
*}

(*notation ( output) "prop" ("#_" [1000] 1000) *)
notation ( output) "Trueprop" ("#_" [1000] 1000)


prove {* (Thm.term_of cgoal2) *}
  apply (tactic {* transconv_fset_tac' @{context} *})
  done

thm length_append (* Not true but worth checking that the goal is correct *)
ML {*
  val m1_novars = snd(no_vars ((Context.Theory @{theory}), @{thm length_append}))
  val goal = build_repabs_goal @{context} m1_novars consts @{typ "'a list"} @{typ "'a fset"}
  val cgoal = cterm_of @{theory} goal
  val cgoal2 = Thm.rhs_of (MetaSimplifier.rewrite false fset_defs_sym cgoal)
*}
prove {* Thm.term_of cgoal2 *}
  apply (tactic {* transconv_fset_tac' @{context} *})
  sorry

thm m2
ML {*
  val m1_novars = snd(no_vars ((Context.Theory @{theory}), @{thm m2}))
  val goal = build_repabs_goal @{context} m1_novars consts @{typ "'a list"} @{typ "'a fset"}
  val cgoal = cterm_of @{theory} goal
  val cgoal2 = Thm.rhs_of (MetaSimplifier.rewrite false fset_defs_sym cgoal)
*}
prove {* Thm.term_of cgoal2 *}
  apply (tactic {* transconv_fset_tac' @{context} *})
  done

thm list_eq.intros(4)
ML {*
  val m1_novars = snd(no_vars ((Context.Theory @{theory}), @{thm list_eq.intros(4)}))
  val goal = build_repabs_goal @{context} m1_novars consts @{typ "'a list"} @{typ "'a fset"}
  val cgoal = cterm_of @{theory} goal
  val cgoal2 = Thm.rhs_of (MetaSimplifier.rewrite false fset_defs_sym cgoal)
  val cgoal3 = Thm.rhs_of (MetaSimplifier.rewrite true @{thms QUOT_TYPE_I_fset.thm10} cgoal2)
*}

(* It is the same, but we need a name for it. *)
prove zzz : {* Thm.term_of cgoal3 *}
  apply (tactic {* transconv_fset_tac' @{context} *})
  done

(*lemma zzz' :
  "(REP_fset (INSERT a (INSERT a (ABS_fset xs))) \<approx> REP_fset (INSERT a (ABS_fset xs)))"
  using list_eq.intros(4) by (simp only: zzz)

thm QUOT_TYPE_I_fset.REPS_same
ML {* val zzz'' = MetaSimplifier.rewrite_rule @{thms QUOT_TYPE_I_fset.REPS_same} @{thm zzz'} *}
*)

thm list_eq.intros(5)
(* prove {* build_repabs_goal @{context} (atomize_thm @{thm list_eq.intros(5)}) consts @{typ "'a list"} @{typ "'a fset"} *} *)
ML {*
  val m1_novars = snd(no_vars ((Context.Theory @{theory}), @{thm list_eq.intros(5)}))
  val goal = build_repabs_goal @{context} m1_novars consts @{typ "'a list"} @{typ "'a fset"}
  val cgoal = cterm_of @{theory} goal
  val cgoal2 = Thm.rhs_of (MetaSimplifier.rewrite true fset_defs_sym cgoal)
*}
prove {* Thm.term_of cgoal2 *}
  apply (tactic {* transconv_fset_tac' @{context} *})
  done

ML {*
  fun lift_theorem_fset_aux thm lthy =
    let
      val ((_, [novars]), lthy2) = Variable.import true [thm] lthy;
      val goal = build_repabs_goal @{context} novars consts @{typ "'a list"} @{typ "'a fset"};
      val cgoal = cterm_of @{theory} goal;
      val cgoal2 = Thm.rhs_of (MetaSimplifier.rewrite true fset_defs_sym cgoal);
      val tac = transconv_fset_tac' @{context};
      val cthm = Goal.prove_internal [] cgoal2 (fn _ => tac);
      val nthm = MetaSimplifier.rewrite_rule [symmetric cthm] (snd (no_vars (Context.Theory @{theory}, thm)))
      val nthm2 = MetaSimplifier.rewrite_rule @{thms QUOT_TYPE_I_fset.REPS_same QUOT_TYPE_I_fset.thm10} nthm;
      val [nthm3] = ProofContext.export lthy2 lthy [nthm2]
    in
      nthm3
    end
*}

ML {* lift_theorem_fset_aux @{thm m1} @{context} *}

ML {*
  fun lift_theorem_fset name thm lthy =
    let
      val lifted_thm = lift_theorem_fset_aux thm lthy;
      val (_, lthy2) = note (name, lifted_thm) lthy;
    in
      lthy2
    end;
*}

(* These do not work without proper definitions to rewrite back *)
local_setup {* lift_theorem_fset @{binding "m1_lift"} @{thm m1} *}
local_setup {* lift_theorem_fset @{binding "leqi4_lift"} @{thm list_eq.intros(4)} *}
local_setup {* lift_theorem_fset @{binding "leqi5_lift"} @{thm list_eq.intros(5)} *}
local_setup {* lift_theorem_fset @{binding "m2_lift"} @{thm m2} *}
thm m1_lift
thm leqi4_lift
thm leqi5_lift
thm m2_lift
ML {* @{thm card1_suc_r} OF [card1_suc_f] *}
(*ML {* Toplevel.program (fn () => lift_theorem_fset @{binding "card_suc"}
     (@{thm card1_suc_r} OF [card1_suc_f]) @{context}) *}*)
(*local_setup {* lift_theorem_fset @{binding "card_suc"} @{thm card1_suc} *}*)

thm leqi4_lift
ML {*
  val (nam, typ) = hd (Term.add_vars (prop_of @{thm leqi4_lift}) [])
  val (_, l) = dest_Type typ
  val t = Type ("QuotMain.fset", l)
  val v = Var (nam, t)
  val cv = cterm_of @{theory} ((term_of @{cpat "REP_fset"}) $ v)
*}

ML {*
  Toplevel.program (fn () =>
    MetaSimplifier.rewrite_rule @{thms QUOT_TYPE_I_fset.thm10} (
      Drule.instantiate' [] [NONE, SOME (cv)] @{thm leqi4_lift}
    )
  )
*}



(*prove aaa: {* (Thm.term_of cgoal2) *}
  apply (tactic {* LocalDefs.unfold_tac @{context} fset_defs *} )
  apply (atomize(full))
  apply (tactic {* transconv_fset_tac' @{context} 1 *})
  done*)

(*
datatype obj1 =
  OVAR1 "string"
| OBJ1 "(string * (string \<Rightarrow> obj1)) list"
| INVOKE1 "obj1 \<Rightarrow> string"
| UPDATE1 "obj1 \<Rightarrow> string \<Rightarrow> (string \<Rightarrow> obj1)"
*)




end