src/Pure/Isar/class.ML
author haftmann
Fri Dec 07 15:08:09 2007 +0100 (2007-12-07)
changeset 25574 016f677ad7b8
parent 25536 01753a944433
child 25597 34860182b250
permissions -rw-r--r--
declaration of instance parameter names
haftmann@24218
     1
(*  Title:      Pure/Isar/class.ML
haftmann@24218
     2
    ID:         $Id$
haftmann@24218
     3
    Author:     Florian Haftmann, TU Muenchen
haftmann@24218
     4
haftmann@24218
     5
Type classes derived from primitive axclasses and locales.
haftmann@24218
     6
*)
haftmann@24218
     7
haftmann@24218
     8
signature CLASS =
haftmann@24218
     9
sig
haftmann@25462
    10
  (*classes*)
haftmann@25002
    11
  val class: bstring -> class list -> Element.context_i Locale.element list
haftmann@24218
    12
    -> string list -> theory -> string * Proof.context
haftmann@25002
    13
  val class_cmd: bstring -> xstring list -> Element.context Locale.element list
haftmann@24589
    14
    -> xstring list -> theory -> string * Proof.context
haftmann@25485
    15
haftmann@25311
    16
  val init: class -> theory -> Proof.context
haftmann@25485
    17
  val logical_const: string -> Markup.property list
wenzelm@25104
    18
    -> (string * mixfix) * term -> theory -> theory
haftmann@25485
    19
  val syntactic_const: string -> Syntax.mode -> Markup.property list
wenzelm@25104
    20
    -> (string * mixfix) * term -> theory -> theory
haftmann@25083
    21
  val refresh_syntax: class -> Proof.context -> Proof.context
haftmann@25485
    22
haftmann@24589
    23
  val intro_classes_tac: thm list -> tactic
haftmann@24589
    24
  val default_intro_classes_tac: thm list -> tactic
haftmann@25195
    25
  val prove_subclass: class * class -> thm list -> Proof.context
haftmann@25195
    26
    -> theory -> theory
haftmann@25485
    27
haftmann@25485
    28
  val class_prefix: string -> string
haftmann@25485
    29
  val is_class: theory -> class -> bool
haftmann@25485
    30
  val these_params: theory -> sort -> (string * (string * typ)) list
haftmann@24589
    31
  val print_classes: theory -> unit
haftmann@24423
    32
haftmann@25462
    33
  (*instances*)
haftmann@25536
    34
  val init_instantiation: string list * sort list * sort -> theory -> local_theory
haftmann@25536
    35
  val prep_spec: local_theory -> term -> term
haftmann@25485
    36
  val instantiation_instance: (local_theory -> local_theory) -> local_theory -> Proof.state
haftmann@25485
    37
  val prove_instantiation_instance: (Proof.context -> tactic) -> local_theory -> local_theory
haftmann@25485
    38
  val conclude_instantiation: local_theory -> local_theory
haftmann@25485
    39
haftmann@25518
    40
  val overloaded_const: string * typ -> theory -> term * theory
haftmann@25485
    41
  val overloaded_def: string -> string * term -> theory -> thm * theory
haftmann@25485
    42
  val instantiation_param: Proof.context -> string -> string option
haftmann@25485
    43
  val confirm_declaration: string -> local_theory -> local_theory
haftmann@25485
    44
haftmann@25485
    45
  val unoverload: theory -> thm -> thm
haftmann@25485
    46
  val overload: theory -> thm -> thm
haftmann@25485
    47
  val unoverload_conv: theory -> conv
haftmann@25485
    48
  val overload_conv: theory -> conv
haftmann@25462
    49
  val unoverload_const: theory -> string * typ -> string
haftmann@25485
    50
  val param_of_inst: theory -> string * string -> string
haftmann@25485
    51
  val inst_of_param: theory -> string -> (string * string) option
haftmann@25462
    52
haftmann@25462
    53
  (*old axclass layer*)
haftmann@25462
    54
  val axclass_cmd: bstring * xstring list
haftmann@25462
    55
    -> ((bstring * Attrib.src list) * string list) list
haftmann@25462
    56
    -> theory -> class * theory
haftmann@25462
    57
  val classrel_cmd: xstring * xstring -> theory -> Proof.state
haftmann@25462
    58
haftmann@25462
    59
  (*old instance layer*)
haftmann@25536
    60
  val instance_arity: (theory -> theory) -> arity -> theory -> Proof.state
haftmann@25536
    61
  val instance_arity_cmd: bstring * xstring list * xstring -> theory -> Proof.state
haftmann@24218
    62
end;
haftmann@24218
    63
haftmann@24218
    64
structure Class : CLASS =
haftmann@24218
    65
struct
haftmann@24218
    66
haftmann@24218
    67
(** auxiliary **)
haftmann@24218
    68
haftmann@25062
    69
val classN = "class";
haftmann@25062
    70
val introN = "intro";
haftmann@25062
    71
haftmann@25002
    72
fun prove_interpretation tac prfx_atts expr inst =
haftmann@25002
    73
  Locale.interpretation_i I prfx_atts expr inst
haftmann@24589
    74
  #> Proof.global_terminal_proof
