src/Pure/Isar/class.ML
author haftmann
Wed Aug 11 17:59:32 2010 +0200 (2010-08-11 ago)
changeset 38382 8b02c5bf1d0e
parent 38381 7d1e2a6831ec
child 38384 07c33be08476
permissions -rw-r--r--
tuned internal structure
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
haftmann@29526
    17
  val print_classes: theory -> unit
haftmann@25311
    18
  val init: class -> theory -> Proof.context
haftmann@38379
    19
  val begin: class list -> sort -> Proof.context -> Proof.context
haftmann@35858
    20
  val declare: class -> (binding * mixfix) * (term list * term) -> theory -> theory
wenzelm@33173
    21
  val abbrev: class -> Syntax.mode -> (binding * mixfix) * term -> theory -> theory
haftmann@38379
    22
  val refresh_syntax: class -> Proof.context -> Proof.context
haftmann@38379
    23
  val redeclare_operations: theory -> sort -> Proof.context -> Proof.context
haftmann@29526
    24
  val class_prefix: string -> string
haftmann@38379
    25
  val register: class -> class list -> ((string * typ) * (string * typ)) list
haftmann@38379
    26
    -> sort -> morphism -> morphism -> thm option -> thm option -> thm
haftmann@38379
    27
    -> theory -> theory
haftmann@25485
    28
haftmann@25462
    29
  (*instances*)
haftmann@38379
    30
  val instantiation: string list * (string * sort) list * sort -> theory -> local_theory
haftmann@26247
    31
  val instantiation_instance: (local_theory -> local_theory)
haftmann@26247
    32
    -> local_theory -> Proof.state
haftmann@26247
    33
  val prove_instantiation_instance: (Proof.context -> tactic)
haftmann@26247
    34
    -> local_theory -> local_theory
haftmann@28666
    35
  val prove_instantiation_exit: (Proof.context -> tactic)
haftmann@28666
    36
    -> local_theory -> theory
haftmann@28666
    37
  val prove_instantiation_exit_result: (morphism -> 'a -> 'b)
