src/HOL/Tools/Lifting/lifting_def.ML
author Walther Neuper <wneuper@ist.tugraz.at>
Sat, 05 Dec 2015 16:09:41 +0100
changeset 59180 85ec71012df8
parent 59006 179b9c43fe84
child 59324 ec559c6ab5ba
permissions -rw-r--r--
switched from Isabelle2014 to Isabelle2015, intermediate state

Note: we dropped jEditC, since libisabelle took over.
kuncar@48153
     1
(*  Title:      HOL/Tools/Lifting/lifting_def.ML
kuncar@48153
     2
    Author:     Ondrej Kuncar
kuncar@48153
     3
kuncar@48153
     4
Definitions for constants on quotient types.
kuncar@48153
     5
*)
kuncar@48153
     6
kuncar@48153
     7
signature LIFTING_DEF =
kuncar@48153
     8
sig
wneuper@59180
     9
  datatype code_eq = UNKNOWN_EQ | NONE_EQ | ABS_EQ | REP_EQ
wneuper@59180
    10
  type lift_def
wneuper@59180
    11
  val rty_of_lift_def: lift_def -> typ
wneuper@59180
    12
  val qty_of_lift_def: lift_def -> typ
wneuper@59180
    13
  val rhs_of_lift_def: lift_def -> term
wneuper@59180
    14
  val lift_const_of_lift_def: lift_def -> term
wneuper@59180
    15
  val def_thm_of_lift_def: lift_def -> thm
wneuper@59180
    16
  val rsp_thm_of_lift_def: lift_def -> thm
wneuper@59180
    17
  val abs_eq_of_lift_def: lift_def -> thm
wneuper@59180
    18
  val rep_eq_of_lift_def: lift_def -> thm option
wneuper@59180
    19
  val code_eq_of_lift_def: lift_def -> code_eq
wneuper@59180
    20
  val transfer_rules_of_lift_def: lift_def -> thm list
wneuper@59180
    21
  val morph_lift_def: morphism -> lift_def -> lift_def
wneuper@59180
    22
  val inst_of_lift_def: Proof.context -> typ -> lift_def -> lift_def
wneuper@59180
    23
  val mk_lift_const_of_lift_def: typ -> lift_def -> term
wneuper@59180
    24
wneuper@59180
    25
  type config = { notes: bool }
wneuper@59180
    26
  val map_config: (bool -> bool) -> config -> config
wneuper@59180
    27
  val default_config: config
wneuper@59180
    28
kuncar@52511
    29
  val generate_parametric_transfer_rule:
kuncar@52511
    30
    Proof.context -> thm -> thm -> thm
kuncar@52511
    31
wneuper@59180
    32
  val add_lift_def: 
wneuper@59180
    33
    config -> binding * mixfix -> typ -> term -> thm -> thm list -> local_theory -> 
wneuper@59180
    34
      lift_def * local_theory
wneuper@59180
    35
  
wneuper@59180
    36
  val prepare_lift_def:
wneuper@59180
    37
    (binding * mixfix -> typ -> term -> thm -> thm list -> Proof.context -> 
wneuper@59180
    38
      lift_def * local_theory) -> 
wneuper@59180
    39
    binding * mixfix -> typ -> term -> thm list -> local_theory -> 
wneuper@59180
    40
    term option * (thm -> Proof.context -> lift_def * local_theory)
kuncar@48153
    41
wneuper@59180
    42
  val gen_lift_def:
wneuper@59180
    43
    (binding * mixfix -> typ -> term -> thm -> thm list -> local_theory -> 
wneuper@59180
    44
      lift_def * local_theory) -> 
wneuper@59180
    45
    binding * mixfix -> typ -> term -> (Proof.context -> tactic) -> thm list -> 
wneuper@59180
    46
    local_theory -> lift_def * local_theory
wneuper@59180
    47
wneuper@59180
    48
  val lift_def: 
wneuper@59180
    49
    config -> binding * mixfix -> typ -> term -> (Proof.context -> tactic) -> thm list -> 
wneuper@59180
    50
    local_theory -> lift_def * local_theory
kuncar@48153
    51
kuncar@48153
    52
  val can_generate_code_cert: thm -> bool
kuncar@54788
    53
end
kuncar@48153
    54
kuncar@48153
    55
structure Lifting_Def: LIFTING_DEF =
kuncar@48153
    56
struct
kuncar@48153
    57
kuncar@48569
    58
open Lifting_Util
kuncar@48153
    59
kuncar@48153
    60
infix 0 MRSL
kuncar@48153
    61
wneuper@59180
    62
datatype code_eq = UNKNOWN_EQ | NONE_EQ | ABS_EQ | REP_EQ
wneuper@59180
    63
wneuper@59180
    64
datatype lift_def = LIFT_DEF of {
wneuper@59180
    65
  rty: typ,
wneuper@59180
    66
  qty: typ,
wneuper@59180
    67
  rhs: term,
wneuper@59180
    68
  lift_const: term,
wneuper@59180
    69
  def_thm: thm,
wneuper@59180
    70
  rsp_thm: thm,
wneuper@59180
    71
  abs_eq: thm,
wneuper@59180
    72
  rep_eq: thm option,
wneuper@59180
    73
  code_eq: code_eq,
wneuper@59180
    74
  transfer_rules: thm list
wneuper@59180
    75
};
wneuper@59180
    76
wneuper@59180
    77
fun rep_lift_def (LIFT_DEF lift_def) = lift_def;
wneuper@59180
    78
val rty_of_lift_def = #rty o rep_lift_def;
wneuper@59180
    79
val qty_of_lift_def = #qty o rep_lift_def;
wneuper@59180
    80
val rhs_of_lift_def = #rhs o rep_lift_def;
wneuper@59180
    81
val lift_const_of_lift_def = #lift_const o rep_lift_def;
wneuper@59180
    82
val def_thm_of_lift_def = #def_thm o rep_lift_def;
wneuper@59180
    83
val rsp_thm_of_lift_def = #rsp_thm o rep_lift_def;
wneuper@59180
    84
val abs_eq_of_lift_def = #abs_eq o rep_lift_def;
wneuper@59180
    85
val rep_eq_of_lift_def = #rep_eq o rep_lift_def;
wneuper@59180
    86
