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