haftmann@24589
    75
      (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
haftmann@24589
    76
  #> ProofContext.theory_of;
haftmann@24589
    77
haftmann@25195
    78
fun prove_interpretation_in tac after_qed (name, expr) =
haftmann@25195
    79
  Locale.interpretation_in_locale
haftmann@25195
    80
      (ProofContext.theory after_qed) (name, expr)
haftmann@25195
    81
  #> Proof.global_terminal_proof
haftmann@25195
    82
      (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
haftmann@25195
    83
  #> ProofContext.theory_of;
haftmann@25195
    84
wenzelm@25020
    85
fun OF_LAST thm1 thm2 = thm1 RSN (Thm.nprems_of thm2, thm2);
haftmann@24589
    86
haftmann@24589
    87
fun strip_all_ofclass thy sort =
haftmann@24589
    88
  let
wenzelm@24847
    89
    val typ = TVar ((Name.aT, 0), sort);
haftmann@24589
    90
    fun prem_inclass t =
haftmann@24589
    91
      case Logic.strip_imp_prems t
haftmann@24589
    92
       of ofcls :: _ => try Logic.dest_inclass ofcls
haftmann@24589
    93
        | [] => NONE;
haftmann@24589
    94
    fun strip_ofclass class thm =
haftmann@24589
    95
      thm OF (fst o AxClass.of_sort thy (typ, [class])) AxClass.cache;
haftmann@24589
    96
    fun strip thm = case (prem_inclass o Thm.prop_of) thm
haftmann@24589
    97
     of SOME (_, class) => thm |> strip_ofclass class |> strip
haftmann@24589
    98
      | NONE => thm;
haftmann@24589
    99
  in strip end;
haftmann@24589
   100
haftmann@25038
   101
fun get_remove_global_constraint c thy =
haftmann@25038
   102
  let
haftmann@25038
   103
    val ty = Sign.the_const_constraint thy c;
haftmann@25038
   104
  in
haftmann@25038
   105
    thy
haftmann@25038
   106
    |> Sign.add_const_constraint (c, NONE)
haftmann@25038
   107
    |> pair (c, Logic.unvarifyT ty)
haftmann@25038
   108
  end;
haftmann@25038
   109
haftmann@24589
   110
haftmann@25485
   111
(** primitive axclass and instance commands **)
haftmann@24589
   112
haftmann@24218
   113
fun axclass_cmd (class, raw_superclasses) raw_specs thy =
haftmann@24218
   114
  let
haftmann@24218
   115
    val ctxt = ProofContext.init thy;
haftmann@24218
   116
    val superclasses = map (Sign.read_class thy) raw_superclasses;
haftmann@24589
   117
    val name_atts = map ((apsnd o map) (Attrib.attribute thy) o fst)
haftmann@24589
   118
      raw_specs;
haftmann@24589
   119
    val axiomss = ProofContext.read_propp (ctxt, map (map (rpair []) o snd)
haftmann@24589
   120
          raw_specs)
haftmann@24218
   121
      |> snd
haftmann@24218
   122
      |> (map o map) fst;
haftmann@24589
   123
  in
haftmann@24589
   124
    AxClass.define_class (class, superclasses) []
haftmann@24589
   125
      (name_atts ~~ axiomss) thy
haftmann@24589
   126
  end;
haftmann@24218
   127
haftmann@24218
   128
local
haftmann@24218
   129
haftmann@24218
   130
fun gen_instance mk_prop add_thm after_qed insts thy =
haftmann@24218
   131
  let
haftmann@24218
   132
    fun after_qed' results =
haftmann@24218
   133
      ProofContext.theory ((fold o fold) add_thm results #> after_qed);
haftmann@24218
   134
  in
haftmann@24218
   135
    thy
haftmann@24218
   136
    |> ProofContext.init
haftmann@24589
   137
    |> Proof.theorem_i NONE after_qed' ((map (fn t => [(t, [])])
haftmann@25536
   138
        o mk_prop thy) insts)
haftmann@24218
   139
  end;
haftmann@24218
   140
haftmann@24218
   141
in
haftmann@24218
   142
haftmann@24589
   143
val instance_arity =
haftmann@24218
   144
  gen_instance (Logic.mk_arities oo Sign.cert_arity) AxClass.add_arity;
haftmann@25502
   145
val instance_arity_cmd =
haftmann@25502
   146
  gen_instance (Logic.mk_arities oo Sign.read_arity) AxClass.add_arity I;
haftmann@24589
   147
val classrel =
haftmann@25536
   148
  gen_instance (single oo (Logic.mk_classrel oo AxClass.cert_classrel)) AxClass.add_classrel I;
haftmann@24589
   149
val classrel_cmd =
haftmann@25536
   150
  gen_instance (single oo (Logic.mk_classrel oo AxClass.read_classrel)) AxClass.add_classrel I;
haftmann@24218
   151
haftmann@24218
   152
end; (*local*)
haftmann@24218
   153
haftmann@24218
   154
haftmann@25462
   155
(** basic overloading **)
haftmann@25462
   156
haftmann@25462
   157
(* bookkeeping *)
haftmann@24304
   158
haftmann@24304
   159
structure InstData = TheoryDataFun
haftmann@24304
   160
(
haftmann@24423
   161
  type T = (string * thm) Symtab.table Symtab.table * (string * string) Symtab.table;
haftmann@24423
   162
    (*constant name ~> type constructor ~> (constant name, equation),
haftmann@24423
   163
        constant name ~> (constant name, type constructor)*)
haftmann@24423
   164
  val empty = (Symtab.empty, Symtab.empty);
haftmann@24304
   165
  val copy = I;
haftmann@24304
   166
  val extend = I;
haftmann@24423
   167
  fun merge _ ((taba1, tabb1), (taba2, tabb2)) =
haftmann@24423
   168
    (Symtab.join (K (Symtab.merge (K true))) (taba1, taba2),
haftmann@24423
   169
      Symtab.merge (K true) (tabb1, tabb2));
haftmann@24304
   170
);
haftmann@24304
   171
haftmann@25462
   172
val inst_tyco = Option.map fst o try (dest_Type o the_single) oo Sign.const_typargs;
haftmann@25462
   173
haftmann@25462
   174
fun inst thy (c, tyco) =
haftmann@25462
   175
  (the o Symtab.lookup ((the o Symtab.lookup (fst (InstData.get thy))) c)) tyco;
haftmann@25462
   176
haftmann@25485
   177
val param_of_inst = fst oo inst;
haftmann@25462
   178
wenzelm@25020
   179
fun inst_thms thy = (Symtab.fold (Symtab.fold (cons o snd o snd) o snd) o fst)
haftmann@25462
   180
  (InstData.get thy) [];
haftmann@25462
   181
haftmann@25485
   182
val inst_of_param = Symtab.lookup o snd o InstData.get;
haftmann@25462
   183
haftmann@24589
   184
fun add_inst (c, tyco) inst = (InstData.map o apfst
haftmann@24589
   185
      o Symtab.map_default (c, Symtab.empty)) (Symtab.update_new (tyco, inst))
haftmann@24423
   186
  #> (InstData.map o apsnd) (Symtab.update_new (fst inst, (c, tyco)));
haftmann@24304
   187
haftmann@25485
   188
fun unoverload thy = MetaSimplifier.simplify true (inst_thms thy);
haftmann@25485
   189
fun overload thy = MetaSimplifier.simplify true (map Thm.symmetric (inst_thms thy));
haftmann@25485
   190
haftmann@25485
   191
fun unoverload_conv thy = MetaSimplifier.rewrite true (inst_thms thy);
haftmann@25485
   192
fun overload_conv thy = MetaSimplifier.rewrite true (map Thm.symmetric (inst_thms thy));
haftmann@24304
   193
haftmann@24423
   194
fun unoverload_const thy (c_ty as (c, _)) =
haftmann@24423
   195
  case AxClass.class_of_param thy c
haftmann@25462
   196
   of SOME class => (case inst_tyco thy c_ty
haftmann@25485
   197
       of SOME tyco => try (param_of_inst thy) (c, tyco) |> the_default c
haftmann@25462
   198
        | NONE => c)
haftmann@24423
   199
    | NONE => c;
haftmann@24423
   200
haftmann@25462
   201
haftmann@25462
   202
(* declaration and definition of instances of overloaded constants *)
haftmann@25462
   203
haftmann@25462
   204
fun primitive_note kind (name, thm) =
haftmann@25462
   205
  PureThy.note_thmss_i kind [((name, []), [([thm], [])])]
haftmann@25462
   206
  #>> (fn [(_, [thm])] => thm);
haftmann@25462
   207
haftmann@25518
   208
fun overloaded_const (c, ty) thy =
haftmann@25462
   209
  let
haftmann@25462
   210
    val SOME class = AxClass.class_of_param thy c;
haftmann@25462
   211
    val SOME tyco = inst_tyco thy (c, ty);
haftmann@25485
   212
    val name_inst = AxClass.instance_name (tyco, class) ^ "_inst";
haftmann@25502
   213
    val c' = NameSpace.base c ^ "_" ^ NameSpace.base tyco;
haftmann@25462
   214
    val ty' = Type.strip_sorts ty;
haftmann@25462
   215
  in
haftmann@25462
   216
    thy
haftmann@25462
   217
    |> Sign.sticky_prefix name_inst
haftmann@25462
   218
    |> Sign.no_base_names
haftmann@25462
   219
    |> Sign.declare_const [] (c', ty', NoSyn)
haftmann@25518
   220
    |-> (fn const' as Const (c'', _) => Thm.add_def false true
haftmann@25462
   221
          (Thm.def_name c', Logic.mk_equals (Const (c, ty'), const'))
haftmann@25462
   222
    #>> Thm.varifyT
haftmann@25462
   223
    #-> (fn thm => add_inst (c, tyco) (c'', thm)
haftmann@25462
   224
    #> primitive_note Thm.internalK (c', thm)
haftmann@25462
   225
    #> snd
haftmann@25462
   226
    #> Sign.restore_naming thy
haftmann@25462
   227
    #> pair (Const (c, ty))))
haftmann@25462
   228
  end;
haftmann@25462
   229
haftmann@25485
   230
fun overloaded_def name (c, t) thy =
haftmann@25462
   231
  let
haftmann@25462
   232
    val ty = Term.fastype_of t;
haftmann@25462
   233
    val SOME tyco = inst_tyco thy (c, ty);
haftmann@25462
   234
    val (c', eq) = inst thy (c, tyco);
haftmann@25462
   235
    val prop = Logic.mk_equals (Const (c', ty), t);
haftmann@25485
   236
    val name' = Thm.def_name_optional
haftmann@25485
   237
      (NameSpace.base c ^ "_" ^ NameSpace.base tyco) name;
haftmann@25462
   238
  in
haftmann@25462
   239
    thy
haftmann@25518
   240
    |> Thm.add_def false false (name', prop)
haftmann@25485
   241
    |>> (fn thm =>  Drule.transitive_thm OF [eq, thm])
haftmann@25462
   242
  end;
haftmann@25462
   243
haftmann@25462
   244
haftmann@24589
   245
(** class data **)
haftmann@24218
   246
haftmann@24218
   247
datatype class_data = ClassData of {
haftmann@24218
   248
  consts: (string * string) list
haftmann@24836
   249
    (*locale parameter ~> constant name*),
haftmann@25062
   250
  base_sort: sort,
haftmann@25083
   251
  inst: term option list
haftmann@25083
   252
    (*canonical interpretation*),
haftmann@25062
   253
  morphism: morphism,
haftmann@25062
   254
    (*partial morphism of canonical interpretation*)
haftmann@24657
   255
  intro: thm,
haftmann@24657
   256
  defs: thm list,
haftmann@25368
   257
  operations: (string * (class * (typ * term))) list
haftmann@24657
   258
};
haftmann@24218
   259
haftmann@24657
   260
fun rep_class_data (ClassData d) = d;
haftmann@25062
   261
fun mk_class_data ((consts, base_sort, inst, morphism, intro),
haftmann@25368
   262
    (defs, operations)) =
haftmann@25062
   263
  ClassData { consts = consts, base_sort = base_sort, inst = inst,
haftmann@25062
   264
    morphism = morphism, intro = intro, defs = defs,
haftmann@25368
   265
    operations = operations };
haftmann@25062
   266
fun map_class_data f (ClassData { consts, base_sort, inst, morphism, intro,
haftmann@25368
   267
    defs, operations }) =
haftmann@25062
   268
  mk_class_data (f ((consts, base_sort, inst, morphism, intro),
haftmann@25368
   269
    (defs, operations)));
haftmann@25038
   270
fun merge_class_data _ (ClassData { consts = consts,
haftmann@25062
   271
    base_sort = base_sort, inst = inst, morphism = morphism, intro = intro,
haftmann@25368
   272
    defs = defs1, operations = operations1 },
haftmann@25062
   273
  ClassData { consts = _, base_sort = _, inst = _, morphism = _, intro = _,
haftmann@25368
   274
    defs = defs2, operations = operations2 }) =
haftmann@25062
   275
  mk_class_data ((consts, base_sort, inst, morphism, intro),
haftmann@24914
   276
    (Thm.merge_thms (defs1, defs2),
haftmann@25368
   277
      AList.merge (op =) (K true) (operations1, operations2)));
haftmann@24218
   278
haftmann@24218
   279
structure ClassData = TheoryDataFun
haftmann@24218
   280
(
haftmann@25038
   281
  type T = class_data Graph.T
haftmann@25038
   282
  val empty = Graph.empty;
haftmann@24218
   283
  val copy = I;
haftmann@24218
   284
  val extend = I;
haftmann@25038
   285
  fun merge _ = Graph.join merge_class_data;
haftmann@24218
   286
);
haftmann@24218
   287
haftmann@24218
   288
haftmann@24218
   289
(* queries *)
haftmann@24218
   290
haftmann@25038
   291
val lookup_class_data = Option.map rep_class_data oo try o Graph.get_node o ClassData.get;
haftmann@24218
   292
haftmann@24589
   293
fun the_class_data thy class = case lookup_class_data thy class
wenzelm@25020
   294
 of NONE => error ("Undeclared class " ^ quote class)
haftmann@24589
   295
  | SOME data => data;
haftmann@24218
   296
haftmann@25038
   297
val is_class = is_some oo lookup_class_data;
haftmann@25038
   298
haftmann@25038
   299
val ancestry = Graph.all_succs o ClassData.get;
haftmann@24218
   300
haftmann@25002
   301
fun these_params thy =
haftmann@24218
   302
  let
haftmann@24218
   303
    fun params class =
haftmann@24218
   304
      let
wenzelm@24930
   305
        val const_typs = (#params o AxClass.get_info thy) class;
haftmann@24657
   306
        val const_names = (#consts o the_class_data thy) class;
haftmann@24218
   307
      in
haftmann@24218
   308
        (map o apsnd) (fn c => (c, (the o AList.lookup (op =) const_typs) c)) const_names
haftmann@24218
   309
      end;
haftmann@24218
   310
  in maps params o ancestry thy end;
haftmann@24218
   311
haftmann@24657
   312
fun these_defs thy = maps (these o Option.map #defs o lookup_class_data thy) o ancestry thy;
haftmann@24218
   313
haftmann@25062
   314
fun morphism thy = #morphism o the_class_data thy;
haftmann@25062
   315
haftmann@24218
   316
fun these_intros thy =
haftmann@24657
   317
  Graph.fold (fn (_, (data, _)) => insert Thm.eq_thm ((#intro o rep_class_data) data))
haftmann@25038
   318
    (ClassData.get thy) [];
haftmann@24218
   319
haftmann@24836
   320
fun these_operations thy =
haftmann@24836
   321
  maps (#operations o the_class_data thy) o ancestry thy;
haftmann@24657
   322
haftmann@24218
   323
fun print_classes thy =
haftmann@24218
   324
  let
wenzelm@24920
   325
    val ctxt = ProofContext.init thy;
haftmann@24218
   326
    val algebra = Sign.classes_of thy;
haftmann@24218
   327
    val arities =
haftmann@24218
   328
      Symtab.empty
haftmann@24218
   329
      |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
haftmann@24218
   330
           Symtab.map_default (class, []) (insert (op =) tyco)) arities)
haftmann@24218
   331
             ((#arities o Sorts.rep_algebra) algebra);
haftmann@24218
   332
    val the_arities = these o Symtab.lookup arities;
haftmann@24218
   333
    fun mk_arity class tyco =
haftmann@24218
   334
      let
haftmann@24218
   335
        val Ss = Sorts.mg_domain algebra tyco [class];
wenzelm@24920
   336
      in Syntax.pretty_arity ctxt (tyco, Ss, [class]) end;
haftmann@24218
   337
    fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
wenzelm@24920
   338
      ^ setmp show_sorts false (Syntax.string_of_typ ctxt o Type.strip_sorts) ty);
haftmann@24218
   339
    fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
haftmann@25062
   340
      (SOME o Pretty.str) ("class " ^ Sign.extern_class thy class ^ ":"),
haftmann@24218
   341
      (SOME o Pretty.block) [Pretty.str "supersort: ",
wenzelm@24920
   342
        (Syntax.pretty_sort ctxt o Sign.minimize_sort thy o Sign.super_classes thy) class],
haftmann@25062
   343
      if is_class thy class then (SOME o Pretty.str)
haftmann@25062
   344
        ("locale: " ^ Locale.extern thy class) else NONE,
haftmann@25062
   345
      ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks)
haftmann@25062
   346
          (Pretty.str "parameters:" :: ps)) o map mk_param
wenzelm@24930
   347
        o these o Option.map #params o try (AxClass.get_info thy)) class,
haftmann@24218
   348
      (SOME o Pretty.block o Pretty.breaks) [
haftmann@24218
   349
        Pretty.str "instances:",
haftmann@24218
   350
        Pretty.list "" "" (map (mk_arity class) (the_arities class))
haftmann@24218
   351
      ]
haftmann@24218
   352
    ]
haftmann@24218
   353
  in
haftmann@24589
   354
    (Pretty.writeln o Pretty.chunks o separate (Pretty.str "")
haftmann@24589
   355
      o map mk_entry o Sorts.all_classes) algebra
haftmann@24218
   356
  end;
haftmann@24218
   357
haftmann@24218
   358
haftmann@24218
   359
(* updaters *)
haftmann@24218
   360
haftmann@25163
   361
fun add_class_data ((class, superclasses), (cs, base_sort, inst, phi, intro)) thy =
haftmann@25002
   362
  let
haftmann@25368
   363
    val operations = map (fn (v_ty as (_, ty), (c, _)) =>
haftmann@25368
   364
      (c, (class, (ty, Free v_ty)))) cs;
haftmann@25002
   365
    val cs = (map o pairself) fst cs;
haftmann@25038
   366
    val add_class = Graph.new_node (class,
haftmann@25368
   367
        mk_class_data ((cs, base_sort, map (SOME o Const) inst, phi, intro), ([], operations)))
haftmann@25002
   368
      #> fold (curry Graph.add_edge class) superclasses;
haftmann@25002
   369
  in
haftmann@25038
   370
    ClassData.map add_class thy
haftmann@25002
   371
  end;
haftmann@24218
   372
haftmann@25368
   373
fun register_operation class (c, (t, some_def)) thy =
haftmann@25062
   374
  let
haftmann@25368
   375
    val base_sort = (#base_sort o the_class_data thy) class;
haftmann@25239
   376
    val prep_typ = map_atyps
haftmann@25368
   377
      (fn TVar (vi as (v, _), sort) => if Name.aT = v
haftmann@25368
   378
        then TFree (v, base_sort) else TVar (vi, sort));
haftmann@25368
   379
    val t' = map_types prep_typ t;
haftmann@25368
   380
    val ty' = Term.fastype_of t';
haftmann@25062
   381
  in
haftmann@25062
   382
    thy
haftmann@25062
   383
    |> (ClassData.map o Graph.map_node class o map_class_data o apsnd)
haftmann@25368
   384
      (fn (defs, operations) =>
haftmann@25096
   385
        (fold cons (the_list some_def) defs,
haftmann@25368
   386
          (c, (class, (ty', t'))) :: operations))
haftmann@25062
   387
  end;
haftmann@24218
   388
haftmann@24589
   389
haftmann@24589
   390
(** rule calculation, tactics and methods **)
haftmann@24589
   391
wenzelm@25024
   392
val class_prefix = Logic.const_of_class o Sign.base_name;
wenzelm@25024
   393
haftmann@25062
   394
fun calculate_morphism class cs =
haftmann@25062
   395
  let
haftmann@25062
   396
    val subst_typ = Term.map_type_tfree (fn var as (v, sort) =>
haftmann@25062
   397
      if v = Name.aT then TVar ((v, 0), [class]) else TVar ((v, 0), sort));
haftmann@25062
   398
    fun subst_aterm (t as Free (v, ty)) = (case AList.lookup (op =) cs v
haftmann@25062
   399
         of SOME (c, _) => Const (c, ty)
haftmann@25062
   400
          | NONE => t)
haftmann@25062
   401
      | subst_aterm t = t;
haftmann@25062
   402
    val subst_term = map_aterms subst_aterm #> map_types subst_typ;
haftmann@25062
   403
  in
haftmann@25209
   404
    Morphism.term_morphism subst_term
haftmann@25062
   405
    $> Morphism.typ_morphism subst_typ
haftmann@25062
   406
  end;
haftmann@25062
   407
haftmann@25038
   408
fun class_intro thy class sups =
haftmann@24589
   409
  let
haftmann@24589
   410
    fun class_elim class =
wenzelm@25020
   411
      case (#axioms o AxClass.get_info thy) class
wenzelm@25020
   412
       of [thm] => SOME (Drule.unconstrainTs thm)
haftmann@24589
   413
        | [] => NONE;
haftmann@25038
   414
    val pred_intro = case Locale.intros thy class
haftmann@24589
   415
     of ([ax_intro], [intro]) => intro |> OF_LAST ax_intro |> SOME
haftmann@24589
   416
      | ([intro], []) => SOME intro
haftmann@24589
   417
      | ([], [intro]) => SOME intro
haftmann@24589
   418
      | _ => NONE;
haftmann@24589
   419
    val pred_intro' = pred_intro
haftmann@24589
   420
      |> Option.map (fn intro => intro OF map_filter class_elim sups);
wenzelm@24930
   421
    val class_intro = (#intro o AxClass.get_info thy) class;
haftmann@24589
   422
    val raw_intro = case pred_intro'
haftmann@24589
   423
     of SOME pred_intro => class_intro |> OF_LAST pred_intro
haftmann@24589
   424
      | NONE => class_intro;
haftmann@24589
   425
    val sort = Sign.super_classes thy class;
wenzelm@24847
   426
    val typ = TVar ((Name.aT, 0), sort);
haftmann@24589
   427
    val defs = these_defs thy sups;
haftmann@24589
   428
  in
haftmann@24589
   429
    raw_intro
haftmann@24589
   430
    |> Drule.instantiate' [SOME (Thm.ctyp_of thy typ)] []
haftmann@24589
   431
    |> strip_all_ofclass thy sort
haftmann@24589
   432
    |> Thm.strip_shyps
haftmann@24589
   433
    |> MetaSimplifier.rewrite_rule defs
haftmann@24589
   434
    |> Drule.unconstrainTs
haftmann@24589
   435
  end;
haftmann@24589
   436
haftmann@24589
   437
fun class_interpretation class facts defs thy =
haftmann@24589
   438
  let
haftmann@25038
   439
    val params = these_params thy [class];
haftmann@25083
   440
    val inst = (#inst o the_class_data thy) class;
wenzelm@25020
   441
    val tac = ALLGOALS (ProofContext.fact_tac facts);
haftmann@25038
   442
    val prfx = class_prefix class;
haftmann@24589
   443
  in
haftmann@25038
   444
    thy
haftmann@25038
   445
    |> fold_map (get_remove_global_constraint o fst o snd) params
ballarin@25094
   446
    ||> prove_interpretation tac ((false, prfx), []) (Locale.Locale class)
ballarin@25094
   447
          (inst, map (fn def => (("", []), def)) defs)
haftmann@25038
   448
    |-> (fn cs => fold (Sign.add_const_constraint o apsnd SOME) cs)
haftmann@24589
   449
  end;
haftmann@24218
   450
haftmann@24218
   451
fun intro_classes_tac facts st =
haftmann@24218
   452
  let
haftmann@24218
   453
    val thy = Thm.theory_of_thm st;
haftmann@24218
   454
    val classes = Sign.all_classes thy;
haftmann@24218
   455
    val class_trivs = map (Thm.class_triv thy) classes;
haftmann@24218
   456
    val class_intros = these_intros thy;
wenzelm@24930
   457
    val axclass_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
haftmann@24218
   458
  in
haftmann@25268
   459
    Method.intros_tac (class_trivs @ class_intros @ axclass_intros) facts st
haftmann@24218
   460
  end;
haftmann@24218
   461
haftmann@24218
   462
fun default_intro_classes_tac [] = intro_classes_tac []
wenzelm@24930
   463
  | default_intro_classes_tac _ = no_tac;
haftmann@24218
   464
haftmann@24218
   465
fun default_tac rules ctxt facts =
haftmann@24218
   466
  HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
haftmann@24218
   467
    default_intro_classes_tac facts;
haftmann@24218
   468
haftmann@24218
   469
val _ = Context.add_setup (Method.add_methods
haftmann@24218
   470
 [("intro_classes", Method.no_args (Method.METHOD intro_classes_tac),
haftmann@24218
   471
    "back-chain introduction rules of classes"),
haftmann@24218
   472
  ("default", Method.thms_ctxt_args (Method.METHOD oo default_tac),
haftmann@24218
   473
    "apply some intro/elim rule")]);
haftmann@24218
   474
haftmann@25195
   475
fun subclass_rule thy (sub, sup) =
haftmann@25195
   476
  let
haftmann@25195
   477
    val ctxt = Locale.init sub thy;
haftmann@25195
   478
    val ctxt_thy = ProofContext.init thy;
haftmann@25195
   479
    val props =
haftmann@25195
   480
      Locale.global_asms_of thy sup
haftmann@25195
   481
      |> maps snd
haftmann@25195
   482
      |> map (ObjectLogic.ensure_propT thy);
haftmann@25195
   483
    fun tac { prems, context } =
haftmann@25195
   484
      Locale.intro_locales_tac true context prems
haftmann@25195
   485
        ORELSE ALLGOALS assume_tac;
haftmann@25195
   486
  in
haftmann@25195
   487
    Goal.prove_multi ctxt [] [] props tac
haftmann@25195
   488
    |> map (Assumption.export false ctxt ctxt_thy)
haftmann@25195
   489
    |> Variable.export ctxt ctxt_thy
haftmann@25195
   490
  end;
haftmann@25195
   491
haftmann@25195
   492
fun prove_single_subclass (sub, sup) thms ctxt thy =
haftmann@25195
   493
  let
haftmann@25195
   494
    val ctxt_thy = ProofContext.init thy;
haftmann@25195
   495
    val subclass_rule = Conjunction.intr_balanced thms
haftmann@25195
   496
      |> Assumption.export false ctxt ctxt_thy
haftmann@25195
   497
      |> singleton (Variable.export ctxt ctxt_thy);
haftmann@25195
   498
    val sub_inst = Thm.ctyp_of thy (TVar ((Name.aT, 0), [sub]));
haftmann@25195
   499
    val sub_ax = #axioms (AxClass.get_info thy sub);
haftmann@25195
   500
    val classrel =
haftmann@25195
   501
      #intro (AxClass.get_info thy sup)
haftmann@25195
   502
      |> Drule.instantiate' [SOME sub_inst] []
haftmann@25195
   503
      |> OF_LAST (subclass_rule OF sub_ax)
haftmann@25195
   504
      |> strip_all_ofclass thy (Sign.super_classes thy sup)
haftmann@25195
   505
      |> Thm.strip_shyps
haftmann@25195
   506
  in
haftmann@25195
   507
    thy
haftmann@25195
   508
    |> AxClass.add_classrel classrel
haftmann@25195
   509
    |> prove_interpretation_in (ALLGOALS (ProofContext.fact_tac thms))
haftmann@25195
   510
         I (sub, Locale.Locale sup)
haftmann@25195
   511
    |> ClassData.map (Graph.add_edge (sub, sup))
haftmann@25195
   512
  end;
haftmann@25195
   513
haftmann@25195
   514
fun prove_subclass (sub, sup) thms ctxt thy =
haftmann@25195
   515
  let
haftmann@25268
   516
    val classes = ClassData.get thy;
haftmann@25268
   517
    val is_sup = not o null o curry (Graph.irreducible_paths classes) sub;
haftmann@25268
   518
    val supclasses = Graph.all_succs classes [sup] |> filter_out is_sup;
haftmann@25195
   519
    fun transform sup' = subclass_rule thy (sup, sup') |> map (fn thm => thm OF thms);
haftmann@25195
   520
  in
haftmann@25195
   521
    thy
haftmann@25195
   522
    |> fold_rev (fn sup' => prove_single_subclass (sub, sup')
haftmann@25195
   523
         (transform sup') ctxt) supclasses
haftmann@25195
   524
 end;
haftmann@25195
   525
haftmann@24218
   526
haftmann@24589
   527
(** classes and class target **)
haftmann@24218
   528
haftmann@25002
   529
(* class context syntax *)
haftmann@24748
   530
haftmann@25083
   531
structure ClassSyntax = ProofDataFun(
haftmann@25083
   532
  type T = {
haftmann@25368
   533
    local_constraints: (string * typ) list,
haftmann@25368
   534
    global_constraints: (string * typ) list,
haftmann@25083
   535
    base_sort: sort,
haftmann@25368
   536
    operations: (string * (typ * term)) list,
haftmann@25195
   537
    unchecks: (term * term) list,
haftmann@25083
   538
    passed: bool
haftmann@25368
   539
  };
haftmann@25368
   540
  fun init _ = {
haftmann@25368
   541
    local_constraints = [],
haftmann@25368
   542
    global_constraints = [],
haftmann@25368
   543
    base_sort = [],
haftmann@25368
   544
    operations = [],
haftmann@25368
   545
    unchecks = [],
haftmann@25368
   546
    passed = true
haftmann@25368
   547
  };;
haftmann@25083
   548
);
haftmann@25083
   549
wenzelm@25344
   550
fun synchronize_syntax sups base_sort ctxt =
haftmann@24914
   551
  let
wenzelm@25344
   552
    val thy = ProofContext.theory_of ctxt;
haftmann@25368
   553
    fun subst_class_typ sort = map_atyps
haftmann@25368
   554
      (fn TFree _ => TVar ((Name.aT, 0), sort) | ty' => ty');
haftmann@25083
   555
    val operations = these_operations thy sups;
haftmann@25368
   556
    val local_constraints =
haftmann@25368
   557
      (map o apsnd) (subst_class_typ base_sort o fst o snd) operations;
haftmann@25368
   558
    val global_constraints =
haftmann@25368
   559
      (map o apsnd) (fn (class, (ty, _)) => subst_class_typ [class] ty) operations;
wenzelm@25318
   560
    fun declare_const (c, _) =
wenzelm@25318
   561
      let val b = Sign.base_name c
wenzelm@25344
   562
      in Sign.intern_const thy b = c ? Variable.declare_const (b, c) end;
haftmann@25368
   563
    val unchecks = map (fn (c, (_, (ty, t))) => (t, Const (c, ty))) operations;
haftmann@25083
   564
  in
haftmann@25083
   565
    ctxt
haftmann@25368
   566
    |> fold declare_const local_constraints
haftmann@25368
   567
    |> fold (ProofContext.add_const_constraint o apsnd SOME) local_constraints
haftmann@25368
   568
    |> ClassSyntax.put {
haftmann@25368
   569
        local_constraints = local_constraints,
haftmann@25368
   570
        global_constraints = global_constraints,
haftmann@25083
   571
        base_sort = base_sort,
haftmann@25368
   572
        operations = (map o apsnd) snd operations,
haftmann@25195
   573
        unchecks = unchecks,
haftmann@25083
   574
        passed = false
haftmann@25368
   575
      }
haftmann@25083
   576
  end;
haftmann@25083
   577
haftmann@25083
   578
fun refresh_syntax class ctxt =
haftmann@25002
   579
  let
haftmann@25002
   580
    val thy = ProofContext.theory_of ctxt;
haftmann@25062
   581
    val base_sort = (#base_sort o the_class_data thy) class;
wenzelm@25344
   582
  in synchronize_syntax [class] base_sort ctxt end;
haftmann@24914
   583
haftmann@25368
   584
val mark_passed = ClassSyntax.map
haftmann@25368
   585
  (fn { local_constraints, global_constraints, base_sort, operations, unchecks, passed } =>
haftmann@25368
   586
    { local_constraints = local_constraints, global_constraints = global_constraints,
haftmann@25368
   587
      base_sort = base_sort, operations = operations, unchecks = unchecks, passed = true });
haftmann@25083
   588
haftmann@25083
   589
fun sort_term_check ts ctxt =
haftmann@24748
   590
  let
haftmann@25368
   591
    val { local_constraints, global_constraints, base_sort, operations, passed, ... } =
haftmann@25368
   592
      ClassSyntax.get ctxt;
haftmann@25368
   593
    fun check_improve (Const (c, ty)) = (case AList.lookup (op =) local_constraints c
haftmann@25368
   594
         of SOME ty0 => (case try (Type.raw_match (ty0, ty)) Vartab.empty
haftmann@25368
   595
             of SOME tyenv => (case Vartab.lookup tyenv (Name.aT, 0)
haftmann@25368
   596
                 of SOME (_, TVar (tvar as (vi, _))) =>
haftmann@25368
   597
                      if TypeInfer.is_param vi then cons tvar else I
haftmann@25368
   598
                  | _ => I)
haftmann@25368
   599
              | NONE => I)
haftmann@25368
   600
          | NONE => I)
haftmann@25368
   601
      | check_improve _ = I;
haftmann@25368
   602
    val improvements = (fold o fold_aterms) check_improve ts [];
haftmann@25368
   603
    val ts' = (map o map_types o map_atyps) (fn ty as TVar tvar =>
haftmann@25368
   604
        if member (op =) improvements tvar
haftmann@25368
   605
          then TFree (Name.aT, base_sort) else ty | ty => ty) ts;
haftmann@25368
   606
    fun check t0 = Envir.expand_term (fn Const (c, ty) => (case AList.lookup (op =) operations c
haftmann@25368
   607
         of SOME (ty0, t) =>
haftmann@25368
   608
              if Type.typ_instance (ProofContext.tsig_of ctxt) (ty, ty0)
haftmann@25368
   609
              then SOME (ty0, check t) else NONE
haftmann@25368
   610
          | NONE => NONE)
haftmann@25368
   611
      | _ => NONE) t0;
haftmann@25368
   612
    val ts'' = map check ts';
haftmann@25368
   613
  in if eq_list (op aconv) (ts, ts'') andalso passed then NONE
haftmann@25083
   614
  else
haftmann@25083
   615
    ctxt
haftmann@25368
   616
    |> fold (ProofContext.add_const_constraint o apsnd SOME) global_constraints
haftmann@25083
   617
    |> mark_passed
haftmann@25368
   618
    |> pair ts''
haftmann@25083
   619
    |> SOME
haftmann@25083
   620
  end;
haftmann@24748
   621
haftmann@25083
   622
fun sort_term_uncheck ts ctxt =
haftmann@25002
   623
  let
haftmann@25002
   624
    val thy = ProofContext.theory_of ctxt;
haftmann@25368
   625
    val unchecks = (#unchecks o ClassSyntax.get) ctxt;
haftmann@25462
   626
    val ts' = map (Pattern.rewrite_term thy unchecks []) ts;
wenzelm@25060
   627
  in if eq_list (op aconv) (ts, ts') then NONE else SOME (ts', ctxt) end;
haftmann@25002
   628
wenzelm@25344
   629
fun init_ctxt sups base_sort ctxt =
haftmann@25083
   630
  ctxt
haftmann@25083
   631
  |> Variable.declare_term
haftmann@25083
   632
      (Logic.mk_type (TFree (Name.aT, base_sort)))
wenzelm@25344
   633
  |> synchronize_syntax sups base_sort
haftmann@25083
   634
  |> Context.proof_map (
haftmann@25083
   635
      Syntax.add_term_check 0 "class" sort_term_check
haftmann@25103
   636
      #> Syntax.add_term_uncheck 0 "class" sort_term_uncheck)
haftmann@24901
   637
haftmann@25311
   638
fun init class thy =
haftmann@25311
   639
  thy
haftmann@25311
   640
  |> Locale.init class
wenzelm@25344
   641
  |> init_ctxt [class] ((#base_sort o the_class_data thy) class);
haftmann@24914
   642
haftmann@24748
   643
haftmann@24589
   644
(* class definition *)
haftmann@24218
   645
haftmann@24218
   646
local
haftmann@24218
   647
haftmann@24748
   648
fun gen_class_spec prep_class prep_expr process_expr thy raw_supclasses raw_includes_elems =
haftmann@24218
   649
  let
haftmann@24748
   650
    val supclasses = map (prep_class thy) raw_supclasses;
haftmann@25209
   651
    val sups = filter (is_class thy) supclasses;
haftmann@25209
   652
    fun the_base_sort class = lookup_class_data thy class
haftmann@25209
   653
      |> Option.map #base_sort
haftmann@25209
   654
      |> the_default [class];
haftmann@25209
   655
    val base_sort = Sign.minimize_sort thy (maps the_base_sort supclasses);
haftmann@24748
   656
    val supsort = Sign.minimize_sort thy supclasses;
haftmann@25038
   657
    val suplocales = map Locale.Locale sups;
haftmann@24748
   658
    val (raw_elems, includes) = fold_rev (fn Locale.Elem e => apfst (cons e)
haftmann@24748
   659
      | Locale.Expr i => apsnd (cons (prep_expr thy i))) raw_includes_elems ([], []);
haftmann@24748
   660
    val supexpr = Locale.Merge suplocales;
haftmann@24748
   661
    val supparams = (map fst o Locale.parameters_of_expr thy) supexpr;
haftmann@25002
   662
    val supconsts = AList.make (the o AList.lookup (op =) (these_params thy sups))
haftmann@24748
   663
      (map fst supparams);
haftmann@24748
   664
    val mergeexpr = Locale.Merge (suplocales @ includes);
haftmann@24748
   665
    val constrain = Element.Constrains ((map o apsnd o map_atyps)
wenzelm@24847
   666
      (fn TFree (_, sort) => TFree (Name.aT, sort)) supparams);
haftmann@24748
   667
  in
haftmann@24748
   668
    ProofContext.init thy
haftmann@24748
   669
    |> Locale.cert_expr supexpr [constrain]
haftmann@24748
   670
    |> snd
wenzelm@25344
   671
    |> init_ctxt sups base_sort
haftmann@24748
   672
    |> process_expr Locale.empty raw_elems
haftmann@24748
   673
    |> fst
haftmann@25062
   674
    |> (fn elems => ((((sups, supconsts), (supsort, base_sort, mergeexpr)),
haftmann@24748
   675
          (*FIXME*) if null includes then constrain :: elems else elems)))
haftmann@24748
   676
  end;
haftmann@24748
   677
haftmann@24748
   678
val read_class_spec = gen_class_spec Sign.intern_class Locale.intern_expr Locale.read_expr;
haftmann@24748
   679
val check_class_spec = gen_class_spec (K I) (K I) Locale.cert_expr;
haftmann@24748
   680
wenzelm@24968
   681
fun define_class_params (name, raw_superclasses) raw_consts raw_dep_axioms other_consts thy =
wenzelm@24968
   682
  let
wenzelm@24968
   683
    val superclasses = map (Sign.certify_class thy) raw_superclasses;
wenzelm@24968
   684
    val consts = (map o apfst o apsnd) (Sign.certify_typ thy) raw_consts;
haftmann@25083
   685
    fun add_const ((c, ty), syn) =
haftmann@25083
   686
      Sign.declare_const [] (c, Type.strip_sorts ty, syn) #>> Term.dest_Const;
wenzelm@24968
   687
    fun mk_axioms cs thy =
wenzelm@24968
   688
      raw_dep_axioms thy cs
wenzelm@24968
   689
      |> (map o apsnd o map) (Sign.cert_prop thy)
wenzelm@24968
   690
      |> rpair thy;
haftmann@25002
   691
    fun constrain_typs class = (map o apsnd o Term.map_type_tfree)
haftmann@25002
   692
      (fn (v, _) => TFree (v, [class]))
wenzelm@24968
   693
  in
wenzelm@24968
   694
    thy
wenzelm@24968
   695
    |> Sign.add_path (Logic.const_of_class name)
wenzelm@24968
   696
    |> fold_map add_const consts
wenzelm@24968
   697
    ||> Sign.restore_naming thy
wenzelm@24968
   698
    |-> (fn cs => mk_axioms cs
wenzelm@24968
   699
    #-> (fn axioms_prop => AxClass.define_class (name, superclasses)
wenzelm@24968
   700
           (map fst cs @ other_consts) axioms_prop
haftmann@25002
   701
    #-> (fn class => `(fn _ => constrain_typs class cs)
haftmann@25002
   702
    #-> (fn cs' => `(fn thy => AxClass.get_info thy class)
haftmann@25002
   703
    #-> (fn {axioms, ...} => fold (Sign.add_const_constraint o apsnd SOME) cs'
haftmann@25002
   704
    #> pair (class, (cs', axioms)))))))
wenzelm@24968
   705
  end;
wenzelm@24968
   706
haftmann@25002
   707
fun gen_class prep_spec prep_param bname
haftmann@24748
   708
    raw_supclasses raw_includes_elems raw_other_consts thy =
haftmann@24748
   709
  let
haftmann@25038
   710
    val class = Sign.full_name thy bname;
haftmann@25062
   711
    val (((sups, supconsts), (supsort, base_sort, mergeexpr)), elems_syn) =
haftmann@24748
   712
      prep_spec thy raw_supclasses raw_includes_elems;
wenzelm@24968
   713
    val other_consts = map (tap (Sign.the_const_type thy) o prep_param thy) raw_other_consts;
haftmann@25163
   714
    fun mk_inst class cs =
haftmann@25163
   715
      (map o apsnd o Term.map_type_tfree) (fn (v, _) => TFree (v, [class])) cs;
haftmann@25062
   716
    fun fork_syntax (Element.Fixes xs) =
haftmann@25062
   717
          fold_map (fn (c, ty, syn) => cons (c, syn) #> pair (c, ty, NoSyn)) xs
haftmann@25062
   718
          #>> Element.Fixes
haftmann@25062
   719
      | fork_syntax x = pair x;
haftmann@25062
   720
    val (elems, global_syn) = fold_map fork_syntax elems_syn [];
wenzelm@25326
   721
    fun globalize (c, ty) =
haftmann@25062
   722
      ((c, Term.map_type_tfree (K (TFree (Name.aT, base_sort))) ty),
haftmann@25062
   723
        (the_default NoSyn o AList.lookup (op =) global_syn) c);
haftmann@25038
   724
    fun extract_params thy =
haftmann@24218
   725
      let
haftmann@25062
   726
        val params = map fst (Locale.parameters_of thy class);
haftmann@24218
   727
      in
haftmann@25062
   728
        (params, (map globalize o snd o chop (length supconsts)) params)
haftmann@24218
   729
      end;
haftmann@25038
   730
    fun extract_assumes params thy cs =
haftmann@24218
   731
      let
haftmann@24218
   732
        val consts = supconsts @ (map (fst o fst) params ~~ cs);
haftmann@24218
   733
        fun subst (Free (c, ty)) =
haftmann@24218
   734
              Const ((fst o the o AList.lookup (op =) consts) c, ty)
haftmann@24218
   735
          | subst t = t;
haftmann@24218
   736
        fun prep_asm ((name, atts), ts) =
wenzelm@25024
   737
          ((Sign.base_name name, map (Attrib.attribute_i thy) atts),
haftmann@24589
   738
            (map o map_aterms) subst ts);
haftmann@24218
   739
      in
haftmann@25038
   740
        Locale.global_asms_of thy class
haftmann@24218
   741
        |> map prep_asm
haftmann@24218
   742
      end;
haftmann@24218
   743
  in
haftmann@24218
   744
    thy
haftmann@24748
   745
    |> Locale.add_locale_i (SOME "") bname mergeexpr elems
haftmann@25038
   746
    |> snd
haftmann@25311
   747
    |> ProofContext.theory_of
haftmann@25311
   748
    |> `extract_params
haftmann@25311
   749
    |-> (fn (all_params, params) =>
wenzelm@24968
   750
        define_class_params (bname, supsort) params
haftmann@25038
   751
          (extract_assumes params) other_consts
haftmann@25038
   752
      #-> (fn (_, (consts, axioms)) =>
haftmann@25038
   753
        `(fn thy => class_intro thy class sups)
haftmann@24218
   754
      #-> (fn class_intro =>
haftmann@25062
   755
        PureThy.note_thmss_qualified "" (NameSpace.append class classN)
haftmann@25062
   756
          [((introN, []), [([class_intro], [])])]
haftmann@25062
   757
      #-> (fn [(_, [class_intro])] =>
haftmann@25038
   758
        add_class_data ((class, sups),
haftmann@25062
   759
          (map fst params ~~ consts, base_sort,
haftmann@25163
   760
            mk_inst class (map snd supconsts @ consts),
haftmann@25062
   761
              calculate_morphism class (supconsts @ (map (fst o fst) params ~~ consts)), class_intro))
haftmann@25038
   762
      #> class_interpretation class axioms []
haftmann@25311
   763
      ))))
haftmann@25268
   764
    |> init class
haftmann@25038
   765
    |> pair class
haftmann@24218
   766
  end;
haftmann@24218
   767
wenzelm@25326
   768
fun read_const thy = #1 o Term.dest_Const o ProofContext.read_const (ProofContext.init thy);
wenzelm@25326
   769
haftmann@24218
   770
in
haftmann@24218
   771
wenzelm@25326
   772
val class_cmd = gen_class read_class_spec read_const;
haftmann@24748
   773
val class = gen_class check_class_spec (K I);
haftmann@24218
   774
haftmann@24218
   775
end; (*local*)
haftmann@24218
   776
haftmann@24218
   777
haftmann@25485
   778
(* class target *)
haftmann@24218
   779
haftmann@25485
   780
fun logical_const class pos ((c, mx), dict) thy =
haftmann@24218
   781
  let
wenzelm@25024
   782
    val prfx = class_prefix class;
wenzelm@25024
   783
    val thy' = thy |> Sign.add_path prfx;
haftmann@25062
   784
    val phi = morphism thy' class;
wenzelm@25024
   785
haftmann@25062
   786
    val c' = Sign.full_name thy' c;
haftmann@25239
   787
    val dict' = Morphism.term phi dict;
haftmann@25239
   788
    val dict_def = map_types Logic.unvarifyT dict';
haftmann@25239
   789
    val ty' = Term.fastype_of dict_def;
haftmann@25083
   790
    val ty'' = Type.strip_sorts ty';
haftmann@25239
   791
    val def_eq = Logic.mk_equals (Const (c', ty'), dict_def);
haftmann@24218
   792
  in
wenzelm@25024
   793
    thy'
haftmann@25096
   794
    |> Sign.declare_const pos (c, ty'', mx) |> snd
haftmann@25518
   795
    |> Thm.add_def false false (c, def_eq)
haftmann@25062
   796
    |>> Thm.symmetric
haftmann@25083
   797
    |-> (fn def => class_interpretation class [def] [Thm.prop_of def]
haftmann@25368
   798
          #> register_operation class (c', (dict', SOME (Thm.varifyT def))))
haftmann@24218
   799
    |> Sign.restore_naming thy
haftmann@25083
   800
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@24218
   801
  end;
haftmann@24218
   802
haftmann@25485
   803
fun syntactic_const class prmode pos ((c, mx), rhs) thy =
haftmann@24836
   804
  let
wenzelm@25024
   805
    val prfx = class_prefix class;
haftmann@25096
   806
    val thy' = thy |> Sign.add_path prfx;
haftmann@25062
   807
    val phi = morphism thy class;
haftmann@25062
   808
haftmann@25096
   809
    val c' = Sign.full_name thy' c;
haftmann@25146
   810
    val rews = map (Logic.dest_equals o Thm.prop_of) (these_defs thy' [class])
haftmann@25146
   811
    val rhs' = (Pattern.rewrite_term thy rews [] o Morphism.term phi) rhs;
haftmann@25239
   812
    val ty' = Logic.unvarifyT (Term.fastype_of rhs');
haftmann@24836
   813
  in
haftmann@25096
   814
    thy'
haftmann@25146
   815
    |> Sign.add_abbrev (#1 prmode) pos (c, map_types Type.strip_sorts rhs') |> snd
haftmann@25096
   816
    |> Sign.add_const_constraint (c', SOME ty')
wenzelm@25024
   817
    |> Sign.notation true prmode [(Const (c', ty'), mx)]
haftmann@25368
   818
    |> register_operation class (c', (rhs', NONE))
haftmann@25096
   819
    |> Sign.restore_naming thy
haftmann@24836
   820
  end;
haftmann@24836
   821
haftmann@25462
   822
haftmann@25462
   823
(** instantiation target **)
haftmann@25462
   824
haftmann@25462
   825
(* bookkeeping *)
haftmann@25462
   826
haftmann@25462
   827
datatype instantiation = Instantiation of {
haftmann@25536
   828
  arities: string list * sort list * sort,
haftmann@25462
   829
  params: ((string * string) * (string * typ)) list
haftmann@25574
   830
    (*(instantiation const, type constructor), (local instantiation parameter, typ)*)
haftmann@25462
   831
}
haftmann@25462
   832
haftmann@25462
   833
structure Instantiation = ProofDataFun
haftmann@25462
   834
(
haftmann@25462
   835
  type T = instantiation
haftmann@25536
   836
  fun init _ = Instantiation { arities = ([], [], []), params = [] };
haftmann@25462
   837
);
haftmann@25462
   838
haftmann@25485
   839
fun mk_instantiation (arities, params) =
haftmann@25485
   840
  Instantiation { arities = arities, params = params };
haftmann@25514
   841
fun get_instantiation lthy = case Instantiation.get (LocalTheory.target_of lthy)
haftmann@25485
   842
 of Instantiation data => data;
haftmann@25514
   843
fun map_instantiation f = (LocalTheory.target o Instantiation.map)
haftmann@25514
   844
  (fn Instantiation { arities, params } => mk_instantiation (f (arities, params)));
haftmann@25462
   845
haftmann@25514
   846
fun the_instantiation lthy = case get_instantiation lthy
haftmann@25536
   847
 of { arities = ([], [], []), ... } => error "No instantiation target"
haftmann@25485
   848
  | data => data;
haftmann@25462
   849
haftmann@25485
   850
val instantiation_params = #params o get_instantiation;
haftmann@25462
   851
haftmann@25514
   852
fun instantiation_param lthy v = instantiation_params lthy
haftmann@25462
   853
  |> find_first (fn (_, (v', _)) => v = v')
haftmann@25462
   854
  |> Option.map (fst o fst);
haftmann@25462
   855
haftmann@25514
   856
fun confirm_declaration c = (map_instantiation o apsnd)
haftmann@25485
   857
  (filter_out (fn (_, (c', _)) => c' = c));
haftmann@25485
   858
haftmann@25462
   859
haftmann@25462
   860
(* syntax *)
haftmann@25462
   861
haftmann@25536
   862
fun subst_param thy params = map_aterms (fn t as Const (c, ty) => (case inst_tyco thy (c, ty)
haftmann@25536
   863
     of SOME tyco => (case AList.lookup (op =) params (c, tyco)
haftmann@25536
   864
         of SOME v_ty => Free v_ty
haftmann@25536
   865
          | NONE => t)
haftmann@25536
   866
      | NONE => t)
haftmann@25536
   867
  | t => t);
haftmann@25536
   868
haftmann@25536
   869
fun prep_spec lthy =
haftmann@25536
   870
  let
haftmann@25536
   871
    val thy = ProofContext.theory_of lthy;
haftmann@25536
   872
    val params = instantiation_params lthy;
haftmann@25536
   873
  in subst_param thy params end;
haftmann@25536
   874
haftmann@25514
   875
fun inst_term_check ts lthy =
haftmann@25462
   876
  let
haftmann@25514
   877
    val params = instantiation_params lthy;
haftmann@25514
   878
    val tsig = ProofContext.tsig_of lthy;
haftmann@25514
   879
    val thy = ProofContext.theory_of lthy;
haftmann@25462
   880
haftmann@25462
   881
    fun check_improve (Const (c, ty)) = (case inst_tyco thy (c, ty)
haftmann@25462
   882
         of SOME tyco => (case AList.lookup (op =) params (c, tyco)
haftmann@25502
   883
             of SOME (_, ty') => perhaps (try (Type.typ_match tsig (ty, ty')))
haftmann@25462
   884
              | NONE => I)
haftmann@25462
   885
          | NONE => I)
haftmann@25462
   886
      | check_improve _ = I;
haftmann@25462
   887
    val improvement = (fold o fold_aterms) check_improve ts Vartab.empty;
haftmann@25462
   888
    val ts' = (map o map_types) (Envir.typ_subst_TVars improvement) ts;
haftmann@25536
   889
    val ts'' = map (subst_param thy params) ts';
haftmann@25514
   890
  in if eq_list (op aconv) (ts, ts'') then NONE else SOME (ts'', lthy) end;
haftmann@25462
   891
haftmann@25514
   892
fun inst_term_uncheck ts lthy =
haftmann@25462
   893
  let
haftmann@25514
   894
    val params = instantiation_params lthy;
haftmann@25462
   895
    val ts' = (map o map_aterms) (fn t as Free (v, ty) =>
haftmann@25462
   896
       (case get_first (fn ((c, _), (v', _)) => if v = v' then SOME c else NONE) params
haftmann@25462
   897
         of SOME c => Const (c, ty)
haftmann@25462
   898
          | NONE => t)
haftmann@25462
   899
      | t => t) ts;
haftmann@25514
   900
  in if eq_list (op aconv) (ts, ts') then NONE else SOME (ts', lthy) end;
haftmann@25462
   901
haftmann@25462
   902
haftmann@25462
   903
(* target *)
haftmann@25462
   904
haftmann@25485
   905
val sanatize_name = (*FIXME*)
haftmann@25485
   906
  let
haftmann@25574
   907
    fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s
haftmann@25574
   908
      orelse s = "'" orelse s = "_";
haftmann@25485
   909
    val is_junk = not o is_valid andf Symbol.is_regular;
haftmann@25485
   910
    val junk = Scan.many is_junk;
haftmann@25485
   911
    val scan_valids = Symbol.scanner "Malformed input"
haftmann@25485
   912
      ((junk |--
haftmann@25485
   913
        (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
haftmann@25485
   914
        --| junk))
haftmann@25485
   915
      -- Scan.repeat ((Scan.many1 is_valid >> implode) --| junk) >> op ::);
haftmann@25485
   916
  in
haftmann@25485
   917
    explode #> scan_valids #> implode
haftmann@25485
   918
  end;
haftmann@25485
   919
haftmann@25536
   920
fun init_instantiation (tycos, sorts, sort) thy =
haftmann@25462
   921
  let
haftmann@25536
   922
    val _ = if null tycos then error "At least one arity must be given" else ();
haftmann@25536
   923
    val _ = map (the_class_data thy) sort;
haftmann@25536
   924
    val vs = map TFree (Name.names Name.context Name.aT sorts);
haftmann@25485
   925
    fun type_name "*" = "prod"
haftmann@25485
   926
      | type_name "+" = "sum"
haftmann@25485
   927
      | type_name s = sanatize_name (NameSpace.base s); (*FIXME*)
haftmann@25536
   928
    fun get_param tyco (param, (c, ty)) = if can (inst thy) (c, tyco)
haftmann@25502
   929
      then NONE else SOME ((unoverload_const thy (c, ty), tyco),
haftmann@25536
   930
        (param ^ "_" ^ type_name tyco, map_atyps (K (Type (tyco, vs))) ty));
haftmann@25536
   931
    val params = map_product get_param tycos (these_params thy sort) |> map_filter I;
haftmann@25485
   932
  in
haftmann@25485
   933
    thy
haftmann@25485
   934
    |> ProofContext.init
haftmann@25536
   935
    |> Instantiation.put (mk_instantiation ((tycos, sorts, sort), params))
haftmann@25536
   936
    |> fold (Variable.declare_term o Logic.mk_type) vs
haftmann@25574
   937
    |> fold (Variable.declare_names o Free o snd) params
haftmann@25536
   938
    |> fold (fn tyco => ProofContext.add_arity (tyco, sorts, sort)) tycos
haftmann@25485
   939
    |> Context.proof_map (
haftmann@25485
   940
        Syntax.add_term_check 0 "instance" inst_term_check
haftmann@25485
   941
        #> Syntax.add_term_uncheck 0 "instance" inst_term_uncheck)
haftmann@25485
   942
  end;
haftmann@25485
   943
haftmann@25485
   944
fun gen_instantiation_instance do_proof after_qed lthy =
haftmann@25485
   945
  let
haftmann@25536
   946
    val (tycos, sorts, sort) = (#arities o the_instantiation) lthy;
haftmann@25536
   947
    val arities_proof = maps (fn tyco => Logic.mk_arities (tyco, sorts, sort)) tycos;
haftmann@25462
   948
    fun after_qed' results =
haftmann@25462
   949
      LocalTheory.theory (fold (AxClass.add_arity o Thm.varifyT) results)
haftmann@25462
   950
      #> after_qed;
haftmann@25462
   951
  in
haftmann@25462
   952
    lthy
haftmann@25462
   953
    |> do_proof after_qed' arities_proof
haftmann@25462
   954
  end;
haftmann@25462
   955
haftmann@25485
   956
val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
haftmann@25462
   957
  Proof.theorem_i NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
haftmann@25462
   958
haftmann@25485
   959
fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
haftmann@25502
   960
  fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
haftmann@25502
   961
    (fn {context, ...} => tac context)) ts) lthy) I;
haftmann@25462
   962
haftmann@25462
   963
fun conclude_instantiation lthy =
haftmann@25462
   964
  let
haftmann@25485
   965
    val { arities, params } = the_instantiation lthy;
haftmann@25536
   966
    val (tycos, sorts, sort) = arities;
haftmann@25462
   967
    val thy = ProofContext.theory_of lthy;
haftmann@25462
   968
    (*val _ = map (fn (tyco, sorts, sort) =>
haftmann@25462
   969
      if Sign.of_sort thy
haftmann@25462
   970
        (Type (tyco, map TFree (Name.names Name.context Name.aT sorts)), sort)
haftmann@25462
   971
      then () else error ("Missing instance proof for type " ^ quote (Sign.extern_type thy tyco)))
haftmann@25462
   972
        arities; FIXME activate when old instance command is gone*)
haftmann@25462
   973
    val params_of = maps (these o try (#params o AxClass.get_info thy))
haftmann@25462
   974
      o Sign.complete_sort thy;
haftmann@25536
   975
    val missing_params = tycos
haftmann@25536
   976
      |> maps (fn tyco => params_of sort |> map (rpair tyco))
haftmann@25462
   977
      |> filter_out (can (inst thy) o apfst fst);
haftmann@25485
   978
    fun declare_missing ((c, ty0), tyco) thy =
haftmann@25485
   979
    (*fun declare_missing ((c, tyco), (_, ty)) thy =*)
haftmann@25462
   980
      let
haftmann@25462
   981
        val SOME class = AxClass.class_of_param thy c;
haftmann@25485
   982
        val name_inst = AxClass.instance_name (tyco, class) ^ "_inst";
haftmann@25502
   983
        val c' = NameSpace.base c ^ "_" ^ NameSpace.base tyco;
haftmann@25462
   984
        val vs = Name.names Name.context Name.aT (replicate (Sign.arity_number thy tyco) []);
haftmann@25485
   985
        val ty = map_atyps (fn _ => Type (tyco, map TFree vs)) ty0;
haftmann@25462
   986
      in
haftmann@25462
   987
        thy
haftmann@25462
   988
        |> Sign.sticky_prefix name_inst
haftmann@25462
   989
        |> Sign.no_base_names
haftmann@25485
   990
        |> Sign.declare_const [] (c', ty, NoSyn)
haftmann@25518
   991
        |-> (fn const' as Const (c'', _) => Thm.add_def false true
haftmann@25485
   992
              (Thm.def_name c', Logic.mk_equals (const', Const (c, ty)))
haftmann@25462
   993
        #>> Thm.varifyT
haftmann@25462
   994
        #-> (fn thm => add_inst (c, tyco) (c'', Thm.symmetric thm)
haftmann@25462
   995
        #> primitive_note Thm.internalK (c', thm)
haftmann@25462
   996
        #> snd
haftmann@25462
   997
        #> Sign.restore_naming thy))
haftmann@25462
   998
      end;
haftmann@25462
   999
  in
haftmann@25462
  1000
    lthy
haftmann@25462
  1001
    |> LocalTheory.theory (fold declare_missing missing_params)
haftmann@25462
  1002
  end;
haftmann@25462
  1003
haftmann@24218
  1004
end;