src/Pure/Isar/class.ML
author wenzelm
Thu, 26 Aug 2010 13:09:12 +0200
changeset 39031 d07959fabde6
parent 38842 25e401d53900
child 39032 2b3e054ae6fc
permissions -rw-r--r--
renamed ProofContext.theory(_result) to ProofContext.background_theory(_result) to emphasize that this belongs to the infrastructure and is rarely appropriate in user-space tools;
haftmann@38605
     1
(*  Title:      Pure/Isar/class.ML
haftmann@24218
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@24218
     3
haftmann@38605
     4
Type classes derived from primitive axclasses and locales.
haftmann@24218
     5
*)
haftmann@24218
     6
haftmann@38605
     7
signature CLASS =
haftmann@24218
     8
sig
haftmann@25462
     9
  (*classes*)
haftmann@29526
    10
  val is_class: theory -> class -> bool
haftmann@29526
    11
  val these_params: theory -> sort -> (string * (class * (string * typ))) list
haftmann@38605
    12
  val base_sort: theory -> class -> sort
haftmann@38605
    13
  val rules: theory -> class -> thm option * thm
haftmann@38605
    14
  val these_defs: theory -> sort -> thm list
haftmann@38605
    15
  val these_operations: theory -> sort
haftmann@38605
    16
    -> (string * (class * (typ * term))) list
haftmann@29526
    17
  val print_classes: theory -> unit
haftmann@25311
    18
  val init: class -> theory -> Proof.context
haftmann@38605
    19
  val begin: class list -> sort -> Proof.context -> Proof.context
haftmann@38842
    20
  val const: class -> (binding * mixfix) * (term list * term) -> local_theory -> local_theory
haftmann@38842
    21
  val abbrev: class -> Syntax.mode -> (binding * mixfix) * term -> local_theory -> local_theory
haftmann@38605
    22
  val redeclare_operations: theory -> sort -> Proof.context -> Proof.context
haftmann@29526
    23
  val class_prefix: string -> string
haftmann@38605
    24
  val register: class -> class list -> ((string * typ) * (string * typ)) list
haftmann@38605
    25
    -> sort -> morphism -> morphism -> thm option -> thm option -> thm
haftmann@38605
    26
    -> theory -> theory
haftmann@25485
    27
haftmann@25462
    28
  (*instances*)
haftmann@38605
    29
  val instantiation: string list * (string * sort) list * sort -> theory -> local_theory
haftmann@26247
    30
  val instantiation_instance: (local_theory -> local_theory)
haftmann@26247
    31
    -> local_theory -> Proof.state
haftmann@26247
    32
  val prove_instantiation_instance: (Proof.context -> tactic)
haftmann@26247
    33
    -> local_theory -> local_theory
haftmann@28666
    34
  val prove_instantiation_exit: (Proof.context -> tactic)
haftmann@28666
    35
    -> local_theory -> theory
haftmann@28666
    36
  val prove_instantiation_exit_result: (morphism -> 'a -> 'b)
