src/Pure/Isar/class_target.ML
author haftmann
Fri Jan 16 14:58:11 2009 +0100 (2009-01-16)
changeset 29509 1ff0f3f08a7b
parent 29439 83601bdadae8
child 29526 0b32c8b84d3e
permissions -rw-r--r--
migrated class package to new locale implementation
haftmann@29358
     1
(*  Title:      Pure/Isar/class_target.ML
haftmann@24218
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@24218
     3
haftmann@29358
     4
Type classes derived from primitive axclasses and locales - mechanisms.
haftmann@24218
     5
*)
haftmann@24218
     6
haftmann@29358
     7
signature CLASS_TARGET =
haftmann@24218
     8
sig
haftmann@25462
     9
  (*classes*)
haftmann@29358
    10
  val register: class -> class list -> ((string * typ) * (string * typ)) list
haftmann@29439
    11
    -> sort -> term list -> morphism
haftmann@29358
    12
    -> thm option -> thm option -> thm -> theory -> theory
haftmann@29509
    13
  val register_subclass: class * class -> thm option
haftmann@29509
    14
    -> theory -> theory
haftmann@25485
    15
haftmann@29358
    16
  val begin: class list -> sort -> Proof.context -> Proof.context
haftmann@25311
    17
  val init: class -> theory -> Proof.context
wenzelm@28017
    18
  val declare: class -> Properties.T
haftmann@27690
    19
    -> (string * mixfix) * term -> theory -> theory
wenzelm@28017
    20
  val abbrev: class -> Syntax.mode -> Properties.T
wenzelm@25104
    21
    -> (string * mixfix) * term -> theory -> theory
haftmann@25083
    22
  val refresh_syntax: class -> Proof.context -> Proof.context
haftmann@25485
    23
haftmann@24589
    24
  val intro_classes_tac: thm list -> tactic
haftmann@26470
    25
  val default_intro_tac: Proof.context -> thm list -> tactic
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@29358
    30
  val these_defs: theory -> sort -> thm list
haftmann@29509
    31
  val eq_morph: theory -> thm list -> morphism
haftmann@29358
    32
  val base_sort: theory -> class -> sort
haftmann@29358
    33
  val rules: theory -> class -> thm option * thm
haftmann@24589
    34
  val print_classes: theory -> unit
haftmann@24423
    35
haftmann@25462
    36
  (*instances*)
haftmann@26247
    37
  val init_instantiation: string list * (string * sort) list * sort
haftmann@26247
    38
    -> theory -> local_theory
haftmann@26247
    39
  val instantiation_instance: (local_theory -> local_theory)
haftmann@26247
    40
    -> local_theory -> Proof.state
haftmann@26247
    41
  val prove_instantiation_instance: (Proof.context -> tactic)
haftmann@26247
    42
    -> local_theory -> local_theory
haftmann@28666
    43
  val prove_instantiation_exit: (Proof.context -> tactic)
haftmann@28666
    44
    -> local_theory -> theory
haftmann@28666
    45
  val prove_instantiation_exit_result: (morphism -> 'a -> 'b)
haftmann@28666
    46
    -> (Proof.context -> 'b -> tactic) -> 'a -> local_theory -> 'b * theory
haftmann@25485
    47
  val conclude_instantiation: local_theory -> local_theory
haftmann@25603
    48
  val instantiation_param: local_theory -> string -> string option
haftmann@25485
    49
  val confirm_declaration: string -> local_theory -> local_theory
haftmann@25603
    50
  val pretty_instantiation: local_theory -> Pretty.T
haftmann@26259
    51
  val type_name: string -> string
haftmann@25485
    52
haftmann@25462
    53
  (*old axclass layer*)
haftmann@25462
    54
  val axclass_cmd: bstring * xstring list
wenzelm@28084
    55
    -> (Attrib.binding * string list) list
haftmann@25462
    56
    -> theory -> class * theory
haftmann@25462
    57
  val classrel_cmd: xstring * xstring -> theory -> Proof.state
haftmann@25462
    58
haftmann@25462
    59
  (*old instance layer*)
haftmann@25536
    60
  val instance_arity: (theory -> theory) -> arity -> theory -> Proof.state
haftmann@25536
    61
  val instance_arity_cmd: bstring * xstring list * xstring -> theory -> Proof.state
haftmann@24218
    62
end;
haftmann@24218
    63
haftmann@29358
    64
structure Class_Target : CLASS_TARGET =
haftmann@24218
    65
struct
haftmann@24218
    66
haftmann@25485
    67
(** primitive axclass and instance commands **)
haftmann@24589
    68
haftmann@24218
    69
fun axclass_cmd (class, raw_superclasses) raw_specs thy =
haftmann@24218
    70
  let
haftmann@24218
    71
    val ctxt = ProofContext.init thy;
haftmann@24218
    72
    val superclasses = map (Sign.read_class thy) raw_superclasses;
haftmann@24589
    73
    val name_atts = map ((apsnd o map) (Attrib.attribute thy) o fst)
haftmann@24589
    74
      raw_specs;
haftmann@24589
    75
    val axiomss = ProofContext.read_propp (ctxt, map (map (rpair []) o snd)
haftmann@24589
    76
          raw_specs)
haftmann@24218
    77
      |> snd
haftmann@24218
    78
      |> (map o map) fst;
haftmann@24589
    79
  in
haftmann@24589
    80
    AxClass.define_class (class, superclasses) []
haftmann@24589
    81
      (name_atts ~~ axiomss) thy
haftmann@24589
    82
  end;
haftmann@24218
    83
haftmann@24218
    84
local
haftmann@24218
    85
haftmann@24218
    86
fun gen_instance mk_prop add_thm after_qed insts thy =
haftmann@24218
    87
  let
haftmann@24218
    88
    fun after_qed' results =
haftmann@24218
    89
      ProofContext.theory ((fold o fold) add_thm results #> after_qed);
haftmann@24218
    90
  in
haftmann@24218
    91
    thy
haftmann@24218
    92
    |> ProofContext.init
haftmann@24589
    93
    |> Proof.theorem_i NONE after_qed' ((map (fn t => [(t, [])])
haftmann@25536
    94
        o mk_prop thy) insts)
