src/Pure/Isar/class.ML
author haftmann
Wed Aug 11 16:02:03 2010 +0200 (2010-08-11 ago)
changeset 38379 67d71449e85b
parent 38377 src/Pure/Isar/class_target.ML@2dfd8b7b8274
child 38381 7d1e2a6831ec
permissions -rw-r--r--
more convenient split of class modules: class and class_declaration
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@25462
   444
haftmann@25462
   445
(* target *)
haftmann@25462
   446
haftmann@37678
   447
val sanitize_name = (*necessary as long as "dirty" type identifiers are permitted*)
haftmann@25485
   448
  let
haftmann@25574
   449
    fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s
haftmann@25574
   450
      orelse s = "'" orelse s = "_";
haftmann@25485
   451
    val is_junk = not o is_valid andf Symbol.is_regular;
haftmann@25485
   452
    val junk = Scan.many is_junk;
haftmann@25485
   453
    val scan_valids = Symbol.scanner "Malformed input"
haftmann@25485
   454
      ((junk |--
haftmann@25485
   455
        (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
haftmann@25485
   456
        --| junk))
wenzelm@25999
   457
      ::: Scan.repeat ((Scan.many1 is_valid >> implode) --| junk));
haftmann@25485
   458
  in
haftmann@25485
   459
    explode #> scan_valids #> implode
haftmann@25485
   460
  end;
haftmann@25485
   461
haftmann@37678
   462
val type_name = sanitize_name o Long_Name.base_name;
haftmann@26259
   463
haftmann@26518
   464
fun resort_terms pp algebra consts constraints ts =
haftmann@26518
   465
  let
haftmann@26518
   466
    fun matchings (Const (c_ty as (c, _))) = (case constraints c
haftmann@26518
   467
         of NONE => I
haftmann@26518
   468
          | SOME sorts => fold2 (curry (Sorts.meet_sort algebra))
haftmann@26518
   469
              (Consts.typargs consts c_ty) sorts)
haftmann@26518
   470
      | matchings _ = I
haftmann@26518
   471
    val tvartab = (fold o fold_aterms) matchings ts Vartab.empty
wenzelm@26642
   472
      handle Sorts.CLASS_ERROR e => error (Sorts.class_error pp e);
haftmann@27089
   473
    val inst = map_type_tvar
haftmann@27089
   474
      (fn (vi, sort) => TVar (vi, the_default sort (Vartab.lookup tvartab vi)));
haftmann@26518
   475
  in if Vartab.is_empty tvartab then NONE else SOME ((map o map_types) inst ts) end;
haftmann@26518
   476
haftmann@25864
   477
fun init_instantiation (tycos, vs, sort) thy =
haftmann@25462
   478
  let
haftmann@25536
   479
    val _ = if null tycos then error "At least one arity must be given" else ();
haftmann@31249
   480
    val class_params = these_params thy (filter (can (AxClass.get_info thy)) sort);
haftmann@29632
   481
    fun get_param tyco (param, (_, (c, ty))) =
haftmann@29632
   482
      if can (AxClass.param_of_inst thy) (c, tyco)
haftmann@25603
   483
      then NONE else SOME ((c, tyco),
haftmann@25864
   484
        (param ^ "_" ^ type_name tyco, map_atyps (K (Type (tyco, map TFree vs))) ty));
haftmann@31249
   485
    val params = map_product get_param tycos class_params |> map_filter I;
haftmann@26518
   486
    val primary_constraints = map (apsnd
haftmann@31249
   487
      (map_atyps (K (TVar ((Name.aT, 0), [])))) o snd o snd) class_params;
wenzelm@26939
   488
    val pp = Syntax.pp_global thy;
haftmann@26518
   489
    val algebra = Sign.classes_of thy
haftmann@26518
   490
      |> fold (fn tyco => Sorts.add_arities pp
haftmann@26518
   491
            (tyco, map (fn class => (class, map snd vs)) sort)) tycos;
haftmann@26518
   492
    val consts = Sign.consts_of thy;
haftmann@26518
   493
    val improve_constraints = AList.lookup (op =)
haftmann@31249
   494
      (map (fn (_, (class, (c, _))) => (c, [[class]])) class_params);
haftmann@33967
   495
    fun resort_check ts ctxt = case resort_terms (Syntax.pp ctxt) algebra consts improve_constraints ts
haftmann@26518
   496
     of NONE => NONE
haftmann@26518
   497
      | SOME ts' => SOME (ts', ctxt);
haftmann@31249
   498
    val lookup_inst_param = AxClass.lookup_inst_param consts params;
haftmann@31210
   499
    val typ_instance = Type.typ_instance (Sign.tsig_of thy);
haftmann@31249
   500
    fun improve (c, ty) = case lookup_inst_param (c, ty)