haftmann@28666
    37
    -> (Proof.context -> 'b -> tactic) -> 'a -> local_theory -> 'b * theory
haftmann@31868
    38
  val read_multi_arity: theory -> xstring list * xstring list * xstring
haftmann@31868
    39
    -> string list * (string * sort) list * sort
haftmann@26259
    40
  val type_name: string -> string
haftmann@38584
    41
  val instantiation_cmd: xstring list * xstring list * xstring -> theory -> local_theory
haftmann@38603
    42
  val instance_arity_cmd: xstring list * xstring list * xstring -> theory -> Proof.state
haftmann@25485
    43
haftmann@31632
    44
  (*subclasses*)
haftmann@31632
    45
  val classrel: class * class -> theory -> Proof.state
haftmann@31632
    46
  val classrel_cmd: xstring * xstring -> theory -> Proof.state
haftmann@38605
    47
  val register_subclass: class * class -> morphism option -> Element.witness option
haftmann@38605
    48
    -> morphism -> theory -> theory
haftmann@31632
    49
haftmann@31632
    50
  (*tactics*)
haftmann@29526
    51
  val intro_classes_tac: thm list -> tactic
haftmann@29526
    52
  val default_intro_tac: Proof.context -> thm list -> tactic
haftmann@24218
    53
end;
haftmann@24218
    54
haftmann@38605
    55
structure Class: CLASS =
haftmann@24218
    56
struct
haftmann@24218
    57
haftmann@24589
    58
(** class data **)
haftmann@24218
    59
haftmann@24218
    60
datatype class_data = ClassData of {
haftmann@28715
    61
haftmann@28715
    62
  (* static part *)
haftmann@24218
    63
  consts: (string * string) list
haftmann@24836
    64
    (*locale parameter ~> constant name*),
haftmann@25062
    65
  base_sort: sort,
haftmann@29545
    66
  base_morph: morphism
haftmann@29437
    67
    (*static part of canonical morphism*),
haftmann@32850
    68
  export_morph: morphism,
haftmann@25618
    69
  assm_intro: thm option,
haftmann@25618
    70
  of_class: thm,
haftmann@25618
    71
  axiom: thm option,
haftmann@28715
    72
  
haftmann@28715
    73
  (* dynamic part *)
haftmann@24657
    74
  defs: thm list,
haftmann@25368
    75
  operations: (string * (class * (typ * term))) list
haftmann@28715
    76
haftmann@24657
    77
};
haftmann@24218
    78
haftmann@32850
    79
fun make_class_data ((consts, base_sort, base_morph, export_morph, assm_intro, of_class, axiom),
haftmann@25368
    80
    (defs, operations)) =
haftmann@29526
    81
  ClassData { consts = consts, base_sort = base_sort,
haftmann@32850
    82
    base_morph = base_morph, export_morph = export_morph, assm_intro = assm_intro,
haftmann@32850
    83
    of_class = of_class, axiom = axiom, defs = defs, operations = operations };
haftmann@32850
    84
fun map_class_data f (ClassData { consts, base_sort, base_morph, export_morph, assm_intro,
haftmann@28715
    85
    of_class, axiom, defs, operations }) =
haftmann@32850
    86
  make_class_data (f ((consts, base_sort, base_morph, export_morph, assm_intro, of_class, axiom),
haftmann@25368
    87
    (defs, operations)));
haftmann@25038
    88
fun merge_class_data _ (ClassData { consts = consts,
haftmann@32850
    89
    base_sort = base_sort, base_morph = base_morph, export_morph = export_morph, assm_intro = assm_intro,
haftmann@25618
    90
    of_class = of_class, axiom = axiom, defs = defs1, operations = operations1 },
haftmann@32850
    91
  ClassData { consts = _, base_sort = _, base_morph = _, export_morph = _, assm_intro = _,
haftmann@25618
    92
    of_class = _, axiom = _, defs = defs2, operations = operations2 }) =
haftmann@32850
    93
  make_class_data ((consts, base_sort, base_morph, export_morph, assm_intro, of_class, axiom),
haftmann@24914
    94
    (Thm.merge_thms (defs1, defs2),
haftmann@25368
    95
      AList.merge (op =) (K true) (operations1, operations2)));
haftmann@24218
    96
wenzelm@33522
    97
structure ClassData = Theory_Data
haftmann@24218
    98
(
haftmann@25038
    99
  type T = class_data Graph.T
haftmann@25038
   100
  val empty = Graph.empty;
haftmann@24218
   101
  val extend = I;
wenzelm@33522
   102
  val merge = Graph.join merge_class_data;
haftmann@24218
   103
);
haftmann@24218
   104
haftmann@24218
   105
haftmann@24218
   106
(* queries *)
haftmann@24218
   107
haftmann@31599
   108
fun lookup_class_data thy class = case try (Graph.get_node (ClassData.get thy)) class
haftmann@31599
   109
 of SOME (ClassData data) => SOME data
haftmann@31599
   110
  | NONE => NONE;
haftmann@24218
   111
haftmann@24589
   112
fun the_class_data thy class = case lookup_class_data thy class
wenzelm@25020
   113
 of NONE => error ("Undeclared class " ^ quote class)
haftmann@24589
   114
  | SOME data => data;
haftmann@24218
   115
haftmann@25038
   116
val is_class = is_some oo lookup_class_data;
haftmann@25038
   117
haftmann@25038
   118
val ancestry = Graph.all_succs o ClassData.get;
haftmann@29509
   119
val heritage = Graph.all_preds o ClassData.get;
haftmann@29509
   120
haftmann@25002
   121
fun these_params thy =
haftmann@24218
   122
  let
haftmann@24218
   123
    fun params class =
haftmann@24218
   124
      let
wenzelm@24930
   125
        val const_typs = (#params o AxClass.get_info thy) class;
haftmann@24657
   126
        val const_names = (#consts o the_class_data thy) class;
haftmann@24218
   127
      in
haftmann@26518
   128
        (map o apsnd)
haftmann@26518
   129
          (fn c => (class, (c, (the o AList.lookup (op =) const_typs) c))) const_names
haftmann@24218
   130
      end;
haftmann@24218
   131
  in maps params o ancestry thy end;
haftmann@24218
   132
haftmann@29526
   133
val base_sort = #base_sort oo the_class_data;
haftmann@29526
   134
haftmann@29526
   135
fun rules thy class =
haftmann@29526
   136
  let val { axiom, of_class, ... } = the_class_data thy class
haftmann@29526
   137
  in (axiom, of_class) end;
haftmann@29526
   138
haftmann@29526
   139
fun all_assm_intros thy =
haftmann@31599
   140
  Graph.fold (fn (_, (ClassData { assm_intro, ... }, _)) => fold (insert Thm.eq_thm)
haftmann@31599
   141
    (the_list assm_intro)) (ClassData.get thy) [];
haftmann@24218
   142
haftmann@29526
   143
fun these_defs thy = maps (#defs o the_class_data thy) o ancestry thy;
haftmann@29526
   144
fun these_operations thy = maps (#operations o the_class_data thy) o ancestry thy;
haftmann@28715
   145
haftmann@29526
   146
val base_morphism = #base_morph oo the_class_data;
haftmann@36674
   147
fun morphism thy class = case Element.eq_morphism thy (these_defs thy [class])
haftmann@36674
   148
 of SOME eq_morph => base_morphism thy class $> eq_morph
haftmann@36674
   149
  | NONE => base_morphism thy class;
haftmann@32850
   150
val export_morphism = #export_morph oo the_class_data;
haftmann@28715
   151
haftmann@24218
   152
fun print_classes thy =
haftmann@24218
   153
  let
wenzelm@36633
   154
    val ctxt = ProofContext.init_global thy;
haftmann@24218
   155
    val algebra = Sign.classes_of thy;
haftmann@24218
   156
    val arities =
haftmann@24218
   157
      Symtab.empty
haftmann@24218
   158
      |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
haftmann@24218
   159
           Symtab.map_default (class, []) (insert (op =) tyco)) arities)
wenzelm@36339
   160
             (Sorts.arities_of algebra);
haftmann@24218
   161
    val the_arities = these o Symtab.lookup arities;
haftmann@24218
   162
    fun mk_arity class tyco =
haftmann@24218
   163
      let
haftmann@24218
   164
        val Ss = Sorts.mg_domain algebra tyco [class];
wenzelm@24920
   165
      in Syntax.pretty_arity ctxt (tyco, Ss, [class]) end;
haftmann@24218
   166
    fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
wenzelm@32966
   167
      ^ setmp_CRITICAL show_sorts false (Syntax.string_of_typ ctxt o Type.strip_sorts) ty);
haftmann@24218
   168
    fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
haftmann@25062
   169
      (SOME o Pretty.str) ("class " ^ Sign.extern_class thy class ^ ":"),
haftmann@24218
   170
      (SOME o Pretty.block) [Pretty.str "supersort: ",
wenzelm@24920
   171
        (Syntax.pretty_sort ctxt o Sign.minimize_sort thy o Sign.super_classes thy) class],
haftmann@25062
   172
      ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks)
haftmann@25062
   173
          (Pretty.str "parameters:" :: ps)) o map mk_param
