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