haftmann@24218
    95
  end;
haftmann@24218
    96
haftmann@24218
    97
in
haftmann@24218
    98
haftmann@24589
    99
val instance_arity =
haftmann@24218
   100
  gen_instance (Logic.mk_arities oo Sign.cert_arity) AxClass.add_arity;
haftmann@25502
   101
val instance_arity_cmd =
haftmann@25502
   102
  gen_instance (Logic.mk_arities oo Sign.read_arity) AxClass.add_arity I;
haftmann@24589
   103
val classrel =
haftmann@25536
   104
  gen_instance (single oo (Logic.mk_classrel oo AxClass.cert_classrel)) AxClass.add_classrel I;
haftmann@24589
   105
val classrel_cmd =
haftmann@25536
   106
  gen_instance (single oo (Logic.mk_classrel oo AxClass.read_classrel)) AxClass.add_classrel I;
haftmann@24218
   107
haftmann@24218
   108
end; (*local*)
haftmann@24218
   109
haftmann@24218
   110
haftmann@24589
   111
(** class data **)
haftmann@24218
   112
haftmann@24218
   113
datatype class_data = ClassData of {
haftmann@28715
   114
haftmann@28715
   115
  (* static part *)
haftmann@24218
   116
  consts: (string * string) list
haftmann@24836
   117
    (*locale parameter ~> constant name*),
haftmann@25062
   118
  base_sort: sort,
haftmann@28715
   119
  inst: term list
haftmann@25083
   120
    (*canonical interpretation*),
haftmann@29439
   121
  base_morph: Morphism.morphism
haftmann@29439
   122
    (*static part of canonical morphism*),
haftmann@25618
   123
  assm_intro: thm option,
haftmann@25618
   124
  of_class: thm,
haftmann@25618
   125
  axiom: thm option,
haftmann@28715
   126
  
haftmann@28715
   127
  (* dynamic part *)
haftmann@24657
   128
  defs: thm list,
haftmann@25368
   129
  operations: (string * (class * (typ * term))) list
haftmann@28715
   130
haftmann@24657
   131
};
haftmann@24218
   132
haftmann@24657
   133
fun rep_class_data (ClassData d) = d;
haftmann@29439
   134
fun mk_class_data ((consts, base_sort, inst, base_morph, assm_intro, of_class, axiom),
haftmann@25368
   135
    (defs, operations)) =
haftmann@25062
   136
  ClassData { consts = consts, base_sort = base_sort, inst = inst,
haftmann@29439
   137
    base_morph = base_morph, assm_intro = assm_intro, of_class = of_class, axiom = axiom,
haftmann@25618
   138
    defs = defs, operations = operations };
haftmann@29439
   139
fun map_class_data f (ClassData { consts, base_sort, inst, base_morph, assm_intro,
haftmann@28715
   140
    of_class, axiom, defs, operations }) =
haftmann@29439
   141
  mk_class_data (f ((consts, base_sort, inst, base_morph, assm_intro, of_class, axiom),
haftmann@25368
   142
    (defs, operations)));
haftmann@25038
   143
fun merge_class_data _ (ClassData { consts = consts,
haftmann@29439
   144
    base_sort = base_sort, inst = inst, base_morph = base_morph, assm_intro = assm_intro,
haftmann@25618
   145
    of_class = of_class, axiom = axiom, defs = defs1, operations = operations1 },
haftmann@29439
   146
  ClassData { consts = _, base_sort = _, inst = _, base_morph = _, assm_intro = _,
haftmann@25618
   147
    of_class = _, axiom = _, defs = defs2, operations = operations2 }) =
haftmann@29439
   148
  mk_class_data ((consts, base_sort, inst, base_morph, assm_intro, of_class, axiom),
haftmann@24914
   149
    (Thm.merge_thms (defs1, defs2),
haftmann@25368
   150
      AList.merge (op =) (K true) (operations1, operations2)));
haftmann@24218
   151
haftmann@24218
   152
structure ClassData = TheoryDataFun
haftmann@24218
   153
(
haftmann@25038
   154
  type T = class_data Graph.T
haftmann@25038
   155
  val empty = Graph.empty;
haftmann@24218
   156
  val copy = I;
haftmann@24218
   157
  val extend = I;
haftmann@25038
   158
  fun merge _ = Graph.join merge_class_data;
haftmann@24218
   159
);
haftmann@24218
   160
haftmann@24218
   161
haftmann@24218
   162
(* queries *)
haftmann@24218
   163
haftmann@25038
   164
val lookup_class_data = Option.map rep_class_data oo try o Graph.get_node o ClassData.get;
haftmann@24218
   165
