src/HOL/Tools/Lifting/lifting_def.ML
author wenzelm
Sat Dec 14 17:28:05 2013 +0100 (2013-12-14)
changeset 54742 7a86358a3c0b
parent 54335 03b10317ba78
child 54947 9e632948ed56
permissions -rw-r--r--
proper context for basic Simplifier operations: rewrite_rule, rewrite_goals_rule, rewrite_goals_tac etc.;
clarified tool context in some boundary cases;
     1 (*  Title:      HOL/Tools/Lifting/lifting_def.ML
     2     Author:     Ondrej Kuncar
     3 
     4 Definitions for constants on quotient types.
     5 *)
     6 
     7 signature LIFTING_DEF =
     8 sig
     9   val generate_parametric_transfer_rule:
    10     Proof.context -> thm -> thm -> thm
    11 
    12   val add_lift_def:
    13     (binding * mixfix) -> typ -> term -> thm -> thm list -> local_theory -> local_theory
    14 
    15   val lift_def_cmd:
    16     (binding * string option * mixfix) * string * (Facts.ref * Args.src list) list -> local_theory -> Proof.state
    17 
    18   val can_generate_code_cert: thm -> bool
    19 end
    20 
    21 structure Lifting_Def: LIFTING_DEF =
    22 struct
    23 
    24 open Lifting_Util
    25 
    26 infix 0 MRSL
    27 
    28 (* Reflexivity prover *)
    29 
    30 fun refl_tac ctxt =
    31   let
    32     fun intro_reflp_tac (ct, i) = 
    33     let
    34       val rule = Thm.incr_indexes (#maxidx (rep_cterm ct) + 1) @{thm reflpD}
    35       val concl_pat = Drule.strip_imp_concl (cprop_of rule)
    36       val insts = Thm.first_order_match (concl_pat, ct)
    37     in
    38       rtac (Drule.instantiate_normalize insts rule) i
    39     end
    40     handle Pattern.MATCH => no_tac
    41 
    42     val rules = @{thm is_equality_eq} ::
    43       ((Transfer.get_relator_eq_raw ctxt) @ (Lifting_Info.get_reflexivity_rules ctxt))
    44   in
    45     EVERY' [CSUBGOAL intro_reflp_tac, 
    46             REPEAT_ALL_NEW (resolve_tac rules)]
    47   end
    48     
    49 fun try_prove_reflexivity ctxt prop =
    50   SOME (Goal.prove ctxt [] [] prop (fn {context, ...} => refl_tac context 1))
    51     handle ERROR _ => NONE
    52 
    53 (* 
    54   Generates a parametrized transfer rule.
    55   transfer_rule - of the form T t f
    56   parametric_transfer_rule - of the form par_R t' t
    57   
    58   Result: par_T t' f, after substituing op= for relations in par_T that relate
    59     a type constructor to the same type constructor, it is a merge of (par_R' OO T) t' f
    60     using Lifting_Term.merge_transfer_relations
    61 *)
    62 
    63 fun generate_parametric_transfer_rule ctxt transfer_rule parametric_transfer_rule =
    64   let
    65     fun preprocess ctxt thm =
    66       let
    67         val tm = (strip_args 2 o HOLogic.dest_Trueprop o concl_of) thm;
    68         val param_rel = (snd o dest_comb o fst o dest_comb) tm;
    69         val thy = Proof_Context.theory_of ctxt;
    70         val free_vars = Term.add_vars param_rel [];
    71         
    72         fun make_subst (var as (_, typ)) subst = 
    73           let
    74             val [rty, rty'] = binder_types typ
    75           in
    76             if (Term.is_TVar rty andalso is_Type rty') then
    77               (Var var, HOLogic.eq_const rty')::subst
    78             else
    79               subst
    80           end;
    81         
    82         val subst = fold make_subst free_vars [];
    83         val csubst = map (pairself (cterm_of thy)) subst;
    84         val inst_thm = Drule.cterm_instantiate csubst thm;
    85       in
    86         Conv.fconv_rule 
    87           ((Conv.concl_conv (nprems_of inst_thm) o HOLogic.Trueprop_conv o Conv.fun2_conv o Conv.arg1_conv)
    88             (Raw_Simplifier.rewrite ctxt false (Transfer.get_sym_relator_eq ctxt))) inst_thm
    89       end
    90 
    91     fun inst_relcomppI thy ant1 ant2 =
    92       let
    93         val t1 = (HOLogic.dest_Trueprop o concl_of) ant1
    94         val t2 = (HOLogic.dest_Trueprop o prop_of) ant2
    95         val fun1 = cterm_of thy (strip_args 2 t1)
    96         val args1 = map (cterm_of thy) (get_args 2 t1)
    97         val fun2 = cterm_of thy (strip_args 2 t2)
    98         val args2 = map (cterm_of thy) (get_args 1 t2)
    99         val relcomppI = Drule.incr_indexes2 ant1 ant2 @{thm relcomppI}
   100         val vars = (rev (Term.add_vars (prop_of relcomppI) []))
   101         val subst = map (apfst ((cterm_of thy) o Var)) (vars ~~ ([fun1] @ args1 @ [fun2] @ args2))
   102       in
   103         Drule.cterm_instantiate subst relcomppI
   104       end
   105 
   106     fun zip_transfer_rules ctxt thm =       let
   107         val thy = Proof_Context.theory_of ctxt
   108         fun mk_POS ty = Const (@{const_name POS}, ty --> ty --> HOLogic.boolT)
   109         val rel = (Thm.dest_fun2 o Thm.dest_arg o cprop_of) thm
   110         val typ = (typ_of o ctyp_of_term) rel
   111         val POS_const = cterm_of thy (mk_POS typ)
   112         val var = cterm_of thy (Var (("X", #maxidx (rep_cterm (rel)) + 1), typ))
   113         val goal = Thm.apply (cterm_of thy HOLogic.Trueprop) (Thm.apply (Thm.apply POS_const rel) var)
   114       in
   115         [Lifting_Term.merge_transfer_relations ctxt goal, thm] MRSL @{thm POS_apply}
   116       end
   117      
   118     val thm = (inst_relcomppI (Proof_Context.theory_of ctxt) parametric_transfer_rule transfer_rule) 
   119                 OF [parametric_transfer_rule, transfer_rule]
   120     val preprocessed_thm = preprocess ctxt thm
   121     val orig_ctxt = ctxt
   122     val (fixed_thm, ctxt) = yield_singleton (apfst snd oo Variable.import true) preprocessed_thm ctxt
   123     val assms = cprems_of fixed_thm
   124     val add_transfer_rule = Thm.attribute_declaration Transfer.transfer_add
   125     val ctxt = Context.proof_map(fold (add_transfer_rule o Thm.assume) assms) ctxt
   126     val zipped_thm =
   127       fixed_thm
   128       |> undisch_all
   129       |> zip_transfer_rules ctxt
   130       |> implies_intr_list assms
   131       |> singleton (Variable.export ctxt orig_ctxt)
   132   in
   133     zipped_thm
   134   end
   135 
   136 fun print_generate_transfer_info msg = 
   137   let
   138     val error_msg = cat_lines 
   139       ["Generation of a parametric transfer rule failed.",
   140       (Pretty.string_of (Pretty.block
   141          [Pretty.str "Reason:", Pretty.brk 2, msg]))]
   142   in
   143     error error_msg
   144   end
   145 
   146 fun map_ter _ x [] = x
   147     | map_ter f _ xs = map f xs
   148 
   149 fun generate_transfer_rules lthy quot_thm rsp_thm def_thm par_thms =
   150   let
   151     val transfer_rule =
   152       ([quot_thm, rsp_thm, def_thm] MRSL @{thm Quotient_to_transfer})
   153       |> Lifting_Term.parametrize_transfer_rule lthy
   154   in
   155     (map_ter (generate_parametric_transfer_rule lthy transfer_rule) [transfer_rule] par_thms
   156     handle Lifting_Term.MERGE_TRANSFER_REL msg => (print_generate_transfer_info msg; [transfer_rule]))
   157   end
   158 
   159 (* Generation of the code certificate from the rsp theorem *)
   160 
   161 fun get_body_types (Type ("fun", [_, U]), Type ("fun", [_, V])) = get_body_types (U, V)
   162   | get_body_types (U, V)  = (U, V)
   163 
   164 fun get_binder_types (Type ("fun", [T, U]), Type ("fun", [V, W])) = (T, V) :: get_binder_types (U, W)
   165   | get_binder_types _ = []
   166 
   167 fun get_binder_types_by_rel (Const (@{const_name "fun_rel"}, _) $ _ $ S) (Type ("fun", [T, U]), Type ("fun", [V, W])) = 
   168     (T, V) :: get_binder_types_by_rel S (U, W)
   169   | get_binder_types_by_rel _ _ = []
   170 
   171 fun get_body_type_by_rel (Const (@{const_name "fun_rel"}, _) $ _ $ S) (Type ("fun", [_, U]), Type ("fun", [_, V])) = 
   172     get_body_type_by_rel S (U, V)
   173   | get_body_type_by_rel _ (U, V)  = (U, V)
   174 
   175 fun force_rty_type ctxt rty rhs = 
   176   let
   177     val thy = Proof_Context.theory_of ctxt
   178     val rhs_schematic = singleton (Variable.polymorphic ctxt) rhs
   179     val rty_schematic = fastype_of rhs_schematic
   180     val match = Sign.typ_match thy (rty_schematic, rty) Vartab.empty
   181   in
   182     Envir.subst_term_types match rhs_schematic
   183   end
   184 
   185 fun unabs_def ctxt def = 
   186   let
   187     val (_, rhs) = Thm.dest_equals (cprop_of def)
   188     fun dest_abs (Abs (var_name, T, _)) = (var_name, T)
   189       | dest_abs tm = raise TERM("get_abs_var",[tm])
   190     val (var_name, T) = dest_abs (term_of rhs)
   191     val (new_var_names, ctxt') = Variable.variant_fixes [var_name] ctxt
   192     val thy = Proof_Context.theory_of ctxt'
   193     val refl_thm = Thm.reflexive (cterm_of thy (Free (hd new_var_names, T)))
   194   in
   195     Thm.combination def refl_thm |>
   196     singleton (Proof_Context.export ctxt' ctxt)
   197   end
   198 
   199 fun unabs_all_def ctxt def = 
   200   let
   201     val (_, rhs) = Thm.dest_equals (cprop_of def)
   202     val xs = strip_abs_vars (term_of rhs)
   203   in  
   204     fold (K (unabs_def ctxt)) xs def
   205   end
   206 
   207 val map_fun_unfolded = 
   208   @{thm map_fun_def[abs_def]} |>
   209   unabs_def @{context} |>
   210   unabs_def @{context} |>
   211   Local_Defs.unfold @{context} [@{thm comp_def}]
   212 
   213 fun unfold_fun_maps ctm =
   214   let
   215     fun unfold_conv ctm =
   216       case (Thm.term_of ctm) of
   217         Const (@{const_name "map_fun"}, _) $ _ $ _ => 
   218           (Conv.arg_conv unfold_conv then_conv Conv.rewr_conv map_fun_unfolded) ctm
   219         | _ => Conv.all_conv ctm
   220   in
   221     (Conv.fun_conv unfold_conv) ctm
   222   end
   223 
   224 fun unfold_fun_maps_beta ctm =
   225   let val try_beta_conv = Conv.try_conv (Thm.beta_conversion false)
   226   in 
   227     (unfold_fun_maps then_conv try_beta_conv) ctm 
   228   end
   229 
   230 fun prove_rel ctxt rsp_thm (rty, qty) =
   231   let
   232     val ty_args = get_binder_types (rty, qty)
   233     fun disch_arg args_ty thm = 
   234       let
   235         val quot_thm = Lifting_Term.prove_quot_thm ctxt args_ty
   236       in
   237         [quot_thm, thm] MRSL @{thm apply_rsp''}
   238       end
   239   in
   240     fold disch_arg ty_args rsp_thm
   241   end
   242 
   243 exception CODE_CERT_GEN of string
   244 
   245 fun simplify_code_eq ctxt def_thm = 
   246   Local_Defs.unfold ctxt [@{thm o_apply}, @{thm map_fun_def}, @{thm id_apply}] def_thm
   247 
   248 (*
   249   quot_thm - quotient theorem (Quotient R Abs Rep T).
   250   returns: whether the Lifting package is capable to generate code for the abstract type
   251     represented by quot_thm
   252 *)
   253 
   254 fun can_generate_code_cert quot_thm  =
   255   case quot_thm_rel quot_thm of
   256     Const (@{const_name HOL.eq}, _) => true
   257     | Const (@{const_name invariant}, _) $ _  => true
   258     | _ => false
   259 
   260 fun generate_code_cert ctxt def_thm rsp_thm (rty, qty) =
   261   let
   262     val thy = Proof_Context.theory_of ctxt
   263     val quot_thm = Lifting_Term.prove_quot_thm ctxt (get_body_types (rty, qty))
   264     val fun_rel = prove_rel ctxt rsp_thm (rty, qty)
   265     val abs_rep_thm = [quot_thm, fun_rel] MRSL @{thm Quotient_rep_abs}
   266     val abs_rep_eq = 
   267       case (HOLogic.dest_Trueprop o prop_of) fun_rel of
   268         Const (@{const_name HOL.eq}, _) $ _ $ _ => abs_rep_thm
   269         | Const (@{const_name invariant}, _) $ _ $ _ $ _ => abs_rep_thm RS @{thm invariant_to_eq}
   270         | _ => raise CODE_CERT_GEN "relation is neither equality nor invariant"
   271     val unfolded_def = Conv.fconv_rule (Conv.arg_conv unfold_fun_maps_beta) def_thm
   272     val unabs_def = unabs_all_def ctxt unfolded_def
   273     val rep = (cterm_of thy o quot_thm_rep) quot_thm
   274     val rep_refl = Thm.reflexive rep RS @{thm meta_eq_to_obj_eq}
   275     val repped_eq = [rep_refl, unabs_def RS @{thm meta_eq_to_obj_eq}] MRSL @{thm cong}
   276     val code_cert = [repped_eq, abs_rep_eq] MRSL @{thm trans}
   277   in
   278     simplify_code_eq ctxt code_cert
   279   end
   280 
   281 fun generate_trivial_rep_eq ctxt def_thm =
   282   let
   283     val unfolded_def = Conv.fconv_rule (Conv.arg_conv unfold_fun_maps_beta) def_thm
   284     val code_eq = unabs_all_def ctxt unfolded_def
   285     val simp_code_eq = simplify_code_eq ctxt code_eq
   286   in
   287     simp_code_eq
   288   end
   289 
   290 fun generate_rep_eq ctxt def_thm rsp_thm (rty, qty) =
   291   if body_type rty = body_type qty then 
   292     SOME (generate_trivial_rep_eq ctxt def_thm)
   293   else 
   294     let
   295       val (rty_body, qty_body) = get_body_types (rty, qty)
   296       val quot_thm = Lifting_Term.prove_quot_thm ctxt (rty_body, qty_body)
   297     in
   298       if can_generate_code_cert quot_thm then
   299         SOME (generate_code_cert ctxt def_thm rsp_thm (rty, qty))
   300       else 
   301         NONE
   302     end
   303 
   304 fun generate_abs_eq ctxt def_thm rsp_thm quot_thm =
   305   let
   306     val abs_eq_with_assms =
   307       let
   308         val (rty, qty) = quot_thm_rty_qty quot_thm
   309         val rel = quot_thm_rel quot_thm
   310         val ty_args = get_binder_types_by_rel rel (rty, qty)
   311         val body_type = get_body_type_by_rel rel (rty, qty)
   312         val quot_ret_thm = Lifting_Term.prove_quot_thm ctxt body_type
   313         
   314         val rep_abs_folded_unmapped_thm = 
   315           let
   316             val rep_id = [quot_thm, def_thm] MRSL @{thm Quotient_Rep_eq}
   317             val ctm = Thm.dest_equals_lhs (cprop_of rep_id)
   318             val unfolded_maps_eq = unfold_fun_maps ctm
   319             val t1 = [quot_thm, def_thm, rsp_thm] MRSL @{thm Quotient_rep_abs_fold_unmap}
   320             val prems_pat = (hd o Drule.cprems_of) t1
   321             val insts = Thm.first_order_match (prems_pat, cprop_of unfolded_maps_eq)
   322           in
   323             unfolded_maps_eq RS (Drule.instantiate_normalize insts t1)
   324           end
   325       in
   326         rep_abs_folded_unmapped_thm
   327         |> fold (fn _ => fn thm => thm RS @{thm fun_relD2}) ty_args
   328         |> (fn x => x RS (@{thm Quotient_rel_abs2} OF [quot_ret_thm]))
   329       end
   330     
   331     val prems = prems_of abs_eq_with_assms
   332     val indexed_prems = map_index (apfst (fn x => x + 1)) prems
   333     val indexed_assms = map (apsnd (try_prove_reflexivity ctxt)) indexed_prems
   334     val proved_assms = map (apsnd the) (filter (is_some o snd) indexed_assms)
   335     val abs_eq = fold_rev (fn (i, assms) => fn thm => assms RSN (i, thm)) proved_assms abs_eq_with_assms
   336   in
   337     simplify_code_eq ctxt abs_eq
   338   end
   339 
   340 fun define_code_using_abs_eq abs_eq_thm lthy =
   341   if null (Logic.strip_imp_prems(prop_of abs_eq_thm)) then
   342     (snd oo Local_Theory.note) ((Binding.empty, [Code.add_default_eqn_attrib]), [abs_eq_thm]) lthy
   343   else
   344     lthy
   345   
   346 fun define_code_using_rep_eq opt_rep_eq_thm lthy = 
   347   case opt_rep_eq_thm of
   348     SOME rep_eq_thm =>   
   349       let
   350         val add_abs_eqn_attribute = 
   351           Thm.declaration_attribute (fn thm => Context.mapping (Code.add_abs_eqn thm) I)
   352         val add_abs_eqn_attrib = Attrib.internal (K add_abs_eqn_attribute);
   353       in
   354         (snd oo Local_Theory.note) ((Binding.empty, [add_abs_eqn_attrib]), [rep_eq_thm]) lthy
   355       end
   356     | NONE => lthy
   357 
   358 fun has_constr ctxt quot_thm =
   359   let
   360     val thy = Proof_Context.theory_of ctxt
   361     val abs_fun = quot_thm_abs quot_thm
   362   in
   363     if is_Const abs_fun then
   364       Code.is_constr thy ((fst o dest_Const) abs_fun)
   365     else
   366       false
   367   end
   368 
   369 fun has_abstr ctxt quot_thm =
   370   let
   371     val thy = Proof_Context.theory_of ctxt
   372     val abs_fun = quot_thm_abs quot_thm
   373   in
   374     if is_Const abs_fun then
   375       Code.is_abstr thy ((fst o dest_Const) abs_fun)
   376     else
   377       false
   378   end
   379 
   380 fun define_code abs_eq_thm opt_rep_eq_thm (rty, qty) lthy =
   381   let
   382     val (rty_body, qty_body) = get_body_types (rty, qty)
   383   in
   384     if rty_body = qty_body then
   385       if null (Logic.strip_imp_prems(prop_of abs_eq_thm)) then
   386         (snd oo Local_Theory.note) ((Binding.empty, [Code.add_default_eqn_attrib]), [abs_eq_thm]) lthy
   387       else
   388         (snd oo Local_Theory.note) ((Binding.empty, [Code.add_default_eqn_attrib]), [the opt_rep_eq_thm]) lthy
   389     else
   390       let 
   391         val body_quot_thm = Lifting_Term.prove_quot_thm lthy (rty_body, qty_body)
   392       in
   393         if has_constr lthy body_quot_thm then
   394           define_code_using_abs_eq abs_eq_thm lthy
   395         else if has_abstr lthy body_quot_thm then
   396           define_code_using_rep_eq opt_rep_eq_thm lthy
   397         else
   398           lthy
   399       end
   400   end
   401 
   402 (*
   403   Defines an operation on an abstract type in terms of a corresponding operation 
   404     on a representation type.
   405 
   406   var - a binding and a mixfix of the new constant being defined
   407   qty - an abstract type of the new constant
   408   rhs - a term representing the new constant on the raw level
   409   rsp_thm - a respectfulness theorem in the internal tagged form (like '(R ===> R ===> R) f f'),
   410     i.e. "(Lifting_Term.equiv_relation (fastype_of rhs, qty)) $ rhs $ rhs"
   411   par_thms - a parametricity theorem for rhs
   412 *)
   413 
   414 fun add_lift_def var qty rhs rsp_thm par_thms lthy =
   415   let
   416     val rty = fastype_of rhs
   417     val quot_thm = Lifting_Term.prove_quot_thm lthy (rty, qty)
   418     val absrep_trm =  quot_thm_abs quot_thm
   419     val rty_forced = (domain_type o fastype_of) absrep_trm
   420     val forced_rhs = force_rty_type lthy rty_forced rhs
   421     val lhs = Free (Binding.name_of (#1 var), qty)
   422     val prop = Logic.mk_equals (lhs, absrep_trm $ forced_rhs)
   423     val (_, prop') = Local_Defs.cert_def lthy prop
   424     val (_, newrhs) = Local_Defs.abs_def prop'
   425 
   426     val ((_, (_ , def_thm)), lthy') = 
   427       Local_Theory.define (var, ((Thm.def_binding (#1 var), []), newrhs)) lthy
   428 
   429     val transfer_rules = generate_transfer_rules lthy' quot_thm rsp_thm def_thm par_thms
   430 
   431     val abs_eq_thm = generate_abs_eq lthy' def_thm rsp_thm quot_thm
   432     val opt_rep_eq_thm = generate_rep_eq lthy' def_thm rsp_thm (rty_forced, qty)
   433 
   434     fun qualify defname suffix = Binding.qualified true suffix defname
   435 
   436     val lhs_name = (#1 var)
   437     val rsp_thm_name = qualify lhs_name "rsp"
   438     val abs_eq_thm_name = qualify lhs_name "abs_eq"
   439     val rep_eq_thm_name = qualify lhs_name "rep_eq"
   440     val transfer_rule_name = qualify lhs_name "transfer"
   441     val transfer_attr = Attrib.internal (K Transfer.transfer_add)
   442   in
   443     lthy'
   444       |> (snd oo Local_Theory.note) ((rsp_thm_name, []), [rsp_thm])
   445       |> (snd oo Local_Theory.note) ((transfer_rule_name, [transfer_attr]), transfer_rules)
   446       |> (snd oo Local_Theory.note) ((abs_eq_thm_name, []), [abs_eq_thm])
   447       |> (case opt_rep_eq_thm of 
   448             SOME rep_eq_thm => (snd oo Local_Theory.note) ((rep_eq_thm_name, []), [rep_eq_thm])
   449             | NONE => I)
   450       |> define_code abs_eq_thm opt_rep_eq_thm (rty_forced, qty)
   451   end
   452 
   453 fun mk_readable_rsp_thm_eq tm lthy =
   454   let
   455     val ctm = cterm_of (Proof_Context.theory_of lthy) tm
   456     
   457     fun simp_arrows_conv ctm =
   458       let
   459         val unfold_conv = Conv.rewrs_conv 
   460           [@{thm fun_rel_eq_invariant[THEN eq_reflection]}, 
   461             @{thm fun_rel_eq[THEN eq_reflection]},
   462             @{thm fun_rel_eq_rel[THEN eq_reflection]}, 
   463             @{thm fun_rel_def[THEN eq_reflection]}]
   464         fun binop_conv2 cv1 cv2 = Conv.combination_conv (Conv.arg_conv cv1) cv2
   465         val invariant_commute_conv = Conv.bottom_conv
   466           (K (Conv.try_conv (Conv.rewrs_conv (Lifting_Info.get_invariant_commute_rules lthy)))) lthy
   467         val relator_eq_conv = Conv.bottom_conv
   468           (K (Conv.try_conv (Conv.rewrs_conv (Transfer.get_relator_eq lthy)))) lthy
   469       in
   470         case (Thm.term_of ctm) of
   471           Const (@{const_name "fun_rel"}, _) $ _ $ _ => 
   472             (binop_conv2 simp_arrows_conv simp_arrows_conv then_conv unfold_conv) ctm
   473           | _ => (invariant_commute_conv then_conv relator_eq_conv) ctm
   474       end
   475     
   476     val unfold_ret_val_invs = Conv.bottom_conv 
   477       (K (Conv.try_conv (Conv.rewr_conv @{thm invariant_same_args}))) lthy 
   478     val simp_conv = HOLogic.Trueprop_conv (Conv.fun2_conv simp_arrows_conv)
   479     val univq_conv = Conv.rewr_conv @{thm HOL.all_simps(6)[symmetric, THEN eq_reflection]}
   480     val univq_prenex_conv = Conv.top_conv (K (Conv.try_conv univq_conv)) lthy
   481     val beta_conv = Thm.beta_conversion true
   482     val eq_thm = 
   483       (simp_conv then_conv univq_prenex_conv then_conv beta_conv then_conv unfold_ret_val_invs) ctm
   484   in
   485     Object_Logic.rulify lthy (eq_thm RS Drule.equal_elim_rule2)
   486   end
   487 
   488 fun rename_to_tnames ctxt term =
   489   let
   490     fun all_typs (Const ("all", _) $ Abs (_, T, t)) = T :: all_typs t
   491       | all_typs _ = []
   492 
   493     fun rename (Const ("all", T1) $ Abs (_, T2, t)) (new_name :: names) = 
   494         (Const ("all", T1) $ Abs (new_name, T2, rename t names)) 
   495       | rename t _ = t
   496 
   497     val (fixed_def_t, _) = yield_singleton (Variable.importT_terms) term ctxt
   498     val new_names = Datatype_Prop.make_tnames (all_typs fixed_def_t)
   499   in
   500     rename term new_names
   501   end
   502 
   503 (*
   504 
   505   lifting_definition command. It opens a proof of a corresponding respectfulness 
   506   theorem in a user-friendly, readable form. Then add_lift_def is called internally.
   507 
   508 *)
   509 
   510 fun lift_def_cmd (raw_var, rhs_raw, par_xthms) lthy =
   511   let
   512     val ((binding, SOME qty, mx), lthy) = yield_singleton Proof_Context.read_vars raw_var lthy 
   513     val rhs = (Syntax.check_term lthy o Syntax.parse_term lthy) rhs_raw
   514     val rsp_rel = Lifting_Term.equiv_relation lthy (fastype_of rhs, qty)
   515     val rty_forced = (domain_type o fastype_of) rsp_rel;
   516     val forced_rhs = force_rty_type lthy rty_forced rhs;
   517     val internal_rsp_tm = HOLogic.mk_Trueprop (rsp_rel $ forced_rhs $ forced_rhs)
   518     val opt_proven_rsp_thm = try_prove_reflexivity lthy internal_rsp_tm
   519     val par_thms = Attrib.eval_thms lthy par_xthms
   520     
   521     fun after_qed internal_rsp_thm lthy = 
   522       add_lift_def (binding, mx) qty rhs internal_rsp_thm par_thms lthy
   523 
   524   in
   525     case opt_proven_rsp_thm of
   526       SOME thm => Proof.theorem NONE (K (after_qed thm)) [] lthy
   527       | NONE =>  
   528         let
   529           val readable_rsp_thm_eq = mk_readable_rsp_thm_eq internal_rsp_tm lthy
   530           val (readable_rsp_tm, _) = Logic.dest_implies (prop_of readable_rsp_thm_eq)
   531           val readable_rsp_tm_tnames = rename_to_tnames lthy readable_rsp_tm
   532       
   533           fun after_qed' thm_list lthy = 
   534             let
   535               val internal_rsp_thm = Goal.prove lthy [] [] internal_rsp_tm 
   536                   (fn {context = ctxt, ...} =>
   537                     rtac readable_rsp_thm_eq 1 THEN Proof_Context.fact_tac ctxt (hd thm_list) 1)
   538             in
   539               after_qed internal_rsp_thm lthy
   540             end
   541         in
   542           Proof.theorem NONE after_qed' [[(readable_rsp_tm_tnames,[])]] lthy
   543         end 
   544   end
   545 
   546 fun quot_thm_err ctxt (rty, qty) pretty_msg =
   547   let
   548     val error_msg = cat_lines
   549        ["Lifting failed for the following types:",
   550         Pretty.string_of (Pretty.block
   551          [Pretty.str "Raw type:", Pretty.brk 2, Syntax.pretty_typ ctxt rty]),
   552         Pretty.string_of (Pretty.block
   553          [Pretty.str "Abstract type:", Pretty.brk 2, Syntax.pretty_typ ctxt qty]),
   554         "",
   555         (Pretty.string_of (Pretty.block
   556          [Pretty.str "Reason:", Pretty.brk 2, pretty_msg]))]
   557   in
   558     error error_msg
   559   end
   560 
   561 fun check_rty_err ctxt (rty_schematic, rty_forced) (raw_var, rhs_raw) =
   562   let
   563     val (_, ctxt') = yield_singleton Proof_Context.read_vars raw_var ctxt 
   564     val rhs = (Syntax.check_term ctxt' o Syntax.parse_term ctxt') rhs_raw
   565     val error_msg = cat_lines
   566        ["Lifting failed for the following term:",
   567         Pretty.string_of (Pretty.block
   568          [Pretty.str "Term:", Pretty.brk 2, Syntax.pretty_term ctxt rhs]),
   569         Pretty.string_of (Pretty.block
   570          [Pretty.str "Type:", Pretty.brk 2, Syntax.pretty_typ ctxt rty_schematic]),
   571         "",
   572         (Pretty.string_of (Pretty.block
   573          [Pretty.str "Reason:", 
   574           Pretty.brk 2, 
   575           Pretty.str "The type of the term cannot be instantiated to",
   576           Pretty.brk 1,
   577           Pretty.quote (Syntax.pretty_typ ctxt rty_forced),
   578           Pretty.str "."]))]
   579     in
   580       error error_msg
   581     end
   582 
   583 fun lift_def_cmd_with_err_handling (raw_var, rhs_raw, par_xthms) lthy =
   584   (lift_def_cmd (raw_var, rhs_raw, par_xthms) lthy
   585     handle Lifting_Term.QUOT_THM (rty, qty, msg) => quot_thm_err lthy (rty, qty) msg)
   586     handle Lifting_Term.CHECK_RTY (rty_schematic, rty_forced) => 
   587       check_rty_err lthy (rty_schematic, rty_forced) (raw_var, rhs_raw)
   588 
   589 (* parser and command *)
   590 val liftdef_parser =
   591   (((Parse.binding -- (@{keyword "::"} |-- (Parse.typ >> SOME) -- Parse.opt_mixfix')) >> Parse.triple2)
   592     --| @{keyword "is"} -- Parse.term -- 
   593       Scan.optional (@{keyword "parametric"} |-- Parse.!!! Parse_Spec.xthms1) []) >> Parse.triple1
   594 val _ =
   595   Outer_Syntax.local_theory_to_proof @{command_spec "lift_definition"}
   596     "definition for constants over the quotient type"
   597       (liftdef_parser >> lift_def_cmd_with_err_handling)
   598 
   599 
   600 end (* structure *)