wenzelm@24930
   174
        o these o Option.map #params o try (AxClass.get_info thy)) class,
haftmann@24218
   175
      (SOME o Pretty.block o Pretty.breaks) [
haftmann@24218
   176
        Pretty.str "instances:",
haftmann@24218
   177
        Pretty.list "" "" (map (mk_arity class) (the_arities class))
haftmann@24218
   178
      ]
haftmann@24218
   179
    ]
haftmann@24218
   180
  in
haftmann@24589
   181
    (Pretty.writeln o Pretty.chunks o separate (Pretty.str "")
haftmann@24589
   182
      o map mk_entry o Sorts.all_classes) algebra
haftmann@24218
   183
  end;
haftmann@24218
   184
haftmann@24218
   185
haftmann@24218
   186
(* updaters *)
haftmann@24218
   187
haftmann@32850
   188
fun register class sups params base_sort base_morph export_morph
haftmann@29358
   189
    axiom assm_intro of_class thy =
haftmann@25002
   190
  let
haftmann@25368
   191
    val operations = map (fn (v_ty as (_, ty), (c, _)) =>
haftmann@25683
   192
      (c, (class, (ty, Free v_ty)))) params;
haftmann@25038
   193
    val add_class = Graph.new_node (class,
haftmann@31599
   194
        make_class_data (((map o pairself) fst params, base_sort,
haftmann@32850
   195
          base_morph, export_morph, assm_intro, of_class, axiom), ([], operations)))
haftmann@29526
   196
      #> fold (curry Graph.add_edge class) sups;
haftmann@25618
   197
  in ClassData.map add_class thy end;
haftmann@24218
   198
haftmann@36674
   199
fun activate_defs class thms thy = case Element.eq_morphism thy thms
haftmann@36674
   200
 of SOME eq_morph => fold (fn cls => fn thy =>
ballarin@38353
   201
      Context.theory_map (Locale.amend_registration (cls, base_morphism thy cls)
ballarin@38353
   202
        (eq_morph, true) (export_morphism thy cls)) thy) (heritage thy [class]) thy
haftmann@36674
   203
  | NONE => thy;
haftmann@29526
   204
haftmann@25368
   205
fun register_operation class (c, (t, some_def)) thy =
haftmann@25062
   206
  let
haftmann@29358
   207
    val base_sort = base_sort thy class;
haftmann@29437
   208
    val prep_typ = map_type_tfree
haftmann@29437
   209
      (fn (v, sort) => if Name.aT = v
haftmann@29437
   210
        then TFree (v, base_sort) else TVar ((v, 0), sort));
haftmann@25368
   211
    val t' = map_types prep_typ t;
haftmann@25368
   212
    val ty' = Term.fastype_of t';
haftmann@25062
   213
  in
haftmann@25062
   214
    thy
haftmann@25062
   215
    |> (ClassData.map o Graph.map_node class o map_class_data o apsnd)
haftmann@25368
   216
      (fn (defs, operations) =>
haftmann@25096
   217
        (fold cons (the_list some_def) defs,
haftmann@25368
   218
          (c, (class, (ty', t'))) :: operations))
haftmann@36674
   219
    |> activate_defs class (the_list some_def)
haftmann@25062
   220
  end;
haftmann@24218
   221
haftmann@29558
   222
fun register_subclass (sub, sup) some_dep_morph some_wit export thy =
haftmann@25062
   223
  let
haftmann@29558
   224
    val intros = (snd o rules thy) sup :: map_filter I
wenzelm@35021
   225
      [Option.map (Drule.export_without_context_open o Element.conclude_witness) some_wit,
haftmann@29558
   226
        (fst o rules thy) sub];
haftmann@29610
   227
    val tac = EVERY (map (TRYALL o Tactic.rtac) intros);
wenzelm@32970
   228
    val classrel = Skip_Proof.prove_global thy [] [] (Logic.mk_classrel (sub, sup))
haftmann@29558
   229
      (K tac);
haftmann@29509
   230
    val diff_sort = Sign.complete_sort thy [sup]
haftmann@31012
   231
      |> subtract (op =) (Sign.complete_sort thy [sub])
haftmann@31012
   232
      |> filter (is_class thy);
haftmann@32066
   233
    val add_dependency = case some_dep_morph
haftmann@32066
   234
     of SOME dep_morph => Locale.add_dependency sub
haftmann@32066
   235
          (sup, dep_morph $> Element.satisfy_morphism (the_list some_wit)) export