haftmann@24589
   166
fun the_class_data thy class = case lookup_class_data thy class
wenzelm@25020
   167
 of NONE => error ("Undeclared class " ^ quote class)
haftmann@24589
   168
  | SOME data => data;
haftmann@24218
   169
haftmann@25038
   170
val is_class = is_some oo lookup_class_data;
haftmann@25038
   171
haftmann@25038
   172
val ancestry = Graph.all_succs o ClassData.get;
haftmann@24218
   173
haftmann@29509
   174
val heritage = Graph.all_preds o ClassData.get;
haftmann@29509
   175
haftmann@28715
   176
fun the_inst thy = #inst o the_class_data thy;
haftmann@28715
   177
haftmann@25002
   178
fun these_params thy =
haftmann@24218
   179
  let
haftmann@24218
   180
    fun params class =
haftmann@24218
   181
      let
wenzelm@24930
   182
        val const_typs = (#params o AxClass.get_info thy) class;
haftmann@24657
   183
        val const_names = (#consts o the_class_data thy) class;
haftmann@24218
   184
      in
haftmann@26518
   185
        (map o apsnd)
haftmann@26518
   186
          (fn c => (class, (c, (the o AList.lookup (op =) const_typs) c))) const_names
haftmann@24218
   187
      end;
haftmann@24218
   188
  in maps params o ancestry thy end;
haftmann@24218
   189
haftmann@25618
   190
fun these_assm_intros thy =
haftmann@25618
   191
  Graph.fold (fn (_, (data, _)) => fold (insert Thm.eq_thm)
haftmann@25618
   192
    ((the_list o #assm_intro o rep_class_data) data)) (ClassData.get thy) [];
haftmann@24218
   193
haftmann@28715
   194
fun these_defs thy = maps (these o Option.map #defs o lookup_class_data thy) o ancestry thy;
haftmann@28715
   195
haftmann@24836
   196
fun these_operations thy =
haftmann@24836
   197
  maps (#operations o the_class_data thy) o ancestry thy;
haftmann@24657
   198
haftmann@29358
   199
val base_sort = #base_sort oo the_class_data;
haftmann@29358
   200
haftmann@29358
   201
fun rules thy class = let
haftmann@29358
   202
    val { axiom, of_class, ... } = the_class_data thy class
haftmann@29358
   203
  in (axiom, of_class) end;
haftmann@29358
   204
haftmann@29439
   205
val class_prefix = Logic.const_of_class o Sign.base_name;
haftmann@29439
   206
haftmann@29439
   207
fun class_binding_morph class =
haftmann@29439
   208
  Binding.map_prefix (K (Binding.add_prefix false (class_prefix class)));
haftmann@29439
   209
haftmann@29509
   210
fun eq_morph thy thms = (*FIXME how general is this?*)
haftmann@29509
   211
  Morphism.term_morphism (MetaSimplifier.rewrite_term thy thms [])
haftmann@29509
   212
  $> Morphism.thm_morphism (MetaSimplifier.rewrite_rule thms);
haftmann@29509
   213
haftmann@28715
   214
fun morphism thy class =
haftmann@28715
   215
  let
haftmann@29439
   216
    val { base_morph, defs, ... } = the_class_data thy class;
haftmann@29509
   217
  in base_morph $> eq_morph thy defs end;
haftmann@28715
   218
haftmann@24218
   219
fun print_classes thy =
haftmann@24218
   220
  let
wenzelm@24920
   221
    val ctxt = ProofContext.init thy;
haftmann@24218
   222
    val algebra = Sign.classes_of thy;
haftmann@24218
   223
    val arities =
haftmann@24218
   224
      Symtab.empty
haftmann@24218
   225
      |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
haftmann@24218
   226
           Symtab.map_default (class, []) (insert (op =) tyco)) arities)
haftmann@24218
   227
             ((#arities o Sorts.rep_algebra) algebra);
haftmann@24218
   228
    val the_arities = these o Symtab.lookup arities;
haftmann@24218
   229
    fun mk_arity class tyco =
haftmann@24218
   230
      let
haftmann@24218
   231
        val Ss = Sorts.mg_domain algebra tyco [class];
wenzelm@24920
   232
      in Syntax.pretty_arity ctxt (tyco, Ss, [class]) end;
haftmann@24218
   233
    fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
wenzelm@24920
   234
      ^ setmp show_sorts false (Syntax.string_of_typ ctxt o Type.strip_sorts) ty);
haftmann@24218
   235
    fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
haftmann@25062
   236
      (SOME o Pretty.str) ("class " ^ Sign.extern_class thy class ^ ":"),
haftmann@24218
   237
      (SOME o Pretty.block) [Pretty.str "supersort: ",
wenzelm@24920
   238
        (Syntax.pretty_sort ctxt o Sign.minimize_sort thy o Sign.super_classes thy) class],
haftmann@25062
   239
      if is_class thy class then (SOME o Pretty.str)
haftmann@29509
   240
        ("locale: " ^ Locale.extern thy class) else NONE,
haftmann@25062
   241
      ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks)
haftmann@25062
   242
          (Pretty.str "parameters:" :: ps)) o map mk_param
wenzelm@24930
   243
        o these o Option.map #params o try (AxClass.get_info thy)) class,
haftmann@24218
   244
      (SOME o Pretty.block o Pretty.breaks) [
haftmann@24218
   245
        Pretty.str "instances:",
haftmann@24218
   246
        Pretty.list "" "" (map (mk_arity class) (the_arities class))
haftmann@24218
   247
      ]
haftmann@24218
   248
    ]
haftmann@24218
   249
  in
haftmann@24589
   250
    (Pretty.writeln o Pretty.chunks o separate (Pretty.str "")
haftmann@24589
   251
      o map mk_entry o Sorts.all_classes) algebra
haftmann@24218
   252
  end;
haftmann@24218
   253
haftmann@24218
   254
haftmann@24218
   255
(* updaters *)
haftmann@24218
   256
haftmann@29439
   257
fun register class superclasses params base_sort inst morph
haftmann@29358
   258
    axiom assm_intro of_class thy =
haftmann@25002
   259
  let
haftmann@25368
   260
    val operations = map (fn (v_ty as (_, ty), (c, _)) =>
haftmann@25683
   261
      (c, (class, (ty, Free v_ty)))) params;
haftmann@25038
   262
    val add_class = Graph.new_node (class,
haftmann@25683
   263
        mk_class_data (((map o pairself) fst params, base_sort,
haftmann@29439
   264
          inst, morph, assm_intro, of_class, axiom), ([], operations)))
haftmann@25002
   265
      #> fold (curry Graph.add_edge class) superclasses;
haftmann@25618
   266
  in ClassData.map add_class thy end;
haftmann@24218
   267
haftmann@25368
   268
fun register_operation class (c, (t, some_def)) thy =
haftmann@25062
   269
  let
haftmann@29358
   270
    val base_sort = base_sort thy class;
haftmann@29439
   271
    val prep_typ = map_type_tfree
haftmann@29439
   272
      (fn (v, sort) => if Name.aT = v
haftmann@29439
   273
        then TFree (v, base_sort) else TVar ((v, 0), sort));
haftmann@25368
   274
    val t' = map_types prep_typ t;
haftmann@25368
   275
    val ty' = Term.fastype_of t';
haftmann@25062
   276
  in
haftmann@25062
   277
    thy
haftmann@25062
   278
    |> (ClassData.map o Graph.map_node class o map_class_data o apsnd)
haftmann@25368
   279
      (fn (defs, operations) =>
haftmann@25096
   280
        (fold cons (the_list some_def) defs,
haftmann@25368
   281
          (c, (class, (ty', t'))) :: operations))
haftmann@25062
   282
  end;
haftmann@24218
   283
haftmann@24589
   284
haftmann@29358
   285
(** tactics and methods **)
haftmann@24589
   286
haftmann@29509
   287
fun register_subclass (sub, sup) thms thy =
haftmann@25618
   288
  let
haftmann@29358
   289
    val of_class = (snd o rules thy) sup;
haftmann@29509
   290
    val intro = case thms
haftmann@27684
   291
     of SOME thm => Drule.standard' (of_class OF [Drule.standard' thm])
haftmann@27684
   292
      | NONE => Thm.instantiate ([pairself (Thm.ctyp_of thy o TVar o pair (Name.aT, 0))
haftmann@27684
   293
          ([], [sub])], []) of_class;
haftmann@29358
   294
    val classrel = (intro OF (the_list o fst o rules thy) sub)
haftmann@27684
   295
      |> Thm.close_derivation;
haftmann@29509
   296
    (*FIXME generic amend operation for classes*)
haftmann@29509
   297
    val amendments = map (fn class => (class, morphism thy class))
haftmann@29509
   298
      (heritage thy [sub]);
haftmann@29509
   299
    val diff_sort = Sign.complete_sort thy [sup]
haftmann@29509
   300
      |> subtract (op =) (Sign.complete_sort thy [sub]);
haftmann@29509
   301
    val defs_morph = eq_morph thy (these_defs thy diff_sort);
haftmann@25618
   302
  in
haftmann@25618
   303
    thy
haftmann@25618
   304
    |> AxClass.add_classrel classrel
haftmann@25618
   305
    |> ClassData.map (Graph.add_edge (sub, sup))
haftmann@29509
   306
    |> fold (Locale.amend_registration defs_morph) amendments
haftmann@25618
   307
  end;
haftmann@25618
   308
haftmann@24218
   309
fun intro_classes_tac facts st =
haftmann@24218
   310
  let
haftmann@24218
   311
    val thy = Thm.theory_of_thm st;
haftmann@24218
   312
    val classes = Sign.all_classes thy;
haftmann@24218
   313
    val class_trivs = map (Thm.class_triv thy) classes;
haftmann@25618
   314
    val class_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
haftmann@25618
   315
    val assm_intros = these_assm_intros thy;
haftmann@24218
   316
  in
haftmann@25618
   317
    Method.intros_tac (class_trivs @ class_intros @ assm_intros) facts st
haftmann@24218
   318
  end;
haftmann@24218
   319
haftmann@26470
   320
fun default_intro_tac ctxt [] =
haftmann@29362
   321
      intro_classes_tac [] ORELSE Old_Locale.intro_locales_tac true ctxt [] ORELSE
ballarin@29029
   322
      Locale.intro_locales_tac true ctxt []
haftmann@26470
   323
  | default_intro_tac _ _ = no_tac;
haftmann@24218
   324
haftmann@24218
   325
fun default_tac rules ctxt facts =
haftmann@24218
   326
  HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
haftmann@26470
   327
    default_intro_tac ctxt facts;
haftmann@24218
   328
wenzelm@26463
   329
val _ = Context.>> (Context.map_theory
wenzelm@26463
   330
  (Method.add_methods
wenzelm@26463
   331
   [("intro_classes", Method.no_args (Method.METHOD intro_classes_tac),
wenzelm@26463
   332
      "back-chain introduction rules of classes"),
wenzelm@26463
   333
    ("default", Method.thms_ctxt_args (Method.METHOD oo default_tac),
wenzelm@26463
   334
      "apply some intro/elim rule")]));
wenzelm@26463
   335
haftmann@24218
   336
haftmann@24589
   337
(** classes and class target **)
haftmann@24218
   338
haftmann@25002
   339
(* class context syntax *)
haftmann@24748
   340
haftmann@26238
   341
fun synchronize_class_syntax sups base_sort ctxt =
haftmann@24914
   342
  let
wenzelm@25344
   343
    val thy = ProofContext.theory_of ctxt;
haftmann@26596
   344
    val algebra = Sign.classes_of thy;
haftmann@25083
   345
    val operations = these_operations thy sups;
haftmann@26518
   346
    fun subst_class_typ sort = map_type_tfree (K (TVar ((Name.aT, 0), sort)));
haftmann@26518
   347
    val primary_constraints =
haftmann@25368
   348
      (map o apsnd) (subst_class_typ base_sort o fst o snd) operations;
haftmann@26518
   349
    val secondary_constraints =
haftmann@25368
   350
      (map o apsnd) (fn (class, (ty, _)) => subst_class_typ [class] ty) operations;
wenzelm@25318
   351
    fun declare_const (c, _) =
wenzelm@25318
   352
      let val b = Sign.base_name c
wenzelm@25344
   353
      in Sign.intern_const thy b = c ? Variable.declare_const (b, c) end;
haftmann@26518
   354
    fun improve (c, ty) = (case AList.lookup (op =) primary_constraints c
haftmann@26238
   355
     of SOME ty' => (case try (Type.raw_match (ty', ty)) Vartab.empty
