src/Pure/Isar/class.ML
author haftmann
Thu Nov 06 09:09:48 2008 +0100 (2008-11-06 ago)
changeset 28715 238f9966c80e
parent 28674 08a77c495dc1
child 28739 bbb5f83ce602
permissions -rw-r--r--
class morphism stemming from locale interpretation
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@26247
    11
  val class: bstring -> class list -> Element.context_i list
haftmann@26518
    12
    -> theory -> string * Proof.context
haftmann@26247
    13
  val class_cmd: bstring -> xstring list -> Element.context list
haftmann@26518
    14
    -> theory -> string * Proof.context
haftmann@25485
    15
haftmann@25311
    16
  val init: class -> theory -> Proof.context
wenzelm@28017
    17
  val declare: class -> Properties.T
haftmann@27690
    18
    -> (string * mixfix) * term -> theory -> theory
wenzelm@28017
    19
  val abbrev: class -> Syntax.mode -> Properties.T
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@26470
    24
  val default_intro_tac: Proof.context -> thm list -> tactic
haftmann@27684
    25
  val prove_subclass: class * class -> thm option -> theory -> theory
haftmann@25485
    26
haftmann@25485
    27
  val class_prefix: string -> string
haftmann@25485
    28
  val is_class: theory -> class -> bool
haftmann@26518
    29
  val these_params: theory -> sort -> (string * (class * (string * typ))) list
haftmann@24589
    30
  val print_classes: theory -> unit
haftmann@24423
    31
haftmann@25462
    32
  (*instances*)
haftmann@26247
    33
  val init_instantiation: string list * (string * sort) list * sort
haftmann@26247
    34
    -> theory -> local_theory
haftmann@26247
    35
  val instantiation_instance: (local_theory -> local_theory)
haftmann@26247
    36
    -> local_theory -> Proof.state
haftmann@26247
    37
  val prove_instantiation_instance: (Proof.context -> tactic)
haftmann@26247
    38
    -> local_theory -> local_theory
haftmann@28666
    39
  val prove_instantiation_exit: (Proof.context -> tactic)
haftmann@28666
    40
    -> local_theory -> theory
haftmann@28666
    41
  val prove_instantiation_exit_result: (morphism -> 'a -> 'b)
