src/Pure/Isar/class.ML
author wenzelm
Sun Oct 30 22:20:45 2011 +0100 (2011-10-30 ago)
changeset 45310 adaf2184b79d
parent 45293 57def0b39696
child 45344 e209da839ff4
permissions -rw-r--r--
removed obsolete argument (cf. aa35859c8741);
haftmann@38379
     1
(*  Title:      Pure/Isar/class.ML
haftmann@24218
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@24218
     3
haftmann@38379
     4
Type classes derived from primitive axclasses and locales.
haftmann@24218
     5
*)
haftmann@24218
     6
haftmann@38379
     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@38379
    12
  val base_sort: theory -> class -> sort
haftmann@38379
    13
  val rules: theory -> class -> thm option * thm
haftmann@38379
    14
  val these_defs: theory -> sort -> thm list
haftmann@38379
    15
  val these_operations: theory -> sort
haftmann@38379
    16
    -> (string * (class * (typ * term))) list
wenzelm@42359
    17
  val print_classes: Proof.context -> unit
haftmann@25311
    18
  val init: class -> theory -> Proof.context
haftmann@38379
    19
  val begin: class list -> sort -> Proof.context -> Proof.context
haftmann@38619
    20
  val const: class -> (binding * mixfix) * (term list * term) -> local_theory -> local_theory
haftmann@38619
    21
  val abbrev: class -> Syntax.mode -> (binding * mixfix) * term -> local_theory -> local_theory
haftmann@38379
    22
  val redeclare_operations: theory -> sort -> Proof.context -> Proof.context
haftmann@29526
    23
  val class_prefix: string -> string
haftmann@38379
    24
  val register: class -> class list -> ((string * typ) * (string * typ)) list
haftmann@38379
    25
    -> sort -> morphism -> morphism -> thm option -> thm option -> thm
haftmann@38379
    26
    -> theory -> theory
haftmann@25485
    27
haftmann@25462
    28
  (*instances*)
haftmann@38379
    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@31869
    38
  val read_multi_arity: theory -> xstring list * xstring list * xstring
haftmann@31869
    39
    -> string list * (string * sort) list * sort
haftmann@26259
    40
  val type_name: string -> string
haftmann@38348
    41
  val instantiation_cmd: xstring list * xstring list * xstring -> theory -> local_theory
haftmann@38377
    42
  val instance_arity_cmd: xstring list * xstring list * xstring -> theory -> Proof.state
haftmann@25485
    43
haftmann@31635
    44
  (*subclasses*)
haftmann@31635
    45
  val classrel: class * class -> theory -> Proof.state
haftmann@31635
    46
  val classrel_cmd: xstring * xstring -> theory -> Proof.state
haftmann@38379
    47
  val register_subclass: class * class -> morphism option -> Element.witness option
haftmann@38379
    48
    -> morphism -> theory -> theory
haftmann@31635
    49
haftmann@31635
    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@38379
    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@29439
    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,
wenzelm@42359
    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@29358
   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
wenzelm@42359
   152
fun print_classes ctxt =
haftmann@24218
   153
  let
wenzelm@42360
   154
    val thy = Proof_Context.theory_of ctxt;
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@36328
   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;
wenzelm@42359
   166
    fun mk_param (c, ty) =
wenzelm@42360
   167
      Pretty.str (Proof_Context.extern_const ctxt c ^ " :: " ^
wenzelm@42359
   168
        Syntax.string_of_typ (Config.put show_sorts false ctxt) (Type.strip_sorts ty));
haftmann@24218
   169
    fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
wenzelm@42360
   170
      (SOME o Pretty.str) ("class " ^ Proof_Context.extern_class ctxt class ^ ":"),
haftmann@24218
   171
      (SOME o Pretty.block) [Pretty.str "supersort: ",
wenzelm@24920
   172
        (Syntax.pretty_sort ctxt o Sign.minimize_sort thy o Sign.super_classes thy) class],
haftmann@25062
   173
      ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks)
haftmann@25062
   174
          (Pretty.str "parameters:" :: ps)) o map mk_param
wenzelm@24930
   175
        o these o Option.map #params o try (AxClass.get_info thy)) class,
haftmann@24218
   176
      (SOME o Pretty.block o Pretty.breaks) [
haftmann@24218
   177
        Pretty.str "instances:",
haftmann@24218
   178
        Pretty.list "" "" (map (mk_arity class) (the_arities class))
haftmann@24218
   179
      ]
haftmann@24218
   180
    ]
haftmann@24218
   181
  in
