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