val code_eq_of_lift_def = #code_eq o rep_lift_def;
wneuper@59180
    87
val transfer_rules_of_lift_def = #transfer_rules o rep_lift_def;
wneuper@59180
    88
wneuper@59180
    89
fun mk_lift_def rty qty rhs lift_const def_thm rsp_thm abs_eq rep_eq code_eq transfer_rules =
wneuper@59180
    90
  LIFT_DEF {rty = rty, qty = qty,
wneuper@59180
    91
            rhs = rhs, lift_const = lift_const,
wneuper@59180
    92
            def_thm = def_thm, rsp_thm = rsp_thm, abs_eq = abs_eq, rep_eq = rep_eq, 
wneuper@59180
    93
            code_eq = code_eq, transfer_rules = transfer_rules };
wneuper@59180
    94
wneuper@59180
    95
fun map_lift_def f1 f2 f3 f4 f5 f6 f7 f8 f9 f10
wneuper@59180
    96
  (LIFT_DEF {rty = rty, qty = qty, rhs = rhs, lift_const = lift_const,
wneuper@59180
    97
  def_thm = def_thm, rsp_thm = rsp_thm, abs_eq = abs_eq, rep_eq = rep_eq, code_eq = code_eq,
wneuper@59180
    98
  transfer_rules = transfer_rules }) =
wneuper@59180
    99
  LIFT_DEF {rty = f1 rty, qty = f2 qty, rhs = f3 rhs, lift_const = f4 lift_const,
wneuper@59180
   100
            def_thm = f5 def_thm, rsp_thm = f6 rsp_thm, abs_eq = f7 abs_eq, rep_eq = f8 rep_eq,
wneuper@59180
   101
            code_eq = f9 code_eq, transfer_rules = f10 transfer_rules }
wneuper@59180
   102
wneuper@59180
   103
fun morph_lift_def phi =
wneuper@59180
   104
  let
wneuper@59180
   105
    val mtyp = Morphism.typ phi
wneuper@59180
   106
    val mterm = Morphism.term phi
wneuper@59180
   107
    val mthm = Morphism.thm phi
wneuper@59180
   108
  in
wneuper@59180
   109
    map_lift_def mtyp mtyp mterm mterm mthm mthm mthm (Option.map mthm) I (map mthm)
wneuper@59180
   110
  end
wneuper@59180
   111
wneuper@59180
   112
fun mk_inst_of_lift_def qty lift_def = Vartab.empty |> Type.raw_match (qty_of_lift_def lift_def, qty)
wneuper@59180
   113
wneuper@59180
   114
fun mk_lift_const_of_lift_def qty lift_def = Envir.subst_term_types (mk_inst_of_lift_def qty lift_def)
wneuper@59180
   115
  (lift_const_of_lift_def lift_def)
wneuper@59180
   116
wneuper@59180
   117
fun inst_of_lift_def ctxt qty lift_def =  mk_inst_of_lift_def qty lift_def
wneuper@59180
   118
  |> instT_morphism ctxt |> (fn phi => morph_lift_def phi lift_def)
wneuper@59180
   119
wneuper@59180
   120
(* Config *)
wneuper@59180
   121
wneuper@59180
   122
type config = { notes: bool };
wneuper@59180
   123
fun map_config f1 { notes = notes } = { notes = f1 notes }
wneuper@59180
   124
val default_config = { notes = true };
wneuper@59180
   125
kuncar@53131
   126
(* Reflexivity prover *)
kuncar@53131
   127
kuncar@56951
   128
fun mono_eq_prover ctxt prop =
kuncar@53131
   129
  let
kuncar@57860
   130
    val refl_rules = Lifting_Info.get_reflexivity_rules ctxt
kuncar@57860
   131
    val transfer_rules = Transfer.get_transfer_raw ctxt
kuncar@57860
   132
    
wneuper@59180
   133
    fun main_tac i = (REPEAT_ALL_NEW (DETERM o resolve_tac ctxt refl_rules) THEN_ALL_NEW 
wneuper@59180
   134
      (REPEAT_ALL_NEW (DETERM o resolve_tac ctxt transfer_rules))) i
kuncar@53131
   135
  in
kuncar@57882
   136
    SOME (Goal.prove ctxt [] [] prop (K (main_tac 1)))
kuncar@56951
   137
      handle ERROR _ => NONE
kuncar@53131
   138
  end
kuncar@57860
   139
kuncar@58984
   140
fun try_prove_refl_rel ctxt rel =
kuncar@58984
   141
  let
kuncar@58984
   142
    fun mk_ge_eq x =
kuncar@58984
   143
      let
kuncar@58984
   144
        val T = fastype_of x
kuncar@58984
   145
      in
kuncar@58984
   146
        Const (@{const_name "less_eq"}, T --> T --> HOLogic.boolT) $ 
kuncar@58984
   147
          (Const (@{const_name HOL.eq}, T)) $ x
kuncar@58984
   148
      end;
kuncar@58984
   149
    val goal = HOLogic.mk_Trueprop (mk_ge_eq rel);
kuncar@58984
   150
  in
kuncar@58984
   151
     mono_eq_prover ctxt goal
kuncar@58984
   152
  end;
kuncar@58984
   153
kuncar@53131
   154
fun try_prove_reflexivity ctxt prop =
kuncar@56951
   155
  let
wneuper@59180
   156
    val cprop = Thm.cterm_of ctxt prop
kuncar@56951
   157
    val rule = @{thm ge_eq_refl}
wneuper@59180
   158
    val concl_pat = Drule.strip_imp_concl (Thm.cprop_of rule)
kuncar@56951
   159
    val insts = Thm.first_order_match (concl_pat, cprop)
kuncar@56951
   160
    val rule = Drule.instantiate_normalize insts rule
wneuper@59180
   161
    val prop = hd (Thm.prems_of rule)
kuncar@56951
   162
  in
kuncar@56951
   163
    case mono_eq_prover ctxt prop of
kuncar@56952
   164
      SOME thm => SOME (thm RS rule)
kuncar@56951
   165
      | NONE => NONE
kuncar@56951
   166
  end
kuncar@53131
   167
kuncar@55223
   168