haftmann@26238
   356
         of SOME tyenv => (case Vartab.lookup tyenv (Name.aT, 0)
haftmann@26596
   357
             of SOME (_, ty' as TVar (tvar as (vi, sort))) =>
haftmann@26238
   358
                  if TypeInfer.is_param vi
haftmann@26596
   359
                    andalso Sorts.sort_le algebra (base_sort, sort)
haftmann@26596
   360
                      then SOME (ty', TFree (Name.aT, base_sort))
haftmann@26596
   361
                      else NONE
haftmann@26238
   362
              | _ => NONE)
haftmann@26238
   363
          | NONE => NONE)
haftmann@26238
   364
      | NONE => NONE)
haftmann@26238
   365
    fun subst (c, ty) = Option.map snd (AList.lookup (op =) operations c);
haftmann@25368
   366
    val unchecks = map (fn (c, (_, (ty, t))) => (t, Const (c, ty))) operations;
haftmann@25083
   367
  in
haftmann@25083
   368
    ctxt
haftmann@26518
   369
    |> fold declare_const primary_constraints
haftmann@26518
   370
    |> Overloading.map_improvable_syntax (K (((primary_constraints, secondary_constraints),
haftmann@26730
   371
        (((improve, subst), true), unchecks)), false))
haftmann@26518
   372
    |> Overloading.set_primary_constraints