haftmann@24589
   182
    (Pretty.writeln o Pretty.chunks o separate (Pretty.str "")
haftmann@24589
   183
      o map mk_entry o Sorts.all_classes) algebra
haftmann@24218
   184
  end;
haftmann@24218
   185
haftmann@24218
   186
haftmann@24218
   187
(* updaters *)
haftmann@24218
   188
haftmann@32850
   189
fun register class sups params base_sort base_morph export_morph
haftmann@29358
   190
    axiom assm_intro of_class thy =
haftmann@25002
   191
  let
haftmann@25368
   192
    val operations = map (fn (v_ty as (_, ty), (c, _)) =>
haftmann@25683
   193
      (c, (class, (ty, Free v_ty)))) params;
haftmann@25038
   194
    val add_class = Graph.new_node (class,
haftmann@31599
   195
        make_class_data (((map o pairself) fst params, base_sort,
haftmann@32850
   196
          base_morph, export_morph, assm_intro, of_class, axiom), ([], operations)))
haftmann@29526
   197
      #> fold (curry Graph.add_edge class) sups;
haftmann@25618
   198
  in ClassData.map add_class thy end;
haftmann@24218
   199
haftmann@36674
   200
fun activate_defs class thms thy = case Element.eq_morphism thy thms
haftmann@36674
   201
 of SOME eq_morph => fold (fn cls => fn thy =>
ballarin@38107
   202
      Context.theory_map (Locale.amend_registration (cls, base_morphism thy cls)
ballarin@38107
   203
        (eq_morph, true) (export_morphism thy cls)) thy) (heritage thy [class]) thy
haftmann@36674
   204
  | NONE => thy;
haftmann@29526
   205
haftmann@25368
   206
fun register_operation class (c, (t, some_def)) thy =
haftmann@25062
   207
  let
haftmann@29358
   208
    val base_sort = base_sort thy class;
haftmann@29439
   209
    val prep_typ = map_type_tfree
haftmann@29439
   210
      (fn (v, sort) => if Name.aT = v
haftmann@29439
   211
        then TFree (v, base_sort) else TVar ((v, 0), sort));
haftmann@25368
   212
    val t' = map_types prep_typ t;
haftmann@25368
   213
    val ty' = Term.fastype_of t';
haftmann@25062
   214
  in
haftmann@25062
   215
    thy
haftmann@25062
   216
    |> (ClassData.map o Graph.map_node class o map_class_data o apsnd)
haftmann@25368
   217
      (fn (defs, operations) =>
haftmann@25096
   218
        (fold cons (the_list some_def) defs,
haftmann@25368
   219
          (c, (class, (ty', t'))) :: operations))
haftmann@36674
   220
    |> activate_defs class (the_list some_def)
haftmann@25062
   221
  end;
haftmann@24218
   222
haftmann@29558
   223
fun register_subclass (sub, sup) some_dep_morph some_wit export thy =
haftmann@25618
   224
  let
haftmann@29558
   225
    val intros = (snd o rules thy) sup :: map_filter I
wenzelm@35021
   226
      [Option.map (Drule.export_without_context_open o Element.conclude_witness) some_wit,
haftmann@29558
   227
        (fst o rules thy) sub];
haftmann@29610
   228
    val tac = EVERY (map (TRYALL o Tactic.rtac) intros);
wenzelm@32970
   229
    val classrel = Skip_Proof.prove_global thy [] [] (Logic.mk_classrel (sub, sup))
haftmann@29558
   230
      (K tac);
haftmann@29509
   231
    val diff_sort = Sign.complete_sort thy [sup]
haftmann@31012
   232
      |> subtract (op =) (Sign.complete_sort thy [sub])
haftmann@31012
   233
      |> filter (is_class thy);
haftmann@32074
   234
    val add_dependency = case some_dep_morph
haftmann@32074
   235
     of SOME dep_morph => Locale.add_dependency sub
ballarin@41270
   236
          (sup, dep_morph $> Element.satisfy_morphism (the_list some_wit)) NONE export
haftmann@32074
   237
      | NONE => I
haftmann@25618
   238
  in
haftmann@25618
   239
    thy
haftmann@37246
   240
    |> AxClass.add_classrel classrel
haftmann@25618
   241
    |> ClassData.map (Graph.add_edge (sub, sup))
haftmann@29526
   242
    |> activate_defs sub (these_defs thy diff_sort)
haftmann@32074
   243
    |> add_dependency
haftmann@24218
   244
  end;
haftmann@24218
   245
haftmann@24218
   246
haftmann@24589
   247
(** classes and class target **)
haftmann@24218
   248
haftmann@25002
   249