haftmann@31249
   501
     of SOME (_, ty') => if typ_instance (ty', ty) then SOME (ty, ty') else NONE
haftmann@26259
   502
      | NONE => NONE;
haftmann@25485
   503
  in
haftmann@25485
   504
    thy
haftmann@32379
   505
    |> Theory.checkpoint
wenzelm@36610
   506
    |> ProofContext.init_global
haftmann@31249
   507
    |> Instantiation.put (mk_instantiation ((tycos, vs, sort), params))
wenzelm@27281
   508
    |> fold (Variable.declare_typ o TFree) vs
haftmann@31249
   509
    |> fold (Variable.declare_names o Free o snd) params
haftmann@26259
   510
    |> (Overloading.map_improvable_syntax o apfst)
haftmann@29969
   511
         (K ((primary_constraints, []), (((improve, K NONE), false), [])))
haftmann@26259
   512
    |> Overloading.add_improvable_syntax
haftmann@26518
   513
    |> Context.proof_map (Syntax.add_term_check 0 "resorting" resort_check)
haftmann@26238
   514
    |> synchronize_inst_syntax
haftmann@25485
   515
  end;
haftmann@25485
   516
haftmann@30519
   517
fun confirm_declaration b = (map_instantiation o apsnd)
haftmann@30519
   518
  (filter_out (fn (_, (c', _)) => c' = Binding.name_of b))
wenzelm@33671
   519
  #> Local_Theory.target synchronize_inst_syntax
haftmann@26238
   520
haftmann@25485
   521
fun gen_instantiation_instance do_proof after_qed lthy =
haftmann@25485
   522
  let
haftmann@25864
   523
    val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
haftmann@25864
   524
    val arities_proof = maps (fn tyco => Logic.mk_arities (tyco, map snd vs, sort)) tycos;
haftmann@25462
   525
    fun after_qed' results =
haftmann@37246
   526
      Local_Theory.theory (fold (AxClass.add_arity o Thm.varifyT_global) results)
haftmann@25462
   527
      #> after_qed;
haftmann@25462
   528
  in
haftmann@25462
   529
    lthy
haftmann@25462
   530
    |> do_proof after_qed' arities_proof
haftmann@25462
   531
  end;
haftmann@25462
   532
haftmann@25485
   533
val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
wenzelm@36323
   534
  Proof.theorem NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
haftmann@25462
   535
haftmann@25485
   536
fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
haftmann@25502
   537
  fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
haftmann@25502
   538
    (fn {context, ...} => tac context)) ts) lthy) I;
haftmann@25462
   539
haftmann@28666
   540
fun prove_instantiation_exit tac = prove_instantiation_instance tac
wenzelm@33671
   541
  #> Local_Theory.exit_global;
haftmann@28666
   542
haftmann@28666
   543
fun prove_instantiation_exit_result f tac x lthy =
haftmann@28666
   544
  let
haftmann@29439
   545
    val morph = ProofContext.export_morphism lthy
wenzelm@36610
   546
      (ProofContext.init_global (ProofContext.theory_of lthy));
haftmann@29439
   547
    val y = f morph x;
haftmann@28666
   548
  in
haftmann@28666
   549
    lthy
haftmann@28666
   550
    |> prove_instantiation_exit (fn ctxt => tac ctxt y)
haftmann@28666
   551
    |> pair y
haftmann@28666
   552
  end;
haftmann@28666
   553
haftmann@25462
   554
fun conclude_instantiation lthy =
haftmann@25462
   555
  let
haftmann@33969
   556
    val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
haftmann@25462
   557
    val thy = ProofContext.theory_of lthy;
haftmann@25597
   558
    val _ = map (fn tyco => if Sign.of_sort thy
haftmann@25864
   559
        (Type (tyco, map TFree vs), sort)
haftmann@25462
   560
      then () else error ("Missing instance proof for type " ^ quote (Sign.extern_type thy tyco)))
haftmann@25597
   561
        tycos;
haftmann@25597
   562
  in lthy end;
haftmann@25462
   563
haftmann@25603
   564
fun pretty_instantiation lthy =
haftmann@25603
   565
  let
haftmann@33969
   566
    val { arities = (tycos, vs, sort), params } = the_instantiation lthy;
haftmann@25603
   567
    val thy = ProofContext.theory_of lthy;
haftmann@25864
   568
    fun pr_arity tyco = Syntax.pretty_arity lthy (tyco, map snd vs, sort);
haftmann@25603
   569
    fun pr_param ((c, _), (v, ty)) =
haftmann@25864
   570
      (Pretty.block o Pretty.breaks) [Pretty.str v, Pretty.str "==",
wenzelm@26939
   571
        (Pretty.str o Sign.extern_const thy) c, Pretty.str "::", Syntax.pretty_typ_global thy ty];
haftmann@25603
   572
  in
haftmann@25603
   573
    (Pretty.block o Pretty.fbreaks)
haftmann@25603
   574
      (Pretty.str "instantiation" :: map pr_arity tycos @ map pr_param params)
haftmann@25603
   575
  end;
haftmann@25603
   576
haftmann@38348
   577
fun syntax_error c = error ("Illegal mixfix syntax for overloaded constant " ^ quote c);
haftmann@38348
   578
