src/HOL/Tools/Lifting/lifting_def.ML
author kuncar
Tue Nov 18 16:19:57 2014 +0100 (2014-11-18)
changeset 60219 2bce9a690b1e
parent 60218 7e24e172052e
child 60221 45545e6c0984
permissions -rw-r--r--
lift_definition: return the result of lifting
kuncar@47308
     1
(*  Title:      HOL/Tools/Lifting/lifting_def.ML
kuncar@47308
     2
    Author:     Ondrej Kuncar
kuncar@47308
     3
kuncar@47308
     4
Definitions for constants on quotient types.
kuncar@47308
     5
*)
kuncar@47308
     6
kuncar@47308
     7
signature LIFTING_DEF =
kuncar@47308
     8
sig
kuncar@60219
     9
  type lift_def
kuncar@60219
    10
  val rty_of_lift_def: lift_def -> typ
kuncar@60219
    11
  val qty_of_lift_def: lift_def -> typ
kuncar@60219
    12
  val rhs_of_lift_def: lift_def -> term
kuncar@60219
    13
  val lift_const_of_lift_def: lift_def -> term
kuncar@60219
    14
  val def_thm_of_lift_def: lift_def -> thm
kuncar@60219
    15
  val rsp_thm_of_lift_def: lift_def -> thm
kuncar@60219
    16
  val abs_eq_of_lift_def: lift_def -> thm
kuncar@60219
    17
  val rep_eq_of_lift_def: lift_def -> thm option
kuncar@60219
    18
  val transfer_rules_of_lift_def: lift_def -> thm list
kuncar@60219
    19
kuncar@51374
    20
  val generate_parametric_transfer_rule:
kuncar@51374
    21
    Proof.context -> thm -> thm -> thm
kuncar@51374
    22
kuncar@47308
    23
  val add_lift_def:
kuncar@60219
    24
    binding * mixfix -> typ -> term -> thm -> thm list -> local_theory -> lift_def * local_theory
kuncar@60218
    25
    
kuncar@60218
    26
  val lift_def: 
kuncar@60218
    27
    binding * mixfix -> typ -> term -> (Proof.context -> tactic) -> thm list -> 
kuncar@60219
    28
    local_theory -> lift_def * local_theory
kuncar@47308
    29
kuncar@47308
    30
  val lift_def_cmd:
wenzelm@58011
    31
    (binding * string option * mixfix) * string * (Facts.ref * Token.src list) list ->
wenzelm@58011
    32
    local_theory -> Proof.state
kuncar@47308
    33
kuncar@47308
    34
  val can_generate_code_cert: thm -> bool
kuncar@53651
    35
end
kuncar@47308
    36
kuncar@47308
    37
structure Lifting_Def: LIFTING_DEF =
kuncar@47308
    38
struct
kuncar@47308
    39
kuncar@47698
    40
open Lifting_Util
kuncar@47308
    41
kuncar@47308
    42
infix 0 MRSL
kuncar@47308
    43
kuncar@60219
    44
datatype lift_def = LIFT_DEF of {
kuncar@60219
    45
  rty: typ,
kuncar@60219
    46
  qty: typ,
kuncar@60219
    47
  rhs: term,
kuncar@60219
    48
  lift_const: term,
kuncar@60219
    49
  def_thm: thm,
kuncar@60219
    50
  rsp_thm: thm,
kuncar@60219
    51
  abs_eq: thm,
kuncar@60219
    52
  rep_eq: thm option,
kuncar@60219
    53
  transfer_rules: thm list
kuncar@60219
    54
};
kuncar@60219
    55
kuncar@60219
    56
fun rep_lift_def (LIFT_DEF lift_def) = lift_def;
kuncar@60219
    57
val rty_of_lift_def = #rty o rep_lift_def;
kuncar@60219
    58
val qty_of_lift_def = #qty o rep_lift_def;
kuncar@60219
    59
val rhs_of_lift_def = #rhs o rep_lift_def;
kuncar@60219
    60
val lift_const_of_lift_def = #lift_const o rep_lift_def;
kuncar@60219
    61
val def_thm_of_lift_def = #def_thm o rep_lift_def;
kuncar@60219
    62
val rsp_thm_of_lift_def = #rsp_thm o rep_lift_def;
kuncar@60219
    63
val abs_eq_of_lift_def = #abs_eq o rep_lift_def;
kuncar@60219
    64
val rep_eq_of_lift_def = #rep_eq o rep_lift_def;
kuncar@60219
    65
val transfer_rules_of_lift_def = #transfer_rules o rep_lift_def;
kuncar@60219
    66
kuncar@60219
    67
fun mk_lift_def rty qty rhs lift_const def_thm rsp_thm abs_eq rep_eq transfer_rules =
kuncar@60219
    68
  LIFT_DEF {rty = rty, qty = qty,
kuncar@60219
    69
            rhs = rhs, lift_const = lift_const,
kuncar@60219
    70
            def_thm = def_thm, rsp_thm = rsp_thm, abs_eq = abs_eq, rep_eq = rep_eq,
kuncar@60219
    71
            transfer_rules = transfer_rules };
kuncar@60219
    72
kuncar@51994
    73
(* Reflexivity prover *)
kuncar@51994
    74
kuncar@55609
    75
fun mono_eq_prover ctxt prop =
kuncar@51994
    76
  let
kuncar@56518
    77
    val refl_rules = Lifting_Info.get_reflexivity_rules ctxt
kuncar@56518
    78
    val transfer_rules = Transfer.get_transfer_raw ctxt
kuncar@56518
    79
    
wenzelm@59498
    80
    fun main_tac i = (REPEAT_ALL_NEW (DETERM o resolve_tac ctxt refl_rules) THEN_ALL_NEW 
wenzelm@59498
    81
      (REPEAT_ALL_NEW (DETERM o resolve_tac ctxt transfer_rules))) i
kuncar@51994
    82
  in
kuncar@56540
    83
    SOME (Goal.prove ctxt [] [] prop (K (main_tac 1)))
kuncar@55609
    84
      handle ERROR _ => NONE
kuncar@51994
    85
  end
kuncar@56518
    86
kuncar@57642
    87
fun try_prove_refl_rel ctxt rel =
kuncar@57642
    88
  let
kuncar@57642
    89
    fun mk_ge_eq x =
kuncar@57642
    90
      let
kuncar@57642
    91
        val T = fastype_of x
kuncar@57642
    92
      in
kuncar@57642
    93
        Const (@{const_name "less_eq"}, T --> T --> HOLogic.boolT) $ 
kuncar@57642
    94
          (Const (@{const_name HOL.eq}, T)) $ x
kuncar@57642
    95
      end;
kuncar@57642
    96
    val goal = HOLogic.mk_Trueprop (mk_ge_eq rel);
kuncar@57642
    97
  in
kuncar@57642
    98
     mono_eq_prover ctxt goal
kuncar@57642
    99
  end;
kuncar@57642
   100
kuncar@51994
   101
fun try_prove_reflexivity ctxt prop =
kuncar@55609
   102
  let
wenzelm@59630
   103
    val cprop = Thm.cterm_of ctxt prop
kuncar@55609
   104
    val rule = @{thm ge_eq_refl}
