theory Lift
imports "../Nominal-General/Nominal2_Atoms" 
        "../Nominal-General/Nominal2_Eqvt" 
        "../Nominal-General/Nominal2_Supp" 
        "Abs" "Perm" "Equivp" "Rsp"
begin


ML {*
fun define_quotient_types binds tys alphas equivps ctxt =
let
  fun def_ty ((b, ty), (alpha, equivp)) ctxt =
    Quotient_Type.add_quotient_type ((([], b, NoSyn), (ty, alpha)), equivp) ctxt;
  val alpha_equivps = List.take (equivps, length alphas)
  val (thms, ctxt') = fold_map def_ty ((binds ~~ tys) ~~ (alphas ~~ alpha_equivps)) ctxt;
  val quot_thms = map fst thms;
  val quots = map (HOLogic.dest_Trueprop o prop_of) quot_thms;
  val reps = map (hd o rev o snd o strip_comb) quots;
  val qtys = map (domain_type o fastype_of) reps;
in
  (qtys, ctxt')
end
*}

(* Renames schematic variables in a theorem *)
ML {*
fun rename_vars fnctn thm =
let
  val vars = Term.add_vars (prop_of thm) []
  val nvars = map (Var o ((apfst o apfst) fnctn)) vars
in
  Thm.certify_instantiate ([], (vars ~~ nvars))  thm
end
*}

ML {*
fun un_raws name =
let
  fun un_raw name = unprefix "_raw" name handle Fail _ => name
  fun add_under names = hd names :: (map (prefix "_") (tl names))
in
  implode (map un_raw (add_under (space_explode "_" name)))
end
*}

(* Similar to Tools/IsaPlanner/rw_tools.ML *)
ML {*
fun rename_term_bvars (Abs(s, ty, t)) = (Abs(un_raws s, ty, rename_term_bvars t))
  | rename_term_bvars (a $ b) = (rename_term_bvars a) $ (rename_term_bvars b)
  | rename_term_bvars x = x;

fun rename_thm_bvars th =
let
  val t = Thm.prop_of th
in
  Thm.rename_boundvars t (rename_term_bvars t) th
end;
*}

ML {*
fun lift_thm qtys ctxt thm =
let
  val un_raw_names = rename_vars un_raws
in
  rename_thm_bvars (un_raw_names (Quotient_Tacs.lifted qtys ctxt thm))
end
*}

ML {*
fun define_fv_alpha_export dt binds bns ctxt =
let
  val (((fv_ts_loc, fv_def_loc), ord_fv_ts_loc), ctxt') =
    define_fv dt binds bns ctxt;
  val (alpha, ctxt'') =
    define_alpha dt binds bns fv_ts_loc ctxt';
  val alpha_ts_loc = #preds alpha
  val alpha_induct_loc = #induct alpha
  val alpha_intros_loc = #intrs alpha;
  val alpha_cases_loc = #elims alpha
  val morphism = ProofContext.export_morphism ctxt'' ctxt;
  val fv_ts = map (Morphism.term morphism) fv_ts_loc;
  val ord_fv_ts = map (Morphism.term morphism) ord_fv_ts_loc;
  val fv_def = Morphism.fact morphism fv_def_loc;
  val alpha_ts = map (Morphism.term morphism) alpha_ts_loc;
  val alpha_induct = Morphism.thm morphism alpha_induct_loc;
  val alpha_intros = Morphism.fact morphism alpha_intros_loc
  val alpha_cases = Morphism.fact morphism alpha_cases_loc
in
  ((((fv_ts, ord_fv_ts), fv_def), ((alpha_ts, alpha_intros), (alpha_cases, alpha_induct))), ctxt'')
end;
*}

end