haftmann@28666
    38
    -> (Proof.context -> 'b -> tactic) -> 'a -> local_theory -> 'b * theory
haftmann@31869
    39
  val read_multi_arity: theory -> xstring list * xstring list * xstring
haftmann@31869
    40
    -> string list * (string * sort) list * sort
haftmann@26259
    41
  val type_name: string -> string
haftmann@38348
    42
  val instantiation_cmd: xstring list * xstring list * xstring -> theory -> local_theory
haftmann@38377
    43
  val instance_arity_cmd: xstring list * xstring list * xstring -> theory -> Proof.state
haftmann@25485
    44
haftmann@31635
    45
  (*subclasses*)
haftmann@31635
    46
  val classrel: class * class -> theory -> Proof.state
haftmann@31635
    47
  val classrel_cmd: xstring * xstring -> theory -> Proof.state
haftmann@38379
    48
  val register_subclass: class * class -> morphism option -> Element.witness option
haftmann@38379
    49
    -> morphism -> theory -> theory
haftmann@31635
    50
haftmann@31635
    51
  (*tactics*)
haftmann@29526
    52
  val intro_classes_tac: thm list -> tactic
haftmann@29526
    53
  val default_intro_tac: Proof.context -> thm list -> tactic
haftmann@24218
    54
end;
haftmann@24218
    55
haftmann@38379
    56
structure Class: CLASS =
haftmann@24218
    57
struct
haftmann@24218
    58
haftmann@24589
    59
(** class data **)
haftmann@24218
    60
haftmann@24218
    61
datatype class_data = ClassData of {
haftmann@28715
    62
haftmann@28715
    63
  (* static part *)
haftmann@24218
    64
  consts: (string * string) list
haftmann@24836
    65
    (*locale parameter ~> constant name*),
haftmann@25062
    66
  base_sort: sort,
haftmann@29545
    67
  base_morph: morphism
haftmann@29439
    68
    (*static part of canonical morphism*),
haftmann@32850
    69
  export_morph: morphism,
haftmann@25618
    70
  assm_intro: thm option,
haftmann@25618
    71
  of_class: thm,
haftmann@25618
    72
  axiom: thm option,
haftmann@28715
    73
  
haftmann@28715
    74
  (* dynamic part *)
haftmann@24657
    75
  defs: thm list,
haftmann@25368
    76
  operations: (string * (class * (typ * term))) list
haftmann@28715
    77
haftmann@24657
    78
};
haftmann@24218
    79
haftmann@32850
    80
fun make_class_data ((consts, base_sort, base_morph, export_morph, assm_intro, of_class, axiom),
haftmann@25368
    81
    (defs, operations)) =
haftmann@29526
    82
  ClassData { consts = consts, base_sort = base_sort,
haftmann@32850
    83
    base_morph = base_morph, export_morph = export_morph, assm_intro = assm_intro,
haftmann@32850
    84
    of_class = of_class, axiom = axiom, defs = defs, operations = operations };
haftmann@32850
    85
fun map_class_data f (ClassData { consts, base_sort, base_morph, export_morph, assm_intro,
haftmann@28715
    86
    of_class, axiom, defs, operations }) =
haftmann@32850
    87
  make_class_data (f ((consts, base_sort, base_morph, export_morph, assm_intro, of_class, axiom),
haftmann@25368
    88
    (defs, operations)));
haftmann@25038
    89
fun merge_class_data _ (ClassData { consts = consts,
haftmann@32850
    90
    base_sort = base_sort, base_morph = base_morph, export_morph = export_morph, assm_intro = assm_intro,
haftmann@25618
    91
    of_class = of_class, axiom = axiom, defs = defs1, operations = operations1 },
haftmann@32850
    92
  ClassData { consts = _, base_sort = _, base_morph = _, export_morph = _, assm_intro = _,
haftmann@25618
    93
    of_class = _, axiom = _, defs = defs2, operations = operations2 }) =
haftmann@32850
    94
  make_class_data ((consts, base_sort, base_morph, export_morph, assm_intro, of_class, axiom),
haftmann@24914
    95
    (Thm.merge_thms (defs1, defs2),
haftmann@25368
    96
      AList.merge (op =) (K true) (operations1, operations2)));
haftmann@24218
    97
wenzelm@33522
    98
structure ClassData = Theory_Data
haftmann@24218
    99
(
haftmann@25038
   100
  type T = class_data Graph.T
haftmann@25038
   101
  val empty = Graph.empty;
haftmann@24218
   102
  val extend = I;
wenzelm@33522
   103
  val merge = Graph.join merge_class_data;
haftmann@24218
   104
);
haftmann@24218
   105
haftmann@24218
   106
haftmann@24218
   107
(* queries *)
haftmann@24218
   108
haftmann@31599
   109
fun lookup_class_data thy class = case try (Graph.get_node (ClassData.get thy)) class
haftmann@31599
   110
 of SOME (ClassData data) => SOME data
haftmann@31599
   111
  | NONE => NONE;
haftmann@24218
   112
haftmann@24589
   113
fun the_class_data thy class = case lookup_class_data thy class
wenzelm@25020
   114
 of NONE => error ("Undeclared class " ^ quote class)
haftmann@24589
   115
  | SOME data => data;
haftmann@24218
   116
haftmann@25038
   117
val is_class = is_some oo lookup_class_data;
haftmann@25038
   118
haftmann@25038
   119
val ancestry = Graph.all_succs o ClassData.get;
haftmann@29509
   120
val heritage = Graph.all_preds o ClassData.get;
haftmann@29509
   121
haftmann@25002
   122
fun these_params thy =
haftmann@24218
   123
  let
haftmann@24218
   124
    fun params class =
haftmann@24218
   125
      let
wenzelm@24930
   126
        val const_typs = (#params o AxClass.get_info thy) class;
haftmann@24657
   127
        val const_names = (#consts o the_class_data thy) class;
haftmann@24218
   128
      in
haftmann@26518
   129
        (map o apsnd)
haftmann@26518
   130
          (fn c => (class, (c, (the o AList.lookup (op =) const_typs) c))) const_names
haftmann@24218
   131
      end;
haftmann@24218
   132
  in maps params o ancestry thy end;
haftmann@24218
   133
haftmann@29526
   134
val base_sort = #base_sort oo the_class_data;
haftmann@29526
   135
haftmann@29526
   136
fun rules thy class =
haftmann@29526
   137
  let val { axiom, of_class, ... } = the_class_data thy class
haftmann@29526
   138
  in (axiom, of_class) end;
haftmann@29526
   139
haftmann@29526
   140
fun all_assm_intros thy =
haftmann@31599
   141
  Graph.fold (fn (_, (ClassData { assm_intro, ... }, _)) => fold (insert Thm.eq_thm)
haftmann@31599
   142
    (the_list assm_intro)) (ClassData.get thy) [];
haftmann@24218
   143
haftmann@29526
   144
fun these_defs thy = maps (#defs o the_class_data thy) o ancestry thy;
haftmann@29526
   145
fun these_operations thy = maps (#operations o the_class_data thy) o ancestry thy;
haftmann@29358
   146
haftmann@29526
   147
val base_morphism = #base_morph oo the_class_data;
haftmann@36674
   148
fun morphism thy class = case Element.eq_morphism thy (these_defs thy [class])
haftmann@36674
   149
 of SOME eq_morph => base_morphism thy class $> eq_morph
haftmann@36674
   150
  | NONE => base_morphism thy class;
haftmann@32850
   151
val export_morphism = #export_morph oo the_class_data;
haftmann@28715
   152
haftmann@24218
   153
fun print_classes thy =
haftmann@24218
   154
  let
wenzelm@36610
   155
    val ctxt = ProofContext.init_global thy;
haftmann@24218
   156
    val algebra = Sign.classes_of thy;
haftmann@24218
   157
    val arities =
haftmann@24218
   158
      Symtab.empty
haftmann@24218
   159
      |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
haftmann@24218
   160
           Symtab.map_default (class, []) (insert (op =) tyco)) arities)
wenzelm@36328
   161
             (Sorts.arities_of algebra);
haftmann@24218
   162
    val the_arities = these o Symtab.lookup arities;
haftmann@24218
   163
    fun mk_arity class tyco =
haftmann@24218
   164
      let
haftmann@24218
   165
        val Ss = Sorts.mg_domain algebra tyco [class];
wenzelm@24920
   166
      in Syntax.pretty_arity ctxt (tyco, Ss, [class]) end;
haftmann@24218
   167
    fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
wenzelm@32966
   168
      ^ setmp_CRITICAL show_sorts false (Syntax.string_of_typ ctxt o Type.strip_sorts) ty);
haftmann@24218
   169
    fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
haftmann@25062
   170
      (SOME o Pretty.str) ("class " ^ Sign.extern_class thy 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
haftmann@32074
   236
          (sup, dep_morph $> Element.satisfy_morphism (the_list some_wit)) 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@25344
   260
    val thy = ProofContext.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@25083
   289
fun refresh_syntax class ctxt =
haftmann@25002
   290
  let
haftmann@25002
   291
    val thy = ProofContext.theory_of ctxt;
haftmann@29358
   292
    val base_sort = base_sort thy class;
haftmann@26238
   293
  in synchronize_class_syntax [class] base_sort ctxt end;
haftmann@25002
   294
haftmann@29632
   295
fun redeclare_operations thy sort =
haftmann@29632
   296
  fold (redeclare_const thy o fst) (these_operations thy sort);
haftmann@29632
   297
haftmann@29577
   298
fun begin sort base_sort ctxt =
haftmann@25083
   299
  ctxt
haftmann@25083
   300
  |> Variable.declare_term
haftmann@25083
   301
      (Logic.mk_type (TFree (Name.aT, base_sort)))
haftmann@29577
   302
  |> synchronize_class_syntax sort base_sort
haftmann@26238
   303
  |> Overloading.add_improvable_syntax;
haftmann@24901
   304
haftmann@25311
   305
fun init class thy =
haftmann@25311
   306
  thy
haftmann@29509
   307
  |> Locale.init class
haftmann@29358
   308
  |> begin [class] (base_sort thy class);
haftmann@24914
   309
haftmann@24748
   310
haftmann@27690
   311
(* class target *)
haftmann@27690
   312
wenzelm@30364
   313
val class_prefix = Logic.const_of_class o Long_Name.base_name;
haftmann@29526
   314
haftmann@35858
   315
fun declare class ((c, mx), (type_params, dict)) thy =
haftmann@27690
   316
  let
haftmann@29577
   317
    val morph = morphism thy class;
wenzelm@30344
   318
    val b = Morphism.binding morph c;
wenzelm@30344
   319
    val b_def = Morphism.binding morph (Binding.suffix_name "_dict" b);
haftmann@29577
   320
    val c' = Sign.full_name thy b;
haftmann@29439
   321
    val dict' = Morphism.term morph dict;
haftmann@35858
   322
    val ty' = map Term.fastype_of type_params ---> Term.fastype_of dict';
haftmann@35858
   323
    val def_eq = Logic.mk_equals (list_comb (Const (c', ty'), type_params), dict')
haftmann@29577
   324
      |> map_types Type.strip_sorts;
haftmann@27690
   325
  in
haftmann@29577
   326
    thy
wenzelm@33173
   327
    |> Sign.declare_const ((b, Type.strip_sorts ty'), mx)
haftmann@29577
   328
    |> snd
haftmann@29577
   329
    |> Thm.add_def false false (b_def, def_eq)
wenzelm@36106
   330
    |>> apsnd Thm.varifyT_global
wenzelm@36106
   331
    |-> (fn (_, def_thm) => PureThy.store_thm (b_def, def_thm)
haftmann@29577
   332
      #> snd
haftmann@35858
   333
      #> null type_params ? register_operation class (c', (dict', SOME (Thm.symmetric def_thm))))
haftmann@27690
   334
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@27690
   335
  end;
haftmann@27690
   336
wenzelm@33173
   337
fun abbrev class prmode ((c, mx), rhs) thy =
haftmann@27690
   338
  let
haftmann@29577
   339
    val morph = morphism thy class;
haftmann@29577
   340
    val unchecks = these_unchecks thy [class];
wenzelm@30344
   341
    val b = Morphism.binding morph c;
haftmann@29577
   342
    val c' = Sign.full_name thy b;
haftmann@27690
   343
    val rhs' = Pattern.rewrite_term thy unchecks [] rhs;
haftmann@27690
   344
    val ty' = Term.fastype_of rhs';
wenzelm@35845
   345
    val rhs'' = map_types Logic.varifyT_global rhs';
haftmann@27690
   346
  in
haftmann@29577
   347
    thy
wenzelm@33173
   348
    |> Sign.add_abbrev (#1 prmode) (b, rhs'')
haftmann@29577
   349
    |> snd
haftmann@27690
   350
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@27690
   351
    |> Sign.notation true prmode [(Const (c', ty'), mx)]
wenzelm@37146
   352
    |> not (#1 prmode = Print_Mode.input) ? register_operation class (c', (rhs', NONE))
haftmann@27690
   353
  end;
haftmann@27690
   354
haftmann@27690
   355
haftmann@31635
   356
(* simple subclasses *)
haftmann@31635
   357
haftmann@31635
   358
local
haftmann@31635
   359
haftmann@31635
   360
fun gen_classrel mk_prop classrel thy =
haftmann@31635
   361
  let
haftmann@31635
   362
    fun after_qed results =
haftmann@37246
   363
      ProofContext.theory ((fold o fold) AxClass.add_classrel results);
haftmann@31635
   364
  in
haftmann@31635
   365
    thy
wenzelm@36610
   366
    |> ProofContext.init_global
wenzelm@36323
   367
    |> Proof.theorem NONE after_qed [[(mk_prop thy classrel, [])]]
haftmann@31635
   368
  end;
haftmann@31635
   369
haftmann@31635
   370
in
haftmann@31635
   371
haftmann@31635
   372
val classrel =
haftmann@31635
   373
  gen_classrel (Logic.mk_classrel oo AxClass.cert_classrel);
haftmann@31635
   374
val classrel_cmd =
haftmann@31635
   375
  gen_classrel (Logic.mk_classrel oo AxClass.read_classrel);
haftmann@31635
   376
haftmann@31635
   377
end; (*local*)
haftmann@31635
   378
haftmann@31635
   379
haftmann@25462
   380
(** instantiation target **)
haftmann@25462
   381
haftmann@25462
   382
(* bookkeeping *)
haftmann@25462
   383
haftmann@25462
   384
datatype instantiation = Instantiation of {
haftmann@25864
   385
  arities: string list * (string * sort) list * sort,
haftmann@25462
   386
  params: ((string * string) * (string * typ)) list
haftmann@25603
   387
    (*(instantiation parameter, type constructor), (local instantiation parameter, typ)*)
haftmann@25462
   388
}
haftmann@25462
   389
wenzelm@33519
   390
structure Instantiation = Proof_Data
haftmann@25462
   391
(
haftmann@25462
   392
  type T = instantiation
haftmann@25536
   393
  fun init _ = Instantiation { arities = ([], [], []), params = [] };
haftmann@25462
   394
);
haftmann@25462
   395
haftmann@25485
   396
fun mk_instantiation (arities, params) =
haftmann@25485
   397
  Instantiation { arities = arities, params = params };
wenzelm@33671
   398
fun get_instantiation lthy = case Instantiation.get (Local_Theory.target_of lthy)
haftmann@25485
   399
 of Instantiation data => data;
wenzelm@33671
   400
fun map_instantiation f = (Local_Theory.target o Instantiation.map)
haftmann@25514
   401
  (fn Instantiation { arities, params } => mk_instantiation (f (arities, params)));
haftmann@25462
   402
haftmann@25514
   403
fun the_instantiation lthy = case get_instantiation lthy
haftmann@25536
   404
 of { arities = ([], [], []), ... } => error "No instantiation target"
haftmann@25485
   405
  | data => data;
haftmann@25462
   406
haftmann@25485
   407
val instantiation_params = #params o get_instantiation;
haftmann@25462
   408
haftmann@30519
   409
fun instantiation_param lthy b = instantiation_params lthy
haftmann@30519
   410
  |> find_first (fn (_, (v, _)) => Binding.name_of b = v)
haftmann@25462
   411
  |> Option.map (fst o fst);
haftmann@25462
   412
haftmann@31869
   413
fun read_multi_arity thy (raw_tycos, raw_sorts, raw_sort) =
haftmann@31869
   414
  let
wenzelm@36610
   415
    val ctxt = ProofContext.init_global thy;
wenzelm@35669
   416
    val all_arities = map (fn raw_tyco => ProofContext.read_arity ctxt
haftmann@31869
   417
      (raw_tyco, raw_sorts, raw_sort)) raw_tycos;
haftmann@31869
   418
    val tycos = map #1 all_arities;
haftmann@31869
   419
    val (_, sorts, sort) = hd all_arities;
haftmann@31869
   420
    val vs = Name.names Name.context Name.aT sorts;
haftmann@31869
   421
  in (tycos, vs, sort) end;
haftmann@31869
   422
haftmann@25462
   423
haftmann@25462
   424
(* syntax *)
haftmann@25462
   425
haftmann@26238
   426
fun synchronize_inst_syntax ctxt =
haftmann@25462
   427
  let
haftmann@33969
   428
    val Instantiation { params, ... } = Instantiation.get ctxt;
haftmann@31249
   429
haftmann@33969
   430
    val lookup_inst_param = AxClass.lookup_inst_param
haftmann@33969
   431
      (Sign.consts_of (ProofContext.theory_of ctxt)) params;
haftmann@31249
   432
    fun subst (c, ty) = case lookup_inst_param (c, ty)
haftmann@31249
   433
     of SOME (v_ty as (_, ty)) => SOME (ty, Free v_ty)
haftmann@31249
   434
      | NONE => NONE;
haftmann@26238
   435
    val unchecks =
haftmann@26238
   436
      map (fn ((c, _), v_ty as (_, ty)) => (Free v_ty, Const (c, ty))) params;
haftmann@26238
   437
  in
haftmann@26238
   438
    ctxt
haftmann@26259
   439
    |> Overloading.map_improvable_syntax
haftmann@26730
   440
         (fn (((primary_constraints, _), (((improve, _), _), _)), _) =>
haftmann@26730
   441
            (((primary_constraints, []), (((improve, subst), false), unchecks)), false))
haftmann@26238
   442
  end;
haftmann@25462
   443
haftmann@38382
   444
fun resort_terms pp algebra consts constraints ts =
haftmann@38382
   445
  let
haftmann@38382
   446
    fun matchings (Const (c_ty as (c, _))) = (case constraints c
haftmann@38382
   447
         of NONE => I
haftmann@38382
   448
          | SOME sorts => fold2 (curry (Sorts.meet_sort algebra))
haftmann@38382
   449
              (Consts.typargs consts c_ty) sorts)
haftmann@38382
   450
      | matchings _ = I
haftmann@38382
   451
    val tvartab = (fold o fold_aterms) matchings ts Vartab.empty
haftmann@38382
   452
      handle Sorts.CLASS_ERROR e => error (Sorts.class_error pp e);
haftmann@38382
   453
    val inst = map_type_tvar
haftmann@38382
   454
      (fn (vi, sort) => TVar (vi, the_default sort (Vartab.lookup tvartab vi)));
haftmann@38382
   455
  in if Vartab.is_empty tvartab then NONE else SOME ((map o map_types) inst ts) end;
haftmann@38382
   456
haftmann@25462
   457
haftmann@25462
   458
(* target *)
haftmann@25462
   459
haftmann@37678
   460
val sanitize_name = (*necessary as long as "dirty" type identifiers are permitted*)
haftmann@25485
   461
  let
haftmann@25574
   462
    fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s
haftmann@25574
   463
      orelse s = "'" orelse s = "_";
haftmann@25485
   464
    val is_junk = not o is_valid andf Symbol.is_regular;
haftmann@25485
   465
    val junk = Scan.many is_junk;
haftmann@25485
   466
    val scan_valids = Symbol.scanner "Malformed input"
haftmann@25485
   467
      ((junk |--
haftmann@25485
   468
        (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
haftmann@25485
   469
        --| junk))
wenzelm@25999
   470
      ::: Scan.repeat ((Scan.many1 is_valid >> implode) --| junk));
haftmann@25485
   471
  in
haftmann@25485
   472
    explode #> scan_valids #> implode
haftmann@25485
   473
  end;
haftmann@25485
   474
haftmann@37678
   475
val type_name = sanitize_name o Long_Name.base_name;
haftmann@26259
   476
haftmann@38382
   477
fun define_overloaded (c, U) v (b_def, rhs) = Local_Theory.theory_result
haftmann@38382
   478
    (AxClass.declare_overloaded (c, U) ##>> AxClass.define_overloaded b_def (c, rhs))
haftmann@38382
   479
  ##> (map_instantiation o apsnd) (filter_out (fn (_, (v', _)) => v' = v))
haftmann@38382
   480
  ##> Local_Theory.target synchronize_inst_syntax;
haftmann@38382
   481
haftmann@38382
   482
fun foundation (((b, U), mx), (b_def, rhs)) (type_params, term_params) lthy =
haftmann@38382
   483
  case instantiation_param lthy b
haftmann@38382
   484
   of SOME c => if mx <> NoSyn then error ("Illegal mixfix syntax for overloaded constant " ^ quote c)
haftmann@38382
   485
        else lthy |> define_overloaded (c, U) (Binding.name_of b) (b_def, rhs)
haftmann@38382
   486
    | NONE => lthy |>
haftmann@38382
   487
        Generic_Target.theory_foundation (((b, U), mx), (b_def, rhs)) (type_params, term_params);
haftmann@38382
   488
haftmann@38382
   489
fun pretty lthy =
haftmann@26518
   490
  let
haftmann@38382
   491
    val { arities = (tycos, vs, sort), params } = the_instantiation lthy;
haftmann@38382
   492
    val thy = ProofContext.theory_of lthy;
haftmann@38382
   493
    fun pr_arity tyco = Syntax.pretty_arity lthy (tyco, map snd vs, sort);
haftmann@38382
   494
    fun pr_param ((c, _), (v, ty)) =
haftmann@38382
   495
      (Pretty.block o Pretty.breaks) [Pretty.str v, Pretty.str "==",
haftmann@38382
   496
        (Pretty.str o Sign.extern_const thy) c, Pretty.str "::", Syntax.pretty_typ_global thy ty];
haftmann@38382
   497
  in Pretty.str "instantiation" :: map pr_arity tycos @ map pr_param params end;
haftmann@26518
   498
haftmann@38382
   499
fun conclude lthy =
haftmann@38382
   500
  let
haftmann@38382
   501
    val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
haftmann@38382
   502
    val thy = ProofContext.theory_of lthy;
haftmann@38382
   503
    val _ = map (fn tyco => if Sign.of_sort thy
haftmann@38382
   504
        (Type (tyco, map TFree vs), sort)
haftmann@38382
   505
      then () else error ("Missing instance proof for type " ^ quote (Sign.extern_type thy tyco)))
haftmann@38382
   506
        tycos;
haftmann@38382
   507
  in lthy end;
haftmann@38382
   508
haftmann@38382
   509
fun instantiation (tycos, vs, sort) thy =
haftmann@25462
   510
  let
haftmann@25536
   511
    val _ = if null tycos then error "At least one arity must be given" else ();
haftmann@31249
   512
    val class_params = these_params thy (filter (can (AxClass.get_info thy)) sort);
haftmann@29632
   513
    fun get_param tyco (param, (_, (c, ty))) =
haftmann@29632
   514
      if can (AxClass.param_of_inst thy) (c, tyco)
haftmann@25603
   515
      then NONE else SOME ((c, tyco),
haftmann@25864
   516
        (param ^ "_" ^ type_name tyco, map_atyps (K (Type (tyco, map TFree vs))) ty));
haftmann@31249
   517
    val params = map_product get_param tycos class_params |> map_filter I;
haftmann@26518
   518
    val primary_constraints = map (apsnd
haftmann@31249
   519
      (map_atyps (K (TVar ((Name.aT, 0), [])))) o snd o snd) class_params;
wenzelm@26939
   520
    val pp = Syntax.pp_global thy;
haftmann@26518
   521
    val algebra = Sign.classes_of thy
haftmann@26518
   522
      |> fold (fn tyco => Sorts.add_arities pp
haftmann@26518
   523
            (tyco, map (fn class => (class, map snd vs)) sort)) tycos;
haftmann@26518
   524
    val consts = Sign.consts_of thy;
haftmann@26518
   525
    val improve_constraints = AList.lookup (op =)
haftmann@31249
   526
      (map (fn (_, (class, (c, _))) => (c, [[class]])) class_params);
haftmann@33967
   527
    fun resort_check ts ctxt = case resort_terms (Syntax.pp ctxt) algebra consts improve_constraints ts
haftmann@26518
   528
     of NONE => NONE
haftmann@26518
   529
      | SOME ts' => SOME (ts', ctxt);
haftmann@31249
   530
    val lookup_inst_param = AxClass.lookup_inst_param consts params;
haftmann@31210
   531
    val typ_instance = Type.typ_instance (Sign.tsig_of thy);
haftmann@31249
   532
    fun improve (c, ty) = case lookup_inst_param (c, ty)
haftmann@31249
   533
     of SOME (_, ty') => if typ_instance (ty', ty) then SOME (ty, ty') else NONE
haftmann@26259
   534
      | NONE => NONE;
haftmann@25485
   535
  in
haftmann@25485
   536
    thy
haftmann@32379
   537
    |> Theory.checkpoint
wenzelm@36610
   538
    |> ProofContext.init_global
haftmann@31249
   539
    |> Instantiation.put (mk_instantiation ((tycos, vs, sort), params))
wenzelm@27281
   540
    |> fold (Variable.declare_typ o TFree) vs
haftmann@31249
   541
    |> fold (Variable.declare_names o Free o snd) params
haftmann@26259
   542
    |> (Overloading.map_improvable_syntax o apfst)
haftmann@29969
   543
         (K ((primary_constraints, []), (((improve, K NONE), false), [])))
haftmann@26259
   544
    |> Overloading.add_improvable_syntax
haftmann@26518
   545
    |> Context.proof_map (Syntax.add_term_check 0 "resorting" resort_check)
haftmann@26238
   546
    |> synchronize_inst_syntax
haftmann@38382
   547
    |> Local_Theory.init NONE ""
haftmann@38382
   548
       {define = Generic_Target.define foundation,
haftmann@38382
   549
        notes = Generic_Target.notes
haftmann@38382
   550
          (fn kind => fn global_facts => fn _ => Generic_Target.theory_notes kind global_facts),
haftmann@38382
   551
        abbrev = Generic_Target.abbrev
haftmann@38382
   552
          (fn prmode => fn (b, mx) => fn (t, _) => fn _ => Generic_Target.theory_abbrev prmode ((b, mx), t)),
haftmann@38382
   553
        declaration = K Generic_Target.theory_declaration,
haftmann@38382
   554
        syntax_declaration = K Generic_Target.theory_declaration,
haftmann@38382
   555
        pretty = pretty,
haftmann@38382
   556
        exit = Local_Theory.target_of o conclude}
haftmann@25485
   557
  end;
haftmann@25485
   558
haftmann@38382
   559
fun instantiation_cmd arities thy =
haftmann@38382
   560
  instantiation (read_multi_arity thy arities) thy;
haftmann@26238
   561
haftmann@25485
   562
fun gen_instantiation_instance do_proof after_qed lthy =
haftmann@25485
   563
  let
haftmann@25864
   564
    val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
haftmann@25864
   565
    val arities_proof = maps (fn tyco => Logic.mk_arities (tyco, map snd vs, sort)) tycos;
haftmann@25462
   566
    fun after_qed' results =
haftmann@37246
   567
      Local_Theory.theory (fold (AxClass.add_arity o Thm.varifyT_global) results)
haftmann@25462
   568
      #> after_qed;
haftmann@25462
   569
  in
haftmann@25462
   570
    lthy
haftmann@25462
   571
    |> do_proof after_qed' arities_proof
haftmann@25462
   572
  end;
haftmann@25462
   573
haftmann@25485
   574
val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
wenzelm@36323
   575
  Proof.theorem NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
haftmann@25462
   576
haftmann@25485
   577
fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
haftmann@25502
   578
  fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
haftmann@25502
   579
    (fn {context, ...} => tac context)) ts) lthy) I;
haftmann@25462
   580
haftmann@28666
   581
fun prove_instantiation_exit tac = prove_instantiation_instance tac
wenzelm@33671
   582
  #> Local_Theory.exit_global;
haftmann@28666
   583
haftmann@28666
   584
fun prove_instantiation_exit_result f tac x lthy =
haftmann@28666
   585
  let
haftmann@29439
   586
    val morph = ProofContext.export_morphism lthy
wenzelm@36610
   587
      (ProofContext.init_global (ProofContext.theory_of lthy));
haftmann@29439
   588
    val y = f morph x;
haftmann@28666
   589
  in
haftmann@28666
   590
    lthy
haftmann@28666
   591
    |> prove_instantiation_exit (fn ctxt => tac ctxt y)
haftmann@28666
   592
    |> pair y
haftmann@28666
   593
  end;
haftmann@28666
   594
haftmann@29526
   595
haftmann@31635
   596
(* simplified instantiation interface with no class parameter *)
haftmann@31635
   597
haftmann@31869
   598
fun instance_arity_cmd raw_arities thy =
haftmann@31635
   599
  let
haftmann@31869
   600
    val (tycos, vs, sort) = read_multi_arity thy raw_arities;
haftmann@31869
   601
    val sorts = map snd vs;
haftmann@31869
   602
    val arities = maps (fn tyco => Logic.mk_arities (tyco, sorts, sort)) tycos;
haftmann@31635
   603
    fun after_qed results = ProofContext.theory
haftmann@37246
   604
      ((fold o fold) AxClass.add_arity results);
haftmann@31635
   605
  in
haftmann@31635
   606
    thy
wenzelm@36610
   607
    |> ProofContext.init_global
wenzelm@36323
   608
    |> Proof.theorem NONE after_qed (map (fn t => [(t, [])]) arities)
haftmann@31635
   609
  end;
haftmann@31635
   610
haftmann@31635
   611
haftmann@29526
   612
(** tactics and methods **)
haftmann@29526
   613
haftmann@29526
   614
fun intro_classes_tac facts st =
haftmann@29526
   615
  let
haftmann@29526
   616
    val thy = Thm.theory_of_thm st;
haftmann@29526
   617
    val classes = Sign.all_classes thy;
haftmann@29526
   618
    val class_trivs = map (Thm.class_triv thy) classes;
haftmann@29526
   619
    val class_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
haftmann@29526
   620
    val assm_intros = all_assm_intros thy;
haftmann@29526
   621
  in
haftmann@29526
   622
    Method.intros_tac (class_trivs @ class_intros @ assm_intros) facts st
haftmann@29526
   623
  end;
haftmann@29526
   624
haftmann@29526
   625
fun default_intro_tac ctxt [] =
haftmann@29577
   626
      intro_classes_tac [] ORELSE Locale.intro_locales_tac true ctxt []
haftmann@29526
   627
  | default_intro_tac _ _ = no_tac;
haftmann@29526
   628
haftmann@29526
   629
fun default_tac rules ctxt facts =
haftmann@29526
   630
  HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
haftmann@29526
   631
    default_intro_tac ctxt facts;
haftmann@29526
   632
haftmann@29526
   633
val _ = Context.>> (Context.map_theory
wenzelm@30515
   634
 (Method.setup (Binding.name "intro_classes") (Scan.succeed (K (METHOD intro_classes_tac)))
wenzelm@30515
   635
    "back-chain introduction rules of classes" #>
wenzelm@30515
   636
  Method.setup (Binding.name "default") (Attrib.thms >> (METHOD oo default_tac))
wenzelm@30515
   637
    "apply some intro/elim rule"));
haftmann@29526
   638
haftmann@24218
   639
end;
haftmann@25683
   640