haftmann@38348
   579
fun instantiation_foundation (((b, U), mx), (b_def, rhs)) (type_params, term_params) lthy =
haftmann@38348
   580
  case instantiation_param lthy b
haftmann@38348
   581
   of SOME c => if mx <> NoSyn then syntax_error c
haftmann@38348
   582
        else lthy |> Local_Theory.theory_result (AxClass.declare_overloaded (c, U)
haftmann@38348
   583
            ##>> AxClass.define_overloaded b_def (c, rhs))
haftmann@38348
   584
          ||> confirm_declaration b
haftmann@38348
   585
    | NONE => lthy |>
haftmann@38348
   586
        Generic_Target.theory_foundation (((b, U), mx), (b_def, rhs)) (type_params, term_params);
haftmann@38348
   587
haftmann@38348
   588
fun instantiation arities thy =
haftmann@38348
   589
  thy
haftmann@38348
   590
  |> init_instantiation arities
haftmann@38348
   591
  |> Local_Theory.init NONE ""
haftmann@38348
   592
     {define = Generic_Target.define instantiation_foundation,
haftmann@38348
   593
      notes = Generic_Target.notes
haftmann@38348
   594
        (fn kind => fn global_facts => fn _ => Generic_Target.theory_notes kind global_facts),
haftmann@38348
   595
      abbrev = Generic_Target.abbrev
haftmann@38348
   596
        (fn prmode => fn (b, mx) => fn (t, _) => fn _ => Generic_Target.theory_abbrev prmode ((b, mx), t)),
haftmann@38348
   597
      declaration = K Generic_Target.theory_declaration,
haftmann@38348
   598
      syntax_declaration = K Generic_Target.theory_declaration,
haftmann@38348
   599
      pretty = single o pretty_instantiation,
haftmann@38348
   600
      reinit = instantiation arities o ProofContext.theory_of,
haftmann@38348
   601
      exit = Local_Theory.target_of o conclude_instantiation};
haftmann@38348
   602
haftmann@38348
   603
fun instantiation_cmd arities thy =
haftmann@38348
   604
  instantiation (read_multi_arity thy arities) thy;
haftmann@38348
   605
haftmann@29526
   606
haftmann@31635
   607
(* simplified instantiation interface with no class parameter *)
haftmann@31635
   608
haftmann@31869
   609
fun instance_arity_cmd raw_arities thy =
haftmann@31635
   610
  let
haftmann@31869
   611
    val (tycos, vs, sort) = read_multi_arity thy raw_arities;
haftmann@31869
   612
    val sorts = map snd vs;
haftmann@31869
   613
    val arities = maps (fn tyco => Logic.mk_arities (tyco, sorts, sort)) tycos;
haftmann@31635
   614
    fun after_qed results = ProofContext.theory
haftmann@37246
   615
      ((fold o fold) AxClass.add_arity results);
haftmann@31635
   616
  in
haftmann@31635
   617
    thy
wenzelm@36610
   618
    |> ProofContext.init_global
wenzelm@36323
   619
    |> Proof.theorem NONE after_qed (map (fn t => [(t, [])]) arities)
haftmann@31635
   620
  end;
haftmann@31635
   621
haftmann@31635
   622
haftmann@29526
   623
(** tactics and methods **)
haftmann@29526
   624
haftmann@29526
   625
fun intro_classes_tac facts st =
haftmann@29526
   626
  let
haftmann@29526
   627
    val thy = Thm.theory_of_thm st;
haftmann@29526
   628
    val classes = Sign.all_classes thy;
haftmann@29526
   629
    val class_trivs = map (Thm.class_triv thy) classes;
haftmann@29526
   630
    val class_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
haftmann@29526
   631
    val assm_intros = all_assm_intros thy;
haftmann@29526
   632
  in
haftmann@29526
   633
    Method.intros_tac (class_trivs @ class_intros @ assm_intros) facts st
haftmann@29526
   634
  end;
haftmann@29526
   635
haftmann@29526
   636
fun default_intro_tac ctxt [] =
haftmann@29577
   637
      intro_classes_tac [] ORELSE Locale.intro_locales_tac true ctxt []
haftmann@29526
   638
  | default_intro_tac _ _ = no_tac;
haftmann@29526
   639
haftmann@29526
   640
fun default_tac rules ctxt facts =
haftmann@29526
   641
  HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
haftmann@29526
   642
    default_intro_tac ctxt facts;
haftmann@29526
   643
haftmann@29526
   644
val _ = Context.>> (Context.map_theory
wenzelm@30515
   645
 (Method.setup (Binding.name "intro_classes") (Scan.succeed (K (METHOD intro_classes_tac)))
wenzelm@30515
   646
    "back-chain introduction rules of classes" #>
wenzelm@30515
   647
  Method.setup (Binding.name "default") (Attrib.thms >> (METHOD oo default_tac))
wenzelm@30515
   648
    "apply some intro/elim rule"));
haftmann@29526
   649
haftmann@24218
   650
end;
haftmann@25683
   651