src/Pure/Tools/class_package.ML
author wenzelm
Fri Sep 15 22:56:13 2006 +0200 (2006-09-15)
changeset 20548 8ef25fe585a8
parent 20465 95f6d354b0ed
child 20601 3e1caf5a07c6
permissions -rw-r--r--
renamed Term.map_term_types to Term.map_types (cf. Term.fold_types);
haftmann@18168
     1
(*  Title:      Pure/Tools/class_package.ML
haftmann@18168
     2
    ID:         $Id$
haftmann@18168
     3
    Author:     Florian Haftmann, TU Muenchen
haftmann@18168
     4
wenzelm@19468
     5
Type classes derived from primitive axclasses and locales.
haftmann@18168
     6
*)
haftmann@18168
     7
haftmann@18168
     8
signature CLASS_PACKAGE =
haftmann@18168
     9
sig
haftmann@20428
    10
  val class: bstring -> class list -> Element.context Locale.element list -> theory
wenzelm@20289
    11
    -> Proof.context * theory
haftmann@20428
    12
  val class_i: bstring -> class list -> Element.context_i Locale.element list -> theory
wenzelm@20289
    13
    -> Proof.context * theory
haftmann@20175
    14
  (*FIXME: in _i variants, bstring should be bstring option*)
haftmann@20175
    15
  val instance_arity: ((xstring * string list) * string) list
haftmann@19136
    16
    -> bstring * Attrib.src list -> ((bstring * Attrib.src list) * string) list
haftmann@18575
    17
    -> theory -> Proof.state
haftmann@20175
    18
  val instance_arity_i: ((string * sort list) * sort) list
haftmann@19136
    19
    -> bstring * attribute list -> ((bstring * attribute list) * term) list
haftmann@18575
    20
    -> theory -> Proof.state
haftmann@20182
    21
  val prove_instance_arity: (thm list -> tactic) -> ((string * sort list) * sort) list
haftmann@19136
    22
    -> bstring * attribute list -> ((bstring * attribute list) * term) list
haftmann@19110
    23
    -> theory -> theory
haftmann@19150
    24
  val instance_sort: string * string -> theory -> Proof.state
haftmann@19150
    25
  val instance_sort_i: class * sort -> theory -> Proof.state
haftmann@19150
    26
  val prove_instance_sort: tactic -> class * sort -> theory -> theory
haftmann@18168
    27
haftmann@18755
    28
  val certify_class: theory -> class -> class
haftmann@19110
    29
  val certify_sort: theory -> sort -> sort
haftmann@20385
    30
  val read_class: theory -> xstring -> class
haftmann@19110
    31
  val read_sort: theory -> string -> sort
haftmann@20465
    32
  val operational_algebra: theory -> (sort -> sort) * Sorts.algebra
haftmann@18702
    33
  val the_consts_sign: theory -> class -> string * (string * typ) list
haftmann@18702
    34
  val the_inst_sign: theory -> class * string -> (string * sort) list * (string * typ) list
haftmann@20175
    35
  val assume_arities_of_sort: theory -> ((string * sort list) * sort) list -> typ * sort -> bool
