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