(* 
kuncar@55223
   169
  Generates a parametrized transfer rule.
kuncar@55223
   170
  transfer_rule - of the form T t f
kuncar@55223
   171
  parametric_transfer_rule - of the form par_R t' t
kuncar@55223
   172
  
kuncar@56289
   173
  Result: par_T t' f, after substituing op= for relations in par_R that relate
kuncar@55223
   174
    a type constructor to the same type constructor, it is a merge of (par_R' OO T) t' f
kuncar@55223
   175
    using Lifting_Term.merge_transfer_relations
kuncar@55223
   176
*)
kuncar@52511
   177
kuncar@52511
   178
fun generate_parametric_transfer_rule ctxt transfer_rule parametric_transfer_rule =
kuncar@52511
   179
  let
kuncar@52511
   180
    fun preprocess ctxt thm =
kuncar@52511
   181
      let
wneuper@59180
   182
        val tm = (strip_args 2 o HOLogic.dest_Trueprop o Thm.concl_of) thm;
kuncar@52511
   183
        val param_rel = (snd o dest_comb o fst o dest_comb) tm;
kuncar@52511
   184
        val free_vars = Term.add_vars param_rel [];
kuncar@52511
   185
        
kuncar@52511
   186
        fun make_subst (var as (_, typ)) subst = 
kuncar@52511
   187
          let
kuncar@52511
   188
            val [rty, rty'] = binder_types typ
kuncar@52511
   189
          in
kuncar@52511
   190
            if (Term.is_TVar rty andalso is_Type rty') then
kuncar@52511
   191
              (Var var, HOLogic.eq_const rty')::subst
kuncar@52511
   192
            else
kuncar@52511
   193
              subst
kuncar@52511
   194
          end;
kuncar@52511
   195
        
kuncar@52511
   196
        val subst = fold make_subst free_vars [];
wneuper@59180
   197
        val csubst = map (apply2 (Thm.cterm_of ctxt)) subst;
kuncar@52511
   198
        val inst_thm = Drule.cterm_instantiate csubst thm;
kuncar@52511
   199
      in
kuncar@52511
   200
        Conv.fconv_rule 
wneuper@59180
   201
          ((Conv.concl_conv (Thm.nprems_of inst_thm) o
wneuper@59180
   202
            HOLogic.Trueprop_conv o Conv.fun2_conv o Conv.arg1_conv)
wenzelm@56084
   203
            (Raw_Simplifier.rewrite ctxt false (Transfer.get_sym_relator_eq ctxt))) inst_thm
kuncar@52511
   204
      end
kuncar@52511
   205
wneuper@59180
   206
    fun inst_relcomppI ctxt ant1 ant2 =
kuncar@52511
   207
      let
wneuper@59180
   208
        val t1 = (HOLogic.dest_Trueprop o Thm.concl_of) ant1
wneuper@59180
   209
        val t2 = (HOLogic.dest_Trueprop o Thm.prop_of) ant2
wneuper@59180
   210
        val fun1 = Thm.cterm_of ctxt (strip_args 2 t1)
wneuper@59180
   211
        val args1 = map (Thm.cterm_of ctxt) (get_args 2 t1)
wneuper@59180
   212
        val fun2 = Thm.cterm_of ctxt (strip_args 2 t2)
wneuper@59180
   213
        val args2 = map (Thm.cterm_of ctxt) (get_args 1 t2)
kuncar@52511
   214
        val relcomppI = Drule.incr_indexes2 ant1 ant2 @{thm relcomppI}
wneuper@59180
   215
        val vars = (rev (Term.add_vars (Thm.prop_of relcomppI) []))
wneuper@59180
   216
        val subst = map (apfst (Thm.cterm_of ctxt o Var)) (vars ~~ ([fun1] @ args1 @ [fun2] @ args2))
kuncar@52511
   217
      in
kuncar@52511
   218
        Drule.cterm_instantiate subst relcomppI
kuncar@52511
   219
      end
kuncar@52511
   220
wenzelm@56337
   221
    fun zip_transfer_rules ctxt thm =
wenzelm@56337
   222
      let
kuncar@52511
   223
        fun mk_POS ty = Const (@{const_name POS}, ty --> ty --> HOLogic.boolT)
wneuper@59180
   224
        val rel = (Thm.dest_fun2 o Thm.dest_arg o Thm.cprop_of) thm
wneuper@59180
   225
        val typ = Thm.typ_of_cterm rel
wneuper@59180
   226
        val POS_const = Thm.cterm_of ctxt (mk_POS typ)
wneuper@59180
   227
        val var = Thm.cterm_of ctxt (Var (("X", Thm.maxidx_of_cterm rel + 1), typ))
wneuper@59180
   228
        val goal =
wneuper@59180
   229
          Thm.apply (Thm.cterm_of ctxt HOLogic.Trueprop) (Thm.apply (Thm.apply POS_const rel) var)
kuncar@52511
   230
      in
kuncar@52511
   231
        [Lifting_Term.merge_transfer_relations ctxt goal, thm] MRSL @{thm POS_apply}
kuncar@52511
   232
      end
kuncar@52511
   233
     
wneuper@59180
   234
    val thm =
wneuper@59180
   235
      inst_relcomppI ctxt parametric_transfer_rule transfer_rule
wneuper@59180
   236
        OF [parametric_transfer_rule, transfer_rule]
kuncar@52511
   237
    val preprocessed_thm = preprocess ctxt thm
kuncar@52511
   238
    val orig_ctxt = ctxt
kuncar@52511
   239
    val (fixed_thm, ctxt) = yield_singleton (apfst snd oo Variable.import true) preprocessed_thm ctxt
kuncar@52511
   240
    val assms = cprems_of fixed_thm
kuncar@52511
   241
    val add_transfer_rule = Thm.attribute_declaration Transfer.transfer_add
wenzelm@56337
   242
    val (prems, ctxt) = fold_map Thm.assume_hyps assms ctxt
wenzelm@56337
   243
    val ctxt = Context.proof_map (fold add_transfer_rule prems) ctxt
kuncar@52511
   244
    val zipped_thm =
kuncar@52511
   245
      fixed_thm
kuncar@52511
   246
      |> undisch_all
kuncar@52511
   247
      |> zip_transfer_rules ctxt
kuncar@52511
   248
      |> implies_intr_list assms
kuncar@52511
   249
      |> singleton (Variable.export ctxt orig_ctxt)
kuncar@52511
   250
  in
kuncar@52511
   251
    zipped_thm
kuncar@52511
   252
  end
kuncar@52511
   253
kuncar@52511
   254
fun print_generate_transfer_info msg = 
kuncar@52511
   255
  let
kuncar@52511
   256
    val error_msg = cat_lines 
kuncar@52511
   257
      ["Generation of a parametric transfer rule failed.",
kuncar@52511
   258
      (Pretty.string_of (Pretty.block
kuncar@52511
   259
         [Pretty.str "Reason:", Pretty.brk 2, msg]))]
kuncar@52511
   260
  in
kuncar@52511
   261
    error error_msg
kuncar@52511
   262
  end
kuncar@52511
   263
kuncar@55088
   264
fun map_ter _ x [] = x
kuncar@55088
   265
    | map_ter f _ xs = map f xs
kuncar@55088
   266
kuncar@55088
   267
fun generate_transfer_rules lthy quot_thm rsp_thm def_thm par_thms =
kuncar@52511
   268
  let
kuncar@52511
   269
    val transfer_rule =
kuncar@52511
   270
      ([quot_thm, rsp_thm, def_thm] MRSL @{thm Quotient_to_transfer})
kuncar@52511
   271
      |> Lifting_Term.parametrize_transfer_rule lthy
kuncar@52511
   272
  in
kuncar@55088
   273
    (map_ter (generate_parametric_transfer_rule lthy transfer_rule) [transfer_rule] par_thms
kuncar@55088
   274
    handle Lifting_Term.MERGE_TRANSFER_REL msg => (print_generate_transfer_info msg; [transfer_rule]))
kuncar@52511
   275
  end
kuncar@52511
   276
kuncar@48569
   277
(* Generation of the code certificate from the rsp theorem *)
kuncar@48153
   278
kuncar@48153
   279
fun get_body_types (Type ("fun", [_, U]), Type ("fun", [_, V])) = get_body_types (U, V)
kuncar@48153
   280
  | get_body_types (U, V)  = (U, V)
kuncar@48153
   281
kuncar@48153
   282
fun get_binder_types (Type ("fun", [T, U]), Type ("fun", [V, W])) = (T, V) :: get_binder_types (U, W)
kuncar@48153
   283
  | get_binder_types _ = []
kuncar@48153
   284
blanchet@57287
   285
fun get_binder_types_by_rel (Const (@{const_name "rel_fun"}, _) $ _ $ S) (Type ("fun", [T, U]), Type ("fun", [V, W])) = 
kuncar@48952
   286
    (T, V) :: get_binder_types_by_rel S (U, W)
kuncar@48952
   287
  | get_binder_types_by_rel _ _ = []
kuncar@48952
   288
blanchet@57287
   289
fun get_body_type_by_rel (Const (@{const_name "rel_fun"}, _) $ _ $ S) (Type ("fun", [_, U]), Type ("fun", [_, V])) = 
kuncar@48952
   290
    get_body_type_by_rel S (U, V)
kuncar@48952
   291
  | get_body_type_by_rel _ (U, V)  = (U, V)
kuncar@48952
   292
kuncar@58984
   293
fun get_binder_rels (Const (@{const_name "rel_fun"}, _) $ R $ S) = R :: get_binder_rels S
kuncar@58984
   294
  | get_binder_rels _ = []
kuncar@58984
   295
kuncar@48153
   296
fun force_rty_type ctxt rty rhs = 
kuncar@48153
   297
  let
kuncar@48153
   298
    val thy = Proof_Context.theory_of ctxt
kuncar@48153
   299
    val rhs_schematic = singleton (Variable.polymorphic ctxt) rhs
kuncar@48153
   300
    val rty_schematic = fastype_of rhs_schematic
kuncar@48153
   301
    val match = Sign.typ_match thy (rty_schematic, rty) Vartab.empty
kuncar@48153
   302
  in
kuncar@48153
   303
    Envir.subst_term_types match rhs_schematic
kuncar@48153
   304
  end
kuncar@48153
   305
kuncar@48153
   306
fun unabs_def ctxt def = 
kuncar@48153
   307
  let
wneuper@59180
   308
    val (_, rhs) = Thm.dest_equals (Thm.cprop_of def)
kuncar@48153
   309
    fun dest_abs (Abs (var_name, T, _)) = (var_name, T)
kuncar@48153
   310
      | dest_abs tm = raise TERM("get_abs_var",[tm])
wneuper@59180
   311
    val (var_name, T) = dest_abs (Thm.term_of rhs)
kuncar@48153
   312
    val (new_var_names, ctxt') = Variable.variant_fixes [var_name] ctxt
wneuper@59180
   313
    val refl_thm = Thm.reflexive (Thm.cterm_of ctxt' (Free (hd new_var_names, T)))
kuncar@48153
   314
  in
kuncar@48153
   315
    Thm.combination def refl_thm |>
kuncar@48153
   316
    singleton (Proof_Context.export ctxt' ctxt)
kuncar@48153
   317
  end
kuncar@48153
   318
kuncar@48153
   319
fun unabs_all_def ctxt def = 
kuncar@48153
   320
  let
wneuper@59180
   321
    val (_, rhs) = Thm.dest_equals (Thm.cprop_of def)
wneuper@59180
   322
    val xs = strip_abs_vars (Thm.term_of rhs)
kuncar@48153
   323
  in  
kuncar@48153
   324
    fold (K (unabs_def ctxt)) xs def
kuncar@48153
   325
  end
kuncar@48153
   326
kuncar@48153
   327
val map_fun_unfolded = 
kuncar@48153
   328
  @{thm map_fun_def[abs_def]} |>
kuncar@48153
   329
  unabs_def @{context} |>
kuncar@48153
   330
  unabs_def @{context} |>
kuncar@48153
   331
  Local_Defs.unfold @{context} [@{thm comp_def}]
kuncar@48153
   332
kuncar@48153
   333
fun unfold_fun_maps ctm =
kuncar@48153
   334
  let
kuncar@48153
   335
    fun unfold_conv ctm =
kuncar@48153
   336
      case (Thm.term_of ctm) of
kuncar@48153
   337
        Const (@{const_name "map_fun"}, _) $ _ $ _ => 
kuncar@48153
   338
          (Conv.arg_conv unfold_conv then_conv Conv.rewr_conv map_fun_unfolded) ctm
kuncar@48153
   339
        | _ => Conv.all_conv ctm
kuncar@48153
   340
  in
kuncar@48952
   341
    (Conv.fun_conv unfold_conv) ctm
kuncar@48952
   342
  end
kuncar@48952
   343
kuncar@48952
   344
fun unfold_fun_maps_beta ctm =
kuncar@48952
   345
  let val try_beta_conv = Conv.try_conv (Thm.beta_conversion false)
kuncar@48952
   346
  in 
kuncar@48952
   347
    (unfold_fun_maps then_conv try_beta_conv) ctm 
kuncar@48153
   348
  end
kuncar@48153
   349
kuncar@48153
   350
fun prove_rel ctxt rsp_thm (rty, qty) =
kuncar@48153
   351
  let
kuncar@48153
   352
    val ty_args = get_binder_types (rty, qty)
kuncar@48153
   353
    fun disch_arg args_ty thm = 
kuncar@48153
   354
      let
kuncar@48375
   355
        val quot_thm = Lifting_Term.prove_quot_thm ctxt args_ty
kuncar@48153
   356
      in
kuncar@48153
   357
        [quot_thm, thm] MRSL @{thm apply_rsp''}
kuncar@48153
   358
      end
kuncar@48153
   359
  in
kuncar@48153
   360
    fold disch_arg ty_args rsp_thm
kuncar@48153
   361
  end
kuncar@48153
   362
kuncar@48153
   363
exception CODE_CERT_GEN of string
kuncar@48153
   364
kuncar@48153
   365
fun simplify_code_eq ctxt def_thm = 
kuncar@49039
   366
  Local_Defs.unfold ctxt [@{thm o_apply}, @{thm map_fun_def}, @{thm id_apply}] def_thm
kuncar@48153
   367
kuncar@48723
   368
(*
kuncar@48723
   369
  quot_thm - quotient theorem (Quotient R Abs Rep T).
kuncar@48723
   370
  returns: whether the Lifting package is capable to generate code for the abstract type
kuncar@48723
   371
    represented by quot_thm
kuncar@48723
   372
*)
kuncar@48723
   373
kuncar@48153
   374
fun can_generate_code_cert quot_thm  =
kuncar@48966
   375
  case quot_thm_rel quot_thm of
kuncar@48153
   376
    Const (@{const_name HOL.eq}, _) => true
kuncar@57861
   377
    | Const (@{const_name eq_onp}, _) $ _  => true
kuncar@48153
   378
    | _ => false
kuncar@48153
   379
kuncar@56952
   380
fun generate_rep_eq ctxt def_thm rsp_thm (rty, qty) =
kuncar@48153
   381
  let
kuncar@48952
   382
    val unfolded_def = Conv.fconv_rule (Conv.arg_conv unfold_fun_maps_beta) def_thm
kuncar@48153
   383
    val unabs_def = unabs_all_def ctxt unfolded_def
kuncar@56952
   384
  in  
kuncar@56952
   385
    if body_type rty = body_type qty then 
kuncar@57065
   386
      SOME (simplify_code_eq ctxt (unabs_def RS @{thm meta_eq_to_obj_eq}))
kuncar@56952
   387
    else 
kuncar@56952
   388
      let
kuncar@56952
   389
        val quot_thm = Lifting_Term.prove_quot_thm ctxt (get_body_types (rty, qty))
blanchet@57287
   390
        val rel_fun = prove_rel ctxt rsp_thm (rty, qty)
blanchet@57287
   391
        val rep_abs_thm = [quot_thm, rel_fun] MRSL @{thm Quotient_rep_abs_eq}
kuncar@56952
   392
      in
wneuper@59180
   393
        case mono_eq_prover ctxt (hd (Thm.prems_of rep_abs_thm)) of
kuncar@56952
   394
          SOME mono_eq_thm =>
kuncar@56952
   395
            let
kuncar@56952
   396
              val rep_abs_eq = mono_eq_thm RS rep_abs_thm
wneuper@59180
   397
              val rep = Thm.cterm_of ctxt (quot_thm_rep quot_thm)
kuncar@56952
   398
              val rep_refl = Thm.reflexive rep RS @{thm meta_eq_to_obj_eq}
kuncar@56952
   399
              val repped_eq = [rep_refl, unabs_def RS @{thm meta_eq_to_obj_eq}] MRSL @{thm cong}
kuncar@56952
   400
              val code_cert = [repped_eq, rep_abs_eq] MRSL trans
kuncar@56952
   401
            in
kuncar@56952
   402
              SOME (simplify_code_eq ctxt code_cert)
kuncar@56952
   403
            end
kuncar@56952
   404
          | NONE => NONE
kuncar@56952
   405
      end
kuncar@48153
   406
  end
kuncar@48153
   407
kuncar@48952
   408
fun generate_abs_eq ctxt def_thm rsp_thm quot_thm =
kuncar@48952
   409
  let
kuncar@48952
   410
    val abs_eq_with_assms =
kuncar@48952
   411
      let
kuncar@48966
   412
        val (rty, qty) = quot_thm_rty_qty quot_thm
kuncar@48966
   413
        val rel = quot_thm_rel quot_thm
kuncar@48952
   414
        val ty_args = get_binder_types_by_rel rel (rty, qty)
kuncar@48952
   415
        val body_type = get_body_type_by_rel rel (rty, qty)
kuncar@48952
   416
        val quot_ret_thm = Lifting_Term.prove_quot_thm ctxt body_type
kuncar@48952
   417
        
kuncar@48952
   418
        val rep_abs_folded_unmapped_thm = 
kuncar@48952
   419
          let
kuncar@48952
   420
            val rep_id = [quot_thm, def_thm] MRSL @{thm Quotient_Rep_eq}
wneuper@59180
   421
            val ctm = Thm.dest_equals_lhs (Thm.cprop_of rep_id)
kuncar@48952
   422
            val unfolded_maps_eq = unfold_fun_maps ctm
kuncar@48952
   423
            val t1 = [quot_thm, def_thm, rsp_thm] MRSL @{thm Quotient_rep_abs_fold_unmap}
kuncar@48952
   424
            val prems_pat = (hd o Drule.cprems_of) t1
wneuper@59180
   425
            val insts = Thm.first_order_match (prems_pat, Thm.cprop_of unfolded_maps_eq)
kuncar@48952
   426
          in
kuncar@48952
   427
            unfolded_maps_eq RS (Drule.instantiate_normalize insts t1)
kuncar@48952
   428
          end
kuncar@48952
   429
      in
kuncar@48952
   430
        rep_abs_folded_unmapped_thm
blanchet@57287
   431
        |> fold (fn _ => fn thm => thm RS @{thm rel_funD2}) ty_args
kuncar@48952
   432
        |> (fn x => x RS (@{thm Quotient_rel_abs2} OF [quot_ret_thm]))
kuncar@48952
   433
      end
kuncar@48952
   434
    
kuncar@58984
   435
    val prem_rels = get_binder_rels (quot_thm_rel quot_thm);
kuncar@58984
   436
    val proved_assms = prem_rels |> map (try_prove_refl_rel ctxt) 
kuncar@58984
   437
      |> map_index (apfst (fn x => x + 1)) |> filter (is_some o snd) |> map (apsnd the) 
kuncar@58984
   438
      |> map (apsnd (fn assm => assm RS @{thm ge_eq_refl}))
kuncar@58984
   439
    val abs_eq = fold_rev (fn (i, assm) => fn thm => assm RSN (i, thm)) proved_assms abs_eq_with_assms
kuncar@48952
   440
  in
kuncar@48952
   441
    simplify_code_eq ctxt abs_eq
kuncar@48952
   442
  end
kuncar@48952
   443
kuncar@57066
   444
kuncar@57066
   445
fun register_code_eq_thy abs_eq_thm opt_rep_eq_thm (rty, qty) thy =
kuncar@57066
   446
  let
kuncar@57066
   447
    fun no_abstr (t $ u) = no_abstr t andalso no_abstr u
kuncar@57066
   448
      | no_abstr (Abs (_, _, t)) = no_abstr t
kuncar@57066
   449
      | no_abstr (Const (name, _)) = not (Code.is_abstr thy name)
kuncar@57066
   450
      | no_abstr _ = true
kuncar@57066
   451
    fun is_valid_eq eqn = can (Code.assert_eqn thy) (mk_meta_eq eqn, true) 
wneuper@59180
   452
      andalso no_abstr (Thm.prop_of eqn)
kuncar@57066
   453
    fun is_valid_abs_eq abs_eq = can (Code.assert_abs_eqn thy NONE) (mk_meta_eq abs_eq)
kuncar@57066
   454
kuncar@57066
   455
  in
kuncar@57066
   456
    if is_valid_eq abs_eq_thm then
wneuper@59180
   457
      (ABS_EQ, Code.add_default_eqn abs_eq_thm thy)
kuncar@57066
   458
    else
kuncar@48153
   459
      let
kuncar@57066
   460
        val (rty_body, qty_body) = get_body_types (rty, qty)
kuncar@48153
   461
      in
kuncar@57066
   462
        if rty_body = qty_body then
wneuper@59180
   463
          (REP_EQ, Code.add_default_eqn (the opt_rep_eq_thm) thy)
kuncar@48952
   464
        else
kuncar@57066
   465
          if is_some opt_rep_eq_thm andalso is_valid_abs_eq (the opt_rep_eq_thm)
kuncar@57066
   466
          then
wneuper@59180
   467
            (REP_EQ, Code.add_abs_default_eqn (the opt_rep_eq_thm) thy)
kuncar@57066
   468
          else
wneuper@59180
   469
            (NONE_EQ, thy)
kuncar@48952
   470
      end
kuncar@48952
   471
  end
kuncar@48153
   472
kuncar@57066
   473
local
kuncar@59005
   474
  fun no_no_code ctxt (rty, qty) =
kuncar@59005
   475
    if same_type_constrs (rty, qty) then
kuncar@59005
   476
      forall (no_no_code ctxt) (Targs rty ~~ Targs qty)
kuncar@59005
   477
    else
kuncar@59005
   478
      if is_Type qty then
kuncar@59005
   479
        if Lifting_Info.is_no_code_type ctxt (Tname qty) then false
kuncar@59005
   480
        else 
kuncar@59005
   481
          let 
kuncar@59005
   482
            val (rty', rtyq) = Lifting_Term.instantiate_rtys ctxt (rty, qty)
kuncar@59005
   483
            val (rty's, rtyqs) = (Targs rty', Targs rtyq)
kuncar@59005
   484
          in
kuncar@59005
   485
            forall (no_no_code ctxt) (rty's ~~ rtyqs)
kuncar@59005
   486
          end
kuncar@59005
   487
      else
kuncar@59005
   488
        true
wneuper@59180
   489
wneuper@59180
   490
  fun encode_code_eq ctxt abs_eq opt_rep_eq (rty, qty) = 
wneuper@59180
   491
    let
wneuper@59180
   492
      fun mk_type typ = typ |> Logic.mk_type |> Thm.cterm_of ctxt |> Drule.mk_term
wneuper@59180
   493
    in
wneuper@59180
   494
      Conjunction.intr_balanced [abs_eq, (the_default TrueI opt_rep_eq), mk_type rty, mk_type qty]
wneuper@59180
   495
    end
wneuper@59180
   496
  
wneuper@59180
   497
  exception DECODE
wneuper@59180
   498
    
wneuper@59180
   499
  fun decode_code_eq thm =
wneuper@59180
   500
    if Thm.nprems_of thm > 0 then raise DECODE 
wneuper@59180
   501
    else
wneuper@59180
   502
      let
wneuper@59180
   503
        val [abs_eq, rep_eq, rty, qty] = Conjunction.elim_balanced 4 thm
wneuper@59180
   504
        val opt_rep_eq = if Thm.eq_thm_prop (rep_eq, TrueI) then NONE else SOME rep_eq
wneuper@59180
   505
        fun dest_type typ = typ |> Drule.dest_term |> Thm.term_of |> Logic.dest_type
wneuper@59180
   506
      in
wneuper@59180
   507
        (abs_eq, opt_rep_eq, (dest_type rty, dest_type qty)) 
wneuper@59180
   508
      end
wneuper@59180
   509
  
wneuper@59180
   510
  structure Data = Generic_Data
wneuper@59180
   511
  (
wneuper@59180
   512
    type T = code_eq option
wneuper@59180
   513
    val empty = NONE
wneuper@59180
   514
    val extend = I
wneuper@59180
   515
    fun merge _ = NONE
wneuper@59180
   516
  );
wneuper@59180
   517
wneuper@59180
   518
  fun register_encoded_code_eq thm thy =
wneuper@59180
   519
    let
wneuper@59180
   520
      val (abs_eq_thm, opt_rep_eq_thm, (rty, qty)) = decode_code_eq thm
wneuper@59180
   521
      val (code_eq, thy) = register_code_eq_thy abs_eq_thm opt_rep_eq_thm (rty, qty) thy
wneuper@59180
   522
    in
wneuper@59180
   523
      Context.theory_map (Data.put (SOME code_eq)) thy
wneuper@59180
   524
    end
wneuper@59180
   525
    handle DECODE => thy
wneuper@59180
   526
  
wneuper@59180
   527
  val register_code_eq_attribute = Thm.declaration_attribute
wneuper@59180
   528
    (fn thm => Context.mapping (register_encoded_code_eq thm) I)
wneuper@59180
   529
  val register_code_eq_attrib = Attrib.internal (K register_code_eq_attribute)
wneuper@59180
   530
kuncar@57066
   531
in
kuncar@57066
   532
kuncar@57066
   533
fun register_code_eq abs_eq_thm opt_rep_eq_thm (rty, qty) lthy =
kuncar@57066
   534
  let
wneuper@59180
   535
    val encoded_code_eq = encode_code_eq lthy abs_eq_thm opt_rep_eq_thm (rty, qty)
kuncar@57066
   536
  in
wneuper@59180
   537
    if no_no_code lthy (rty, qty) then
wneuper@59180
   538
      let
wneuper@59180
   539
        val lthy = (snd oo Local_Theory.note) 
wneuper@59180
   540
          ((Binding.empty, [register_code_eq_attrib]), [encoded_code_eq]) lthy
wneuper@59180
   541
        val opt_code_eq = Data.get (Context.Theory (Proof_Context.theory_of lthy))
wneuper@59180
   542
        val code_eq = if is_some opt_code_eq then the opt_code_eq 
wneuper@59180
   543
          else UNKNOWN_EQ (* UNKNOWN_EQ means that we are in a locale and we do not know
wneuper@59180
   544
            which code equation is going to be used. This is going to be resolved at the
wneuper@59180
   545
            point when an interpretation of the locale is executed. *)
wneuper@59180
   546
        val lthy = Local_Theory.declaration {syntax = false, pervasive = true} 
wneuper@59180
   547
          (K (Data.put NONE)) lthy
wneuper@59180
   548
      in
wneuper@59180
   549
        (code_eq, lthy)
wneuper@59180
   550
      end
kuncar@59005
   551
    else
wneuper@59180
   552
      (NONE_EQ, lthy)
kuncar@57066
   553
  end
kuncar@57066
   554
end
kuncar@57066
   555
            
kuncar@48723
   556
(*
kuncar@48723
   557
  Defines an operation on an abstract type in terms of a corresponding operation 
kuncar@48723
   558
    on a representation type.
kuncar@48723
   559
kuncar@48723
   560
  var - a binding and a mixfix of the new constant being defined
kuncar@48723
   561
  qty - an abstract type of the new constant
kuncar@48723
   562
  rhs - a term representing the new constant on the raw level
kuncar@48952
   563
  rsp_thm - a respectfulness theorem in the internal tagged form (like '(R ===> R ===> R) f f'),
kuncar@48723
   564
    i.e. "(Lifting_Term.equiv_relation (fastype_of rhs, qty)) $ rhs $ rhs"
kuncar@55223
   565
  par_thms - a parametricity theorem for rhs
kuncar@48723
   566
*)
kuncar@48153
   567
wneuper@59180
   568
fun add_lift_def (config: config) var qty rhs rsp_thm par_thms lthy =
kuncar@48153
   569
  let
kuncar@48153
   570
    val rty = fastype_of rhs
kuncar@48952
   571
    val quot_thm = Lifting_Term.prove_quot_thm lthy (rty, qty)
kuncar@48966
   572
    val absrep_trm =  quot_thm_abs quot_thm
kuncar@48153
   573
    val rty_forced = (domain_type o fastype_of) absrep_trm
kuncar@48153
   574
    val forced_rhs = force_rty_type lthy rty_forced rhs
wenzelm@54344
   575
    val lhs = Free (Binding.name_of (#1 var), qty)
kuncar@48153
   576
    val prop = Logic.mk_equals (lhs, absrep_trm $ forced_rhs)
kuncar@48153
   577
    val (_, prop') = Local_Defs.cert_def lthy prop
kuncar@48153
   578
    val (_, newrhs) = Local_Defs.abs_def prop'
wneuper@59180
   579
    val var = (#notes config = false ? apfst Binding.concealed) var
wneuper@59180
   580
    val def_name = if #notes config then Thm.def_binding (#1 var) else Binding.empty
wneuper@59180
   581
    
wneuper@59180
   582
    val ((lift_const, (_ , def_thm)), lthy) = 
wneuper@59180
   583
      Local_Theory.define (var, ((def_name, []), newrhs)) lthy
kuncar@48153
   584
wneuper@59180
   585
    val transfer_rules = generate_transfer_rules lthy quot_thm rsp_thm def_thm par_thms
kuncar@48153
   586
wneuper@59180
   587
    val abs_eq_thm = generate_abs_eq lthy def_thm rsp_thm quot_thm
wneuper@59180
   588
    val opt_rep_eq_thm = generate_rep_eq lthy def_thm rsp_thm (rty_forced, qty)
huffman@48209
   589
kuncar@48411
   590
    fun qualify defname suffix = Binding.qualified true suffix defname
kuncar@48153
   591
wneuper@59180
   592
    fun notes names =
wneuper@59180
   593
      let
wneuper@59180
   594
        val lhs_name = (#1 var)
wneuper@59180
   595
        val rsp_thmN = qualify lhs_name "rsp"
wneuper@59180
   596
        val abs_eq_thmN = qualify lhs_name "abs_eq"
wneuper@59180
   597
        val rep_eq_thmN = qualify lhs_name "rep_eq"
wneuper@59180
   598
        val transfer_ruleN = qualify lhs_name "transfer"
wneuper@59180
   599
        val notes = 
wneuper@59180
   600
          [(rsp_thmN, [], [rsp_thm]), 
wneuper@59180
   601
          (transfer_ruleN, @{attributes [transfer_rule]}, transfer_rules),
wneuper@59180
   602
          (abs_eq_thmN, [], [abs_eq_thm])] 
wneuper@59180
   603
          @ (case opt_rep_eq_thm of SOME rep_eq_thm => [(rep_eq_thmN, [], [rep_eq_thm])] | NONE => [])
wneuper@59180
   604
      in
wneuper@59180
   605
        if names then map (fn (name, attrs, thms) => ((name, []), [(thms, attrs)])) notes
wneuper@59180
   606
        else map_filter (fn (_, attrs, thms) => if null attrs then NONE 
wneuper@59180
   607
          else SOME ((Binding.empty, []), [(thms, attrs)])) notes
wneuper@59180
   608
      end
wneuper@59180
   609
    val (code_eq, lthy) = register_code_eq abs_eq_thm opt_rep_eq_thm (rty_forced, qty) lthy
wneuper@59180
   610
    val lift_def = mk_lift_def rty_forced qty newrhs lift_const def_thm rsp_thm abs_eq_thm 
wneuper@59180
   611
          opt_rep_eq_thm code_eq transfer_rules
kuncar@48153
   612
  in
wneuper@59180
   613
    lthy
wneuper@59180
   614
      |> Local_Theory.notes (notes (#notes config)) |> snd
wneuper@59180
   615
      |> ` (fn lthy => morph_lift_def (Local_Theory.target_morphism lthy) lift_def)
wneuper@59180
   616
      ||> Local_Theory.restore
kuncar@48470
   617
  end
kuncar@48153
   618
kuncar@57882
   619
(* This is not very cheap way of getting the rules but we have only few active
kuncar@57882
   620
  liftings in the current setting *)
kuncar@57882
   621
fun get_cr_pcr_eqs ctxt =
kuncar@57882
   622
  let
kuncar@57882
   623
    fun collect (data : Lifting_Info.quotient) l =
kuncar@57882
   624
      if is_some (#pcr_info data) 
kuncar@57882
   625
      then ((Thm.symmetric o safe_mk_meta_eq o #pcr_cr_eq o the o #pcr_info) data :: l) 
kuncar@57882
   626
      else l
kuncar@57882
   627
    val table = Lifting_Info.get_quotients ctxt
kuncar@57882
   628
  in
kuncar@57882
   629
    Symtab.fold (fn (_, data) => fn l => collect data l) table []
kuncar@57882
   630
  end
kuncar@57882
   631
wneuper@59180
   632
fun prepare_lift_def add_lift_def var qty rhs par_thms lthy =
kuncar@48153
   633
  let
kuncar@53131
   634
    val rsp_rel = Lifting_Term.equiv_relation lthy (fastype_of rhs, qty)
kuncar@48153
   635
    val rty_forced = (domain_type o fastype_of) rsp_rel;
kuncar@53131
   636
    val forced_rhs = force_rty_type lthy rty_forced rhs;
kuncar@57882
   637
    val cr_to_pcr_conv = HOLogic.Trueprop_conv (Conv.fun2_conv 
kuncar@57882
   638
      (Raw_Simplifier.rewrite lthy false (get_cr_pcr_eqs lthy)))
kuncar@57882
   639
    val (prsp_tm, rsp_prsp_eq) = HOLogic.mk_Trueprop (rsp_rel $ forced_rhs $ forced_rhs)
wneuper@59180
   640
      |> Thm.cterm_of lthy
kuncar@57882
   641
      |> cr_to_pcr_conv
wneuper@59180
   642
      |> `Thm.concl_of
kuncar@57882
   643
      |>> Logic.dest_equals
kuncar@57882
   644
      |>> snd
kuncar@57882
   645
    val to_rsp = rsp_prsp_eq RS Drule.equal_elim_rule2
kuncar@57882
   646
    val opt_proven_rsp_thm = try_prove_reflexivity lthy prsp_tm
kuncar@53131
   647
    
kuncar@53131
   648
    fun after_qed internal_rsp_thm lthy = 
wneuper@59180
   649
      add_lift_def var qty rhs (internal_rsp_thm RS to_rsp) par_thms lthy
kuncar@48153
   650
  in
kuncar@52511
   651
    case opt_proven_rsp_thm of
wneuper@59180
   652
      SOME thm => (NONE, K (after_qed thm))
wneuper@59180
   653
      | NONE => (SOME prsp_tm, after_qed) 
kuncar@48153
   654
  end
kuncar@48153
   655
wneuper@59180
   656
fun gen_lift_def add_lift_def var qty rhs tac par_thms lthy =
kuncar@48237
   657
  let
wneuper@59180
   658
    val (goal, after_qed) = prepare_lift_def add_lift_def var qty rhs par_thms lthy
kuncar@48237
   659
  in
wneuper@59180
   660
    case goal of
wneuper@59180
   661
      SOME goal => 
wneuper@59180
   662
        let 
wneuper@59180
   663
          val rsp_thm = Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} => tac ctxt)
wneuper@59180
   664
            |> Thm.close_derivation
wneuper@59180
   665
        in
wneuper@59180
   666
          after_qed rsp_thm lthy
wneuper@59180
   667
        end
wneuper@59180
   668
      | NONE => after_qed Drule.dummy_thm lthy
kuncar@48237
   669
  end
kuncar@48237
   670
wneuper@59180
   671
fun lift_def config var qty rhs tac par_thms lthy = gen_lift_def (add_lift_def config)
wneuper@59180
   672
  var qty rhs tac par_thms lthy
kuncar@48153
   673
kuncar@54788
   674
end (* structure *)