haftmann@20175
    36
  val assume_arities_thy: theory -> ((string * sort list) * sort) list -> (theory -> 'a) -> 'a
haftmann@20175
    37
    (*'a must not keep any reference to theory*)
haftmann@19110
    38
haftmann@18702
    39
  val print_classes: theory -> unit
haftmann@19110
    40
  val intro_classes_tac: thm list -> tactic
haftmann@19110
    41
  val default_intro_classes_tac: thm list -> tactic
haftmann@18168
    42
end;
haftmann@18168
    43
haftmann@20182
    44
structure ClassPackage : CLASS_PACKAGE =
haftmann@18168
    45
struct
haftmann@18168
    46
haftmann@18168
    47
haftmann@20455
    48
(** theory data **)
haftmann@18168
    49
haftmann@19456
    50
datatype class_data = ClassData of {
haftmann@18575
    51
  name_locale: string,
haftmann@18575
    52
  name_axclass: string,
haftmann@18575
    53
  var: string,
haftmann@19966
    54
  consts: (string * (string * typ)) list,
haftmann@20385
    55
    (*locale parameter ~> toplevel theory constant*)
haftmann@19966
    56
  propnames: string list
haftmann@19966
    57
} * thm list Symtab.table;
haftmann@18168
    58
haftmann@19456
    59
fun rep_classdata (ClassData c) = c;
haftmann@19456
    60
haftmann@18575
    61
structure ClassData = TheoryDataFun (
haftmann@18168
    62
  struct
haftmann@18168
    63
    val name = "Pure/classes";
haftmann@19966
    64
    type T = class_data Symtab.table;
haftmann@19966
    65
    val empty = Symtab.empty;
haftmann@18168
    66
    val copy = I;
haftmann@18168
    67
    val extend = I;
haftmann@19966
    68
    fun merge _ = Symtab.join (fn _ => fn (ClassData (classd, instd1), ClassData (_, instd2)) =>
haftmann@19966
    69
      (ClassData (classd, Symtab.merge (K true) (instd1, instd2))));
haftmann@19966
    70
    fun print thy data =
haftmann@18575
    71
      let
haftmann@19966
    72
        fun pretty_class (name, ClassData ({name_locale, name_axclass, var, consts, ...}, _)) =
haftmann@18575
    73
          (Pretty.block o Pretty.fbreaks) [
haftmann@18575
    74
            Pretty.str ("class " ^ name ^ ":"),
haftmann@18575
    75
            Pretty.str ("locale: " ^ name_locale),
haftmann@18575
    76
            Pretty.str ("axclass: " ^ name_axclass),
haftmann@18575
    77
            Pretty.str ("class variable: " ^ var),
haftmann@18575
    78
            (Pretty.block o Pretty.fbreaks) (
haftmann@18575
    79
              Pretty.str "constants: "
haftmann@19280
    80
              :: map (fn (_, (c, ty)) => Pretty.str (c ^ " :: " ^ Sign.string_of_typ thy ty)) consts
haftmann@18575
    81
            )
haftmann@18575
    82
          ]
haftmann@18575
    83
      in
haftmann@19966
    84
        (Pretty.writeln o Pretty.chunks o map pretty_class o Symtab.dest) data
haftmann@18575
    85
      end;
haftmann@18168
    86
  end
haftmann@18168
    87
);
haftmann@18168
    88
wenzelm@18708
    89
val _ = Context.add_setup ClassData.init;
haftmann@18575
    90
val print_classes = ClassData.print;
haftmann@18575
    91
haftmann@19038
    92
haftmann@19038
    93
(* queries *)
haftmann@19038
    94
haftmann@19966
    95
val lookup_class_data = Option.map rep_classdata oo Symtab.lookup o ClassData.get;
haftmann@18168
    96
haftmann@19038
    97
fun the_class_data thy class =
haftmann@18168
    98
  case lookup_class_data thy class
haftmann@20455
    99
    of NONE => error ("undeclared constructive class " ^ quote class)
haftmann@18168
   100
     | SOME data => data;
haftmann@18168
   101
haftmann@19280
   102
fun is_operational_class thy cls =
haftmann@18702
   103
  lookup_class_data thy cls
haftmann@19966
   104
  |> Option.map (not o null o #consts o fst)
haftmann@18702
   105
  |> the_default false;
haftmann@18168
   106
haftmann@20455
   107
fun the_ancestry thy classes =
haftmann@18360
   108
  let
haftmann@20455
   109
    fun proj_class class =
haftmann@19280
   110
      if is_operational_class thy class
haftmann@19110
   111
      then [class]
haftmann@20455
   112
      else (Sign.certify_sort thy o maps proj_class o Sign.super_classes thy) class;
haftmann@19038
   113
    fun ancestry class anc =
haftmann@19038
   114
      anc
haftmann@20385
   115
      |> insert (op =) class
haftmann@20455
   116
      |> fold ancestry ((maps proj_class o Sign.super_classes thy) class);
haftmann@19038
   117
  in fold ancestry classes [] end;
haftmann@19038
   118
haftmann@20455
   119
val the_parm_map = #consts o fst oo the_class_data;
haftmann@20455
   120
haftmann@20455
   121
val the_propnames = #propnames o fst oo the_class_data;
haftmann@20455
   122
haftmann@19038
   123
fun subst_clsvar v ty_subst =
haftmann@19038
   124
  map_type_tfree (fn u as (w, _) =>
haftmann@19038
   125
    if w = v then ty_subst else TFree u);
haftmann@19038
   126
haftmann@18168
   127
haftmann@19038
   128
(* updaters *)
haftmann@19038
   129
haftmann@19966
   130
fun add_class_data (class, (name_locale, name_axclass, var, consts, propnames)) =
haftmann@19957
   131
  ClassData.map (
haftmann@19966
   132
    Symtab.update_new (class, ClassData ({
haftmann@19957
   133
      name_locale = name_locale,
haftmann@19957
   134
      name_axclass = name_axclass,
haftmann@19957
   135
      var = var,
haftmann@19966
   136
      consts = consts,
haftmann@19966
   137
      propnames = propnames}, Symtab.empty))
haftmann@19957
   138
  );
haftmann@19038
   139
haftmann@19966
   140
fun add_inst_def ((class, tyco), thm) =
haftmann@19966
   141
  ClassData.map (
haftmann@19966
   142
    Symtab.map_entry class (fn ClassData (classd, instd) =>
haftmann@19966
   143
      ClassData (classd, Symtab.insert_list eq_thm (tyco, thm) instd))
haftmann@19966
   144
  );
haftmann@19038
   145
haftmann@20106
   146
haftmann@20385
   147
(* certification and reading *)
haftmann@19038
   148
haftmann@19038
   149
fun certify_class thy class =
haftmann@19110
   150
  (fn class => (the_class_data thy class; class)) (Sign.certify_class thy class);
haftmann@19110
   151
haftmann@19110
   152
fun certify_sort thy sort =
haftmann@19110
   153
  map (fn class => (the_class_data thy class; class)) (Sign.certify_sort thy sort);
haftmann@19110
   154
haftmann@20385
   155
fun read_class thy =
haftmann@19957
   156
  certify_class thy o Sign.intern_class thy;
haftmann@19110
   157
haftmann@19110
   158
fun read_sort thy =
haftmann@19110
   159
  certify_sort thy o Sign.read_sort thy;
haftmann@19110
   160
haftmann@19110
   161
haftmann@20455
   162
haftmann@20455
   163
(** contexts with arity assumptions **)
haftmann@20175
   164
haftmann@20175
   165
fun assume_arities_of_sort thy arities ty_sort =
haftmann@20175
   166
  let
haftmann@20175
   167
    val pp = Sign.pp thy;
haftmann@20175
   168
    val algebra = Sign.classes_of thy
haftmann@20175
   169
      |> fold (fn ((tyco, asorts), sort) =>
haftmann@20175
   170
           Sorts.add_arities pp (tyco, map (fn class => (class, asorts)) sort)) arities;
haftmann@20175
   171
  in Sorts.of_sort algebra ty_sort end;
haftmann@20175
   172
haftmann@20175
   173
fun assume_arities_thy thy arities f =
haftmann@20175
   174
  let
haftmann@20175
   175
    val thy_read = (fold (fn ((tyco, asorts), sort)
haftmann@20175
   176
      => Sign.primitive_arity (tyco, asorts, sort)) arities o Theory.copy) thy
haftmann@20175
   177
  in f thy_read end;
haftmann@20175
   178
haftmann@20455
   179
haftmann@20455
   180
haftmann@20455
   181
(** tactics and methods **)
haftmann@19110
   182
haftmann@19110
   183
fun intro_classes_tac facts st =
haftmann@19110
   184
  (ALLGOALS (Method.insert_tac facts THEN'
haftmann@19928
   185
      REPEAT_ALL_NEW (resolve_tac (AxClass.class_intros (Thm.theory_of_thm st))))
haftmann@19110
   186
    THEN Tactic.distinct_subgoals_tac) st;
haftmann@19110
   187
haftmann@19110
   188
fun default_intro_classes_tac [] = intro_classes_tac []
haftmann@19110
   189
  | default_intro_classes_tac _ = Tactical.no_tac;    (*no error message!*)
haftmann@19110
   190
haftmann@19110
   191
fun default_tac rules ctxt facts =
haftmann@19110
   192
  HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
haftmann@19110
   193
    default_intro_classes_tac facts;
haftmann@19038
   194
wenzelm@19468
   195
val _ = Context.add_setup (Method.add_methods
wenzelm@19468
   196
 [("intro_classes", Method.no_args (Method.METHOD intro_classes_tac),
wenzelm@19468
   197
    "back-chain introduction rules of classes"),
wenzelm@19468
   198
  ("default", Method.thms_ctxt_args (Method.METHOD oo default_tac),
wenzelm@19468
   199
    "apply some intro/elim rule")]);
wenzelm@19468
   200
haftmann@19038
   201
haftmann@20455
   202
haftmann@20455
   203
(** axclass instances **)
wenzelm@19246
   204
wenzelm@19246
   205
local
wenzelm@19246
   206
haftmann@20175
   207
fun gen_instance mk_prop add_thm after_qed insts thy =
wenzelm@20368
   208
  let
wenzelm@20368
   209
    fun after_qed' results =
wenzelm@20368
   210
      ProofContext.theory ((fold o fold) add_thm results #> after_qed);
wenzelm@20368
   211
  in
wenzelm@20368
   212
    thy
wenzelm@20368
   213
    |> ProofContext.init
wenzelm@20368
   214
    |> Proof.theorem_i PureThy.internalK NONE after_qed' NONE ("", [])
wenzelm@20368
   215
      ((map (fn t => (("", []), [(t, [])])) o maps (mk_prop thy)) insts)
wenzelm@20368
   216
  end;
wenzelm@19246
   217
wenzelm@19246
   218
in
wenzelm@19246
   219
wenzelm@19246
   220
val axclass_instance_arity =
wenzelm@19412
   221
  gen_instance (Logic.mk_arities oo Sign.read_arity) AxClass.add_arity;
wenzelm@19246
   222
val axclass_instance_arity_i =
wenzelm@19412
   223
  gen_instance (Logic.mk_arities oo Sign.cert_arity) AxClass.add_arity;
haftmann@20182
   224
val axclass_instance_sort =      
haftmann@20182
   225
  gen_instance (single oo (Logic.mk_classrel oo AxClass.read_classrel)) AxClass.add_classrel I o single;
wenzelm@19246
   226
wenzelm@19246
   227
end;
wenzelm@19246
   228
wenzelm@19246
   229
haftmann@20455
   230
haftmann@20455
   231
(** classes and instances **)
haftmann@19038
   232
haftmann@19038
   233
local
haftmann@19038
   234
haftmann@19957
   235
fun add_axclass_i (name, supsort) params axs thy =
haftmann@19110
   236
  let
wenzelm@19395
   237
    val (c, thy') = thy
haftmann@19957
   238
      |> AxClass.define_class_i (name, supsort) params axs;
wenzelm@19518
   239
    val {intro, axioms, ...} = AxClass.get_definition thy' c;
wenzelm@19395
   240
  in ((c, (intro, axioms)), thy') end;
haftmann@19110
   241
haftmann@20385
   242
(*FIXME proper locale interface*)
haftmann@19110
   243
fun prove_interpretation_i (prfx, atts) expr insts tac thy =
haftmann@19038
   244
  let
wenzelm@20368
   245
    fun ad_hoc_term (Const (c, ty)) =
haftmann@19110
   246
          let
haftmann@19110
   247
            val p = setmp show_types true (setmp show_sorts true (setmp print_mode [] (Sign.pretty_typ thy))) ty;
haftmann@19110
   248
            val s = c ^ "::" ^ Pretty.output p;
wenzelm@20368
   249
          in s end
wenzelm@20368
   250
      | ad_hoc_term t =
haftmann@19110
   251
          let
haftmann@19110
   252
            val p = setmp show_types true (setmp show_sorts true (setmp print_mode [] (Sign.pretty_term thy))) t;
haftmann@19110
   253
            val s = Pretty.output p;
wenzelm@20368
   254
          in s end;
haftmann@19110
   255
  in
haftmann@19110
   256
    thy
wenzelm@20368
   257
    |> Locale.interpretation I (prfx, atts) expr (map (Option.map ad_hoc_term) insts)
haftmann@19110
   258
    |> Proof.global_terminal_proof (Method.Basic (fn _ => Method.SIMPLE_METHOD tac), NONE)
wenzelm@20368
   259
    |> ProofContext.theory_of
haftmann@19110
   260
  end;
haftmann@19110
   261
haftmann@19150
   262
fun gen_class add_locale prep_class bname raw_supclasses raw_elems thy =
haftmann@19110
   263
  let
haftmann@20428
   264
    val (elems, exprs) = fold_rev (fn Locale.Elem e => apfst (cons e)
haftmann@20428
   265
                                   | Locale.Expr e => apsnd (cons e))
haftmann@20428
   266
      raw_elems ([], []);
haftmann@19110
   267
    val supclasses = map (prep_class thy) raw_supclasses;
haftmann@19038
   268
    val supsort =
haftmann@19038
   269
      supclasses
haftmann@19966
   270
      |> map (#name_axclass o fst o the_class_data thy)
wenzelm@19468
   271
      |> Sign.certify_sort thy
haftmann@19038
   272
      |> null ? K (Sign.defaultS thy);
haftmann@20428
   273
    val expr_supclasses = Locale.Merge
haftmann@20428
   274
      (map (Locale.Locale o #name_locale o fst o the_class_data thy) supclasses);
haftmann@20428
   275
    val expr = Locale.Merge (map (Locale.Locale o #name_locale o fst o the_class_data thy) supclasses
haftmann@20428
   276
      @ exprs);
haftmann@19280
   277
    val mapp_sup = AList.make
wenzelm@19468
   278
      (the o AList.lookup (op =) ((flat o map (the_parm_map thy) o the_ancestry thy) supclasses))
haftmann@20428
   279
      ((map (fst o fst) o Locale.parameters_of_expr thy) expr_supclasses);
haftmann@19038
   280
    fun extract_tyvar_consts thy name_locale =
haftmann@19038
   281
      let
haftmann@20175
   282
        fun extract_classvar ((c, ty), _) w =
haftmann@20428
   283
          (case Term.add_tfreesT ty []
haftmann@20175
   284
           of [(v, _)] => (case w
haftmann@20385
   285
               of SOME u => if u = v then w else error ("Additonal type variable in type signature of constant " ^ quote c)
haftmann@20175
   286
                | NONE => SOME v)
haftmann@20385
   287
            | [] => error ("No type variable in type signature of constant " ^ quote c)
haftmann@20385
   288
            | _ => error ("More than one type variable in type signature of constant " ^ quote c));
haftmann@19110
   289
        val consts1 =
haftmann@19038
   290
          Locale.parameters_of thy name_locale
haftmann@19038
   291
          |> map (apsnd Syntax.unlocalize_mixfix)
haftmann@20175
   292
        val SOME v = fold extract_classvar consts1 NONE;
haftmann@19110
   293
        val consts2 = map ((apfst o apsnd) (subst_clsvar v (TFree (v, [])))) consts1;
haftmann@19280
   294
      in (v, chop (length mapp_sup) consts2) end;
haftmann@19110
   295
    fun add_consts v raw_cs_sup raw_cs_this thy =
haftmann@19110
   296
      let
haftmann@19110
   297
        fun add_global_const ((c, ty), syn) thy =
wenzelm@20265
   298
          ((c, (Sign.full_name thy c, ty)),
wenzelm@20265
   299
            thy
wenzelm@20265
   300
            |> Sign.add_consts_i [(c, ty |> subst_clsvar v (TFree (v, Sign.defaultS thy)), syn)]);
haftmann@19110
   301
      in
haftmann@19110
   302
        thy
haftmann@19110
   303
        |> fold_map add_global_const raw_cs_this
haftmann@19110
   304
      end;
haftmann@19110
   305
    fun extract_assumes thy name_locale cs_mapp =
haftmann@19110
   306
      let
haftmann@19110
   307
        val subst_assume =
haftmann@19110
   308
          map_aterms (fn Free (c, ty) => Const ((fst o the o AList.lookup (op =) cs_mapp) c, ty)
haftmann@19110
   309
                       | t => t)
haftmann@19110
   310
        fun prep_asm ((name, atts), ts) =
haftmann@19957
   311
          ((NameSpace.base name, map (Attrib.attribute thy) atts), map subst_assume ts)
haftmann@19110
   312
      in
haftmann@19110
   313
        (map prep_asm o Locale.local_asms_of thy) name_locale
haftmann@19110
   314
      end;
haftmann@19280
   315
    fun add_global_constraint v class (_, (c, ty)) thy =
haftmann@19038
   316
      thy
haftmann@19136
   317
      |> Sign.add_const_constraint_i (c, SOME (subst_clsvar v (TFree (v, [class])) ty));
haftmann@19110
   318
    fun mk_const thy class v (c, ty) =
haftmann@19110
   319
      Const (c, subst_clsvar v (TFree (v, [class])) ty);
haftmann@19038
   320
  in
haftmann@19038
   321
    thy
haftmann@20428
   322
    |> add_locale bname expr elems
haftmann@19928
   323
    |-> (fn (name_locale, ctxt) =>
haftmann@19038
   324
          `(fn thy => extract_tyvar_consts thy name_locale)
haftmann@19110
   325
    #-> (fn (v, (raw_cs_sup, raw_cs_this)) =>
haftmann@19110
   326
          add_consts v raw_cs_sup raw_cs_this
haftmann@19280
   327
    #-> (fn mapp_this =>
haftmann@19280
   328
          `(fn thy => extract_assumes thy name_locale (mapp_sup @ mapp_this))
haftmann@19110
   329
    #-> (fn loc_axioms =>
haftmann@19957
   330
          add_axclass_i (bname, supsort) (map (fst o snd) mapp_this) loc_axioms
haftmann@19110
   331
    #-> (fn (name_axclass, (_, ax_axioms)) =>
haftmann@19280
   332
          fold (add_global_constraint v name_axclass) mapp_this
haftmann@19966
   333
    #> add_class_data (name_locale, (name_locale, name_axclass, v, mapp_this,
haftmann@19966
   334
         map (fst o fst) loc_axioms))
haftmann@19110
   335
    #> prove_interpretation_i (NameSpace.base name_locale, [])
haftmann@19280
   336
          (Locale.Locale name_locale) (map (SOME o mk_const thy name_axclass v) (map snd (mapp_sup @ mapp_this)))
haftmann@19929
   337
          ((ALLGOALS o ProofContext.fact_tac) ax_axioms)
haftmann@19110
   338
    #> pair ctxt
haftmann@19110
   339
    )))))
haftmann@19038
   340
  end;
haftmann@19038
   341
haftmann@19038
   342
in
haftmann@19038
   343
haftmann@20385
   344
val class = gen_class (Locale.add_locale false) read_class;
haftmann@19928
   345
val class_i = gen_class (Locale.add_locale_i false) certify_class;
haftmann@19038
   346
haftmann@20455
   347
end; (*local*)
haftmann@19038
   348
haftmann@19110
   349
local
haftmann@19110
   350
haftmann@20175
   351
fun gen_read_def thy prep_att read_def ((raw_name, raw_atts), raw_t) =
haftmann@19038
   352
  let
haftmann@19957
   353
    val (_, t) = read_def thy (raw_name, raw_t);
haftmann@19957
   354
    val ((c, ty), _) = Sign.cert_def (Sign.pp thy) t;
haftmann@19957
   355
    val atts = map (prep_att thy) raw_atts;
haftmann@20175
   356
    val insts = (Consts.typargs (Sign.consts_of thy) (c, ty))
haftmann@19957
   357
    val name = case raw_name
haftmann@20385
   358
     of "" => NONE
haftmann@20385
   359
      | _ => SOME raw_name;
haftmann@20175
   360
  in (c, (insts, ((name, t), atts))) end;
haftmann@19110
   361
haftmann@19957
   362
fun read_def thy = gen_read_def thy Attrib.attribute read_axm;
haftmann@19957
   363
fun read_def_i thy = gen_read_def thy (K I) (K I);
haftmann@19110
   364
haftmann@20175
   365
fun gen_instance_arity prep_arity prep_att read_def do_proof raw_arities (raw_name, raw_atts) raw_defs theory =
haftmann@19110
   366
  let
haftmann@20175
   367
    fun prep_arity' ((tyco, asorts), sort) = prep_arity theory (tyco, asorts, sort);
haftmann@20175
   368
    val arities = map prep_arity' raw_arities;
haftmann@20175
   369
    val arities_pair = map (fn (tyco, asorts, sort) => ((tyco, asorts), sort)) arities;
haftmann@20175
   370
    val _ = if null arities then error "at least one arity must be given" else ();
haftmann@20175
   371
    val _ = case (duplicates (op =) o map #1) arities
haftmann@20175
   372
     of [] => ()
haftmann@20175
   373
      | dupl_tycos => error ("type constructors occur more than once in arities: "
haftmann@20175
   374
        ^ (commas o map quote) dupl_tycos);
haftmann@20393
   375
    val (bind_always, name) = case raw_name
haftmann@20393
   376
     of "" => (false, Thm.def_name ((space_implode "_" o map NameSpace.base)
haftmann@20175
   377
                (maps (fn (tyco, _, sort) => sort @ [tyco])
haftmann@20393
   378
                (sort (fn ((tyco1, _, _), (tyco2, _, _)) => string_ord (tyco1, tyco2)) arities))))
haftmann@20393
   379
      | _ => (true, raw_name);
haftmann@19136
   380
    val atts = map (prep_att theory) raw_atts;
haftmann@20175
   381
    fun already_defined (c, ty_inst) = 
haftmann@20175
   382
      is_some (find_first (fn (_, { lhs = [ty_inst'], ...}) =>
haftmann@20175
   383
          Sign.typ_instance theory (ty_inst', ty_inst) orelse Sign.typ_instance theory (ty_inst, ty_inst'))
haftmann@20175
   384
        (Defs.specifications_of (Theory.defs_of theory) c));
haftmann@20175
   385
    fun get_consts_class tyco ty class =
haftmann@19110
   386
      let
haftmann@19966
   387
        val data = (fst o the_class_data theory) class;
haftmann@19957
   388
        val subst_ty = map_type_tfree (fn (v, sort) =>
haftmann@20175
   389
          if #var data = v then ty else TVar ((v, 0), sort));
haftmann@19957
   390
      in
haftmann@19957
   391
        (map_filter (fn (_, (c, ty)) =>
haftmann@20175
   392
          if already_defined (c, ty)
haftmann@20175
   393
          then NONE else SOME ((c, ((tyco, class), subst_ty ty)))) o #consts) data
haftmann@19957
   394
      end;
haftmann@20175
   395
    fun get_consts_sort (tyco, asorts, sort) =
haftmann@19957
   396
      let
haftmann@20192
   397
        val ty = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) (Name.names Name.context "'a" asorts))
haftmann@20175
   398
      in maps (get_consts_class tyco ty) (the_ancestry theory sort) end;
haftmann@20175
   399
    val cs = maps get_consts_sort arities;
haftmann@20385
   400
    fun mk_typnorm thy (ty, ty_sc) =
haftmann@20385
   401
      case try (Sign.typ_match thy (Logic.varifyT ty_sc, ty)) Vartab.empty
haftmann@20385
   402
       of SOME env => SOME (Logic.varifyT #> Envir.typ_subst_TVars env #> Logic.unvarifyT)
haftmann@20385
   403
        | NONE => NONE;
haftmann@20175
   404
    fun read_defs defs cs thy_read =
haftmann@20175
   405
      let
haftmann@19957
   406
        fun read raw_def cs =
haftmann@19957
   407
          let
haftmann@20385
   408
            val (c, (inst, ((name_opt, t), atts))) = read_def thy_read raw_def;
haftmann@20385
   409
            val ty = Consts.instance (Sign.consts_of thy_read) (c, inst);
haftmann@20175
   410
            val ((tyco, class), ty') = case AList.lookup (op =) cs c
haftmann@19957
   411
             of NONE => error ("superfluous definition for constant " ^ quote c)
haftmann@19966
   412
              | SOME class_ty => class_ty;
haftmann@20385
   413
            val name = case name_opt
haftmann@20385
   414
             of NONE => Thm.def_name (NameSpace.base c ^ "_" ^ NameSpace.base tyco)
haftmann@20385
   415
              | SOME name => name;
haftmann@20385
   416
            val t' = case mk_typnorm thy_read (ty', ty)
haftmann@19966
   417
             of NONE => error ("superfluous definition for constant " ^
haftmann@19966
   418
                  quote c ^ "::" ^ Sign.string_of_typ thy_read ty)
wenzelm@20548
   419
              | SOME norm => map_types norm t
haftmann@20175
   420
          in (((class, tyco), ((name, t'), atts)), AList.delete (op =) c cs) end;
haftmann@19957
   421
      in fold_map read defs cs end;
haftmann@20175
   422
    val (defs, _) = assume_arities_thy theory arities_pair (read_defs raw_defs cs);
haftmann@19110
   423
    fun get_remove_contraint c thy =
haftmann@19110
   424
      let
haftmann@19110
   425
        val ty = Sign.the_const_constraint thy c;
haftmann@19110
   426
      in
haftmann@19110
   427
        thy
haftmann@19110
   428
        |> Sign.add_const_constraint_i (c, NONE)
haftmann@20385
   429
        |> pair (c, Logic.unvarifyT ty)
haftmann@19110
   430
      end;
haftmann@19966
   431
    fun add_defs defs thy =
haftmann@19966
   432
      thy
haftmann@19966
   433
      |> PureThy.add_defs_i true (map snd defs)
haftmann@19966
   434
      |-> (fn thms => pair (map fst defs ~~ thms));
haftmann@19966
   435
    fun note_all thy =
haftmann@20175
   436
      (*FIXME: should avoid binding duplicated names*)
haftmann@19966
   437
      let
haftmann@20393
   438
        val bind = bind_always orelse not (can (PureThy.get_thms thy) (Name name));
haftmann@20175
   439
        val thms = maps (fn (tyco, _, sort) => maps (fn class =>
haftmann@20175
   440
          Symtab.lookup_list
haftmann@20175
   441
            ((snd o the_class_data thy) class) tyco) (the_ancestry thy sort)) arities;
haftmann@20393
   442
      in if bind then
haftmann@19966
   443
        thy
haftmann@19966
   444
        |> PureThy.note_thmss_i PureThy.internalK [((name, atts), [(thms, [])])]
haftmann@19966
   445
        |> snd
haftmann@20393
   446
      else
haftmann@20393
   447
        thy
haftmann@19966
   448
      end;
haftmann@19110
   449
    fun after_qed cs thy =
haftmann@19110
   450
      thy
wenzelm@19412
   451
      |> fold Sign.add_const_constraint_i (map (apsnd SOME) cs);
haftmann@19038
   452
  in
haftmann@19110
   453
    theory
haftmann@20385
   454
    |> fold_map get_remove_contraint (map fst cs |> distinct (op =))
haftmann@19966
   455
    ||>> add_defs defs
wenzelm@20076
   456
    |-> (fn (cs, def_thms) =>
haftmann@20175
   457
       fold add_inst_def def_thms
haftmann@19966
   458
    #> note_all
haftmann@20182
   459
    #> do_proof (map snd def_thms) (after_qed cs) arities)
haftmann@19038
   460
  end;
haftmann@19038
   461
haftmann@19957
   462
fun instance_arity' do_proof = gen_instance_arity Sign.read_arity Attrib.attribute
haftmann@19957
   463
  read_def do_proof;
haftmann@19957
   464
fun instance_arity_i' do_proof = gen_instance_arity Sign.cert_arity (K I)
haftmann@19957
   465
  read_def_i do_proof;
haftmann@20182
   466
fun tactic_proof tac def_thms after_qed arities =
haftmann@20182
   467
  fold (fn arity => AxClass.prove_arity arity (tac def_thms)) arities
haftmann@20175
   468
  #> after_qed;
haftmann@19110
   469
haftmann@19110
   470
in
haftmann@19110
   471
haftmann@20182
   472
val instance_arity = instance_arity' (K axclass_instance_arity_i);
haftmann@20182
   473
val instance_arity_i = instance_arity_i' (K axclass_instance_arity_i);
haftmann@19150
   474
val prove_instance_arity = instance_arity_i' o tactic_proof;
haftmann@19110
   475
haftmann@20455
   476
end; (*local*)
haftmann@19110
   477
haftmann@19110
   478
local
haftmann@19110
   479
wenzelm@20368
   480
fun prove_interpretation_in tac after_qed (name, expr) thy =
haftmann@19136
   481
  thy
wenzelm@20368
   482
  |> Locale.interpretation_in_locale (ProofContext.theory after_qed) (name, expr)
haftmann@19136
   483
  |> Proof.global_terminal_proof (Method.Basic (fn _ => Method.SIMPLE_METHOD tac), NONE)
wenzelm@20368
   484
  |> ProofContext.theory_of;
haftmann@19038
   485
haftmann@20385
   486
(*FIXME very ad-hoc, needs proper locale interface*)
haftmann@19150
   487
fun gen_instance_sort prep_class prep_sort do_proof (raw_class, raw_sort) theory =
haftmann@19110
   488
  let
haftmann@19110
   489
    val class = prep_class theory raw_class;
haftmann@19110
   490
    val sort = prep_sort theory raw_sort;
haftmann@19966
   491
    val loc_name = (#name_locale o fst o the_class_data theory) class;
wenzelm@19468
   492
    val loc_expr =
haftmann@19966
   493
      (Locale.Merge o map (Locale.Locale o #name_locale o fst o the_class_data theory)) sort;
haftmann@19966
   494
    val const_names = (map (NameSpace.base o fst o snd)
haftmann@19966
   495
      o maps (#consts o fst o the_class_data theory)
haftmann@19966
   496
      o the_ancestry theory) [class];
haftmann@20106
   497
    fun get_thms thy =
haftmann@20106
   498
      the_ancestry thy sort
haftmann@20106
   499
      |> AList.make (the_propnames thy)
haftmann@20106
   500
      |> map (apsnd (map (NameSpace.append (loc_name))))
haftmann@20106
   501
      |> map_filter (fn (superclass, thm_names) =>
haftmann@20106
   502
          case map_filter (try (PureThy.get_thm thy o Name)) thm_names
haftmann@20106
   503
           of [] => NONE
haftmann@20106
   504
            | thms => SOME (superclass, thms));
haftmann@20106
   505
    fun after_qed thy =
haftmann@20106
   506
      thy
haftmann@20106
   507
      |> `get_thms
haftmann@20106
   508
      |-> fold (fn (supclass, thms) => I
haftmann@20106
   509
            AxClass.prove_classrel (class, supclass)
haftmann@20106
   510
              (ALLGOALS (K (intro_classes_tac [])) THEN
haftmann@20106
   511
                (ALLGOALS o ProofContext.fact_tac) thms))
haftmann@19110
   512
  in
haftmann@19110
   513
    theory
haftmann@19136
   514
    |> do_proof after_qed (loc_name, loc_expr)
haftmann@19110
   515
  end;
haftmann@19110
   516
haftmann@20385
   517
fun instance_sort' do_proof = gen_instance_sort read_class read_sort do_proof;
haftmann@19150
   518
fun instance_sort_i' do_proof = gen_instance_sort certify_class certify_sort do_proof;
wenzelm@20368
   519
val setup_proof = Locale.interpretation_in_locale o ProofContext.theory;
haftmann@19136
   520
val tactic_proof = prove_interpretation_in;
haftmann@19110
   521
haftmann@19110
   522
in
haftmann@19110
   523
haftmann@19150
   524
val instance_sort = instance_sort' setup_proof;
haftmann@19150
   525
val instance_sort_i = instance_sort_i' setup_proof;
haftmann@19150
   526
val prove_instance_sort = instance_sort_i' o tactic_proof;
haftmann@19110
   527
haftmann@19110
   528
end; (* local *)
haftmann@19038
   529
haftmann@19957
   530
haftmann@18168
   531
haftmann@20455
   532
(** code generation view **)
haftmann@18168
   533
haftmann@20455
   534
fun operational_algebra thy =
haftmann@20455
   535
  Sorts.project_algebra (Sign.pp thy)
haftmann@20455
   536
    (is_operational_class thy) (Sign.classes_of thy);
haftmann@18168
   537
haftmann@20455
   538
fun the_consts_sign thy class =
haftmann@20455
   539
  let
haftmann@20455
   540
    val _ = if is_operational_class thy class then () else error ("no operational class: " ^ quote class);
haftmann@20455
   541
    val data = (fst o the_class_data thy) class
haftmann@20455
   542
  in (#var data, (map snd o #consts) data) end;
haftmann@19213
   543
haftmann@20455
   544
fun the_inst_sign thy (class, tyco) =
haftmann@18168
   545
  let
haftmann@20455
   546
    val _ = if is_operational_class thy class then () else error ("no operational class: " ^ quote class);
haftmann@20455
   547
    val asorts = Sign.arity_sorts thy tyco [class];
haftmann@20455
   548
    val (clsvar, const_sign) = the_consts_sign thy class;
haftmann@20455
   549
    fun add_var sort used =
haftmann@20455
   550
      let val v = hd (Name.invents used "'a" 1);
haftmann@20455
   551
      in ((v, sort), Name.declare v used) end;
haftmann@20455
   552
    val (vsorts, _) =
haftmann@20455
   553
      Name.context
haftmann@20455
   554
      |> Name.declare clsvar
haftmann@20455
   555
      |> fold (fn (_, ty) => fold Name.declare
haftmann@20455
   556
           ((map (fst o fst) o typ_tvars) ty @ map fst (Term.add_tfreesT  ty []))) const_sign
haftmann@20455
   557
      |> fold_map add_var asorts;
haftmann@20455
   558
    val ty_inst = Type (tyco, map TFree vsorts);
haftmann@20455
   559
    val inst_signs = map (apsnd (subst_clsvar clsvar ty_inst)) const_sign;
haftmann@20455
   560
  in (vsorts, inst_signs) end;
haftmann@18168
   561
haftmann@18884
   562
haftmann@20455
   563
haftmann@20455
   564
(** toplevel interface **)
haftmann@18515
   565
haftmann@18515
   566
local
haftmann@18515
   567
haftmann@18515
   568
structure P = OuterParse
haftmann@18515
   569
and K = OuterKeyword
haftmann@18515
   570
haftmann@18515
   571
in
haftmann@18515
   572
haftmann@20385
   573
val (classK, instanceK, print_classesK) = ("class", "instance", "print_classes")
haftmann@18515
   574
haftmann@20385
   575
fun wrap_add_instance_sort (class, sort) thy =
haftmann@20385
   576
  (if forall (is_some o lookup_class_data thy) (Sign.read_sort thy sort)
haftmann@20385
   577
  then instance_sort else axclass_instance_sort) (class, sort) thy;
haftmann@19136
   578
haftmann@20385
   579
val class_subP = P.name -- Scan.repeat (P.$$$ "+" |-- P.name) >> (op ::);
haftmann@20428
   580
val class_bodyP = P.!!! (Scan.repeat1 P.locale_element);
haftmann@20385
   581
haftmann@20385
   582
val inst =
haftmann@19136
   583
  (Scan.optional (P.$$$ "(" |-- P.!!! (P.list1 P.sort --| P.$$$ ")")) [] -- P.xname --| P.$$$ "::" -- P.sort)
haftmann@19136
   584
    >> (fn ((asorts, tyco), sort) => ((tyco, asorts), sort))
haftmann@19136
   585
  || (P.xname --| P.$$$ "::" -- P.!!! P.arity)
haftmann@19136
   586
    >> (fn (tyco, (asorts, sort)) => ((tyco, asorts), sort));
haftmann@18911
   587
haftmann@18515
   588
val classP =
haftmann@20385
   589
  OuterSyntax.command classK "define operational type class" K.thy_decl (
haftmann@18849
   590
    P.name --| P.$$$ "="
haftmann@19280
   591
    -- (
haftmann@19280
   592
      class_subP --| P.$$$ "+" -- class_bodyP
haftmann@19280
   593
      || class_subP >> rpair []
haftmann@19280
   594
      || class_bodyP >> pair []
haftmann@19280
   595
    ) >> (Toplevel.theory_context
haftmann@19280
   596
          o (fn (bname, (supclasses, elems)) => class bname supclasses elems)));
haftmann@18515
   597
haftmann@18575
   598
val instanceP =
haftmann@18849
   599
  OuterSyntax.command instanceK "prove type arity or subclass relation" K.thy_goal ((
haftmann@20385
   600
      P.xname -- ((P.$$$ "\\<subseteq>" || P.$$$ "<") |-- P.!!! P.xname) >> wrap_add_instance_sort
haftmann@20385
   601
      || P.opt_thm_name ":" -- (P.and_list1 inst -- Scan.repeat (P.opt_thm_name ":" -- P.prop))
haftmann@20175
   602
           >> (fn (("", []), ([((tyco, asorts), sort)], [])) => axclass_instance_arity I [(tyco, asorts, sort)]
haftmann@20175
   603
                | (natts, (arities, defs)) => instance_arity arities natts defs)
haftmann@18849
   604
    ) >> (Toplevel.print oo Toplevel.theory_to_proof));
haftmann@18575
   605
haftmann@20385
   606
val print_classesP =
haftmann@20385
   607
  OuterSyntax.improper_command print_classesK "print classes of this theory" K.diag
haftmann@20385
   608
    (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_theory
haftmann@20385
   609
      o Toplevel.keep (print_classes o Toplevel.theory_of)));
haftmann@20385
   610
haftmann@20385
   611
val _ = OuterSyntax.add_parsers [classP, instanceP, print_classesP];
haftmann@19110
   612
haftmann@20455
   613
end; (*local*)
haftmann@18515
   614
haftmann@20455
   615
end;