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