haftmann@32066
   236
      | NONE => I
haftmann@25618
   237
  in
haftmann@25618
   238
    thy
haftmann@37243
   239
    |> AxClass.add_classrel classrel
haftmann@25618
   240
    |> ClassData.map (Graph.add_edge (sub, sup))
haftmann@29526
   241
    |> activate_defs sub (these_defs thy diff_sort)
haftmann@32066
   242
    |> add_dependency
haftmann@25618
   243
  end;
haftmann@25618
   244
haftmann@24218
   245
haftmann@24589
   246
(** classes and class target **)
haftmann@24218
   247
haftmann@25002
   248
(* class context syntax *)
haftmann@24748
   249
haftmann@35858
   250
fun these_unchecks thy = map (fn (c, (_, (ty, t))) => (t, Const (c, ty)))
haftmann@35858
   251
  o these_operations thy;
haftmann@29577
   252
haftmann@29632
   253
fun redeclare_const thy c =
wenzelm@30364
   254
  let val b = Long_Name.base_name c
haftmann@29632
   255
  in Sign.intern_const thy b = c ? Variable.declare_const (b, c) end;
haftmann@29632
   256
haftmann@29577
   257
fun synchronize_class_syntax sort base_sort ctxt =
haftmann@24914
   258
  let
wenzelm@25344
   259
    val thy = ProofContext.theory_of ctxt;
haftmann@26596
   260
    val algebra = Sign.classes_of thy;
haftmann@29577
   261
    val operations = these_operations thy sort;
haftmann@26518
   262
    fun subst_class_typ sort = map_type_tfree (K (TVar ((Name.aT, 0), sort)));
haftmann@26518
   263
    val primary_constraints =
haftmann@25368
   264
      (map o apsnd) (subst_class_typ base_sort o fst o snd) operations;
haftmann@26518
   265
    val secondary_constraints =
haftmann@25368
   266
      (map o apsnd) (fn (class, (ty, _)) => subst_class_typ [class] ty) operations;
haftmann@26518
   267
    fun improve (c, ty) = (case AList.lookup (op =) primary_constraints c
haftmann@26238
   268
     of SOME ty' => (case try (Type.raw_match (ty', ty)) Vartab.empty
haftmann@26238
   269
         of SOME tyenv => (case Vartab.lookup tyenv (Name.aT, 0)
haftmann@33968
   270
             of SOME (_, ty' as TVar (vi, sort)) =>
wenzelm@37153
   271
                  if Type_Infer.is_param vi
haftmann@26596
   272
                    andalso Sorts.sort_le algebra (base_sort, sort)
haftmann@26596
   273
                      then SOME (ty', TFree (Name.aT, base_sort))
haftmann@26596
   274
                      else NONE
haftmann@26238
   275
              | _ => NONE)
haftmann@26238
   276
          | NONE => NONE)
haftmann@26238
   277
      | NONE => NONE)
haftmann@26238
   278
    fun subst (c, ty) = Option.map snd (AList.lookup (op =) operations c);
haftmann@29577
   279
    val unchecks = these_unchecks thy sort;
haftmann@25083
   280
  in
haftmann@25083
   281
    ctxt
haftmann@29632
   282
    |> fold (redeclare_const thy o fst) primary_constraints
haftmann@26518
   283
    |> Overloading.map_improvable_syntax (K (((primary_constraints, secondary_constraints),
haftmann@26730
   284
        (((improve, subst), true), unchecks)), false))
haftmann@26518
   285
    |> Overloading.set_primary_constraints
haftmann@25083
   286
  end;
haftmann@25083
   287
haftmann@29632
   288
fun redeclare_operations thy sort =
haftmann@29632
   289
  fold (redeclare_const thy o fst) (these_operations thy sort);
haftmann@29632
   290
haftmann@29577
   291
fun begin sort base_sort ctxt =
haftmann@25083
   292
  ctxt
haftmann@25083
   293
  |> Variable.declare_term
haftmann@25083
   294
      (Logic.mk_type (TFree (Name.aT, base_sort)))
haftmann@29577
   295
  |> synchronize_class_syntax sort base_sort
haftmann@26238
   296
  |> Overloading.add_improvable_syntax;
haftmann@24901
   297
haftmann@25311
   298
fun init class thy =
haftmann@25311
   299
  thy
haftmann@29509
   300
  |> Locale.init class
haftmann@29358
   301
  |> begin [class] (base_sort thy class);
haftmann@24914
   302
haftmann@24748
   303
haftmann@27690
   304
(* class target *)
haftmann@27690
   305
wenzelm@30364
   306
val class_prefix = Logic.const_of_class o Long_Name.base_name;
haftmann@29526
   307
haftmann@38842
   308
fun target_extension f class lthy =
haftmann@38842
   309
  lthy
haftmann@38842
   310
  |> Local_Theory.raw_theory f
haftmann@38842
   311
  |> Local_Theory.target (synchronize_class_syntax [class]
haftmann@38842
   312
      (base_sort (ProofContext.theory_of lthy) class));
haftmann@38842
   313
haftmann@38842
   314
local
haftmann@38842
   315
haftmann@38842
   316
fun target_const class ((c, mx), (type_params, dict)) thy =
haftmann@27690
   317
  let
haftmann@29577
   318
    val morph = morphism thy class;
wenzelm@30350
   319
    val b = Morphism.binding morph c;
wenzelm@30350
   320
    val b_def = Morphism.binding morph (Binding.suffix_name "_dict" b);
haftmann@29577
   321
    val c' = Sign.full_name thy b;