haftmann@28666
    42
    -> (Proof.context -> 'b -> tactic) -> 'a -> local_theory -> 'b * theory
haftmann@25485
    43
  val conclude_instantiation: local_theory -> local_theory
haftmann@25603
    44
  val instantiation_param: local_theory -> string -> string option
haftmann@25485
    45
  val confirm_declaration: string -> local_theory -> local_theory
haftmann@25603
    46
  val pretty_instantiation: local_theory -> Pretty.T
haftmann@26259
    47
  val type_name: string -> string
haftmann@25485
    48
haftmann@25462
    49
  (*old axclass layer*)
haftmann@25462
    50
  val axclass_cmd: bstring * xstring list
wenzelm@28084
    51
    -> (Attrib.binding * string list) list
haftmann@25462
    52
    -> theory -> class * theory
haftmann@25462
    53
  val classrel_cmd: xstring * xstring -> theory -> Proof.state
haftmann@25462
    54
haftmann@25462
    55
  (*old instance layer*)
haftmann@25536
    56
  val instance_arity: (theory -> theory) -> arity -> theory -> Proof.state
haftmann@25536
    57
  val instance_arity_cmd: bstring * xstring list * xstring -> theory -> Proof.state
haftmann@24218
    58
end;
haftmann@24218
    59
haftmann@24218
    60
structure Class : CLASS =
haftmann@24218
    61
struct
haftmann@24218
    62
haftmann@24218
    63
(** auxiliary **)
haftmann@24218
    64
haftmann@25002
    65
fun prove_interpretation tac prfx_atts expr inst =
haftmann@28715
    66
  Locale.interpretation_i I prfx_atts expr inst
haftmann@28715
    67
  ##> Proof.global_terminal_proof
ballarin@27761
    68
      (Method.Basic (fn ctxt => Method.SIMPLE_METHOD (tac ctxt), Position.none), NONE)
haftmann@28715
    69
  ##> ProofContext.theory_of;
haftmann@24589
    70
haftmann@25195
    71
fun prove_interpretation_in tac after_qed (name, expr) =
haftmann@25195
    72
  Locale.interpretation_in_locale
haftmann@25195
    73
      (ProofContext.theory after_qed) (name, expr)
haftmann@25195
    74
  #> Proof.global_terminal_proof
haftmann@25195
    75
      (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
haftmann@25195
    76
  #> ProofContext.theory_of;
haftmann@25195
    77
haftmann@28715
    78
val class_prefix = Logic.const_of_class o Sign.base_name;
haftmann@28715
    79
haftmann@28715
    80
fun activate_class_morphism thy class inst morphism =
haftmann@28715
    81
  Locale.get_interpret_morph thy (class_prefix class) "" morphism class inst;
haftmann@28715
    82
haftmann@28715
    83
fun prove_class_interpretation class inst consts hyp_facts def_facts thy =
haftmann@28715
    84
  let
haftmann@28715
    85
    val constraints = map (fn (class, c) => map_atyps (K (TFree (Name.aT,
haftmann@28715
    86
      [class]))) (Sign.the_const_type thy c)) consts;
haftmann@28715
    87
    val no_constraints = map (map_atyps (K (TFree (Name.aT, [])))) constraints;
haftmann@28715
    88
    fun add_constraint c T = Sign.add_const_constraint (c, SOME T);
haftmann@28715
    89
    fun tac ctxt = ALLGOALS (ProofContext.fact_tac (hyp_facts @ def_facts)
haftmann@28715
    90
      ORELSE' (fn n => SELECT_GOAL (Locale.intro_locales_tac false ctxt []) n));
haftmann@28715
    91
    val prfx = class_prefix class;
haftmann@28715
    92
  in
haftmann@28715
    93
    thy
haftmann@28715
    94
    |> fold2 add_constraint (map snd consts) no_constraints
haftmann@28715
    95
    |> prove_interpretation tac (false, prfx) (Locale.Locale class)
haftmann@28715
    96
          (map SOME inst, map (pair (Attrib.no_binding) o Thm.prop_of) def_facts)
haftmann@28715
    97
    ||> fold2 add_constraint (map snd consts) constraints
haftmann@28715
    98
  end;
haftmann@28715
    99
haftmann@24589
   100
haftmann@25485
   101
(** primitive axclass and instance commands **)
haftmann@24589
   102
haftmann@24218
   103
fun axclass_cmd (class, raw_superclasses) raw_specs thy =
haftmann@24218
   104
  let
haftmann@24218
   105
    val ctxt = ProofContext.init thy;
haftmann@24218
   106
    val superclasses = map (Sign.read_class thy) raw_superclasses;
haftmann@24589
   107
    val name_atts = map ((apsnd o map) (Attrib.attribute thy) o fst)
haftmann@24589
   108
      raw_specs;
haftmann@24589
   109
    val axiomss = ProofContext.read_propp (ctxt, map (map (rpair []) o snd)
haftmann@24589
   110
          raw_specs)
haftmann@24218
   111
      |> snd
haftmann@24218
   112
      |> (map o map) fst;
haftmann@24589
   113
  in
haftmann@24589
   114
    AxClass.define_class (class, superclasses) []
haftmann@24589
   115
      (name_atts ~~ axiomss) thy
haftmann@24589
   116
  end;
haftmann@24218
   117
haftmann@24218
   118
local
haftmann@24218
   119
haftmann@24218
   120
fun gen_instance mk_prop add_thm after_qed insts thy =
haftmann@24218
   121
  let
haftmann@24218
   122
    fun after_qed' results =
haftmann@24218
   123
      ProofContext.theory ((fold o fold) add_thm results #> after_qed);
haftmann@24218
   124
  in
haftmann@24218
   125
    thy
haftmann@24218
   126
    |> ProofContext.init
haftmann@24589
   127
    |> Proof.theorem_i NONE after_qed' ((map (fn t => [(t, [])])
haftmann@25536
   128
        o mk_prop thy) insts)
haftmann@24218
   129
  end;
haftmann@24218
   130
haftmann@24218
   131
in
haftmann@24218
   132
haftmann@24589
   133
val instance_arity =
haftmann@24218
   134
  gen_instance (Logic.mk_arities oo Sign.cert_arity) AxClass.add_arity;
haftmann@25502
   135
val instance_arity_cmd =
haftmann@25502
   136
  gen_instance (Logic.mk_arities oo Sign.read_arity) AxClass.add_arity I;
haftmann@24589
   137
val classrel =
haftmann@25536
   138
  gen_instance (single oo (Logic.mk_classrel oo AxClass.cert_classrel)) AxClass.add_classrel I;
haftmann@24589
   139
val classrel_cmd =
haftmann@25536
   140
  gen_instance (single oo (Logic.mk_classrel oo AxClass.read_classrel)) AxClass.add_classrel I;
haftmann@24218
   141
haftmann@24218
   142
end; (*local*)
haftmann@24218
   143
haftmann@24218
   144
haftmann@24589
   145
(** class data **)
haftmann@24218
   146
haftmann@24218
   147
datatype class_data = ClassData of {
haftmann@28715
   148
haftmann@28715
   149
  (* static part *)
haftmann@24218
   150
  consts: (string * string) list
haftmann@24836
   151
    (*locale parameter ~> constant name*),
haftmann@25062
   152
  base_sort: sort,
haftmann@28715
   153
  inst: term list
haftmann@25083
   154
    (*canonical interpretation*),
haftmann@28715
   155
  morphism: Morphism.morphism * ((typ Vartab.table * typ list) * (term Vartab.table * term list))
haftmann@28715
   156
    (*morphism cookie of canonical interpretation*),
haftmann@25618
   157
  assm_intro: thm option,
haftmann@25618
   158
  of_class: thm,
haftmann@25618
   159
  axiom: thm option,
haftmann@28715
   160
  
haftmann@28715
   161
  (* dynamic part *)
haftmann@24657
   162
  defs: thm list,
haftmann@25368
   163
  operations: (string * (class * (typ * term))) list
haftmann@28715
   164
haftmann@24657
   165
};
haftmann@24218
   166
haftmann@24657
   167
fun rep_class_data (ClassData d) = d;
haftmann@25618
   168
fun mk_class_data ((consts, base_sort, inst, morphism, assm_intro, of_class, axiom),
haftmann@25368
   169
    (defs, operations)) =
haftmann@25062
   170
  ClassData { consts = consts, base_sort = base_sort, inst = inst,
wenzelm@26463
   171
    morphism = morphism, assm_intro = assm_intro, of_class = of_class, axiom = axiom,
haftmann@25618
   172
    defs = defs, operations = operations };
haftmann@28715
   173
fun map_class_data f (ClassData { consts, base_sort, inst, morphism, assm_intro,
haftmann@28715
   174
    of_class, axiom, defs, operations }) =
haftmann@25618
   175
  mk_class_data (f ((consts, base_sort, inst, morphism, assm_intro, of_class, axiom),
haftmann@25368
   176
    (defs, operations)));
haftmann@25038
   177
fun merge_class_data _ (ClassData { consts = consts,
haftmann@25618
   178
    base_sort = base_sort, inst = inst, morphism = morphism, assm_intro = assm_intro,
haftmann@25618
   179
    of_class = of_class, axiom = axiom, defs = defs1, operations = operations1 },
haftmann@25618
   180
  ClassData { consts = _, base_sort = _, inst = _, morphism = _, assm_intro = _,
haftmann@25618
   181
    of_class = _, axiom = _, defs = defs2, operations = operations2 }) =
haftmann@25618
   182
  mk_class_data ((consts, base_sort, inst, morphism, assm_intro, of_class, axiom),
haftmann@24914
   183
    (Thm.merge_thms (defs1, defs2),
haftmann@25368
   184
      AList.merge (op =) (K true) (operations1, operations2)));
haftmann@24218
   185
haftmann@24218
   186
structure ClassData = TheoryDataFun
haftmann@24218
   187
(
haftmann@25038
   188
  type T = class_data Graph.T
haftmann@25038
   189
  val empty = Graph.empty;
haftmann@24218
   190
  val copy = I;
haftmann@24218
   191
  val extend = I;
haftmann@25038
   192
  fun merge _ = Graph.join merge_class_data;
haftmann@24218
   193
);
haftmann@24218
   194
haftmann@24218
   195
haftmann@24218
   196
(* queries *)
haftmann@24218
   197
haftmann@25038
   198
val lookup_class_data = Option.map rep_class_data oo try o Graph.get_node o ClassData.get;
haftmann@24218
   199
haftmann@24589
   200
fun the_class_data thy class = case lookup_class_data thy class
wenzelm@25020
   201
 of NONE => error ("Undeclared class " ^ quote class)
haftmann@24589
   202
  | SOME data => data;
haftmann@24218
   203
haftmann@25038
   204
val is_class = is_some oo lookup_class_data;
haftmann@25038
   205
haftmann@25038
   206
val ancestry = Graph.all_succs o ClassData.get;
haftmann@24218
   207
haftmann@28715
   208
fun the_inst thy = #inst o the_class_data thy;
haftmann@28715
   209
haftmann@25002
   210
fun these_params thy =
haftmann@24218
   211
  let
haftmann@24218
   212
    fun params class =
haftmann@24218
   213
      let
wenzelm@24930
   214
        val const_typs = (#params o AxClass.get_info thy) class;
haftmann@24657
   215
        val const_names = (#consts o the_class_data thy) class;
haftmann@24218
   216
      in
haftmann@26518
   217
        (map o apsnd)
haftmann@26518
   218
          (fn c => (class, (c, (the o AList.lookup (op =) const_typs) c))) const_names
haftmann@24218
   219
      end;
haftmann@24218
   220
  in maps params o ancestry thy end;
haftmann@24218
   221
haftmann@25618
   222
fun these_assm_intros thy =
haftmann@25618
   223
  Graph.fold (fn (_, (data, _)) => fold (insert Thm.eq_thm)
haftmann@25618
   224
    ((the_list o #assm_intro o rep_class_data) data)) (ClassData.get thy) [];
haftmann@24218
   225
haftmann@28715
   226
fun these_defs thy = maps (these o Option.map #defs o lookup_class_data thy) o ancestry thy;
haftmann@28715
   227
haftmann@24836
   228
fun these_operations thy =
haftmann@24836
   229
  maps (#operations o the_class_data thy) o ancestry thy;
haftmann@24657
   230
haftmann@28715
   231
fun morphism thy class =
haftmann@28715
   232
  let
haftmann@28715
   233
    val { inst, morphism, ... } = the_class_data thy class;
haftmann@28715
   234
  in activate_class_morphism thy class inst morphism end;
haftmann@28715
   235
haftmann@24218
   236
fun print_classes thy =
haftmann@24218
   237
  let
wenzelm@24920
   238
    val ctxt = ProofContext.init thy;
haftmann@24218
   239
    val algebra = Sign.classes_of thy;
haftmann@24218
   240
    val arities =
haftmann@24218
   241
      Symtab.empty
haftmann@24218
   242
      |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
haftmann@24218
   243
           Symtab.map_default (class, []) (insert (op =) tyco)) arities)
haftmann@24218
   244
             ((#arities o Sorts.rep_algebra) algebra);
haftmann@24218
   245
    val the_arities = these o Symtab.lookup arities;
haftmann@24218
   246
    fun mk_arity class tyco =
haftmann@24218
   247
      let
haftmann@24218
   248
        val Ss = Sorts.mg_domain algebra tyco [class];
wenzelm@24920
   249
      in Syntax.pretty_arity ctxt (tyco, Ss, [class]) end;
haftmann@24218
   250
    fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
wenzelm@24920
   251
      ^ setmp show_sorts false (Syntax.string_of_typ ctxt o Type.strip_sorts) ty);
haftmann@24218
   252
    fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
haftmann@25062
   253
      (SOME o Pretty.str) ("class " ^ Sign.extern_class thy class ^ ":"),
haftmann@24218
   254
      (SOME o Pretty.block) [Pretty.str "supersort: ",
wenzelm@24920
   255
        (Syntax.pretty_sort ctxt o Sign.minimize_sort thy o Sign.super_classes thy) class],
haftmann@25062
   256
      if is_class thy class then (SOME o Pretty.str)
haftmann@25062
   257
        ("locale: " ^ Locale.extern thy class) else NONE,
haftmann@25062
   258
      ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks)
haftmann@25062
   259
          (Pretty.str "parameters:" :: ps)) o map mk_param
wenzelm@24930
   260
        o these o Option.map #params o try (AxClass.get_info thy)) class,
haftmann@24218
   261
      (SOME o Pretty.block o Pretty.breaks) [
haftmann@24218
   262
        Pretty.str "instances:",
haftmann@24218
   263
        Pretty.list "" "" (map (mk_arity class) (the_arities class))
haftmann@24218
   264
      ]
haftmann@24218
   265
    ]
haftmann@24218
   266
  in
haftmann@24589
   267
    (Pretty.writeln o Pretty.chunks o separate (Pretty.str "")
haftmann@24589
   268
      o map mk_entry o Sorts.all_classes) algebra
haftmann@24218
   269
  end;
haftmann@24218
   270
haftmann@24218
   271
haftmann@24218
   272
(* updaters *)
haftmann@24218
   273
haftmann@25618
   274
fun add_class_data ((class, superclasses),
haftmann@25711
   275
    (params, base_sort, inst, phi, axiom, assm_intro, of_class)) thy =
haftmann@25002
   276
  let
haftmann@25368
   277
    val operations = map (fn (v_ty as (_, ty), (c, _)) =>
haftmann@25683
   278
      (c, (class, (ty, Free v_ty)))) params;
haftmann@25038
   279
    val add_class = Graph.new_node (class,
haftmann@25683
   280
        mk_class_data (((map o pairself) fst params, base_sort,
haftmann@28715
   281
          inst, phi, assm_intro, of_class, axiom), ([], operations)))
haftmann@25002
   282
      #> fold (curry Graph.add_edge class) superclasses;
haftmann@25618
   283
  in ClassData.map add_class thy end;
haftmann@24218
   284
haftmann@25368
   285
fun register_operation class (c, (t, some_def)) thy =
haftmann@25062
   286
  let
haftmann@25368
   287
    val base_sort = (#base_sort o the_class_data thy) class;
haftmann@26518
   288
    val prep_typ = map_type_tvar
haftmann@26518
   289
      (fn (vi as (v, _), sort) => if Name.aT = v
haftmann@25368
   290
        then TFree (v, base_sort) else TVar (vi, sort));
haftmann@25368
   291
    val t' = map_types prep_typ t;
haftmann@25368
   292
    val ty' = Term.fastype_of t';
haftmann@25062
   293
  in
haftmann@25062
   294
    thy
haftmann@25062
   295
    |> (ClassData.map o Graph.map_node class o map_class_data o apsnd)
haftmann@25368
   296
      (fn (defs, operations) =>
haftmann@25096
   297
        (fold cons (the_list some_def) defs,
haftmann@25368
   298
          (c, (class, (ty', t'))) :: operations))
haftmann@25062
   299
  end;
haftmann@24218
   300
haftmann@24589
   301
haftmann@24589
   302
(** rule calculation, tactics and methods **)
haftmann@24589
   303
haftmann@28715
   304
fun calculate_axiom thy sups base_sort assm_axiom param_map class =
haftmann@28715
   305
  case Locale.intros thy class
haftmann@28715
   306
   of (_, []) => assm_axiom
haftmann@28715
   307
    | (_, [intro]) =>
haftmann@28715
   308
      let
haftmann@28715
   309
        fun instantiate thy sort = Thm.instantiate ([pairself (Thm.ctyp_of thy o TVar o pair (Name.aT, 0))
haftmann@28715
   310
          (base_sort, sort)], map (fn (v, (c, ty)) => pairself (Thm.cterm_of thy)
haftmann@28715
   311
            (Var ((v, 0), map_atyps (fn _ => TVar ((Name.aT, 0), sort)) ty),
haftmann@28715
   312
              Const (c, map_atyps (fn _ => TVar ((Name.aT, 0), sort)) ty))) param_map);
haftmann@28715
   313
        val axiom_premises = map_filter (#axiom o the_class_data thy) sups
haftmann@28715
   314
          @ the_list assm_axiom;
haftmann@28715
   315
      in intro
haftmann@28715
   316
        |> instantiate thy [class]
haftmann@28715
   317
        |> (fn thm => thm OF axiom_premises)
haftmann@28715
   318
        |> Drule.standard'
haftmann@28715
   319
        |> Thm.close_derivation
haftmann@28715
   320
        |> SOME
haftmann@28715
   321
      end;
wenzelm@25024
   322
haftmann@28715
   323
fun calculate_rules thy phi sups base_sort param_map axiom class =
haftmann@25062
   324
  let
haftmann@25711
   325
    fun instantiate thy sort = Thm.instantiate ([pairself (Thm.ctyp_of thy o TVar o pair (Name.aT, 0))
haftmann@25711
   326
      (base_sort, sort)], map (fn (v, (c, ty)) => pairself (Thm.cterm_of thy)
haftmann@25711
   327
        (Var ((v, 0), map_atyps (fn _ => TVar ((Name.aT, 0), sort)) ty),
haftmann@25711
   328
          Const (c, map_atyps (fn _ => TVar ((Name.aT, 0), sort)) ty))) param_map);
haftmann@25711
   329
    val defs = these_defs thy sups;
haftmann@28715
   330
    val assm_intro = Locale.intros thy class
haftmann@28715
   331
      |> fst
haftmann@28715
   332
      |> map (instantiate thy base_sort)
haftmann@28715
   333
      |> map (MetaSimplifier.rewrite_rule defs)
haftmann@28715
   334
      |> map Thm.close_derivation
haftmann@28715
   335
      |> try the_single;
haftmann@25711
   336
    val fixate = Thm.instantiate
haftmann@25711
   337
      (map (pairself (Thm.ctyp_of thy)) [(TVar ((Name.aT, 0), []), TFree (Name.aT, base_sort)),
haftmann@25711
   338
        (TVar ((Name.aT, 0), base_sort), TFree (Name.aT, base_sort))], [])
haftmann@25618
   339
    val of_class_sups = if null sups
haftmann@25711
   340
      then map (fixate o Thm.class_triv thy) base_sort
haftmann@25711
   341
      else map (fixate o #of_class o the_class_data thy) sups;
haftmann@25683
   342
    val locale_dests = map Drule.standard' (Locale.dests thy class);
haftmann@25711
   343
    val num_trivs = case length locale_dests
haftmann@25711
   344
     of 0 => if is_none axiom then 0 else 1
haftmann@25711
   345
      | n => n;
haftmann@25711
   346
    val pred_trivs = if num_trivs = 0 then []
haftmann@25711
   347
      else the axiom
haftmann@25711
   348
        |> Thm.prop_of
haftmann@25711
   349
        |> (map_types o map_atyps o K) (TFree (Name.aT, base_sort))
haftmann@25711
   350
        |> (Thm.assume o Thm.cterm_of thy)
haftmann@25711
   351
        |> replicate num_trivs;
haftmann@28715
   352
    val axclass_intro = (#intro o AxClass.get_info thy) class;
haftmann@28715
   353
    val of_class = (fixate axclass_intro OF of_class_sups OF locale_dests OF pred_trivs)
haftmann@25711
   354
      |> Drule.standard'
wenzelm@26628
   355
      |> Thm.close_derivation;
haftmann@28715
   356
  in (assm_intro, of_class) end;
haftmann@24218
   357
haftmann@27684
   358
fun prove_subclass (sub, sup) some_thm thy =
haftmann@25618
   359
  let
haftmann@25711
   360
    val of_class = (#of_class o the_class_data thy) sup;
haftmann@27684
   361
    val intro = case some_thm
haftmann@27684
   362
     of SOME thm => Drule.standard' (of_class OF [Drule.standard' thm])
haftmann@27684
   363
      | NONE => Thm.instantiate ([pairself (Thm.ctyp_of thy o TVar o pair (Name.aT, 0))
haftmann@27684
   364
          ([], [sub])], []) of_class;
haftmann@27684
   365
    val classrel = (intro OF (the_list o #axiom o the_class_data thy) sub)
haftmann@27684
   366
      |> Thm.close_derivation;
haftmann@25618
   367
  in
haftmann@25618
   368
    thy
haftmann@25618
   369
    |> AxClass.add_classrel classrel
haftmann@27684
   370
    |> prove_interpretation_in (ALLGOALS (ProofContext.fact_tac (the_list some_thm)))
haftmann@25618
   371
         I (sub, Locale.Locale sup)
haftmann@25618
   372
    |> ClassData.map (Graph.add_edge (sub, sup))
haftmann@25618
   373
  end;
haftmann@25618
   374
haftmann@28715
   375
fun note_assm_intro class assm_intro thy =
haftmann@28715
   376
  thy
haftmann@28715
   377
  |> Sign.sticky_prefix (class_prefix class ^ "_" ^ AxClass.axiomsN)
haftmann@28715
   378
  |> PureThy.store_thm (AxClass.introN, assm_intro)
haftmann@28715
   379
  |> snd
haftmann@28715
   380
  |> Sign.restore_naming thy;
haftmann@28715
   381
haftmann@24218
   382
fun intro_classes_tac facts st =
haftmann@24218
   383
  let
haftmann@24218
   384
    val thy = Thm.theory_of_thm st;
haftmann@24218
   385
    val classes = Sign.all_classes thy;
haftmann@24218
   386
    val class_trivs = map (Thm.class_triv thy) classes;
haftmann@25618
   387
    val class_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
haftmann@25618
   388
    val assm_intros = these_assm_intros thy;
haftmann@24218
   389
  in
haftmann@25618
   390
    Method.intros_tac (class_trivs @ class_intros @ assm_intros) facts st
haftmann@24218
   391
  end;
haftmann@24218
   392
haftmann@26470
   393
fun default_intro_tac ctxt [] =
haftmann@26470
   394
      intro_classes_tac [] ORELSE Locale.intro_locales_tac true ctxt []
haftmann@26470
   395
  | default_intro_tac _ _ = no_tac;
haftmann@24218
   396
haftmann@24218
   397
fun default_tac rules ctxt facts =
haftmann@24218
   398
  HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
haftmann@26470
   399
    default_intro_tac ctxt facts;
haftmann@24218
   400
wenzelm@26463
   401
val _ = Context.>> (Context.map_theory
wenzelm@26463
   402
  (Method.add_methods
wenzelm@26463
   403
   [("intro_classes", Method.no_args (Method.METHOD intro_classes_tac),
wenzelm@26463
   404
      "back-chain introduction rules of classes"),
wenzelm@26463
   405
    ("default", Method.thms_ctxt_args (Method.METHOD oo default_tac),
wenzelm@26463
   406
      "apply some intro/elim rule")]));
wenzelm@26463
   407
haftmann@24218
   408
haftmann@24589
   409
(** classes and class target **)
haftmann@24218
   410
haftmann@25002
   411
(* class context syntax *)
haftmann@24748
   412
haftmann@26238
   413
fun synchronize_class_syntax sups base_sort ctxt =
haftmann@24914
   414
  let
wenzelm@25344
   415
    val thy = ProofContext.theory_of ctxt;
haftmann@26596
   416
    val algebra = Sign.classes_of thy;
haftmann@25083
   417
    val operations = these_operations thy sups;
haftmann@26518
   418
    fun subst_class_typ sort = map_type_tfree (K (TVar ((Name.aT, 0), sort)));
haftmann@26518
   419
    val primary_constraints =
haftmann@25368
   420
      (map o apsnd) (subst_class_typ base_sort o fst o snd) operations;
haftmann@26518
   421
    val secondary_constraints =
haftmann@25368
   422
      (map o apsnd) (fn (class, (ty, _)) => subst_class_typ [class] ty) operations;
wenzelm@25318
   423
    fun declare_const (c, _) =
wenzelm@25318
   424
      let val b = Sign.base_name c
wenzelm@25344
   425
      in Sign.intern_const thy b = c ? Variable.declare_const (b, c) end;
haftmann@26518
   426
    fun improve (c, ty) = (case AList.lookup (op =) primary_constraints c
haftmann@26238
   427
     of SOME ty' => (case try (Type.raw_match (ty', ty)) Vartab.empty
haftmann@26238
   428
         of SOME tyenv => (case Vartab.lookup tyenv (Name.aT, 0)
haftmann@26596
   429
             of SOME (_, ty' as TVar (tvar as (vi, sort))) =>
haftmann@26238
   430
                  if TypeInfer.is_param vi
haftmann@26596
   431
                    andalso Sorts.sort_le algebra (base_sort, sort)
haftmann@26596
   432
                      then SOME (ty', TFree (Name.aT, base_sort))
haftmann@26596
   433
                      else NONE
haftmann@26238
   434
              | _ => NONE)
haftmann@26238
   435
          | NONE => NONE)
haftmann@26238
   436
      | NONE => NONE)
haftmann@26238
   437
    fun subst (c, ty) = Option.map snd (AList.lookup (op =) operations c);
haftmann@25368
   438
    val unchecks = map (fn (c, (_, (ty, t))) => (t, Const (c, ty))) operations;
haftmann@25083
   439
  in
haftmann@25083
   440
    ctxt
haftmann@26518
   441
    |> fold declare_const primary_constraints
haftmann@26518
   442
    |> Overloading.map_improvable_syntax (K (((primary_constraints, secondary_constraints),
haftmann@26730
   443
        (((improve, subst), true), unchecks)), false))
haftmann@26518
   444
    |> Overloading.set_primary_constraints
haftmann@25083
   445
  end;
haftmann@25083
   446
haftmann@25083
   447
fun refresh_syntax class ctxt =
haftmann@25002
   448
  let
haftmann@25002
   449
    val thy = ProofContext.theory_of ctxt;
haftmann@25062
   450
    val base_sort = (#base_sort o the_class_data thy) class;
haftmann@26238
   451
  in synchronize_class_syntax [class] base_sort ctxt end;
haftmann@25002
   452
wenzelm@25344
   453
fun init_ctxt sups base_sort ctxt =
haftmann@25083
   454
  ctxt
haftmann@25083
   455
  |> Variable.declare_term
haftmann@25083
   456
      (Logic.mk_type (TFree (Name.aT, base_sort)))
haftmann@26238
   457
  |> synchronize_class_syntax sups base_sort
haftmann@26238
   458
  |> Overloading.add_improvable_syntax;
haftmann@24901
   459
haftmann@25311
   460
fun init class thy =
haftmann@25311
   461
  thy
haftmann@25311
   462
  |> Locale.init class
wenzelm@25344
   463
  |> init_ctxt [class] ((#base_sort o the_class_data thy) class);
haftmann@24914
   464
haftmann@24748
   465
haftmann@27690
   466
(* class target *)
haftmann@27690
   467
haftmann@27690
   468
fun declare class pos ((c, mx), dict) thy =
haftmann@27690
   469
  let
haftmann@27690
   470
    val prfx = class_prefix class;
haftmann@27690
   471
    val thy' = thy |> Sign.add_path prfx;
haftmann@27690
   472
    val phi = morphism thy' class;
haftmann@28715
   473
    val inst = the_inst thy' class;
haftmann@28715
   474
    val params = map (apsnd fst o snd) (these_params thy' [class]);
haftmann@27690
   475
haftmann@27690
   476
    val c' = Sign.full_name thy' c;
haftmann@27690
   477
    val dict' = Morphism.term phi dict;
haftmann@27690
   478
    val dict_def = map_types Logic.unvarifyT dict';
haftmann@27690
   479
    val ty' = Term.fastype_of dict_def;
haftmann@27690
   480
    val ty'' = Type.strip_sorts ty';
haftmann@27690
   481
    val def_eq = Logic.mk_equals (Const (c', ty'), dict_def);
wenzelm@28674
   482
    fun get_axiom thy = ((Thm.varifyT o Thm.axiom thy) c', thy);
haftmann@27690
   483
  in
haftmann@27690
   484
    thy'
wenzelm@28110
   485
    |> Sign.declare_const pos ((Name.binding c, ty''), mx) |> snd
haftmann@27690
   486
    |> Thm.add_def false false (c, def_eq)
haftmann@27690
   487
    |>> Thm.symmetric
haftmann@27690
   488
    ||>> get_axiom
haftmann@28715
   489
    |-> (fn (def, def') => prove_class_interpretation class inst params [] [def]
haftmann@28715
   490
      #> snd
haftmann@28715
   491
        (*assumption: interpretation cookie does not change
haftmann@28715
   492
          by adding equations to interpretation*)
haftmann@27690
   493
      #> register_operation class (c', (dict', SOME (Thm.symmetric def')))
haftmann@27690
   494
      #> PureThy.store_thm (c ^ "_raw", def')
haftmann@27690
   495
      #> snd)
haftmann@27690
   496
    |> Sign.restore_naming thy
haftmann@27690
   497
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@27690
   498
  end;
haftmann@27690
   499
haftmann@27690
   500
fun abbrev class prmode pos ((c, mx), rhs) thy =
haftmann@27690
   501
  let
haftmann@27690
   502
    val prfx = class_prefix class;
haftmann@27690
   503
    val thy' = thy |> Sign.add_path prfx;
haftmann@27690
   504
haftmann@27690
   505
    val unchecks = map (fn (c, (_, (ty, t))) => (t, Const (c, ty)))
haftmann@27690
   506
      (these_operations thy [class]);
haftmann@27690
   507
    val c' = Sign.full_name thy' c;
haftmann@27690
   508
    val rhs' = Pattern.rewrite_term thy unchecks [] rhs;
haftmann@27690
   509
    val rhs'' = map_types Logic.varifyT rhs';
haftmann@27690
   510
    val ty' = Term.fastype_of rhs';
haftmann@27690
   511
  in
haftmann@27690
   512
    thy'
haftmann@27690
   513
    |> Sign.add_abbrev (#1 prmode) pos (c, map_types Type.strip_sorts rhs'') |> snd
haftmann@27690
   514
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@27690
   515
    |> Sign.notation true prmode [(Const (c', ty'), mx)]
haftmann@27690
   516
    |> not (#1 prmode = PrintMode.input) ? register_operation class (c', (rhs', NONE))
haftmann@27690
   517
    |> Sign.restore_naming thy
haftmann@27690
   518
  end;
haftmann@27690
   519
haftmann@27690
   520
haftmann@24589
   521
(* class definition *)
haftmann@24218
   522
haftmann@24218
   523
local
haftmann@24218
   524
haftmann@26247
   525
fun gen_class_spec prep_class process_expr thy raw_supclasses raw_elems =
haftmann@24218
   526
  let
haftmann@24748
   527
    val supclasses = map (prep_class thy) raw_supclasses;
haftmann@24748
   528
    val supsort = Sign.minimize_sort thy supclasses;
haftmann@25618
   529
    val sups = filter (is_class thy) supsort;
haftmann@26995
   530
    val supparam_names = map fst (these_params thy sups);
haftmann@26995
   531
    val _ = if has_duplicates (op =) supparam_names
haftmann@26995
   532
      then error ("Duplicate parameter(s) in superclasses: "
haftmann@26995
   533
        ^ (commas o map quote o duplicates (op =)) supparam_names)
haftmann@26995
   534
      else ();
haftmann@25618
   535
    val base_sort = if null sups then supsort else
haftmann@26167
   536
      foldr1 (Sorts.inter_sort (Sign.classes_of thy))
haftmann@26167
   537
        (map (#base_sort o the_class_data thy) sups);
haftmann@25038
   538
    val suplocales = map Locale.Locale sups;
haftmann@24748
   539
    val supexpr = Locale.Merge suplocales;
haftmann@24748
   540
    val supparams = (map fst o Locale.parameters_of_expr thy) supexpr;
haftmann@26247
   541
    val mergeexpr = Locale.Merge (suplocales);
haftmann@24748
   542
    val constrain = Element.Constrains ((map o apsnd o map_atyps)
haftmann@26167
   543
      (K (TFree (Name.aT, base_sort))) supparams);
haftmann@25683
   544
    fun fork_syn (Element.Fixes xs) =
wenzelm@28083
   545
          fold_map (fn (c, ty, syn) => cons (Name.name_of c, syn) #> pair (c, ty, NoSyn)) xs
haftmann@25683
   546
          #>> Element.Fixes
haftmann@25683
   547
      | fork_syn x = pair x;
haftmann@25683
   548
    fun fork_syntax elems =
haftmann@25683
   549
      let
haftmann@25683
   550
        val (elems', global_syntax) = fold_map fork_syn elems [];
haftmann@26247
   551
      in (constrain :: elems', global_syntax) end;
haftmann@25683
   552
    val (elems, global_syntax) =
haftmann@25683
   553
      ProofContext.init thy
haftmann@25683
   554
      |> Locale.cert_expr supexpr [constrain]
haftmann@25683
   555
      |> snd
haftmann@25683
   556
      |> init_ctxt sups base_sort
haftmann@25683
   557
      |> process_expr Locale.empty raw_elems
haftmann@25683
   558
      |> fst
haftmann@25683
   559
      |> fork_syntax
haftmann@25683
   560
  in (((sups, supparams), (supsort, base_sort, mergeexpr)), (elems, global_syntax)) end;
haftmann@24748
   561
haftmann@26247
   562
val read_class_spec = gen_class_spec Sign.intern_class Locale.read_expr;
haftmann@26247
   563
val check_class_spec = gen_class_spec (K I) Locale.cert_expr;
haftmann@24748
   564
haftmann@28715
   565
fun add_consts bname class base_sort sups supparams global_syntax thy =
wenzelm@24968
   566
  let
haftmann@25683
   567
    val supconsts = map fst supparams
haftmann@26518
   568
      |> AList.make (snd o the o AList.lookup (op =) (these_params thy sups))
haftmann@25683
   569
      |> (map o apsnd o apsnd o map_atyps o K o TFree) (Name.aT, [class]);
haftmann@25683
   570
    val all_params = map fst (Locale.parameters_of thy class);
haftmann@28715
   571
    val raw_params = (snd o chop (length supparams)) all_params;
haftmann@25683
   572
    fun add_const (v, raw_ty) thy =
haftmann@25683
   573
      let
haftmann@25683
   574
        val c = Sign.full_name thy v;
haftmann@25683
   575
        val ty = map_atyps (K (TFree (Name.aT, base_sort))) raw_ty;
haftmann@25683
   576
        val ty0 = Type.strip_sorts ty;
haftmann@25683
   577
        val ty' = map_atyps (K (TFree (Name.aT, [class]))) ty0;
haftmann@25683
   578
        val syn = (the_default NoSyn o AList.lookup (op =) global_syntax) v;
haftmann@25683
   579
      in
haftmann@25683
   580
        thy
wenzelm@28110
   581
        |> Sign.declare_const [] ((Name.binding v, ty0), syn)
haftmann@25683
   582
        |> snd
haftmann@25683
   583
        |> pair ((v, ty), (c, ty'))
haftmann@25683
   584
      end;
haftmann@28715
   585
  in
haftmann@28715
   586
    thy
haftmann@28715
   587
    |> Sign.add_path (Logic.const_of_class bname)
haftmann@28715
   588
    |> fold_map add_const raw_params
haftmann@28715
   589
    ||> Sign.restore_naming thy
haftmann@28715
   590
    |-> (fn params => pair (supconsts @ (map o apfst) fst params, params))
haftmann@28715
   591
  end;
haftmann@28715
   592
haftmann@28715
   593
fun adjungate_axclass bname class base_sort sups supsort supparams global_syntax thy =
haftmann@28715
   594
  let
haftmann@25683
   595
    fun globalize param_map = map_aterms
haftmann@25683
   596
      (fn Free (v, ty) => Const ((fst o the o AList.lookup (op =) param_map) v, ty)
haftmann@25683
   597
        | t => t);
haftmann@25683
   598
    val raw_pred = Locale.intros thy class
haftmann@25683
   599
      |> fst
haftmann@25683
   600
      |> map (Logic.unvarify o Logic.strip_imp_concl o Thm.prop_of);
haftmann@25683
   601
    fun get_axiom thy = case (#axioms o AxClass.get_info thy) class
haftmann@25683
   602
     of [] => NONE
haftmann@25683
   603
      | [thm] => SOME thm;
wenzelm@24968
   604
  in
wenzelm@24968
   605
    thy
haftmann@28715
   606
    |> add_consts bname class base_sort sups supparams global_syntax
haftmann@25683
   607
    |-> (fn (param_map, params) => AxClass.define_class (bname, supsort)
haftmann@26518
   608
          (map (fst o snd) params)
wenzelm@28083
   609
          [((Name.binding (bname ^ "_" ^ AxClass.axiomsN), []), map (globalize param_map) raw_pred)]
haftmann@25683
   610
    #> snd
haftmann@25683
   611
    #> `get_axiom
haftmann@25683
   612
    #-> (fn assm_axiom => fold (Sign.add_const_constraint o apsnd SOME o snd) params
haftmann@28715
   613
    #> pair (map (Const o snd) param_map, param_map, params, assm_axiom)))
wenzelm@24968
   614
  end;
wenzelm@24968
   615
haftmann@26518
   616
fun gen_class prep_spec bname raw_supclasses raw_elems thy =
haftmann@24748
   617
  let
haftmann@25038
   618
    val class = Sign.full_name thy bname;
haftmann@25683
   619
    val (((sups, supparams), (supsort, base_sort, mergeexpr)), (elems, global_syntax)) =
haftmann@26247
   620
      prep_spec thy raw_supclasses raw_elems;
haftmann@28715
   621
    val supconsts = map (apsnd fst o snd) (these_params thy sups);
haftmann@24218
   622
  in
haftmann@24218
   623
    thy
haftmann@27684
   624
    |> Locale.add_locale_i "" bname mergeexpr elems
haftmann@25038
   625
    |> snd
haftmann@25311
   626
    |> ProofContext.theory_of
haftmann@26518
   627
    |> adjungate_axclass bname class base_sort sups supsort supparams global_syntax
haftmann@28715
   628
    |-> (fn (inst, param_map, params, assm_axiom) =>
haftmann@28715
   629
        `(fn thy => calculate_axiom thy sups base_sort assm_axiom param_map class)
haftmann@28715
   630
    #-> (fn axiom =>
haftmann@28715
   631
        prove_class_interpretation class inst
haftmann@28715
   632
          (supconsts @ map (pair class o fst o snd) params) (the_list axiom) []
haftmann@28715
   633
    #-> (fn morphism =>
haftmann@28715
   634
        `(fn thy => activate_class_morphism thy class inst morphism)
haftmann@28715
   635
    #-> (fn phi =>
haftmann@28715
   636
        `(fn thy => calculate_rules thy phi sups base_sort param_map axiom class)
haftmann@28715
   637
    #-> (fn (assm_intro, of_class) =>
haftmann@28715
   638
        add_class_data ((class, sups), (params, base_sort, inst,
haftmann@28715
   639
          morphism, axiom, assm_intro, of_class))
haftmann@28715
   640
    #> fold (note_assm_intro class) (the_list assm_intro))))))
haftmann@25268
   641
    |> init class
haftmann@25038
   642
    |> pair class
haftmann@24218
   643
  end;
haftmann@24218
   644
haftmann@24218
   645
in
haftmann@24218
   646
haftmann@26518
   647
val class_cmd = gen_class read_class_spec;
haftmann@26518
   648
val class = gen_class check_class_spec;
haftmann@24218
   649
haftmann@24218
   650
end; (*local*)
haftmann@24218
   651
haftmann@24218
   652
haftmann@25462
   653
haftmann@25462
   654
(** instantiation target **)
haftmann@25462
   655
haftmann@25462
   656
(* bookkeeping *)
haftmann@25462
   657
haftmann@25462
   658
datatype instantiation = Instantiation of {
haftmann@25864
   659
  arities: string list * (string * sort) list * sort,
haftmann@25462
   660
  params: ((string * string) * (string * typ)) list
haftmann@25603
   661
    (*(instantiation parameter, type constructor), (local instantiation parameter, typ)*)
haftmann@25462
   662
}
haftmann@25462
   663
haftmann@25462
   664
structure Instantiation = ProofDataFun
haftmann@25462
   665
(
haftmann@25462
   666
  type T = instantiation
haftmann@25536
   667
  fun init _ = Instantiation { arities = ([], [], []), params = [] };
haftmann@25462
   668
);
haftmann@25462
   669
haftmann@25485
   670
fun mk_instantiation (arities, params) =
haftmann@25485
   671
  Instantiation { arities = arities, params = params };
haftmann@25514
   672
fun get_instantiation lthy = case Instantiation.get (LocalTheory.target_of lthy)
haftmann@25485
   673
 of Instantiation data => data;
haftmann@25514
   674
fun map_instantiation f = (LocalTheory.target o Instantiation.map)
haftmann@25514
   675
  (fn Instantiation { arities, params } => mk_instantiation (f (arities, params)));
haftmann@25462
   676
haftmann@25514
   677
fun the_instantiation lthy = case get_instantiation lthy
haftmann@25536
   678
 of { arities = ([], [], []), ... } => error "No instantiation target"
haftmann@25485
   679
  | data => data;
haftmann@25462
   680
haftmann@25485
   681
val instantiation_params = #params o get_instantiation;
haftmann@25462
   682
haftmann@25514
   683
fun instantiation_param lthy v = instantiation_params lthy
haftmann@25462
   684
  |> find_first (fn (_, (v', _)) => v = v')
haftmann@25462
   685
  |> Option.map (fst o fst);
haftmann@25462
   686
haftmann@25462
   687
haftmann@25462
   688
(* syntax *)
haftmann@25462
   689
haftmann@26238
   690
fun synchronize_inst_syntax ctxt =
haftmann@25462
   691
  let
haftmann@26259
   692
    val Instantiation { arities = (_, _, sort), params = params } = Instantiation.get ctxt;
haftmann@26238
   693
    val thy = ProofContext.theory_of ctxt;
haftmann@26238
   694
    fun subst (c, ty) = case AxClass.inst_tyco_of thy (c, ty)
haftmann@26238
   695
         of SOME tyco => (case AList.lookup (op =) params (c, tyco)
haftmann@26238
   696
             of SOME (v_ty as (_, ty)) => SOME (ty, Free v_ty)
haftmann@26238
   697
              | NONE => NONE)
haftmann@26238
   698
          | NONE => NONE;
haftmann@26238
   699
    val unchecks =
haftmann@26238
   700
      map (fn ((c, _), v_ty as (_, ty)) => (Free v_ty, Const (c, ty))) params;
haftmann@26238
   701
  in
haftmann@26238
   702
    ctxt
haftmann@26259
   703
    |> Overloading.map_improvable_syntax
haftmann@26730
   704
         (fn (((primary_constraints, _), (((improve, _), _), _)), _) =>
haftmann@26730
   705
            (((primary_constraints, []), (((improve, subst), false), unchecks)), false))
haftmann@26238
   706
  end;
haftmann@25462
   707
haftmann@25462
   708
haftmann@25462
   709
(* target *)
haftmann@25462
   710
haftmann@25485
   711
val sanatize_name = (*FIXME*)
haftmann@25485
   712
  let
haftmann@25574
   713
    fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s
haftmann@25574
   714
      orelse s = "'" orelse s = "_";
haftmann@25485
   715
    val is_junk = not o is_valid andf Symbol.is_regular;
haftmann@25485
   716
    val junk = Scan.many is_junk;
haftmann@25485
   717
    val scan_valids = Symbol.scanner "Malformed input"
haftmann@25485
   718
      ((junk |--
haftmann@25485
   719
        (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
haftmann@25485
   720
        --| junk))
wenzelm@25999
   721
      ::: Scan.repeat ((Scan.many1 is_valid >> implode) --| junk));
haftmann@25485
   722
  in
haftmann@25485
   723
    explode #> scan_valids #> implode
haftmann@25485
   724
  end;
haftmann@25485
   725
haftmann@26259
   726
fun type_name "*" = "prod"
haftmann@26259
   727
  | type_name "+" = "sum"
haftmann@26259
   728
  | type_name s = sanatize_name (NameSpace.base s); (*FIXME*)
haftmann@26259
   729
haftmann@26518
   730
fun resort_terms pp algebra consts constraints ts =
haftmann@26518
   731
  let
haftmann@26518
   732
    fun matchings (Const (c_ty as (c, _))) = (case constraints c
haftmann@26518
   733
         of NONE => I
haftmann@26518
   734
          | SOME sorts => fold2 (curry (Sorts.meet_sort algebra))
haftmann@26518
   735
              (Consts.typargs consts c_ty) sorts)
haftmann@26518
   736
      | matchings _ = I
haftmann@26518
   737
    val tvartab = (fold o fold_aterms) matchings ts Vartab.empty
wenzelm@26642
   738
      handle Sorts.CLASS_ERROR e => error (Sorts.class_error pp e);
haftmann@27089
   739
    val inst = map_type_tvar
haftmann@27089
   740
      (fn (vi, sort) => TVar (vi, the_default sort (Vartab.lookup tvartab vi)));
haftmann@26518
   741
  in if Vartab.is_empty tvartab then NONE else SOME ((map o map_types) inst ts) end;
haftmann@26518
   742
haftmann@25864
   743
fun init_instantiation (tycos, vs, sort) thy =
haftmann@25462
   744
  let
haftmann@25536
   745
    val _ = if null tycos then error "At least one arity must be given" else ();
haftmann@26518
   746
    val params = these_params thy sort;
haftmann@26518
   747
    fun get_param tyco (param, (_, (c, ty))) = if can (AxClass.param_of_inst thy) (c, tyco)
haftmann@25603
   748
      then NONE else SOME ((c, tyco),
haftmann@25864
   749
        (param ^ "_" ^ type_name tyco, map_atyps (K (Type (tyco, map TFree vs))) ty));
haftmann@26518
   750
    val inst_params = map_product get_param tycos params |> map_filter I;
haftmann@26518
   751
    val primary_constraints = map (apsnd
haftmann@26518
   752
      (map_atyps (K (TVar ((Name.aT, 0), [])))) o snd o snd) params;
wenzelm@26939
   753
    val pp = Syntax.pp_global thy;
haftmann@26518
   754
    val algebra = Sign.classes_of thy
haftmann@26518
   755
      |> fold (fn tyco => Sorts.add_arities pp
haftmann@26518
   756
            (tyco, map (fn class => (class, map snd vs)) sort)) tycos;
haftmann@26518
   757
    val consts = Sign.consts_of thy;
haftmann@26518
   758
    val improve_constraints = AList.lookup (op =)
haftmann@26518
   759
      (map (fn (_, (class, (c, _))) => (c, [[class]])) params);
haftmann@26518
   760
    fun resort_check ts ctxt = case resort_terms pp algebra consts improve_constraints ts
haftmann@26518
   761
     of NONE => NONE
haftmann@26518
   762
      | SOME ts' => SOME (ts', ctxt);
haftmann@26518
   763
    fun improve (c, ty) = case AxClass.inst_tyco_of thy (c, ty)
haftmann@26329
   764
     of SOME tyco => (case AList.lookup (op =) inst_params (c, tyco)
haftmann@26518
   765
         of SOME (_, ty') => if Type.raw_instance (ty', ty) then SOME (ty, ty') else NONE
haftmann@26259
   766
          | NONE => NONE)
haftmann@26259
   767
      | NONE => NONE;
haftmann@25485
   768
  in
haftmann@25485
   769
    thy
haftmann@25485
   770
    |> ProofContext.init
haftmann@26329
   771
    |> Instantiation.put (mk_instantiation ((tycos, vs, sort), inst_params))
wenzelm@27281
   772
    |> fold (Variable.declare_typ o TFree) vs
haftmann@26329
   773
    |> fold (Variable.declare_names o Free o snd) inst_params
haftmann@26259
   774
    |> (Overloading.map_improvable_syntax o apfst)
haftmann@26329
   775
         (fn ((_, _), ((_, subst), unchecks)) =>
haftmann@26730
   776
            ((primary_constraints, []), (((improve, K NONE), false), [])))
haftmann@26259
   777
    |> Overloading.add_improvable_syntax
haftmann@26518
   778
    |> Context.proof_map (Syntax.add_term_check 0 "resorting" resort_check)
haftmann@26238
   779
    |> synchronize_inst_syntax
haftmann@25485
   780
  end;
haftmann@25485
   781
haftmann@26238
   782
fun confirm_declaration c = (map_instantiation o apsnd)
haftmann@26238
   783
  (filter_out (fn (_, (c', _)) => c' = c))
haftmann@26238
   784
  #> LocalTheory.target synchronize_inst_syntax
haftmann@26238
   785
haftmann@25485
   786
fun gen_instantiation_instance do_proof after_qed lthy =
haftmann@25485
   787
  let
haftmann@25864
   788
    val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
haftmann@25864
   789
    val arities_proof = maps (fn tyco => Logic.mk_arities (tyco, map snd vs, sort)) tycos;
haftmann@25462
   790
    fun after_qed' results =
haftmann@25462
   791
      LocalTheory.theory (fold (AxClass.add_arity o Thm.varifyT) results)
haftmann@25462
   792
      #> after_qed;
haftmann@25462
   793
  in
haftmann@25462
   794
    lthy
haftmann@25462
   795
    |> do_proof after_qed' arities_proof
haftmann@25462
   796
  end;
haftmann@25462
   797
haftmann@25485
   798
val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
haftmann@25462
   799
  Proof.theorem_i NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
haftmann@25462
   800
haftmann@25485
   801
fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
haftmann@25502
   802
  fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
haftmann@25502
   803
    (fn {context, ...} => tac context)) ts) lthy) I;
haftmann@25462
   804
haftmann@28666
   805
fun prove_instantiation_exit tac = prove_instantiation_instance tac
haftmann@28666
   806
  #> LocalTheory.exit_global;
haftmann@28666
   807
haftmann@28666
   808
fun prove_instantiation_exit_result f tac x lthy =
haftmann@28666
   809
  let
haftmann@28666
   810
    val phi = ProofContext.export_morphism lthy
haftmann@28666
   811
      (ProofContext.init (ProofContext.theory_of lthy));
haftmann@28666
   812
    val y = f phi x;
haftmann@28666
   813
  in
haftmann@28666
   814
    lthy
haftmann@28666
   815
    |> prove_instantiation_exit (fn ctxt => tac ctxt y)
haftmann@28666
   816
    |> pair y
haftmann@28666
   817
  end;
haftmann@28666
   818
haftmann@25462
   819
fun conclude_instantiation lthy =
haftmann@25462
   820
  let
haftmann@25485
   821
    val { arities, params } = the_instantiation lthy;
haftmann@25864
   822
    val (tycos, vs, sort) = arities;
haftmann@25462
   823
    val thy = ProofContext.theory_of lthy;
haftmann@25597
   824
    val _ = map (fn tyco => if Sign.of_sort thy
haftmann@25864
   825
        (Type (tyco, map TFree vs), sort)
haftmann@25462
   826
      then () else error ("Missing instance proof for type " ^ quote (Sign.extern_type thy tyco)))
haftmann@25597
   827
        tycos;
haftmann@25597
   828
  in lthy end;
haftmann@25462
   829
haftmann@25603
   830
fun pretty_instantiation lthy =
haftmann@25603
   831
  let
haftmann@25603
   832
    val { arities, params } = the_instantiation lthy;
haftmann@25864
   833
    val (tycos, vs, sort) = arities;
haftmann@25603
   834
    val thy = ProofContext.theory_of lthy;
haftmann@25864
   835
    fun pr_arity tyco = Syntax.pretty_arity lthy (tyco, map snd vs, sort);
haftmann@25603
   836
    fun pr_param ((c, _), (v, ty)) =
haftmann@25864
   837
      (Pretty.block o Pretty.breaks) [Pretty.str v, Pretty.str "==",
wenzelm@26939
   838
        (Pretty.str o Sign.extern_const thy) c, Pretty.str "::", Syntax.pretty_typ_global thy ty];
haftmann@25603
   839
  in
haftmann@25603
   840
    (Pretty.block o Pretty.fbreaks)
haftmann@25603
   841
      (Pretty.str "instantiation" :: map pr_arity tycos @ map pr_param params)
haftmann@25603
   842
  end;
haftmann@25603
   843
haftmann@24218
   844
end;
haftmann@25683
   845