haftmann@25083
   373
  end;
haftmann@25083
   374
haftmann@25083
   375
fun refresh_syntax class ctxt =
haftmann@25002
   376
  let
haftmann@25002
   377
    val thy = ProofContext.theory_of ctxt;
haftmann@29358
   378
    val base_sort = base_sort thy class;
haftmann@26238
   379
  in synchronize_class_syntax [class] base_sort ctxt end;
haftmann@25002
   380
haftmann@29358
   381
fun begin sups base_sort ctxt =
haftmann@25083
   382
  ctxt
haftmann@25083
   383
  |> Variable.declare_term
haftmann@25083
   384
      (Logic.mk_type (TFree (Name.aT, base_sort)))
haftmann@26238
   385
  |> synchronize_class_syntax sups base_sort
haftmann@26238
   386
  |> Overloading.add_improvable_syntax;
haftmann@24901
   387
haftmann@25311
   388
fun init class thy =
haftmann@25311
   389
  thy
haftmann@29509
   390
  |> Locale.init class
haftmann@29358
   391
  |> begin [class] (base_sort thy class);
haftmann@24914
   392
haftmann@24748
   393
haftmann@27690
   394
(* class target *)
haftmann@27690
   395
haftmann@27690
   396
fun declare class pos ((c, mx), dict) thy =
haftmann@27690
   397
  let
haftmann@27690
   398
    val prfx = class_prefix class;
haftmann@27690
   399
    val thy' = thy |> Sign.add_path prfx;
haftmann@29439
   400
    val morph = morphism thy' class;
haftmann@28715
   401
    val inst = the_inst thy' class;