wenzelm@59582
   105
    val concl_pat = Drule.strip_imp_concl (Thm.cprop_of rule)
kuncar@55609
   106
    val insts = Thm.first_order_match (concl_pat, cprop)
kuncar@55609
   107
    val rule = Drule.instantiate_normalize insts rule
wenzelm@59582
   108
    val prop = hd (Thm.prems_of rule)
kuncar@55609
   109
  in
kuncar@55609
   110
    case mono_eq_prover ctxt prop of
kuncar@55610
   111
      SOME thm => SOME (thm RS rule)
kuncar@55609
   112
      | NONE => NONE
kuncar@55609
   113
  end
kuncar@51994
   114
kuncar@54335
   115
(* 
kuncar@54335
   116
  Generates a parametrized transfer rule.
kuncar@54335
   117
  transfer_rule - of the form T t f
kuncar@54335
   118
  parametric_transfer_rule - of the form par_R t' t
kuncar@54335
   119
  
kuncar@54947
   120
  Result: par_T t' f, after substituing op= for relations in par_R that relate
kuncar@54335
   121
    a type constructor to the same type constructor, it is a merge of (par_R' OO T) t' f
kuncar@54335
   122
    using Lifting_Term.merge_transfer_relations
kuncar@54335
   123
*)
kuncar@51374
   124
kuncar@51374
   125
fun generate_parametric_transfer_rule ctxt transfer_rule parametric_transfer_rule =
kuncar@51374
   126
  let
kuncar@51374
   127
    fun preprocess ctxt thm =
kuncar@51374
   128
      let
wenzelm@59582
   129
        val tm = (strip_args 2 o HOLogic.dest_Trueprop o Thm.concl_of) thm;
kuncar@51374
   130
        val param_rel = (snd o dest_comb o fst o dest_comb) tm;
kuncar@51374
   131
        val free_vars = Term.add_vars param_rel [];
kuncar@51374
   132
        
kuncar@51374
   133
        fun make_subst (var as (_, typ)) subst = 
kuncar@51374
   134
          let
kuncar@51374
   135
            val [rty, rty'] = binder_types typ
kuncar@51374
   136
          in
kuncar@51374
   137
            if (Term.is_TVar rty andalso is_Type rty') then
kuncar@51374
   138
              (Var var, HOLogic.eq_const rty')::subst
kuncar@51374
   139
            else
kuncar@51374
   140
              subst
kuncar@51374
   141
          end;
kuncar@51374
   142
        
kuncar@51374
   143
        val subst = fold make_subst free_vars [];
wenzelm@59630
   144
        val csubst = map (apply2 (Thm.cterm_of ctxt)) subst;
kuncar@51374
   145
        val inst_thm = Drule.cterm_instantiate csubst thm;
kuncar@51374
   146
      in
kuncar@51374
   147
        Conv.fconv_rule 
wenzelm@59582
   148
          ((Conv.concl_conv (Thm.nprems_of inst_thm) o
wenzelm@59582
   149
            HOLogic.Trueprop_conv o Conv.fun2_conv o Conv.arg1_conv)
wenzelm@54742
   150
            (Raw_Simplifier.rewrite ctxt false (Transfer.get_sym_relator_eq ctxt))) inst_thm
kuncar@51374
   151
      end
kuncar@51374
   152
wenzelm@59630
   153
    fun inst_relcomppI ctxt ant1 ant2 =
kuncar@51374
   154
      let
wenzelm@59582
   155
        val t1 = (HOLogic.dest_Trueprop o Thm.concl_of) ant1
wenzelm@59582
   156
        val t2 = (HOLogic.dest_Trueprop o Thm.prop_of) ant2
wenzelm@59630
   157
        val fun1 = Thm.cterm_of ctxt (strip_args 2 t1)
wenzelm@59630
   158
        val args1 = map (Thm.cterm_of ctxt) (get_args 2 t1)
wenzelm@59630
   159
        val fun2 = Thm.cterm_of ctxt (strip_args 2 t2)
wenzelm@59630
   160
        val args2 = map (Thm.cterm_of ctxt) (get_args 1 t2)
kuncar@51374
   161
        val relcomppI = Drule.incr_indexes2 ant1 ant2 @{thm relcomppI}
wenzelm@59582
   162
        val vars = (rev (Term.add_vars (Thm.prop_of relcomppI) []))
wenzelm@59630
   163
        val subst = map (apfst (Thm.cterm_of ctxt o Var)) (vars ~~ ([fun1] @ args1 @ [fun2] @ args2))
kuncar@51374
   164
      in
kuncar@51374
   165
        Drule.cterm_instantiate subst relcomppI
kuncar@51374
   166
      end
kuncar@51374
   167
wenzelm@54995
   168
    fun zip_transfer_rules ctxt thm =
wenzelm@54995
   169
      let
kuncar@51374
   170
        fun mk_POS ty = Const (@{const_name POS}, ty --> ty --> HOLogic.boolT)
wenzelm@59582
   171
        val rel = (Thm.dest_fun2 o Thm.dest_arg o Thm.cprop_of) thm
wenzelm@59586
   172
        val typ = Thm.typ_of_cterm rel
wenzelm@59630
   173
        val POS_const = Thm.cterm_of ctxt (mk_POS typ)
wenzelm@59630
   174
        val var = Thm.cterm_of ctxt (Var (("X", Thm.maxidx_of_cterm rel + 1), typ))
wenzelm@59582
   175
        val goal =
wenzelm@59630
   176
          Thm.apply (Thm.cterm_of ctxt HOLogic.Trueprop) (Thm.apply (Thm.apply POS_const rel) var)
kuncar@51374
   177
      in
kuncar@51374
   178
        [Lifting_Term.merge_transfer_relations ctxt goal, thm] MRSL @{thm POS_apply}
kuncar@51374
   179
      end
kuncar@51374
   180
     
wenzelm@59630
   181
    val thm =
wenzelm@59630
   182
      inst_relcomppI ctxt parametric_transfer_rule transfer_rule
wenzelm@59630
   183
        OF [parametric_transfer_rule, transfer_rule]
kuncar@51374
   184
    val preprocessed_thm = preprocess ctxt thm
kuncar@51374
   185
    val orig_ctxt = ctxt
kuncar@51374
   186
    val (fixed_thm, ctxt) = yield_singleton (apfst snd oo Variable.import true) preprocessed_thm ctxt
kuncar@51374
   187
    val assms = cprems_of fixed_thm
kuncar@51374
   188
    val add_transfer_rule = Thm.attribute_declaration Transfer.transfer_add
wenzelm@54995
   189
    val (prems, ctxt) = fold_map Thm.assume_hyps assms ctxt
wenzelm@54995
   190
    val ctxt = Context.proof_map (fold add_transfer_rule prems) ctxt
kuncar@51374
   191
    val zipped_thm =
kuncar@51374
   192
      fixed_thm
kuncar@51374
   193
      |> undisch_all
kuncar@51374
   194
      |> zip_transfer_rules ctxt
kuncar@51374
   195
      |> implies_intr_list assms
kuncar@51374
   196
      |> singleton (Variable.export ctxt orig_ctxt)
kuncar@51374
   197
  in
kuncar@51374
   198
    zipped_thm
kuncar@51374
   199
  end
kuncar@51374
   200
kuncar@51374
   201
fun print_generate_transfer_info msg = 
kuncar@51374
   202
  let
kuncar@51374
   203
    val error_msg = cat_lines 
kuncar@51374
   204
      ["Generation of a parametric transfer rule failed.",
kuncar@51374
   205
      (Pretty.string_of (Pretty.block
kuncar@51374
   206
         [Pretty.str "Reason:", Pretty.brk 2, msg]))]
kuncar@51374
   207
  in
kuncar@51374
   208
    error error_msg
kuncar@51374
   209
  end
kuncar@51374
   210
kuncar@53951
   211
fun map_ter _ x [] = x
kuncar@53951
   212
    | map_ter f _ xs = map f xs
kuncar@53951
   213
kuncar@53951
   214
fun generate_transfer_rules lthy quot_thm rsp_thm def_thm par_thms =
kuncar@51374
   215
  let
kuncar@51374
   216
    val transfer_rule =
kuncar@51374
   217
      ([quot_thm, rsp_thm, def_thm] MRSL @{thm Quotient_to_transfer})
kuncar@51374
   218
      |> Lifting_Term.parametrize_transfer_rule lthy
kuncar@51374
   219
  in
kuncar@53951
   220
    (map_ter (generate_parametric_transfer_rule lthy transfer_rule) [transfer_rule] par_thms
kuncar@53951
   221
    handle Lifting_Term.MERGE_TRANSFER_REL msg => (print_generate_transfer_info msg; [transfer_rule]))
kuncar@51374
   222
  end
kuncar@51374
   223
kuncar@47698
   224
(* Generation of the code certificate from the rsp theorem *)
kuncar@47308
   225
kuncar@47308
   226
fun get_body_types (Type ("fun", [_, U]), Type ("fun", [_, V])) = get_body_types (U, V)
kuncar@47308
   227
  | get_body_types (U, V)  = (U, V)
kuncar@47308
   228
kuncar@47308
   229
fun get_binder_types (Type ("fun", [T, U]), Type ("fun", [V, W])) = (T, V) :: get_binder_types (U, W)
kuncar@47308
   230
  | get_binder_types _ = []
kuncar@47308
   231
blanchet@55945
   232
fun get_binder_types_by_rel (Const (@{const_name "rel_fun"}, _) $ _ $ S) (Type ("fun", [T, U]), Type ("fun", [V, W])) = 
kuncar@47937
   233
    (T, V) :: get_binder_types_by_rel S (U, W)
kuncar@47937
   234
  | get_binder_types_by_rel _ _ = []
kuncar@47937
   235
blanchet@55945
   236
fun get_body_type_by_rel (Const (@{const_name "rel_fun"}, _) $ _ $ S) (Type ("fun", [_, U]), Type ("fun", [_, V])) = 
kuncar@47937
   237
    get_body_type_by_rel S (U, V)
kuncar@47937
   238
  | get_body_type_by_rel _ (U, V)  = (U, V)
kuncar@47937
   239
kuncar@57642
   240
fun get_binder_rels (Const (@{const_name "rel_fun"}, _) $ R $ S) = R :: get_binder_rels S
kuncar@57642
   241
  | get_binder_rels _ = []
kuncar@57642
   242
kuncar@47308
   243
fun force_rty_type ctxt rty rhs = 
kuncar@47308
   244
  let
kuncar@47308
   245
    val thy = Proof_Context.theory_of ctxt
kuncar@47308
   246
    val rhs_schematic = singleton (Variable.polymorphic ctxt) rhs
kuncar@47308
   247
    val rty_schematic = fastype_of rhs_schematic
kuncar@47308
   248
    val match = Sign.typ_match thy (rty_schematic, rty) Vartab.empty
kuncar@47308
   249
  in
kuncar@47308
   250
    Envir.subst_term_types match rhs_schematic
kuncar@47308
   251
  end
kuncar@47308
   252
kuncar@47308
   253
fun unabs_def ctxt def = 
kuncar@47308
   254
  let
wenzelm@59582
   255
    val (_, rhs) = Thm.dest_equals (Thm.cprop_of def)
kuncar@47308
   256
    fun dest_abs (Abs (var_name, T, _)) = (var_name, T)
kuncar@47308
   257
      | dest_abs tm = raise TERM("get_abs_var",[tm])
wenzelm@59582
   258
    val (var_name, T) = dest_abs (Thm.term_of rhs)
kuncar@47308
   259
    val (new_var_names, ctxt') = Variable.variant_fixes [var_name] ctxt
wenzelm@59630
   260
    val refl_thm = Thm.reflexive (Thm.cterm_of ctxt' (Free (hd new_var_names, T)))
kuncar@47308
   261
  in
kuncar@47308
   262
    Thm.combination def refl_thm |>
kuncar@47308
   263
    singleton (Proof_Context.export ctxt' ctxt)
kuncar@47308
   264
  end
kuncar@47308
   265
kuncar@47308
   266
fun unabs_all_def ctxt def = 
kuncar@47308
   267
  let
wenzelm@59582
   268
    val (_, rhs) = Thm.dest_equals (Thm.cprop_of def)
wenzelm@59582
   269
    val xs = strip_abs_vars (Thm.term_of rhs)
kuncar@47308
   270
  in  
kuncar@47308
   271
    fold (K (unabs_def ctxt)) xs def
kuncar@47308
   272
  end
kuncar@47308
   273
kuncar@47308
   274
val map_fun_unfolded = 
kuncar@47308
   275
  @{thm map_fun_def[abs_def]} |>
kuncar@47308
   276
  unabs_def @{context} |>
kuncar@47308
   277
  unabs_def @{context} |>
kuncar@47308
   278
  Local_Defs.unfold @{context} [@{thm comp_def}]
kuncar@47308
   279
kuncar@47308
   280
fun unfold_fun_maps ctm =
kuncar@47308
   281
  let
kuncar@47308
   282
    fun unfold_conv ctm =
kuncar@47308
   283
      case (Thm.term_of ctm) of
kuncar@47308
   284
        Const (@{const_name "map_fun"}, _) $ _ $ _ => 
kuncar@47308
   285
          (Conv.arg_conv unfold_conv then_conv Conv.rewr_conv map_fun_unfolded) ctm
kuncar@47308
   286
        | _ => Conv.all_conv ctm
kuncar@47308
   287
  in
kuncar@47937
   288
    (Conv.fun_conv unfold_conv) ctm
kuncar@47937
   289
  end
kuncar@47937
   290
kuncar@47937
   291
fun unfold_fun_maps_beta ctm =
kuncar@47937
   292
  let val try_beta_conv = Conv.try_conv (Thm.beta_conversion false)
kuncar@47937
   293
  in 
kuncar@47937
   294
    (unfold_fun_maps then_conv try_beta_conv) ctm 
kuncar@47308
   295
  end
kuncar@47308
   296
kuncar@47308
   297
fun prove_rel ctxt rsp_thm (rty, qty) =
kuncar@47308
   298
  let
kuncar@47308
   299
    val ty_args = get_binder_types (rty, qty)
kuncar@47308
   300
    fun disch_arg args_ty thm = 
kuncar@47308
   301
      let
kuncar@47504
   302
        val quot_thm = Lifting_Term.prove_quot_thm ctxt args_ty
kuncar@47308
   303
      in
kuncar@47308
   304
        [quot_thm, thm] MRSL @{thm apply_rsp''}
kuncar@47308
   305
      end
kuncar@47308
   306
  in
kuncar@47308
   307
    fold disch_arg ty_args rsp_thm
kuncar@47308
   308
  end
kuncar@47308
   309
kuncar@47308
   310
exception CODE_CERT_GEN of string
kuncar@47308
   311
kuncar@47308
   312
fun simplify_code_eq ctxt def_thm = 
kuncar@48024
   313
  Local_Defs.unfold ctxt [@{thm o_apply}, @{thm map_fun_def}, @{thm id_apply}] def_thm
kuncar@47308
   314
kuncar@47852
   315
(*
kuncar@47852
   316
  quot_thm - quotient theorem (Quotient R Abs Rep T).
kuncar@47852
   317
  returns: whether the Lifting package is capable to generate code for the abstract type
kuncar@47852
   318
    represented by quot_thm
kuncar@47852
   319
*)
kuncar@47852
   320
kuncar@47308
   321
fun can_generate_code_cert quot_thm  =
kuncar@47951
   322
  case quot_thm_rel quot_thm of
kuncar@47308
   323
    Const (@{const_name HOL.eq}, _) => true
kuncar@56519
   324
    | Const (@{const_name eq_onp}, _) $ _  => true
kuncar@47308
   325
    | _ => false
kuncar@47308
   326
kuncar@55610
   327
fun generate_rep_eq ctxt def_thm rsp_thm (rty, qty) =
kuncar@47308
   328
  let
kuncar@47937
   329
    val unfolded_def = Conv.fconv_rule (Conv.arg_conv unfold_fun_maps_beta) def_thm
kuncar@47308
   330
    val unabs_def = unabs_all_def ctxt unfolded_def
kuncar@55610
   331
  in  
kuncar@55610
   332
    if body_type rty = body_type qty then 
kuncar@55723
   333
      SOME (simplify_code_eq ctxt (unabs_def RS @{thm meta_eq_to_obj_eq}))
kuncar@55610
   334
    else 
kuncar@55610
   335
      let
kuncar@55610
   336
        val quot_thm = Lifting_Term.prove_quot_thm ctxt (get_body_types (rty, qty))
blanchet@55945
   337
        val rel_fun = prove_rel ctxt rsp_thm (rty, qty)
blanchet@55945
   338
        val rep_abs_thm = [quot_thm, rel_fun] MRSL @{thm Quotient_rep_abs_eq}
kuncar@55610
   339
      in
wenzelm@59582
   340
        case mono_eq_prover ctxt (hd (Thm.prems_of rep_abs_thm)) of
kuncar@55610
   341
          SOME mono_eq_thm =>
kuncar@55610
   342
            let
kuncar@55610
   343
              val rep_abs_eq = mono_eq_thm RS rep_abs_thm
wenzelm@59630
   344
              val rep = Thm.cterm_of ctxt (quot_thm_rep quot_thm)
kuncar@55610
   345
              val rep_refl = Thm.reflexive rep RS @{thm meta_eq_to_obj_eq}
kuncar@55610
   346
              val repped_eq = [rep_refl, unabs_def RS @{thm meta_eq_to_obj_eq}] MRSL @{thm cong}
kuncar@55610
   347
              val code_cert = [repped_eq, rep_abs_eq] MRSL trans
kuncar@55610
   348
            in
kuncar@55610
   349
              SOME (simplify_code_eq ctxt code_cert)
kuncar@55610
   350
            end
kuncar@55610
   351
          | NONE => NONE
kuncar@55610
   352
      end
kuncar@47308
   353
  end
kuncar@47308
   354
kuncar@47937
   355
fun generate_abs_eq ctxt def_thm rsp_thm quot_thm =
kuncar@47308
   356
  let
kuncar@47937
   357
    val abs_eq_with_assms =
kuncar@47937
   358
      let
kuncar@47951
   359
        val (rty, qty) = quot_thm_rty_qty quot_thm
kuncar@47951
   360
        val rel = quot_thm_rel quot_thm
kuncar@47937
   361
        val ty_args = get_binder_types_by_rel rel (rty, qty)
kuncar@47937
   362
        val body_type = get_body_type_by_rel rel (rty, qty)
kuncar@47937
   363
        val quot_ret_thm = Lifting_Term.prove_quot_thm ctxt body_type
kuncar@47937
   364
        
kuncar@47937
   365
        val rep_abs_folded_unmapped_thm = 
kuncar@47937
   366
          let
kuncar@47937
   367
            val rep_id = [quot_thm, def_thm] MRSL @{thm Quotient_Rep_eq}
wenzelm@59582
   368
            val ctm = Thm.dest_equals_lhs (Thm.cprop_of rep_id)
kuncar@47937
   369
            val unfolded_maps_eq = unfold_fun_maps ctm
kuncar@47937
   370
            val t1 = [quot_thm, def_thm, rsp_thm] MRSL @{thm Quotient_rep_abs_fold_unmap}
kuncar@47937
   371
            val prems_pat = (hd o Drule.cprems_of) t1
wenzelm@59582
   372
            val insts = Thm.first_order_match (prems_pat, Thm.cprop_of unfolded_maps_eq)
kuncar@47937
   373
          in
kuncar@47937
   374
            unfolded_maps_eq RS (Drule.instantiate_normalize insts t1)
kuncar@47937
   375
          end
kuncar@47937
   376
      in
kuncar@47937
   377
        rep_abs_folded_unmapped_thm
blanchet@55945
   378
        |> fold (fn _ => fn thm => thm RS @{thm rel_funD2}) ty_args
kuncar@47937
   379
        |> (fn x => x RS (@{thm Quotient_rel_abs2} OF [quot_ret_thm]))
kuncar@47937
   380
      end
kuncar@47937
   381
    
kuncar@57642
   382
    val prem_rels = get_binder_rels (quot_thm_rel quot_thm);
kuncar@57642
   383
    val proved_assms = prem_rels |> map (try_prove_refl_rel ctxt) 
kuncar@57642
   384
      |> map_index (apfst (fn x => x + 1)) |> filter (is_some o snd) |> map (apsnd the) 
kuncar@57642
   385
      |> map (apsnd (fn assm => assm RS @{thm ge_eq_refl}))
kuncar@57642
   386
    val abs_eq = fold_rev (fn (i, assm) => fn thm => assm RSN (i, thm)) proved_assms abs_eq_with_assms
kuncar@47308
   387
  in
kuncar@47937
   388
    simplify_code_eq ctxt abs_eq
kuncar@47937
   389
  end
kuncar@47937
   390
kuncar@47937
   391
kuncar@55724
   392
fun register_code_eq_thy abs_eq_thm opt_rep_eq_thm (rty, qty) thy =
kuncar@47937
   393
  let
kuncar@55724
   394
    fun no_abstr (t $ u) = no_abstr t andalso no_abstr u
kuncar@55724
   395
      | no_abstr (Abs (_, _, t)) = no_abstr t
kuncar@55724
   396
      | no_abstr (Const (name, _)) = not (Code.is_abstr thy name)
kuncar@55724
   397
      | no_abstr _ = true
kuncar@55724
   398
    fun is_valid_eq eqn = can (Code.assert_eqn thy) (mk_meta_eq eqn, true) 
wenzelm@59582
   399
      andalso no_abstr (Thm.prop_of eqn)
kuncar@55724
   400
    fun is_valid_abs_eq abs_eq = can (Code.assert_abs_eqn thy NONE) (mk_meta_eq abs_eq)
kuncar@47308
   401
kuncar@47308
   402
  in
kuncar@55724
   403
    if is_valid_eq abs_eq_thm then
kuncar@55724
   404
      Code.add_default_eqn abs_eq_thm thy
kuncar@47937
   405
    else
kuncar@55724
   406
      let
kuncar@55724
   407
        val (rty_body, qty_body) = get_body_types (rty, qty)
kuncar@47937
   408
      in
kuncar@55724
   409
        if rty_body = qty_body then
kuncar@55724
   410
         Code.add_default_eqn (the opt_rep_eq_thm) thy
kuncar@47937
   411
        else
kuncar@55724
   412
          if is_some opt_rep_eq_thm andalso is_valid_abs_eq (the opt_rep_eq_thm)
kuncar@55724
   413
          then
haftmann@59458
   414
            Code.add_abs_default_eqn (the opt_rep_eq_thm) thy
kuncar@55724
   415
          else
kuncar@55724
   416
            thy
kuncar@47937
   417
      end
kuncar@47937
   418
  end
kuncar@47308
   419
kuncar@55724
   420
local
wenzelm@59630
   421
  fun encode_code_eq ctxt abs_eq opt_rep_eq (rty, qty) = 
kuncar@55724
   422
    let
wenzelm@59630
   423
      fun mk_type typ = typ |> Logic.mk_type |> Thm.cterm_of ctxt |> Drule.mk_term
kuncar@55724
   424
    in
kuncar@55724
   425
      Conjunction.intr_balanced [abs_eq, (the_default TrueI opt_rep_eq), mk_type rty, mk_type qty]
kuncar@55724
   426
    end
kuncar@55724
   427
  
kuncar@57664
   428
  exception DECODE
kuncar@57664
   429
    
kuncar@55724
   430
  fun decode_code_eq thm =
wenzelm@59582
   431
    if Thm.nprems_of thm > 0 then raise DECODE 
kuncar@57664
   432
    else
kuncar@57664
   433
      let
kuncar@57664
   434
        val [abs_eq, rep_eq, rty, qty] = Conjunction.elim_balanced 4 thm
kuncar@57664
   435
        val opt_rep_eq = if Thm.eq_thm_prop (rep_eq, TrueI) then NONE else SOME rep_eq
wenzelm@59582
   436
        fun dest_type typ = typ |> Drule.dest_term |> Thm.term_of |> Logic.dest_type
kuncar@57664
   437
      in
kuncar@57664
   438
        (abs_eq, opt_rep_eq, (dest_type rty, dest_type qty)) 
kuncar@57664
   439
      end
kuncar@55724
   440
  
kuncar@55724
   441
  fun register_encoded_code_eq thm thy =
kuncar@55724
   442
    let
kuncar@55724
   443
      val (abs_eq_thm, opt_rep_eq_thm, (rty, qty)) = decode_code_eq thm
kuncar@55724
   444
    in
kuncar@55724
   445
      register_code_eq_thy abs_eq_thm opt_rep_eq_thm (rty, qty) thy
kuncar@55724
   446
    end
kuncar@57664
   447
    handle DECODE => thy
kuncar@55724
   448
  
kuncar@55724
   449
  val register_code_eq_attribute = Thm.declaration_attribute
kuncar@55724
   450
    (fn thm => Context.mapping (register_encoded_code_eq thm) I)
kuncar@55724
   451
  val register_code_eq_attrib = Attrib.internal (K register_code_eq_attribute)
kuncar@57663
   452
kuncar@57663
   453
  fun no_no_code ctxt (rty, qty) =
kuncar@57663
   454
    if same_type_constrs (rty, qty) then
kuncar@57663
   455
      forall (no_no_code ctxt) (Targs rty ~~ Targs qty)
kuncar@57663
   456
    else
kuncar@57663
   457
      if is_Type qty then
kuncar@57663
   458
        if Lifting_Info.is_no_code_type ctxt (Tname qty) then false
kuncar@57663
   459
        else 
kuncar@57663
   460
          let 
kuncar@57663
   461
            val (rty', rtyq) = Lifting_Term.instantiate_rtys ctxt (rty, qty)
kuncar@57663
   462
            val (rty's, rtyqs) = (Targs rty', Targs rtyq)
kuncar@57663
   463
          in
kuncar@57663
   464
            forall (no_no_code ctxt) (rty's ~~ rtyqs)
kuncar@57663
   465
          end
kuncar@57663
   466
      else
kuncar@57663
   467
        true
kuncar@55724
   468
in
kuncar@55724
   469
kuncar@55724
   470
fun register_code_eq abs_eq_thm opt_rep_eq_thm (rty, qty) lthy =
kuncar@55724
   471
  let
wenzelm@59630
   472
    val encoded_code_eq = encode_code_eq lthy abs_eq_thm opt_rep_eq_thm (rty, qty)
kuncar@55724
   473
  in
kuncar@57663
   474
    if no_no_code lthy (rty, qty) then 
kuncar@57663
   475
      (snd oo Local_Theory.note) ((Binding.empty, [register_code_eq_attrib]), [encoded_code_eq]) lthy
kuncar@57663
   476
    else
kuncar@57663
   477
      lthy
kuncar@55724
   478
  end
kuncar@55724
   479
end
kuncar@55724
   480
            
kuncar@47852
   481
(*
kuncar@47852
   482
  Defines an operation on an abstract type in terms of a corresponding operation 
kuncar@47852
   483
    on a representation type.
kuncar@47852
   484
kuncar@47852
   485
  var - a binding and a mixfix of the new constant being defined
kuncar@47852
   486
  qty - an abstract type of the new constant
kuncar@47852
   487
  rhs - a term representing the new constant on the raw level
kuncar@47937
   488
  rsp_thm - a respectfulness theorem in the internal tagged form (like '(R ===> R ===> R) f f'),
kuncar@47852
   489
    i.e. "(Lifting_Term.equiv_relation (fastype_of rhs, qty)) $ rhs $ rhs"
kuncar@54335
   490
  par_thms - a parametricity theorem for rhs
kuncar@47852
   491
*)
kuncar@47308
   492
kuncar@53951
   493
fun add_lift_def var qty rhs rsp_thm par_thms lthy =
kuncar@47308
   494
  let
kuncar@47308
   495
    val rty = fastype_of rhs
kuncar@47937
   496
    val quot_thm = Lifting_Term.prove_quot_thm lthy (rty, qty)
kuncar@47951
   497
    val absrep_trm =  quot_thm_abs quot_thm
kuncar@47308
   498
    val rty_forced = (domain_type o fastype_of) absrep_trm
kuncar@47308
   499
    val forced_rhs = force_rty_type lthy rty_forced rhs
wenzelm@53207
   500
    val lhs = Free (Binding.name_of (#1 var), qty)
kuncar@47308
   501
    val prop = Logic.mk_equals (lhs, absrep_trm $ forced_rhs)
kuncar@47308
   502
    val (_, prop') = Local_Defs.cert_def lthy prop
kuncar@47308
   503
    val (_, newrhs) = Local_Defs.abs_def prop'
kuncar@47308
   504
kuncar@60219
   505
    val ((lift_const, (_ , def_thm)), lthy') = 
kuncar@47308
   506
      Local_Theory.define (var, ((Thm.def_binding (#1 var), []), newrhs)) lthy
kuncar@47308
   507
kuncar@53951
   508
    val transfer_rules = generate_transfer_rules lthy' quot_thm rsp_thm def_thm par_thms
huffman@49975
   509
kuncar@47937
   510
    val abs_eq_thm = generate_abs_eq lthy' def_thm rsp_thm quot_thm
kuncar@51374
   511
    val opt_rep_eq_thm = generate_rep_eq lthy' def_thm rsp_thm (rty_forced, qty)
huffman@47351
   512
kuncar@47545
   513
    fun qualify defname suffix = Binding.qualified true suffix defname
kuncar@47308
   514
kuncar@47545
   515
    val lhs_name = (#1 var)
kuncar@47308
   516
    val rsp_thm_name = qualify lhs_name "rsp"
kuncar@47937
   517
    val abs_eq_thm_name = qualify lhs_name "abs_eq"
kuncar@47937
   518
    val rep_eq_thm_name = qualify lhs_name "rep_eq"
kuncar@51374
   519
    val transfer_rule_name = qualify lhs_name "transfer"
huffman@47373
   520
    val transfer_attr = Attrib.internal (K Transfer.transfer_add)
kuncar@60219
   521
    val lift_def = mk_lift_def rty_forced qty newrhs lift_const def_thm rsp_thm abs_eq_thm 
kuncar@60219
   522
      opt_rep_eq_thm transfer_rules 
kuncar@47308
   523
  in
kuncar@47308
   524
    lthy'
kuncar@47308
   525
      |> (snd oo Local_Theory.note) ((rsp_thm_name, []), [rsp_thm])
kuncar@53951
   526
      |> (snd oo Local_Theory.note) ((transfer_rule_name, [transfer_attr]), transfer_rules)
kuncar@47937
   527
      |> (snd oo Local_Theory.note) ((abs_eq_thm_name, []), [abs_eq_thm])
kuncar@51374
   528
      |> (case opt_rep_eq_thm of 
kuncar@47937
   529
            SOME rep_eq_thm => (snd oo Local_Theory.note) ((rep_eq_thm_name, []), [rep_eq_thm])
kuncar@47937
   530
            | NONE => I)
kuncar@55724
   531
      |> register_code_eq abs_eq_thm opt_rep_eq_thm (rty_forced, qty)
kuncar@60219
   532
      |> pair lift_def
kuncar@47308
   533
  end
kuncar@47308
   534
kuncar@55731
   535
local
kuncar@56519
   536
  val eq_onp_assms_tac_fixed_rules = map (Transfer.prep_transfer_domain_thm @{context})
kuncar@55731
   537
    [@{thm pcr_Domainp_total}, @{thm pcr_Domainp_par_left_total}, @{thm pcr_Domainp_par}, 
kuncar@55731
   538
      @{thm pcr_Domainp}]
kuncar@55731
   539
in
kuncar@47308
   540
fun mk_readable_rsp_thm_eq tm lthy =
kuncar@47308
   541
  let
wenzelm@59621
   542
    val ctm = Thm.cterm_of lthy tm
kuncar@47308
   543
    
kuncar@55731
   544
    fun assms_rewr_conv tactic rule ct =
kuncar@55731
   545
      let
kuncar@55731
   546
        fun prove_extra_assms thm =
kuncar@55731
   547
          let
kuncar@55731
   548
            val assms = cprems_of thm
kuncar@55731
   549
            fun finish thm = if Thm.no_prems thm then SOME (Goal.conclude thm) else NONE
kuncar@55731
   550
            fun prove ctm = Option.mapPartial finish (SINGLE tactic (Goal.init ctm))
kuncar@55731
   551
          in
kuncar@55731
   552
            map_interrupt prove assms
kuncar@55731
   553
          end
kuncar@55731
   554
    
wenzelm@59582
   555
        fun cconl_of thm = Drule.strip_imp_concl (Thm.cprop_of thm)
kuncar@55731
   556
        fun lhs_of thm = fst (Thm.dest_equals (cconl_of thm))
kuncar@55731
   557
        fun rhs_of thm = snd (Thm.dest_equals (cconl_of thm))
wenzelm@59586
   558
        val rule1 = Thm.incr_indexes (Thm.maxidx_of_cterm ct + 1) rule;
kuncar@55731
   559
        val lhs = lhs_of rule1;
kuncar@55731
   560
        val rule2 = Thm.rename_boundvars (Thm.term_of lhs) (Thm.term_of ct) rule1;
kuncar@55731
   561
        val rule3 =
kuncar@55731
   562
          Thm.instantiate (Thm.match (lhs, ct)) rule2
kuncar@55731
   563
            handle Pattern.MATCH => raise CTERM ("assms_rewr_conv", [lhs, ct]);
kuncar@55731
   564
        val proved_assms = prove_extra_assms rule3
kuncar@55731
   565
      in
kuncar@55731
   566
        case proved_assms of
kuncar@55731
   567
          SOME proved_assms =>
kuncar@55731
   568
            let
kuncar@55731
   569
              val rule3 = proved_assms MRSL rule3
kuncar@55731
   570
              val rule4 =
kuncar@55731
   571
                if lhs_of rule3 aconvc ct then rule3
kuncar@55731
   572
                else
kuncar@55731
   573
                  let val ceq = Thm.dest_fun2 (Thm.cprop_of rule3)
kuncar@55731
   574
                  in rule3 COMP Thm.trivial (Thm.mk_binop ceq ct (rhs_of rule3)) end
kuncar@55731
   575
            in Thm.transitive rule4 (Thm.beta_conversion true (rhs_of rule4)) end
kuncar@55731
   576
          | NONE => Conv.no_conv ct
kuncar@55731
   577
      end
kuncar@55731
   578
kuncar@55731
   579
    fun assms_rewrs_conv tactic rules = Conv.first_conv (map (assms_rewr_conv tactic) rules)
kuncar@55731
   580
kuncar@47308
   581
    fun simp_arrows_conv ctm =
kuncar@47308
   582
      let
kuncar@47308
   583
        val unfold_conv = Conv.rewrs_conv 
kuncar@56519
   584
          [@{thm rel_fun_eq_eq_onp[THEN eq_reflection]}, 
kuncar@56519
   585
            @{thm rel_fun_eq_onp_rel[THEN eq_reflection]},
blanchet@55945
   586
            @{thm rel_fun_eq[THEN eq_reflection]},
blanchet@55945
   587
            @{thm rel_fun_eq_rel[THEN eq_reflection]}, 
blanchet@55945
   588
            @{thm rel_fun_def[THEN eq_reflection]}]
kuncar@47308
   589
        fun binop_conv2 cv1 cv2 = Conv.combination_conv (Conv.arg_conv cv1) cv2
kuncar@56519
   590
        val eq_onp_assms_tac_rules = @{thm left_unique_OO} :: 
kuncar@56519
   591
            eq_onp_assms_tac_fixed_rules @ (Transfer.get_transfer_raw lthy)
wenzelm@59498
   592
        val eq_onp_assms_tac = (TRY o REPEAT_ALL_NEW (resolve_tac lthy eq_onp_assms_tac_rules) 
kuncar@55731
   593
          THEN_ALL_NEW (DETERM o Transfer.eq_tac lthy)) 1
kuncar@56519
   594
        val relator_eq_onp_conv = Conv.bottom_conv
kuncar@56519
   595
          (K (Conv.try_conv (assms_rewrs_conv eq_onp_assms_tac
kuncar@56519
   596
            (Lifting_Info.get_relator_eq_onp_rules lthy)))) lthy
kuncar@49626
   597
        val relator_eq_conv = Conv.bottom_conv
kuncar@49626
   598
          (K (Conv.try_conv (Conv.rewrs_conv (Transfer.get_relator_eq lthy)))) lthy
kuncar@47308
   599
      in
kuncar@47308
   600
        case (Thm.term_of ctm) of
blanchet@55945
   601
          Const (@{const_name "rel_fun"}, _) $ _ $ _ => 
kuncar@49626
   602
            (binop_conv2 simp_arrows_conv simp_arrows_conv then_conv unfold_conv) ctm
kuncar@56519
   603
          | _ => (relator_eq_onp_conv then_conv relator_eq_conv) ctm
kuncar@47308
   604
      end
kuncar@47937
   605
    
kuncar@47308
   606
    val unfold_ret_val_invs = Conv.bottom_conv 
kuncar@56524
   607
      (K (Conv.try_conv (Conv.rewr_conv @{thm eq_onp_same_args[THEN eq_reflection]}))) lthy
kuncar@55773
   608
    val unfold_inv_conv = 
kuncar@56519
   609
      Conv.top_sweep_conv (K (Conv.rewr_conv @{thm eq_onp_def[THEN eq_reflection]})) lthy
kuncar@56540
   610
    val simp_conv = HOLogic.Trueprop_conv (Conv.fun2_conv simp_arrows_conv)
kuncar@47308
   611
    val univq_conv = Conv.rewr_conv @{thm HOL.all_simps(6)[symmetric, THEN eq_reflection]}
kuncar@47308
   612
    val univq_prenex_conv = Conv.top_conv (K (Conv.try_conv univq_conv)) lthy
kuncar@47308
   613
    val beta_conv = Thm.beta_conversion true
kuncar@47308
   614
    val eq_thm = 
kuncar@55773
   615
      (simp_conv then_conv univq_prenex_conv then_conv beta_conv then_conv unfold_ret_val_invs
kuncar@55773
   616
         then_conv unfold_inv_conv) ctm
kuncar@47308
   617
  in
wenzelm@54742
   618
    Object_Logic.rulify lthy (eq_thm RS Drule.equal_elim_rule2)
kuncar@47308
   619
  end
kuncar@55731
   620
end
kuncar@47308
   621
kuncar@47607
   622
fun rename_to_tnames ctxt term =
kuncar@47607
   623
  let
wenzelm@56245
   624
    fun all_typs (Const (@{const_name Pure.all}, _) $ Abs (_, T, t)) = T :: all_typs t
kuncar@47607
   625
      | all_typs _ = []
kuncar@47308
   626
wenzelm@56245
   627
    fun rename (Const (@{const_name Pure.all}, T1) $ Abs (_, T2, t)) (new_name :: names) = 
wenzelm@56245
   628
        (Const (@{const_name Pure.all}, T1) $ Abs (new_name, T2, rename t names)) 
kuncar@47607
   629
      | rename t _ = t
kuncar@47607
   630
kuncar@47607
   631
    val (fixed_def_t, _) = yield_singleton (Variable.importT_terms) term ctxt
blanchet@58112
   632
    val new_names = Old_Datatype_Prop.make_tnames (all_typs fixed_def_t)
kuncar@47607
   633
  in
kuncar@47607
   634
    rename term new_names
kuncar@47607
   635
  end
kuncar@47308
   636
kuncar@56540
   637
(* This is not very cheap way of getting the rules but we have only few active
kuncar@56540
   638
  liftings in the current setting *)
kuncar@56540
   639
fun get_cr_pcr_eqs ctxt =
kuncar@56540
   640
  let
kuncar@56540
   641
    fun collect (data : Lifting_Info.quotient) l =
kuncar@56540
   642
      if is_some (#pcr_info data) 
kuncar@56540
   643
      then ((Thm.symmetric o safe_mk_meta_eq o #pcr_cr_eq o the o #pcr_info) data :: l) 
kuncar@56540
   644
      else l
kuncar@56540
   645
    val table = Lifting_Info.get_quotients ctxt
kuncar@56540
   646
  in
kuncar@56540
   647
    Symtab.fold (fn (_, data) => fn l => collect data l) table []
kuncar@56540
   648
  end
kuncar@56540
   649
kuncar@60218
   650
fun prepare_lift_def var qty rhs par_thms lthy =
kuncar@47308
   651
  let
kuncar@51994
   652
    val rsp_rel = Lifting_Term.equiv_relation lthy (fastype_of rhs, qty)
kuncar@47308
   653
    val rty_forced = (domain_type o fastype_of) rsp_rel;
kuncar@51994
   654
    val forced_rhs = force_rty_type lthy rty_forced rhs;
kuncar@56540
   655
    val cr_to_pcr_conv = HOLogic.Trueprop_conv (Conv.fun2_conv 
kuncar@56540
   656
      (Raw_Simplifier.rewrite lthy false (get_cr_pcr_eqs lthy)))
kuncar@56540
   657
    val (prsp_tm, rsp_prsp_eq) = HOLogic.mk_Trueprop (rsp_rel $ forced_rhs $ forced_rhs)
wenzelm@59621
   658
      |> Thm.cterm_of lthy
kuncar@56540
   659
      |> cr_to_pcr_conv
wenzelm@59582
   660
      |> `Thm.concl_of
kuncar@56540
   661
      |>> Logic.dest_equals
kuncar@56540
   662
      |>> snd
kuncar@56540
   663
    val to_rsp = rsp_prsp_eq RS Drule.equal_elim_rule2
kuncar@56540
   664
    val opt_proven_rsp_thm = try_prove_reflexivity lthy prsp_tm
kuncar@51994
   665
    
kuncar@51994
   666
    fun after_qed internal_rsp_thm lthy = 
kuncar@60218
   667
      add_lift_def var qty rhs (internal_rsp_thm RS to_rsp) par_thms lthy
kuncar@47308
   668
  in
kuncar@51374
   669
    case opt_proven_rsp_thm of
kuncar@60218
   670
      SOME thm => (NONE, K (after_qed thm))
kuncar@51994
   671
      | NONE =>  
kuncar@51994
   672
        let
kuncar@56540
   673
          val readable_rsp_thm_eq = mk_readable_rsp_thm_eq prsp_tm lthy
wenzelm@59582
   674
          val (readable_rsp_tm, _) = Logic.dest_implies (Thm.prop_of readable_rsp_thm_eq)
kuncar@51994
   675
          val readable_rsp_tm_tnames = rename_to_tnames lthy readable_rsp_tm
kuncar@51994
   676
      
kuncar@51994
   677
          fun after_qed' thm_list lthy = 
kuncar@51994
   678
            let
kuncar@56540
   679
              val internal_rsp_thm = Goal.prove lthy [] [] prsp_tm 
wenzelm@54742
   680
                  (fn {context = ctxt, ...} =>
wenzelm@54742
   681
                    rtac readable_rsp_thm_eq 1 THEN Proof_Context.fact_tac ctxt (hd thm_list) 1)
kuncar@51994
   682
            in
kuncar@51994
   683
              after_qed internal_rsp_thm lthy
kuncar@51994
   684
            end
kuncar@51994
   685
        in
kuncar@60218
   686
          (SOME readable_rsp_tm_tnames, after_qed')
kuncar@51994
   687
        end 
kuncar@47308
   688
  end
kuncar@47308
   689
kuncar@60218
   690
fun lift_def var qty rhs tac par_thms lthy =
kuncar@60218
   691
  let
kuncar@60218
   692
    val (goal, after_qed) = prepare_lift_def var qty rhs par_thms lthy
kuncar@60218
   693
  in
kuncar@60218
   694
    case goal of
kuncar@60218
   695
      SOME goal => 
kuncar@60218
   696
        let 
kuncar@60218
   697
          val rsp_thm = Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} => tac ctxt)
kuncar@60218
   698
            |> Thm.close_derivation
kuncar@60218
   699
        in
kuncar@60218
   700
          after_qed [[rsp_thm]] lthy
kuncar@60218
   701
        end
kuncar@60218
   702
      | NONE => after_qed [[Drule.dummy_thm]] lthy
kuncar@60218
   703
  end
kuncar@60218
   704
kuncar@60218
   705
(*
kuncar@60218
   706
kuncar@60218
   707
  lifting_definition command. It opens a proof of a corresponding respectfulness 
kuncar@60218
   708
  theorem in a user-friendly, readable form. Then add_lift_def is called internally.
kuncar@60218
   709
kuncar@60218
   710
*)
kuncar@60218
   711
kuncar@60218
   712
fun lift_def_cmd (raw_var, rhs_raw, par_xthms) lthy =
kuncar@60218
   713
  let
kuncar@60218
   714
    val ((binding, SOME qty, mx), lthy) = yield_singleton Proof_Context.read_vars raw_var lthy 
kuncar@60218
   715
    val var = (binding, mx)
kuncar@60218
   716
    val rhs = (Syntax.check_term lthy o Syntax.parse_term lthy) rhs_raw
kuncar@60218
   717
    val par_thms = Attrib.eval_thms lthy par_xthms
kuncar@60218
   718
    val (goal, after_qed) = prepare_lift_def var qty rhs par_thms lthy
kuncar@60218
   719
  in
kuncar@60219
   720
    Proof.theorem NONE (snd oo after_qed) [map (rpair []) (the_list goal)] lthy
kuncar@60218
   721
  end
kuncar@60218
   722
kuncar@47379
   723
fun quot_thm_err ctxt (rty, qty) pretty_msg =
kuncar@47379
   724
  let
kuncar@47379
   725
    val error_msg = cat_lines
kuncar@47379
   726
       ["Lifting failed for the following types:",
kuncar@47379
   727
        Pretty.string_of (Pretty.block
kuncar@47379
   728
         [Pretty.str "Raw type:", Pretty.brk 2, Syntax.pretty_typ ctxt rty]),
kuncar@47379
   729
        Pretty.string_of (Pretty.block
kuncar@47379
   730
         [Pretty.str "Abstract type:", Pretty.brk 2, Syntax.pretty_typ ctxt qty]),
kuncar@47379
   731
        "",
kuncar@47379
   732
        (Pretty.string_of (Pretty.block
kuncar@47379
   733
         [Pretty.str "Reason:", Pretty.brk 2, pretty_msg]))]
kuncar@47379
   734
  in
kuncar@47379
   735
    error error_msg
kuncar@47379
   736
  end
kuncar@47379
   737
kuncar@47504
   738
fun check_rty_err ctxt (rty_schematic, rty_forced) (raw_var, rhs_raw) =
kuncar@47379
   739
  let
kuncar@47504
   740
    val (_, ctxt') = yield_singleton Proof_Context.read_vars raw_var ctxt 
kuncar@47504
   741
    val rhs = (Syntax.check_term ctxt' o Syntax.parse_term ctxt') rhs_raw
kuncar@47379
   742
    val error_msg = cat_lines
kuncar@47379
   743
       ["Lifting failed for the following term:",
kuncar@47379
   744
        Pretty.string_of (Pretty.block
kuncar@47379
   745
         [Pretty.str "Term:", Pretty.brk 2, Syntax.pretty_term ctxt rhs]),
kuncar@47379
   746
        Pretty.string_of (Pretty.block
kuncar@47504
   747
         [Pretty.str "Type:", Pretty.brk 2, Syntax.pretty_typ ctxt rty_schematic]),
kuncar@47379
   748
        "",
kuncar@47379
   749
        (Pretty.string_of (Pretty.block
kuncar@47379
   750
         [Pretty.str "Reason:", 
kuncar@47379
   751
          Pretty.brk 2, 
kuncar@51957
   752
          Pretty.str "The type of the term cannot be instantiated to",
kuncar@47379
   753
          Pretty.brk 1,
kuncar@47504
   754
          Pretty.quote (Syntax.pretty_typ ctxt rty_forced),
kuncar@47379
   755
          Pretty.str "."]))]
kuncar@47379
   756
    in
kuncar@47379
   757
      error error_msg
kuncar@47379
   758
    end
kuncar@47379
   759
kuncar@53951
   760
fun lift_def_cmd_with_err_handling (raw_var, rhs_raw, par_xthms) lthy =
kuncar@53951
   761
  (lift_def_cmd (raw_var, rhs_raw, par_xthms) lthy
kuncar@47379
   762
    handle Lifting_Term.QUOT_THM (rty, qty, msg) => quot_thm_err lthy (rty, qty) msg)
kuncar@47504
   763
    handle Lifting_Term.CHECK_RTY (rty_schematic, rty_forced) => 
kuncar@47504
   764
      check_rty_err lthy (rty_schematic, rty_forced) (raw_var, rhs_raw)
kuncar@47379
   765
kuncar@47308
   766
(* parser and command *)
kuncar@47308
   767
val liftdef_parser =
kuncar@51374
   768
  (((Parse.binding -- (@{keyword "::"} |-- (Parse.typ >> SOME) -- Parse.opt_mixfix')) >> Parse.triple2)
kuncar@53951
   769
    --| @{keyword "is"} -- Parse.term -- 
wenzelm@58028
   770
      Scan.optional (@{keyword "parametric"} |-- Parse.!!! Parse.xthms1) []) >> Parse.triple1
kuncar@47308
   771
val _ =
wenzelm@59936
   772
  Outer_Syntax.local_theory_to_proof @{command_keyword lift_definition}
kuncar@47308
   773
    "definition for constants over the quotient type"
kuncar@47379
   774
      (liftdef_parser >> lift_def_cmd_with_err_handling)
kuncar@47308
   775
kuncar@47308
   776
kuncar@53651
   777
end (* structure *)