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