haftmann@28715
   402
    val params = map (apsnd fst o snd) (these_params thy' [class]);
haftmann@29509
   403
    val amendments = map (fn class => (class, morphism thy' class))
haftmann@29509
   404
      (heritage thy' [class]);
haftmann@27690
   405
haftmann@28965
   406
    val c' = Sign.full_bname thy' c;
haftmann@29439
   407
    val dict' = Morphism.term morph dict;
haftmann@29439
   408
    val ty' = Term.fastype_of dict';
haftmann@27690
   409
    val ty'' = Type.strip_sorts ty';
haftmann@29439
   410
    val def_eq = Logic.mk_equals (Const (c', ty'), dict');
haftmann@29509
   411
    (*FIXME a mess*)
haftmann@29509
   412
    fun amend def def' (class, morph) thy =
haftmann@29509
   413
      Locale.amend_registration (eq_morph thy [Thm.varifyT def])
haftmann@29509
   414
        (class, morph) thy;
wenzelm@28674
   415
    fun get_axiom thy = ((Thm.varifyT o Thm.axiom thy) c', thy);
haftmann@27690
   416
  in
haftmann@27690
   417
    thy'
haftmann@28965
   418
    |> Sign.declare_const pos ((Binding.name c, ty''), mx) |> snd
haftmann@27690
   419
    |> Thm.add_def false false (c, def_eq)
haftmann@27690
   420
    |>> Thm.symmetric
haftmann@27690
   421
    ||>> get_axiom
haftmann@29509
   422
    |-> (fn (def, def') => register_operation class (c', (dict', SOME (Thm.symmetric def')))
haftmann@29509
   423
      #> fold (amend def def') amendments
haftmann@29509
   424
      #> PureThy.store_thm (c ^ "_raw", def') (*FIXME name*)
haftmann@27690
   425
      #> snd)
haftmann@27690
   426
    |> Sign.restore_naming thy
haftmann@27690
   427
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@27690
   428
  end;
haftmann@27690
   429
haftmann@27690
   430
fun abbrev class prmode pos ((c, mx), rhs) thy =
haftmann@27690
   431
  let
haftmann@27690
   432
    val prfx = class_prefix class;
haftmann@27690
   433
    val thy' = thy |> Sign.add_path prfx;
haftmann@27690
   434
haftmann@27690
   435
    val unchecks = map (fn (c, (_, (ty, t))) => (t, Const (c, ty)))
haftmann@27690
   436
      (these_operations thy [class]);
haftmann@28965
   437
    val c' = Sign.full_bname thy' c;
haftmann@27690
   438
    val rhs' = Pattern.rewrite_term thy unchecks [] rhs;
haftmann@27690
   439
    val rhs'' = map_types Logic.varifyT rhs';
haftmann@27690
   440
    val ty' = Term.fastype_of rhs';
haftmann@27690
   441
  in
haftmann@27690
   442
    thy'
haftmann@28965
   443
    |> Sign.add_abbrev (#1 prmode) pos (Binding.name c, map_types Type.strip_sorts rhs'') |> snd
haftmann@27690
   444
    |> Sign.add_const_constraint (c', SOME ty')
haftmann@27690
   445
    |> Sign.notation true prmode [(Const (c', ty'), mx)]
haftmann@27690
   446
    |> not (#1 prmode = PrintMode.input) ? register_operation class (c', (rhs', NONE))
haftmann@27690
   447
    |> Sign.restore_naming thy
haftmann@27690
   448
  end;
haftmann@27690
   449
haftmann@27690
   450
haftmann@25462
   451
(** instantiation target **)
haftmann@25462
   452
haftmann@25462
   453
(* bookkeeping *)
haftmann@25462
   454
haftmann@25462
   455
datatype instantiation = Instantiation of {
haftmann@25864
   456
  arities: string list * (string * sort) list * sort,
haftmann@25462
   457
  params: ((string * string) * (string * typ)) list
haftmann@25603
   458
    (*(instantiation parameter, type constructor), (local instantiation parameter, typ)*)
haftmann@25462
   459
}
haftmann@25462
   460
haftmann@25462
   461
structure Instantiation = ProofDataFun
haftmann@25462
   462
(
haftmann@25462
   463
  type T = instantiation
haftmann@25536
   464
  fun init _ = Instantiation { arities = ([], [], []), params = [] };
haftmann@25462
   465
);
haftmann@25462
   466
haftmann@25485
   467
fun mk_instantiation (arities, params) =
haftmann@25485
   468
  Instantiation { arities = arities, params = params };
haftmann@25514
   469
fun get_instantiation lthy = case Instantiation.get (LocalTheory.target_of lthy)
haftmann@25485
   470
 of Instantiation data => data;
haftmann@25514
   471
fun map_instantiation f = (LocalTheory.target o Instantiation.map)
haftmann@25514
   472
  (fn Instantiation { arities, params } => mk_instantiation (f (arities, params)));
haftmann@25462
   473
haftmann@25514
   474
fun the_instantiation lthy = case get_instantiation lthy
haftmann@25536
   475
 of { arities = ([], [], []), ... } => error "No instantiation target"
haftmann@25485
   476
  | data => data;
haftmann@25462
   477
haftmann@25485
   478
val instantiation_params = #params o get_instantiation;
haftmann@25462
   479
haftmann@25514
   480
fun instantiation_param lthy v = instantiation_params lthy
haftmann@25462
   481
  |> find_first (fn (_, (v', _)) => v = v')
haftmann@25462
   482
  |> Option.map (fst o fst);
haftmann@25462
   483
haftmann@25462
   484
haftmann@25462
   485
(* syntax *)
haftmann@25462
   486
haftmann@26238
   487
fun synchronize_inst_syntax ctxt =
haftmann@25462
   488
  let
haftmann@26259
   489
    val Instantiation { arities = (_, _, sort), params = params } = Instantiation.get ctxt;
haftmann@26238
   490
    val thy = ProofContext.theory_of ctxt;
haftmann@26238
   491
    fun subst (c, ty) = case AxClass.inst_tyco_of thy (c, ty)
haftmann@26238
   492
         of SOME tyco => (case AList.lookup (op =) params (c, tyco)
haftmann@26238
   493
             of SOME (v_ty as (_, ty)) => SOME (ty, Free v_ty)
haftmann@26238
   494
              | NONE => NONE)
haftmann@26238
   495
          | NONE => NONE;
haftmann@26238
   496
    val unchecks =
haftmann@26238
   497
      map (fn ((c, _), v_ty as (_, ty)) => (Free v_ty, Const (c, ty))) params;
haftmann@26238
   498
  in
haftmann@26238
   499
    ctxt
haftmann@26259
   500
    |> Overloading.map_improvable_syntax
haftmann@26730
   501
         (fn (((primary_constraints, _), (((improve, _), _), _)), _) =>
haftmann@26730
   502
            (((primary_constraints, []), (((improve, subst), false), unchecks)), false))
haftmann@26238
   503
  end;
haftmann@25462
   504
haftmann@25462
   505
haftmann@25462
   506
(* target *)
haftmann@25462
   507
haftmann@25485
   508
val sanatize_name = (*FIXME*)
haftmann@25485
   509
  let
haftmann@25574
   510
    fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s
haftmann@25574
   511
      orelse s = "'" orelse s = "_";
haftmann@25485
   512
    val is_junk = not o is_valid andf Symbol.is_regular;
haftmann@25485
   513
    val junk = Scan.many is_junk;
haftmann@25485
   514
    val scan_valids = Symbol.scanner "Malformed input"
haftmann@25485
   515
      ((junk |--
haftmann@25485
   516
        (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
haftmann@25485
   517
        --| junk))
wenzelm@25999
   518
      ::: Scan.repeat ((Scan.many1 is_valid >> implode) --| junk));
haftmann@25485
   519
  in
haftmann@25485
   520
    explode #> scan_valids #> implode
haftmann@25485
   521
  end;
haftmann@25485
   522
haftmann@26259
   523
fun type_name "*" = "prod"
haftmann@26259
   524
  | type_name "+" = "sum"
haftmann@26259
   525
  | type_name s = sanatize_name (NameSpace.base s); (*FIXME*)
haftmann@26259
   526
haftmann@26518
   527
fun resort_terms pp algebra consts constraints ts =
haftmann@26518
   528
  let
haftmann@26518
   529
    fun matchings (Const (c_ty as (c, _))) = (case constraints c
haftmann@26518
   530
         of NONE => I
haftmann@26518
   531
          | SOME sorts => fold2 (curry (Sorts.meet_sort algebra))
haftmann@26518
   532
              (Consts.typargs consts c_ty) sorts)
haftmann@26518
   533
      | matchings _ = I
haftmann@26518
   534
    val tvartab = (fold o fold_aterms) matchings ts Vartab.empty
wenzelm@26642
   535
      handle Sorts.CLASS_ERROR e => error (Sorts.class_error pp e);
haftmann@27089
   536
    val inst = map_type_tvar
haftmann@27089
   537
      (fn (vi, sort) => TVar (vi, the_default sort (Vartab.lookup tvartab vi)));
haftmann@26518
   538
  in if Vartab.is_empty tvartab then NONE else SOME ((map o map_types) inst ts) end;
haftmann@26518
   539
haftmann@25864
   540
fun init_instantiation (tycos, vs, sort) thy =
haftmann@25462
   541
  let
haftmann@25536
   542
    val _ = if null tycos then error "At least one arity must be given" else ();
haftmann@26518
   543
    val params = these_params thy sort;
haftmann@26518
   544
    fun get_param tyco (param, (_, (c, ty))) = if can (AxClass.param_of_inst thy) (c, tyco)
haftmann@25603
   545
      then NONE else SOME ((c, tyco),
haftmann@25864
   546
        (param ^ "_" ^ type_name tyco, map_atyps (K (Type (tyco, map TFree vs))) ty));
haftmann@26518
   547
    val inst_params = map_product get_param tycos params |> map_filter I;
haftmann@26518
   548
    val primary_constraints = map (apsnd
haftmann@26518
   549
      (map_atyps (K (TVar ((Name.aT, 0), [])))) o snd o snd) params;
wenzelm@26939
   550
    val pp = Syntax.pp_global thy;
haftmann@26518
   551
    val algebra = Sign.classes_of thy
haftmann@26518
   552
      |> fold (fn tyco => Sorts.add_arities pp
haftmann@26518
   553
            (tyco, map (fn class => (class, map snd vs)) sort)) tycos;
haftmann@26518
   554
    val consts = Sign.consts_of thy;
haftmann@26518
   555
    val improve_constraints = AList.lookup (op =)
haftmann@26518
   556
      (map (fn (_, (class, (c, _))) => (c, [[class]])) params);
haftmann@26518
   557
    fun resort_check ts ctxt = case resort_terms pp algebra consts improve_constraints ts
haftmann@26518
   558
     of NONE => NONE
haftmann@26518
   559
      | SOME ts' => SOME (ts', ctxt);
haftmann@26518
   560
    fun improve (c, ty) = case AxClass.inst_tyco_of thy (c, ty)
haftmann@26329
   561
     of SOME tyco => (case AList.lookup (op =) inst_params (c, tyco)
haftmann@26518
   562
         of SOME (_, ty') => if Type.raw_instance (ty', ty) then SOME (ty, ty') else NONE
haftmann@26259
   563
          | NONE => NONE)
haftmann@26259
   564
      | NONE => NONE;
haftmann@25485
   565
  in
haftmann@25485
   566
    thy
haftmann@25485
   567
    |> ProofContext.init
haftmann@26329
   568
    |> Instantiation.put (mk_instantiation ((tycos, vs, sort), inst_params))
wenzelm@27281
   569
    |> fold (Variable.declare_typ o TFree) vs
haftmann@26329
   570
    |> fold (Variable.declare_names o Free o snd) inst_params
haftmann@26259
   571
    |> (Overloading.map_improvable_syntax o apfst)
haftmann@26329
   572
         (fn ((_, _), ((_, subst), unchecks)) =>
haftmann@26730
   573
            ((primary_constraints, []), (((improve, K NONE), false), [])))
haftmann@26259
   574
    |> Overloading.add_improvable_syntax
haftmann@26518
   575
    |> Context.proof_map (Syntax.add_term_check 0 "resorting" resort_check)
haftmann@26238
   576
    |> synchronize_inst_syntax
haftmann@25485
   577
  end;
haftmann@25485
   578
haftmann@26238
   579
fun confirm_declaration c = (map_instantiation o apsnd)
haftmann@26238
   580
  (filter_out (fn (_, (c', _)) => c' = c))
haftmann@26238
   581
  #> LocalTheory.target synchronize_inst_syntax
haftmann@26238
   582
haftmann@25485
   583
fun gen_instantiation_instance do_proof after_qed lthy =
haftmann@25485
   584
  let
haftmann@25864
   585
    val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
haftmann@25864
   586
    val arities_proof = maps (fn tyco => Logic.mk_arities (tyco, map snd vs, sort)) tycos;
haftmann@25462
   587
    fun after_qed' results =
haftmann@25462
   588
      LocalTheory.theory (fold (AxClass.add_arity o Thm.varifyT) results)
haftmann@25462
   589
      #> after_qed;
haftmann@25462
   590
  in
haftmann@25462
   591
    lthy
haftmann@25462
   592
    |> do_proof after_qed' arities_proof
haftmann@25462
   593
  end;
haftmann@25462
   594
haftmann@25485
   595
val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
haftmann@25462
   596
  Proof.theorem_i NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
haftmann@25462
   597
haftmann@25485
   598
fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
haftmann@25502
   599
  fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
haftmann@25502
   600
    (fn {context, ...} => tac context)) ts) lthy) I;
haftmann@25462
   601
haftmann@28666
   602
fun prove_instantiation_exit tac = prove_instantiation_instance tac
haftmann@28666
   603
  #> LocalTheory.exit_global;
haftmann@28666
   604
haftmann@28666
   605
fun prove_instantiation_exit_result f tac x lthy =
haftmann@28666
   606
  let
haftmann@29439
   607
    val morph = ProofContext.export_morphism lthy
haftmann@28666
   608
      (ProofContext.init (ProofContext.theory_of lthy));
haftmann@29439
   609
    val y = f morph x;
haftmann@28666
   610
  in
haftmann@28666
   611
    lthy
haftmann@28666
   612
    |> prove_instantiation_exit (fn ctxt => tac ctxt y)
haftmann@28666
   613
    |> pair y
haftmann@28666
   614
  end;
haftmann@28666
   615
haftmann@25462
   616
fun conclude_instantiation lthy =
haftmann@25462
   617
  let
haftmann@25485
   618
    val { arities, params } = the_instantiation lthy;
haftmann@25864
   619
    val (tycos, vs, sort) = arities;
haftmann@25462
   620
    val thy = ProofContext.theory_of lthy;
haftmann@25597
   621
    val _ = map (fn tyco => if Sign.of_sort thy
haftmann@25864
   622
        (Type (tyco, map TFree vs), sort)
haftmann@25462
   623
      then () else error ("Missing instance proof for type " ^ quote (Sign.extern_type thy tyco)))
haftmann@25597
   624
        tycos;
haftmann@25597
   625
  in lthy end;
haftmann@25462
   626
haftmann@25603
   627
fun pretty_instantiation lthy =
haftmann@25603
   628
  let
haftmann@25603
   629
    val { arities, params } = the_instantiation lthy;
haftmann@25864
   630
    val (tycos, vs, sort) = arities;
haftmann@25603
   631
    val thy = ProofContext.theory_of lthy;
haftmann@25864
   632
    fun pr_arity tyco = Syntax.pretty_arity lthy (tyco, map snd vs, sort);
haftmann@25603
   633
    fun pr_param ((c, _), (v, ty)) =
haftmann@25864
   634
      (Pretty.block o Pretty.breaks) [Pretty.str v, Pretty.str "==",
wenzelm@26939
   635
        (Pretty.str o Sign.extern_const thy) c, Pretty.str "::", Syntax.pretty_typ_global thy ty];
haftmann@25603
   636
  in
haftmann@25603
   637
    (Pretty.block o Pretty.fbreaks)
haftmann@25603
   638
      (Pretty.str "instantiation" :: map pr_arity tycos @ map pr_param params)
haftmann@25603
   639
  end;
haftmann@25603
   640
haftmann@24218
   641
end;
haftmann@25683
   642