haftmann@29437
   322
    val dict' = Morphism.term morph dict;
haftmann@35858
   323
    val ty' = map Term.fastype_of type_params ---> Term.fastype_of dict';
haftmann@35858
   324
    val def_eq = Logic.mk_equals (list_comb (Const (c', ty'), type_params), dict')
haftmann@29577
   325
      |> map_types Type.strip_sorts;
haftmann@27690
   326
  in
haftmann@29577
   327
    thy
wenzelm@33173
   328
    |> Sign.declare_const ((b, Type.strip_sorts ty'), mx)
haftmann@29577
   329
    |> snd
haftmann@29577
   330
    |> Thm.add_def false false (b_def, def_eq)
wenzelm@36106
   331
    |>> apsnd Thm.varifyT_global
wenzelm@36106
   332
    |-> (fn (_, def_thm) => PureThy.store_thm (b_def, def_thm)
haftmann@29577
   333
      #> snd
haftmann@35858
   334
      #> null type_params ? register_operation class (c', (dict', SOME (Thm.symmetric def_thm))))
haftmann@27690
   335
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@27690
   336
  end;
haftmann@27690
   337
haftmann@38842
   338
fun target_abbrev class prmode ((c, mx), rhs) thy =
haftmann@27690
   339
  let
haftmann@29577
   340
    val morph = morphism thy class;
haftmann@29577
   341
    val unchecks = these_unchecks thy [class];
wenzelm@30350
   342
    val b = Morphism.binding morph c;
haftmann@29577
   343
    val c' = Sign.full_name thy b;
haftmann@27690
   344
    val rhs' = Pattern.rewrite_term thy unchecks [] rhs;
haftmann@27690
   345
    val ty' = Term.fastype_of rhs';
wenzelm@35845
   346
    val rhs'' = map_types Logic.varifyT_global rhs';
haftmann@27690
   347
  in
haftmann@29577
   348
    thy
wenzelm@33173
   349
    |> Sign.add_abbrev (#1 prmode) (b, rhs'')
haftmann@29577
   350
    |> snd
haftmann@27690
   351
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@27690
   352
    |> Sign.notation true prmode [(Const (c', ty'), mx)]
wenzelm@37154
   353
    |> not (#1 prmode = Print_Mode.input) ? register_operation class (c', (rhs', NONE))
haftmann@27690
   354
  end;
haftmann@27690
   355
haftmann@38842
   356
in
haftmann@38842
   357
haftmann@38842
   358
fun const class arg = target_extension (target_const class arg) class;
haftmann@38842
   359
fun abbrev class prmode arg = target_extension (target_abbrev class prmode arg) class;
haftmann@38842
   360
haftmann@38842
   361
end;
haftmann@38842
   362
haftmann@27690
   363
haftmann@31632
   364
(* simple subclasses *)
haftmann@31632
   365
haftmann@31632
   366
local
haftmann@31632
   367
haftmann@31632
   368
fun gen_classrel mk_prop classrel thy =
haftmann@31632
   369
  let
haftmann@31632
   370
    fun after_qed results =
wenzelm@39031
   371
      ProofContext.background_theory ((fold o fold) AxClass.add_classrel results);
haftmann@31632
   372
  in
haftmann@31632
   373
    thy
wenzelm@36633
   374
    |> ProofContext.init_global
wenzelm@36334
   375
    |> Proof.theorem NONE after_qed [[(mk_prop thy classrel, [])]]
haftmann@31632
   376
  end;
haftmann@31632
   377
haftmann@31632
   378
in
haftmann@31632
   379
haftmann@31632
   380
val classrel =
haftmann@31632
   381
  gen_classrel (Logic.mk_classrel oo AxClass.cert_classrel);
haftmann@31632
   382
val classrel_cmd =
haftmann@31632
   383
  gen_classrel (Logic.mk_classrel oo AxClass.read_classrel);
haftmann@31632
   384
haftmann@31632
   385
end; (*local*)
haftmann@31632
   386
haftmann@31632
   387
haftmann@25462
   388
(** instantiation target **)
haftmann@25462
   389
haftmann@25462
   390
(* bookkeeping *)
haftmann@25462
   391
haftmann@25462
   392
datatype instantiation = Instantiation of {
haftmann@25864
   393
  arities: string list * (string * sort) list * sort,
haftmann@25462
   394
  params: ((string * string) * (string * typ)) list
haftmann@25603
   395
    (*(instantiation parameter, type constructor), (local instantiation parameter, typ)*)
haftmann@25462
   396
}
haftmann@25462
   397
wenzelm@33519
   398
structure Instantiation = Proof_Data
haftmann@25462
   399
(
haftmann@25462
   400
  type T = instantiation
haftmann@25536
   401
  fun init _ = Instantiation { arities = ([], [], []), params = [] };
haftmann@25462
   402
);
haftmann@25462
   403
haftmann@25485
   404
fun mk_instantiation (arities, params) =
haftmann@25485
   405
  Instantiation { arities = arities, params = params };
wenzelm@33673
   406
fun get_instantiation lthy = case Instantiation.get (Local_Theory.target_of lthy)
haftmann@25485
   407
 of Instantiation data => data;
wenzelm@33673
   408
fun map_instantiation f = (Local_Theory.target o Instantiation.map)
haftmann@25514
   409
  (fn Instantiation { arities, params } => mk_instantiation (f (arities, params)));
haftmann@25462
   410
haftmann@25514
   411
fun the_instantiation lthy = case get_instantiation lthy
haftmann@25536
   412
 of { arities = ([], [], []), ... } => error "No instantiation target"
haftmann@25485
   413
  | data => data;
haftmann@25462
   414
haftmann@25485
   415
val instantiation_params = #params o get_instantiation;
haftmann@25462
   416
haftmann@30511
   417
fun instantiation_param lthy b = instantiation_params lthy
haftmann@30511
   418
  |> find_first (fn (_, (v, _)) => Binding.name_of b = v)
haftmann@25462
   419
  |> Option.map (fst o fst);
haftmann@25462
   420
haftmann@31868
   421
fun read_multi_arity thy (raw_tycos, raw_sorts, raw_sort) =
haftmann@31868
   422
  let
wenzelm@36633
   423
    val ctxt = ProofContext.init_global thy;
wenzelm@35676
   424
    val all_arities = map (fn raw_tyco => ProofContext.read_arity ctxt
haftmann@31868
   425
      (raw_tyco, raw_sorts, raw_sort)) raw_tycos;
haftmann@31868
   426
    val tycos = map #1 all_arities;
haftmann@31868
   427
    val (_, sorts, sort) = hd all_arities;
haftmann@31868
   428
    val vs = Name.names Name.context Name.aT sorts;
haftmann@31868
   429
  in (tycos, vs, sort) end;
haftmann@31868
   430
haftmann@25462
   431
haftmann@25462
   432
(* syntax *)
haftmann@25462
   433
haftmann@26238
   434
fun synchronize_inst_syntax ctxt =
haftmann@25462
   435
  let
haftmann@33968
   436
    val Instantiation { params, ... } = Instantiation.get ctxt;
haftmann@31243
   437
haftmann@33968
   438
    val lookup_inst_param = AxClass.lookup_inst_param
haftmann@33968
   439
      (Sign.consts_of (ProofContext.theory_of ctxt)) params;
haftmann@31243
   440
    fun subst (c, ty) = case lookup_inst_param (c, ty)
haftmann@31243
   441
     of SOME (v_ty as (_, ty)) => SOME (ty, Free v_ty)
haftmann@31243
   442
      | NONE => NONE;
haftmann@26238
   443
    val unchecks =
haftmann@26238
   444
      map (fn ((c, _), v_ty as (_, ty)) => (Free v_ty, Const (c, ty))) params;
haftmann@26238
   445
  in
haftmann@26238
   446
    ctxt
haftmann@26259
   447
    |> Overloading.map_improvable_syntax
haftmann@26730
   448
         (fn (((primary_constraints, _), (((improve, _), _), _)), _) =>
haftmann@26730
   449
            (((primary_constraints, []), (((improve, subst), false), unchecks)), false))
haftmann@26238
   450
  end;
haftmann@25462
   451
haftmann@38608
   452
fun resort_terms pp algebra consts constraints ts =
haftmann@38608
   453
  let
haftmann@38608
   454
    fun matchings (Const (c_ty as (c, _))) = (case constraints c
haftmann@38608
   455
         of NONE => I
haftmann@38608
   456
          | SOME sorts => fold2 (curry (Sorts.meet_sort algebra))
haftmann@38608
   457
              (Consts.typargs consts c_ty) sorts)
haftmann@38608
   458
      | matchings _ = I
haftmann@38608
   459
    val tvartab = (fold o fold_aterms) matchings ts Vartab.empty
haftmann@38608
   460
      handle Sorts.CLASS_ERROR e => error (Sorts.class_error pp e);
haftmann@38608
   461
    val inst = map_type_tvar
haftmann@38608
   462
      (fn (vi, sort) => TVar (vi, the_default sort (Vartab.lookup tvartab vi)));
haftmann@38608
   463
  in if Vartab.is_empty tvartab then NONE else SOME ((map o map_types) inst ts) end;
haftmann@38608
   464
haftmann@25462
   465
haftmann@25462
   466
(* target *)
haftmann@25462
   467
haftmann@37678
   468
val sanitize_name = (*necessary as long as "dirty" type identifiers are permitted*)
haftmann@25485
   469
  let
haftmann@25574
   470
    fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s
haftmann@25574
   471
      orelse s = "'" orelse s = "_";
haftmann@25485
   472
    val is_junk = not o is_valid andf Symbol.is_regular;
haftmann@25485
   473
    val junk = Scan.many is_junk;
haftmann@25485
   474
    val scan_valids = Symbol.scanner "Malformed input"
haftmann@25485
   475
      ((junk |--
haftmann@25485
   476
        (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
haftmann@25485
   477
        --| junk))
wenzelm@25999
   478
      ::: Scan.repeat ((Scan.many1 is_valid >> implode) --| junk));
haftmann@25485
   479
  in
haftmann@25485
   480
    explode #> scan_valids #> implode
haftmann@25485
   481
  end;
haftmann@25462
   482
haftmann@37678
   483
val type_name = sanitize_name o Long_Name.base_name;
haftmann@26259
   484
haftmann@38608
   485
fun define_overloaded (c, U) v (b_def, rhs) = Local_Theory.theory_result
haftmann@38608
   486
    (AxClass.declare_overloaded (c, U) ##>> AxClass.define_overloaded b_def (c, rhs))
haftmann@38608
   487
  ##> (map_instantiation o apsnd) (filter_out (fn (_, (v', _)) => v' = v))
haftmann@38608
   488
  ##> Local_Theory.target synchronize_inst_syntax;
haftmann@38608
   489
haftmann@38608
   490
fun foundation (((b, U), mx), (b_def, rhs)) (type_params, term_params) lthy =
haftmann@38608
   491
  case instantiation_param lthy b
haftmann@38608
   492
   of SOME c => if mx <> NoSyn then error ("Illegal mixfix syntax for overloaded constant " ^ quote c)
haftmann@38608
   493
        else lthy |> define_overloaded (c, U) (Binding.name_of b) (b_def, rhs)
haftmann@38608
   494
    | NONE => lthy |>
haftmann@38608
   495
        Generic_Target.theory_foundation (((b, U), mx), (b_def, rhs)) (type_params, term_params);
haftmann@38608
   496
haftmann@38608
   497
fun pretty lthy =
haftmann@26518
   498
  let
haftmann@38608
   499
    val { arities = (tycos, vs, sort), params } = the_instantiation lthy;
haftmann@38608
   500
    val thy = ProofContext.theory_of lthy;
haftmann@38608
   501
    fun pr_arity tyco = Syntax.pretty_arity lthy (tyco, map snd vs, sort);
haftmann@38608
   502
    fun pr_param ((c, _), (v, ty)) =
haftmann@38608
   503
      (Pretty.block o Pretty.breaks) [Pretty.str v, Pretty.str "==",
haftmann@38608
   504
        (Pretty.str o Sign.extern_const thy) c, Pretty.str "::", Syntax.pretty_typ_global thy ty];
haftmann@38608
   505
  in Pretty.str "instantiation" :: map pr_arity tycos @ map pr_param params end;
haftmann@26518
   506
haftmann@38608
   507
fun conclude lthy =
haftmann@38608
   508
  let
haftmann@38608
   509
    val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
haftmann@38608
   510
    val thy = ProofContext.theory_of lthy;
haftmann@38608
   511
    val _ = map (fn tyco => if Sign.of_sort thy
haftmann@38608
   512
        (Type (tyco, map TFree vs), sort)
haftmann@38608
   513
      then () else error ("Missing instance proof for type " ^ quote (Sign.extern_type thy tyco)))
haftmann@38608
   514
        tycos;
haftmann@38608
   515
  in lthy end;
haftmann@38608
   516
haftmann@38608
   517
fun instantiation (tycos, vs, sort) thy =
haftmann@25462
   518
  let
haftmann@25536
   519
    val _ = if null tycos then error "At least one arity must be given" else ();
haftmann@31243
   520
    val class_params = these_params thy (filter (can (AxClass.get_info thy)) sort);
haftmann@29632
   521
    fun get_param tyco (param, (_, (c, ty))) =
haftmann@29632
   522
      if can (AxClass.param_of_inst thy) (c, tyco)
haftmann@25603
   523
      then NONE else SOME ((c, tyco),
haftmann@25864
   524
        (param ^ "_" ^ type_name tyco, map_atyps (K (Type (tyco, map TFree vs))) ty));
haftmann@31243
   525
    val params = map_product get_param tycos class_params |> map_filter I;
haftmann@26518
   526
    val primary_constraints = map (apsnd
haftmann@31243
   527
      (map_atyps (K (TVar ((Name.aT, 0), [])))) o snd o snd) class_params;
wenzelm@26939
   528
    val pp = Syntax.pp_global thy;
haftmann@26518
   529
    val algebra = Sign.classes_of thy
haftmann@26518
   530
      |> fold (fn tyco => Sorts.add_arities pp
haftmann@26518
   531
            (tyco, map (fn class => (class, map snd vs)) sort)) tycos;
haftmann@26518
   532
    val consts = Sign.consts_of thy;
haftmann@26518
   533
    val improve_constraints = AList.lookup (op =)
haftmann@31243
   534
      (map (fn (_, (class, (c, _))) => (c, [[class]])) class_params);
haftmann@33966
   535
    fun resort_check ts ctxt = case resort_terms (Syntax.pp ctxt) algebra consts improve_constraints ts
haftmann@26518
   536
     of NONE => NONE
haftmann@26518
   537
      | SOME ts' => SOME (ts', ctxt);
haftmann@31243
   538
    val lookup_inst_param = AxClass.lookup_inst_param consts params;
haftmann@31210
   539
    val typ_instance = Type.typ_instance (Sign.tsig_of thy);
haftmann@31243
   540
    fun improve (c, ty) = case lookup_inst_param (c, ty)
haftmann@31243
   541
     of SOME (_, ty') => if typ_instance (ty', ty) then SOME (ty, ty') else NONE
haftmann@26259
   542
      | NONE => NONE;
haftmann@25485
   543
  in
haftmann@25485
   544
    thy
haftmann@32379
   545
    |> Theory.checkpoint
wenzelm@36633
   546
    |> ProofContext.init_global
haftmann@31243
   547
    |> Instantiation.put (mk_instantiation ((tycos, vs, sort), params))
wenzelm@27281
   548
    |> fold (Variable.declare_typ o TFree) vs
haftmann@31243
   549
    |> fold (Variable.declare_names o Free o snd) params
haftmann@26259
   550
    |> (Overloading.map_improvable_syntax o apfst)
haftmann@29906
   551
         (K ((primary_constraints, []), (((improve, K NONE), false), [])))
haftmann@26259
   552
    |> Overloading.add_improvable_syntax
haftmann@26518
   553
    |> Context.proof_map (Syntax.add_term_check 0 "resorting" resort_check)
haftmann@26238
   554
    |> synchronize_inst_syntax
haftmann@38608
   555
    |> Local_Theory.init NONE ""
haftmann@38608
   556
       {define = Generic_Target.define foundation,
haftmann@38608
   557
        notes = Generic_Target.notes
haftmann@38608
   558
          (fn kind => fn global_facts => fn _ => Generic_Target.theory_notes kind global_facts),
haftmann@38608
   559
        abbrev = Generic_Target.abbrev
haftmann@38608
   560
          (fn prmode => fn (b, mx) => fn (t, _) => fn _ => Generic_Target.theory_abbrev prmode ((b, mx), t)),
haftmann@38608
   561
        declaration = K Generic_Target.theory_declaration,
haftmann@38608
   562
        syntax_declaration = K Generic_Target.theory_declaration,
haftmann@38608
   563
        pretty = pretty,
haftmann@38608
   564
        exit = Local_Theory.target_of o conclude}
haftmann@25485
   565
  end;
haftmann@25485
   566
haftmann@38608
   567
fun instantiation_cmd arities thy =
haftmann@38608
   568
  instantiation (read_multi_arity thy arities) thy;
haftmann@26238
   569
haftmann@25485
   570
fun gen_instantiation_instance do_proof after_qed lthy =
haftmann@25485
   571
  let
haftmann@25864
   572
    val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
haftmann@25864
   573
    val arities_proof = maps (fn tyco => Logic.mk_arities (tyco, map snd vs, sort)) tycos;
haftmann@25462
   574
    fun after_qed' results =
haftmann@37243
   575
      Local_Theory.theory (fold (AxClass.add_arity o Thm.varifyT_global) results)
haftmann@25462
   576
      #> after_qed;
haftmann@25462
   577
  in
haftmann@25462
   578
    lthy
haftmann@25462
   579
    |> do_proof after_qed' arities_proof
haftmann@25462
   580
  end;
haftmann@25462
   581
haftmann@25485
   582
val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
wenzelm@36334
   583
  Proof.theorem NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
haftmann@25462
   584
haftmann@25485
   585
fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
haftmann@25502
   586
  fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
haftmann@25502
   587
    (fn {context, ...} => tac context)) ts) lthy) I;
haftmann@25462
   588
haftmann@28666
   589
fun prove_instantiation_exit tac = prove_instantiation_instance tac
wenzelm@33673
   590
  #> Local_Theory.exit_global;
haftmann@28666
   591
haftmann@28666
   592
fun prove_instantiation_exit_result f tac x lthy =
haftmann@28666
   593
  let
haftmann@29437
   594
    val morph = ProofContext.export_morphism lthy
wenzelm@36633
   595
      (ProofContext.init_global (ProofContext.theory_of lthy));
haftmann@29437
   596
    val y = f morph x;
haftmann@28666
   597
  in
haftmann@28666
   598
    lthy
haftmann@28666
   599
    |> prove_instantiation_exit (fn ctxt => tac ctxt y)
haftmann@28666
   600
    |> pair y
haftmann@28666
   601
  end;
haftmann@28666
   602
haftmann@29526
   603
haftmann@31632
   604
(* simplified instantiation interface with no class parameter *)
haftmann@31632
   605
haftmann@31868
   606
fun instance_arity_cmd raw_arities thy =
haftmann@31632
   607
  let
haftmann@31868
   608
    val (tycos, vs, sort) = read_multi_arity thy raw_arities;
haftmann@31868
   609
    val sorts = map snd vs;
haftmann@31868
   610
    val arities = maps (fn tyco => Logic.mk_arities (tyco, sorts, sort)) tycos;
wenzelm@39031
   611
    fun after_qed results = ProofContext.background_theory
haftmann@37243
   612
      ((fold o fold) AxClass.add_arity results);
haftmann@31632
   613
  in
haftmann@31632
   614
    thy
wenzelm@36633
   615
    |> ProofContext.init_global
wenzelm@36334
   616
    |> Proof.theorem NONE after_qed (map (fn t => [(t, [])]) arities)
haftmann@31632
   617
  end;
haftmann@31632
   618
haftmann@31632
   619
haftmann@29526
   620
(** tactics and methods **)
haftmann@29526
   621
haftmann@29526
   622
fun intro_classes_tac facts st =
haftmann@29526
   623
  let
haftmann@29526
   624
    val thy = Thm.theory_of_thm st;
haftmann@29526
   625
    val classes = Sign.all_classes thy;
haftmann@29526
   626
    val class_trivs = map (Thm.class_triv thy) classes;
haftmann@29526
   627
    val class_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
haftmann@29526
   628
    val assm_intros = all_assm_intros thy;
haftmann@29526
   629
  in
haftmann@29526
   630
    Method.intros_tac (class_trivs @ class_intros @ assm_intros) facts st
haftmann@29526
   631
  end;
haftmann@29526
   632
haftmann@29526
   633
fun default_intro_tac ctxt [] =
haftmann@29577
   634
      intro_classes_tac [] ORELSE Locale.intro_locales_tac true ctxt []
haftmann@29526
   635
  | default_intro_tac _ _ = no_tac;
haftmann@29526
   636
haftmann@29526
   637
fun default_tac rules ctxt facts =
haftmann@29526
   638
  HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
haftmann@29526
   639
    default_intro_tac ctxt facts;
haftmann@29526
   640
haftmann@29526
   641
val _ = Context.>> (Context.map_theory
wenzelm@30520
   642
 (Method.setup (Binding.name "intro_classes") (Scan.succeed (K (METHOD intro_classes_tac)))
wenzelm@30520
   643
    "back-chain introduction rules of classes" #>
wenzelm@30520
   644
  Method.setup (Binding.name "default") (Attrib.thms >> (METHOD oo default_tac))
wenzelm@30520
   645
    "apply some intro/elim rule"));
haftmann@29526
   646
haftmann@24218
   647
end;
haftmann@25683
   648