(* class context syntax *)
haftmann@24748
   250
haftmann@35858
   251
fun these_unchecks thy = map (fn (c, (_, (ty, t))) => (t, Const (c, ty)))
haftmann@35858
   252
  o these_operations thy;
haftmann@29577
   253
haftmann@29632
   254
fun redeclare_const thy c =
wenzelm@30364
   255
  let val b = Long_Name.base_name c
haftmann@29632
   256
  in Sign.intern_const thy b = c ? Variable.declare_const (b, c) end;
haftmann@29632
   257
haftmann@29577
   258
fun synchronize_class_syntax sort base_sort ctxt =
haftmann@24914
   259
  let
wenzelm@42360
   260
    val thy = Proof_Context.theory_of ctxt;
haftmann@26596
   261
    val algebra = Sign.classes_of thy;
haftmann@29577
   262
    val operations = these_operations thy sort;
haftmann@26518
   263
    fun subst_class_typ sort = map_type_tfree (K (TVar ((Name.aT, 0), sort)));
haftmann@26518
   264
    val primary_constraints =
haftmann@25368
   265
      (map o apsnd) (subst_class_typ base_sort o fst o snd) operations;
haftmann@26518
   266
    val secondary_constraints =
haftmann@25368
   267
      (map o apsnd) (fn (class, (ty, _)) => subst_class_typ [class] ty) operations;
haftmann@26518
   268
    fun improve (c, ty) = (case AList.lookup (op =) primary_constraints c
haftmann@26238
   269
     of SOME ty' => (case try (Type.raw_match (ty', ty)) Vartab.empty
haftmann@26238
   270
         of SOME tyenv => (case Vartab.lookup tyenv (Name.aT, 0)
haftmann@33969
   271
             of SOME (_, ty' as TVar (vi, sort)) =>
wenzelm@37145
   272
                  if Type_Infer.is_param vi
haftmann@26596
   273
                    andalso Sorts.sort_le algebra (base_sort, sort)
haftmann@26596
   274
                      then SOME (ty', TFree (Name.aT, base_sort))
haftmann@26596
   275
                      else NONE
haftmann@26238
   276
              | _ => NONE)
haftmann@26238
   277
          | NONE => NONE)
haftmann@26238
   278
      | NONE => NONE)
haftmann@26238
   279
    fun subst (c, ty) = Option.map snd (AList.lookup (op =) operations c);
haftmann@29577
   280
    val unchecks = these_unchecks thy sort;
haftmann@25083
   281
  in
haftmann@25083
   282
    ctxt
haftmann@29632
   283
    |> fold (redeclare_const thy o fst) primary_constraints
haftmann@26518
   284
    |> Overloading.map_improvable_syntax (K (((primary_constraints, secondary_constraints),
haftmann@26730
   285
        (((improve, subst), true), unchecks)), false))
haftmann@26518
   286
    |> Overloading.set_primary_constraints
haftmann@25083
   287
  end;
haftmann@25083
   288
haftmann@29632
   289
fun redeclare_operations thy sort =
haftmann@29632
   290
  fold (redeclare_const thy o fst) (these_operations thy sort);
haftmann@29632
   291
haftmann@29577
   292
fun begin sort base_sort ctxt =
haftmann@25083
   293
  ctxt
haftmann@25083
   294
  |> Variable.declare_term
haftmann@25083
   295
      (Logic.mk_type (TFree (Name.aT, base_sort)))
haftmann@29577
   296
  |> synchronize_class_syntax sort base_sort
haftmann@39378
   297
  |> Overloading.activate_improvable_syntax;
haftmann@24901
   298
haftmann@25311
   299
fun init class thy =
haftmann@25311
   300
  thy
haftmann@29509
   301
  |> Locale.init class
haftmann@29358
   302
  |> begin [class] (base_sort thy class);
haftmann@24914
   303
haftmann@24748
   304
haftmann@27690
   305
(* class target *)
haftmann@27690
   306
wenzelm@30364
   307
val class_prefix = Logic.const_of_class o Long_Name.base_name;
haftmann@29526
   308
haftmann@38619
   309
fun target_extension f class lthy =
haftmann@38619
   310
  lthy
haftmann@38619
   311
  |> Local_Theory.raw_theory f
haftmann@38619
   312
  |> Local_Theory.target (synchronize_class_syntax [class]
wenzelm@42360
   313
      (base_sort (Proof_Context.theory_of lthy) class));
haftmann@38619
   314
haftmann@38619
   315
local
haftmann@38619
   316
haftmann@38619
   317
