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