fun target_const class ((c, mx), (type_params, dict)) thy =
haftmann@27690
   318
  let
haftmann@29577
   319
    val morph = morphism thy class;
wenzelm@30344
   320
    val b = Morphism.binding morph c;
wenzelm@30344
   321
    val b_def = Morphism.binding morph (Binding.suffix_name "_dict" b);
haftmann@29577
   322
    val c' = Sign.full_name thy b;
haftmann@29439
   323
    val dict' = Morphism.term morph dict;
haftmann@35858
   324
    val ty' = map Term.fastype_of type_params ---> Term.fastype_of dict';
haftmann@35858
   325
    val def_eq = Logic.mk_equals (list_comb (Const (c', ty'), type_params), dict')
haftmann@29577
   326
      |> map_types Type.strip_sorts;
haftmann@27690
   327
  in
haftmann@29577
   328
    thy
wenzelm@42375
   329
    |> Sign.declare_const_global ((b, Type.strip_sorts ty'), mx)
haftmann@29577
   330
    |> snd
wenzelm@42375
   331
    |> Thm.add_def_global false false (b_def, def_eq)
wenzelm@36106
   332
    |>> apsnd Thm.varifyT_global
wenzelm@39557
   333
    |-> (fn (_, def_thm) => Global_Theory.store_thm (b_def, def_thm)
haftmann@29577
   334
      #> snd
haftmann@35858
   335
      #> null type_params ? register_operation class (c', (dict', SOME (Thm.symmetric def_thm))))
haftmann@27690
   336
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@27690
   337
  end;
haftmann@27690
   338
haftmann@38619
   339
fun target_abbrev class prmode ((c, mx), rhs) thy =
haftmann@27690
   340
  let
haftmann@29577
   341
    val morph = morphism thy class;
haftmann@29577
   342
    val unchecks = these_unchecks thy [class];
wenzelm@30344
   343
    val b = Morphism.binding morph c;
haftmann@29577
   344
    val c' = Sign.full_name thy b;
haftmann@27690
   345
    val rhs' = Pattern.rewrite_term thy unchecks [] rhs;
haftmann@27690
   346
    val ty' = Term.fastype_of rhs';
wenzelm@35845
   347
    val rhs'' = map_types Logic.varifyT_global rhs';
haftmann@27690
   348
  in
haftmann@29577
   349
    thy
wenzelm@33173
   350
    |> Sign.add_abbrev (#1 prmode) (b, rhs'')
haftmann@29577
   351
    |> snd
haftmann@27690
   352
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@27690
   353
    |> Sign.notation true prmode [(Const (c', ty'), mx)]
wenzelm@37146
   354
    |> not (#1 prmode = Print_Mode.input) ? register_operation class (c', (rhs', NONE))
haftmann@27690
   355
  end;
haftmann@27690
   356
haftmann@38619
   357
in
haftmann@38619
   358
haftmann@38619
   359
fun const class arg = target_extension (target_const class arg) class;
haftmann@38619
   360
fun abbrev class prmode arg = target_extension (target_abbrev class prmode arg) class;
haftmann@38619
   361
haftmann@38619
   362
end;
haftmann@38619
   363
haftmann@27690
   364
haftmann@31635
   365
(* simple subclasses *)
haftmann@31635
   366
haftmann@31635
   367
local
haftmann@31635
   368
haftmann@31635
   369
fun gen_classrel mk_prop classrel thy =
haftmann@31635
   370
  let
haftmann@31635
   371
    fun after_qed results =
wenzelm@42360
   372
      Proof_Context.background_theory ((fold o fold) AxClass.add_classrel results);
haftmann@31635
   373
  in
haftmann@31635
   374
    thy
wenzelm@42360
   375
    |> Proof_Context.init_global
wenzelm@36323
   376
    |> Proof.theorem NONE after_qed [[(mk_prop thy classrel, [])]]
haftmann@31635
   377
  end;
haftmann@31635
   378
haftmann@31635
   379
in
haftmann@31635
   380
haftmann@31635
   381
val classrel =
haftmann@31635
   382
  gen_classrel (Logic.mk_classrel oo AxClass.cert_classrel);
haftmann@31635
   383
val classrel_cmd =
haftmann@31635
   384
  gen_classrel (Logic.mk_classrel oo AxClass.read_classrel);
haftmann@31635
   385
haftmann@31635
   386
end; (*local*)
haftmann@31635
   387
haftmann@31635
   388
haftmann@25462
   389
(** instantiation target **)
haftmann@25462
   390
haftmann@25462
   391
(* bookkeeping *)
haftmann@25462
   392
haftmann@25462
   393
datatype instantiation = Instantiation of {
haftmann@25864
   394
  arities: string list * (string * sort) list * sort,
haftmann@25462
   395
  params: ((string * string) * (string * typ)) list
haftmann@25603
   396
    (*(instantiation parameter, type constructor), (local instantiation parameter, typ)*)
haftmann@25462
   397
}
haftmann@25462
   398
wenzelm@33519
   399
structure Instantiation = Proof_Data
haftmann@25462
   400
(
haftmann@25462
   401
  type T = instantiation
haftmann@25536
   402
  fun init _ = Instantiation { arities = ([], [], []), params = [] };
haftmann@25462
   403
);
haftmann@25462
   404
haftmann@25485
   405
fun mk_instantiation (arities, params) =
haftmann@25485
   406
  Instantiation { arities = arities, params = params };
wenzelm@33671
   407
fun get_instantiation lthy = case Instantiation.get (Local_Theory.target_of lthy)
haftmann@25485
   408
 of Instantiation data => data;
wenzelm@33671
   409
fun map_instantiation f = (Local_Theory.target o Instantiation.map)
haftmann@25514
   410
  (fn Instantiation { arities, params } => mk_instantiation (f (arities, params)));
haftmann@25462
   411
haftmann@25514
   412
fun the_instantiation lthy = case get_instantiation lthy
haftmann@25536
   413
 of { arities = ([], [], []), ... } => error "No instantiation target"
haftmann@25485
   414
  | data => data;
haftmann@25462
   415
haftmann@25485
   416
val instantiation_params = #params o get_instantiation;
haftmann@25462
   417
haftmann@30519
   418
fun instantiation_param lthy b = instantiation_params lthy
haftmann@30519
   419
  |> find_first (fn (_, (v, _)) => Binding.name_of b = v)
haftmann@25462
   420
  |> Option.map (fst o fst);
haftmann@25462
   421
haftmann@31869
   422
fun read_multi_arity thy (raw_tycos, raw_sorts, raw_sort) =
haftmann@31869
   423
  let
wenzelm@42360
   424
    val ctxt = Proof_Context.init_global thy;
wenzelm@42360
   425
    val all_arities = map (fn raw_tyco => Proof_Context.read_arity ctxt
haftmann@31869
   426
      (raw_tyco, raw_sorts, raw_sort)) raw_tycos;
haftmann@31869
   427
    val tycos = map #1 all_arities;
haftmann@31869
   428
    val (_, sorts, sort) = hd all_arities;
wenzelm@43329
   429
    val vs = Name.invent_names Name.context Name.aT sorts;
haftmann@31869
   430
  in (tycos, vs, sort) end;
haftmann@31869
   431
haftmann@25462
   432
haftmann@25462
   433
(* syntax *)
haftmann@25462
   434
haftmann@26238
   435
fun synchronize_inst_syntax ctxt =
haftmann@25462
   436
  let
haftmann@33969
   437
    val Instantiation { params, ... } = Instantiation.get ctxt;
haftmann@31249
   438
haftmann@33969
   439
    val lookup_inst_param = AxClass.lookup_inst_param
wenzelm@42360
   440
      (Sign.consts_of (Proof_Context.theory_of ctxt)) params;
haftmann@31249
   441
    fun subst (c, ty) = case lookup_inst_param (c, ty)
haftmann@31249
   442
     of SOME (v_ty as (_, ty)) => SOME (ty, Free v_ty)
haftmann@31249
   443
      | NONE => NONE;
haftmann@26238
   444
    val unchecks =
haftmann@26238
   445
      map (fn ((c, _), v_ty as (_, ty)) => (Free v_ty, Const (c, ty))) params;
haftmann@26238
   446
  in
haftmann@26238
   447
    ctxt
haftmann@26259
   448
    |> Overloading.map_improvable_syntax
haftmann@26730
   449
         (fn (((primary_constraints, _), (((improve, _), _), _)), _) =>
haftmann@26730
   450
            (((primary_constraints, []), (((improve, subst), false), unchecks)), false))
haftmann@26238
   451
  end;
haftmann@25462
   452
wenzelm@42385
   453
fun resort_terms ctxt algebra consts constraints ts =
haftmann@38382
   454
  let
wenzelm@42385
   455
    fun matchings (Const (c_ty as (c, _))) =
wenzelm@42385
   456
          (case constraints c of
wenzelm@42385
   457
            NONE => I
wenzelm@42385
   458
          | SOME sorts =>
wenzelm@42385
   459
              fold2 (curry (Sorts.meet_sort algebra)) (Consts.typargs consts c_ty) sorts)
wenzelm@42385
   460
      | matchings _ = I;
haftmann@38382
   461
    val tvartab = (fold o fold_aterms) matchings ts Vartab.empty
wenzelm@42385
   462
      handle Sorts.CLASS_ERROR e => error (Sorts.class_error ctxt e);
haftmann@38382
   463
    val inst = map_type_tvar
haftmann@38382
   464
      (fn (vi, sort) => TVar (vi, the_default sort (Vartab.lookup tvartab vi)));
wenzelm@42402
   465
  in if Vartab.is_empty tvartab then ts else (map o map_types) inst ts end;
haftmann@38382
   466
haftmann@25462
   467
haftmann@25462
   468
(* target *)
haftmann@25462
   469
haftmann@37678
   470
val sanitize_name = (*necessary as long as "dirty" type identifiers are permitted*)
haftmann@25485
   471
  let
haftmann@25574
   472
    fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s
haftmann@25574
   473
      orelse s = "'" orelse s = "_";
haftmann@25485
   474
    val is_junk = not o is_valid andf Symbol.is_regular;
haftmann@25485
   475
    val junk = Scan.many is_junk;
haftmann@25485
   476
    val scan_valids = Symbol.scanner "Malformed input"
haftmann@25485
   477
      ((junk |--
haftmann@25485
   478
        (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
haftmann@25485
   479
        --| junk))
wenzelm@25999
   480
      ::: Scan.repeat ((Scan.many1 is_valid >> implode) --| junk));
haftmann@25485
   481
  in
wenzelm@40627
   482
    raw_explode #> scan_valids #> implode
haftmann@25485
   483
  end;
haftmann@25485
   484
haftmann@37678
   485
val type_name = sanitize_name o Long_Name.base_name;
haftmann@26259
   486
wenzelm@38757
   487
fun define_overloaded (c, U) v (b_def, rhs) = Local_Theory.background_theory_result
haftmann@38382
   488
    (AxClass.declare_overloaded (c, U) ##>> AxClass.define_overloaded b_def (c, rhs))
haftmann@38382
   489
  ##> (map_instantiation o apsnd) (filter_out (fn (_, (v', _)) => v' = v))
haftmann@38382
   490
  ##> Local_Theory.target synchronize_inst_syntax;
haftmann@38382
   491
haftmann@38382
   492
fun foundation (((b, U), mx), (b_def, rhs)) (type_params, term_params) lthy =
haftmann@38382
   493
  case instantiation_param lthy b
haftmann@38382
   494
   of SOME c => if mx <> NoSyn then error ("Illegal mixfix syntax for overloaded constant " ^ quote c)
haftmann@38382
   495
        else lthy |> define_overloaded (c, U) (Binding.name_of b) (b_def, rhs)
haftmann@38382
   496
    | NONE => lthy |>
haftmann@38382
   497
        Generic_Target.theory_foundation (((b, U), mx), (b_def, rhs)) (type_params, term_params);
haftmann@38382
   498
haftmann@38382
   499
fun pretty lthy =
haftmann@26518
   500
  let
haftmann@38382
   501
    val { arities = (tycos, vs, sort), params } = the_instantiation lthy;
wenzelm@42360
   502
    val thy = Proof_Context.theory_of lthy;
haftmann@38382
   503
    fun pr_arity tyco = Syntax.pretty_arity lthy (tyco, map snd vs, sort);
haftmann@38382
   504
    fun pr_param ((c, _), (v, ty)) =
wenzelm@42359
   505
      Pretty.block (Pretty.breaks
wenzelm@42360
   506
        [Pretty.str v, Pretty.str "==", Pretty.str (Proof_Context.extern_const lthy c),
wenzelm@42359
   507
          Pretty.str "::", Syntax.pretty_typ lthy ty]);
haftmann@38382
   508
  in Pretty.str "instantiation" :: map pr_arity tycos @ map pr_param params end;
haftmann@26518
   509
haftmann@38382
   510
fun conclude lthy =
haftmann@38382
   511
  let
wenzelm@42359
   512
    val (tycos, vs, sort) = #arities (the_instantiation lthy);
wenzelm@42360
   513
    val thy = Proof_Context.theory_of lthy;
wenzelm@42359
   514
    val _ = tycos |> List.app (fn tyco =>
wenzelm@42359
   515
      if Sign.of_sort thy
haftmann@38382
   516
        (Type (tyco, map TFree vs), sort)
wenzelm@42359
   517
      then ()
wenzelm@42360
   518
      else error ("Missing instance proof for type " ^ quote (Proof_Context.extern_type lthy tyco)));
haftmann@38382
   519
  in lthy end;
haftmann@38382
   520
haftmann@38382
   521
fun instantiation (tycos, vs, sort) thy =
haftmann@25462
   522
  let
haftmann@25536
   523
    val _ = if null tycos then error "At least one arity must be given" else ();
haftmann@31249
   524
    val class_params = these_params thy (filter (can (AxClass.get_info thy)) sort);
haftmann@29632
   525
    fun get_param tyco (param, (_, (c, ty))) =
haftmann@29632
   526
      if can (AxClass.param_of_inst thy) (c, tyco)
haftmann@25603
   527
      then NONE else SOME ((c, tyco),
haftmann@25864
   528
        (param ^ "_" ^ type_name tyco, map_atyps (K (Type (tyco, map TFree vs))) ty));
haftmann@31249
   529
    val params = map_product get_param tycos class_params |> map_filter I;
haftmann@26518
   530
    val primary_constraints = map (apsnd
haftmann@31249
   531
      (map_atyps (K (TVar ((Name.aT, 0), [])))) o snd o snd) class_params;
haftmann@26518
   532
    val algebra = Sign.classes_of thy
wenzelm@42387
   533
      |> fold (fn tyco => Sorts.add_arities (Proof_Context.init_global thy)
haftmann@26518
   534
            (tyco, map (fn class => (class, map snd vs)) sort)) tycos;
haftmann@26518
   535
    val consts = Sign.consts_of thy;
haftmann@26518
   536
    val improve_constraints = AList.lookup (op =)
haftmann@31249
   537
      (map (fn (_, (class, (c, _))) => (c, [[class]])) class_params);
wenzelm@42402
   538
    fun resort_check ctxt ts = resort_terms ctxt algebra consts improve_constraints ts;
haftmann@31249
   539
    val lookup_inst_param = AxClass.lookup_inst_param consts params;
wenzelm@42388
   540
    fun improve (c, ty) =
wenzelm@42388
   541
      (case lookup_inst_param (c, ty) of
wenzelm@42388
   542
        SOME (_, ty') => if Sign.typ_instance thy (ty', ty) then SOME (ty, ty') else NONE
wenzelm@42388
   543
      | NONE => NONE);
haftmann@25485
   544
  in
haftmann@25485
   545
    thy
haftmann@32379
   546
    |> Theory.checkpoint
wenzelm@42360
   547
    |> Proof_Context.init_global
haftmann@31249
   548
    |> Instantiation.put (mk_instantiation ((tycos, vs, sort), params))
wenzelm@27281
   549
    |> fold (Variable.declare_typ o TFree) vs
haftmann@31249
   550
    |> fold (Variable.declare_names o Free o snd) params
haftmann@26259
   551
    |> (Overloading.map_improvable_syntax o apfst)
haftmann@29969
   552
         (K ((primary_constraints, []), (((improve, K NONE), false), [])))
haftmann@39378
   553
    |> Overloading.activate_improvable_syntax
haftmann@26518
   554
    |> Context.proof_map (Syntax.add_term_check 0 "resorting" resort_check)
haftmann@26238
   555
    |> synchronize_inst_syntax
haftmann@38382
   556
    |> Local_Theory.init NONE ""
haftmann@38382
   557
       {define = Generic_Target.define foundation,
haftmann@38382
   558
        notes = Generic_Target.notes
haftmann@38382
   559
          (fn kind => fn global_facts => fn _ => Generic_Target.theory_notes kind global_facts),
haftmann@38382
   560
        abbrev = Generic_Target.abbrev
wenzelm@42385
   561
          (fn prmode => fn (b, mx) => fn (t, _) => fn _ =>
wenzelm@42385
   562
            Generic_Target.theory_abbrev prmode ((b, mx), t)),
wenzelm@45310
   563
        declaration = K Generic_Target.theory_declaration,
haftmann@38382
   564
        pretty = pretty,
haftmann@38382
   565
        exit = Local_Theory.target_of o conclude}
haftmann@25485
   566
  end;
haftmann@25485
   567
haftmann@38382
   568
fun instantiation_cmd arities thy =
haftmann@38382
   569
  instantiation (read_multi_arity thy arities) thy;
haftmann@26238
   570
haftmann@25485
   571
fun gen_instantiation_instance do_proof after_qed lthy =
haftmann@25485
   572
  let
haftmann@25864
   573
    val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
haftmann@25864
   574
    val arities_proof = maps (fn tyco => Logic.mk_arities (tyco, map snd vs, sort)) tycos;
haftmann@25462
   575
    fun after_qed' results =
wenzelm@38757
   576
      Local_Theory.background_theory (fold (AxClass.add_arity o Thm.varifyT_global) results)
haftmann@25462
   577
      #> after_qed;
haftmann@25462
   578
  in
haftmann@25462
   579
    lthy
haftmann@25462
   580
    |> do_proof after_qed' arities_proof
haftmann@25462
   581
  end;
haftmann@25462
   582
haftmann@25485
   583
val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
wenzelm@36323
   584
  Proof.theorem NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
haftmann@25462
   585
haftmann@25485
   586
fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
haftmann@25502
   587
  fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
haftmann@25502
   588
    (fn {context, ...} => tac context)) ts) lthy) I;
haftmann@25462
   589
haftmann@28666
   590
fun prove_instantiation_exit tac = prove_instantiation_instance tac
wenzelm@33671
   591
  #> Local_Theory.exit_global;
haftmann@28666
   592
haftmann@28666
   593
fun prove_instantiation_exit_result f tac x lthy =
haftmann@28666
   594
  let
wenzelm@42360
   595
    val morph = Proof_Context.export_morphism lthy
wenzelm@42360
   596
      (Proof_Context.init_global (Proof_Context.theory_of lthy));
haftmann@29439
   597
    val y = f morph x;
haftmann@28666
   598
  in
haftmann@28666
   599
    lthy
haftmann@28666
   600
    |> prove_instantiation_exit (fn ctxt => tac ctxt y)
haftmann@28666
   601
    |> pair y
haftmann@28666
   602
  end;
haftmann@28666
   603
haftmann@29526
   604
haftmann@31635
   605
(* simplified instantiation interface with no class parameter *)
haftmann@31635
   606
haftmann@31869
   607
fun instance_arity_cmd raw_arities thy =
haftmann@31635
   608
  let
haftmann@31869
   609
    val (tycos, vs, sort) = read_multi_arity thy raw_arities;
haftmann@31869
   610
    val sorts = map snd vs;
haftmann@31869
   611
    val arities = maps (fn tyco => Logic.mk_arities (tyco, sorts, sort)) tycos;
wenzelm@42360
   612
    fun after_qed results = Proof_Context.background_theory
haftmann@37246
   613
      ((fold o fold) AxClass.add_arity results);
haftmann@31635
   614
  in
haftmann@31635
   615
    thy
wenzelm@42360
   616
    |> Proof_Context.init_global
wenzelm@36323
   617
    |> Proof.theorem NONE after_qed (map (fn t => [(t, [])]) arities)
haftmann@31635
   618
  end;
haftmann@31635
   619
haftmann@31635
   620
haftmann@29526
   621
(** tactics and methods **)
haftmann@29526
   622
haftmann@29526
   623
fun intro_classes_tac facts st =
haftmann@29526
   624
  let
haftmann@29526
   625
    val thy = Thm.theory_of_thm st;
haftmann@29526
   626
    val classes = Sign.all_classes thy;
haftmann@29526
   627
    val class_trivs = map (Thm.class_triv thy) classes;
haftmann@29526
   628
    val class_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
haftmann@29526
   629
    val assm_intros = all_assm_intros thy;
haftmann@29526
   630
  in
haftmann@29526
   631
    Method.intros_tac (class_trivs @ class_intros @ assm_intros) facts st
haftmann@29526
   632
  end;
haftmann@29526
   633
haftmann@29526
   634
fun default_intro_tac ctxt [] =
wenzelm@39438
   635
      COND Thm.no_prems no_tac
wenzelm@39438
   636
        (intro_classes_tac [] ORELSE Locale.intro_locales_tac true ctxt [])
haftmann@29526
   637
  | default_intro_tac _ _ = no_tac;
haftmann@29526
   638
haftmann@29526
   639
fun default_tac rules ctxt facts =
haftmann@29526
   640
  HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
haftmann@29526
   641
    default_intro_tac ctxt facts;
haftmann@29526
   642
haftmann@29526
   643
val _ = Context.>> (Context.map_theory
wenzelm@30515
   644
 (Method.setup (Binding.name "intro_classes") (Scan.succeed (K (METHOD intro_classes_tac)))
wenzelm@30515
   645
    "back-chain introduction rules of classes" #>
wenzelm@30515
   646
  Method.setup (Binding.name "default") (Attrib.thms >> (METHOD oo default_tac))
wenzelm@30515
   647
    "apply some intro/elim rule"));
haftmann@29526
   648
haftmann@24218
   649
end;
haftmann@25683
   650