src/Pure/Isar/class.ML
author haftmann
Fri Nov 30 20:13:08 2007 +0100 (2007-11-30)
changeset 25514 4b508bb31a6c
parent 25502 9200b36280c0
child 25518 00d5cc16e891
permissions -rw-r--r--
first working version of instance target
     1 (*  Title:      Pure/Isar/class.ML
     2     ID:         $Id$
     3     Author:     Florian Haftmann, TU Muenchen
     4 
     5 Type classes derived from primitive axclasses and locales.
     6 *)
     7 
     8 signature CLASS =
     9 sig
    10   (*classes*)
    11   val class: bstring -> class list -> Element.context_i Locale.element list
    12     -> string list -> theory -> string * Proof.context
    13   val class_cmd: bstring -> xstring list -> Element.context Locale.element list
    14     -> xstring list -> theory -> string * Proof.context
    15 
    16   val init: class -> theory -> Proof.context
    17   val logical_const: string -> Markup.property list
    18     -> (string * mixfix) * term -> theory -> theory
    19   val syntactic_const: string -> Syntax.mode -> Markup.property list
    20     -> (string * mixfix) * term -> theory -> theory
    21   val refresh_syntax: class -> Proof.context -> Proof.context
    22 
    23   val intro_classes_tac: thm list -> tactic
    24   val default_intro_classes_tac: thm list -> tactic
    25   val prove_subclass: class * class -> thm list -> Proof.context
    26     -> theory -> theory
    27 
    28   val class_prefix: string -> string
    29   val is_class: theory -> class -> bool
    30   val these_params: theory -> sort -> (string * (string * typ)) list
    31   val print_classes: theory -> unit
    32 
    33   (*instances*)
    34   val init_instantiation: arity list -> theory -> local_theory
    35   val instantiation_instance: (local_theory -> local_theory) -> local_theory -> Proof.state
    36   val prove_instantiation_instance: (Proof.context -> tactic) -> local_theory -> local_theory
    37   val conclude_instantiation: local_theory -> local_theory
    38 
    39   val overloaded_const: string * typ * mixfix -> theory -> term * theory
    40   val overloaded_def: string -> string * term -> theory -> thm * theory
    41   val instantiation_param: Proof.context -> string -> string option
    42   val confirm_declaration: string -> local_theory -> local_theory
    43 
    44   val unoverload: theory -> thm -> thm
    45   val overload: theory -> thm -> thm
    46   val unoverload_conv: theory -> conv
    47   val overload_conv: theory -> conv
    48   val unoverload_const: theory -> string * typ -> string
    49   val param_of_inst: theory -> string * string -> string
    50   val inst_of_param: theory -> string -> (string * string) option
    51 
    52   (*old axclass layer*)
    53   val axclass_cmd: bstring * xstring list
    54     -> ((bstring * Attrib.src list) * string list) list
    55     -> theory -> class * theory
    56   val classrel_cmd: xstring * xstring -> theory -> Proof.state
    57 
    58   (*old instance layer*)
    59   val instance_arity: (theory -> theory) -> arity list -> theory -> Proof.state
    60   val instance_arity_cmd: (bstring * xstring list * xstring) list -> theory -> Proof.state
    61 end;
    62 
    63 structure Class : CLASS =
    64 struct
    65 
    66 (** auxiliary **)
    67 
    68 val classN = "class";
    69 val introN = "intro";
    70 
    71 fun prove_interpretation tac prfx_atts expr inst =
    72   Locale.interpretation_i I prfx_atts expr inst
    73   #> Proof.global_terminal_proof
    74       (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
    75   #> ProofContext.theory_of;
    76 
    77 fun prove_interpretation_in tac after_qed (name, expr) =
    78   Locale.interpretation_in_locale
    79       (ProofContext.theory after_qed) (name, expr)
    80   #> Proof.global_terminal_proof
    81       (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
    82   #> ProofContext.theory_of;
    83 
    84 fun OF_LAST thm1 thm2 = thm1 RSN (Thm.nprems_of thm2, thm2);
    85 
    86 fun strip_all_ofclass thy sort =
    87   let
    88     val typ = TVar ((Name.aT, 0), sort);
    89     fun prem_inclass t =
    90       case Logic.strip_imp_prems t
    91        of ofcls :: _ => try Logic.dest_inclass ofcls
    92         | [] => NONE;
    93     fun strip_ofclass class thm =
    94       thm OF (fst o AxClass.of_sort thy (typ, [class])) AxClass.cache;
    95     fun strip thm = case (prem_inclass o Thm.prop_of) thm
    96      of SOME (_, class) => thm |> strip_ofclass class |> strip
    97       | NONE => thm;
    98   in strip end;
    99 
   100 fun get_remove_global_constraint c thy =
   101   let
   102     val ty = Sign.the_const_constraint thy c;
   103   in
   104     thy
   105     |> Sign.add_const_constraint (c, NONE)
   106     |> pair (c, Logic.unvarifyT ty)
   107   end;
   108 
   109 
   110 (** primitive axclass and instance commands **)
   111 
   112 fun axclass_cmd (class, raw_superclasses) raw_specs thy =
   113   let
   114     val ctxt = ProofContext.init thy;
   115     val superclasses = map (Sign.read_class thy) raw_superclasses;
   116     val name_atts = map ((apsnd o map) (Attrib.attribute thy) o fst)
   117       raw_specs;
   118     val axiomss = ProofContext.read_propp (ctxt, map (map (rpair []) o snd)
   119           raw_specs)
   120       |> snd
   121       |> (map o map) fst;
   122   in
   123     AxClass.define_class (class, superclasses) []
   124       (name_atts ~~ axiomss) thy
   125   end;
   126 
   127 local
   128 
   129 fun gen_instance mk_prop add_thm after_qed insts thy =
   130   let
   131     fun after_qed' results =
   132       ProofContext.theory ((fold o fold) add_thm results #> after_qed);
   133   in
   134     thy
   135     |> ProofContext.init
   136     |> Proof.theorem_i NONE after_qed' ((map (fn t => [(t, [])])
   137         o maps (mk_prop thy)) insts)
   138   end;
   139 
   140 in
   141 
   142 val instance_arity =
   143   gen_instance (Logic.mk_arities oo Sign.cert_arity) AxClass.add_arity;
   144 val instance_arity_cmd =
   145   gen_instance (Logic.mk_arities oo Sign.read_arity) AxClass.add_arity I;
   146 val classrel =
   147   gen_instance (single oo (Logic.mk_classrel oo AxClass.cert_classrel))
   148     AxClass.add_classrel I o single;
   149 val classrel_cmd =
   150   gen_instance (single oo (Logic.mk_classrel oo AxClass.read_classrel))
   151     AxClass.add_classrel I o single;
   152 
   153 end; (*local*)
   154 
   155 
   156 (** basic overloading **)
   157 
   158 (* bookkeeping *)
   159 
   160 structure InstData = TheoryDataFun
   161 (
   162   type T = (string * thm) Symtab.table Symtab.table * (string * string) Symtab.table;
   163     (*constant name ~> type constructor ~> (constant name, equation),
   164         constant name ~> (constant name, type constructor)*)
   165   val empty = (Symtab.empty, Symtab.empty);
   166   val copy = I;
   167   val extend = I;
   168   fun merge _ ((taba1, tabb1), (taba2, tabb2)) =
   169     (Symtab.join (K (Symtab.merge (K true))) (taba1, taba2),
   170       Symtab.merge (K true) (tabb1, tabb2));
   171 );
   172 
   173 val inst_tyco = Option.map fst o try (dest_Type o the_single) oo Sign.const_typargs;
   174 
   175 fun inst thy (c, tyco) =
   176   (the o Symtab.lookup ((the o Symtab.lookup (fst (InstData.get thy))) c)) tyco;
   177 
   178 val param_of_inst = fst oo inst;
   179 
   180 fun inst_thms thy = (Symtab.fold (Symtab.fold (cons o snd o snd) o snd) o fst)
   181   (InstData.get thy) [];
   182 
   183 val inst_of_param = Symtab.lookup o snd o InstData.get;
   184 
   185 fun add_inst (c, tyco) inst = (InstData.map o apfst
   186       o Symtab.map_default (c, Symtab.empty)) (Symtab.update_new (tyco, inst))
   187   #> (InstData.map o apsnd) (Symtab.update_new (fst inst, (c, tyco)));
   188 
   189 fun unoverload thy = MetaSimplifier.simplify true (inst_thms thy);
   190 fun overload thy = MetaSimplifier.simplify true (map Thm.symmetric (inst_thms thy));
   191 
   192 fun unoverload_conv thy = MetaSimplifier.rewrite true (inst_thms thy);
   193 fun overload_conv thy = MetaSimplifier.rewrite true (map Thm.symmetric (inst_thms thy));
   194 
   195 fun unoverload_const thy (c_ty as (c, _)) =
   196   case AxClass.class_of_param thy c
   197    of SOME class => (case inst_tyco thy c_ty
   198        of SOME tyco => try (param_of_inst thy) (c, tyco) |> the_default c
   199         | NONE => c)
   200     | NONE => c;
   201 
   202 
   203 (* declaration and definition of instances of overloaded constants *)
   204 
   205 fun primitive_note kind (name, thm) =
   206   PureThy.note_thmss_i kind [((name, []), [([thm], [])])]
   207   #>> (fn [(_, [thm])] => thm);
   208 
   209 fun overloaded_const (c, ty, mx) thy =
   210   let
   211     val _ = if mx <> NoSyn then
   212       error ("Illegal mixfix syntax for constant to be instantiated " ^ quote c)
   213       else ();
   214     val SOME class = AxClass.class_of_param thy c;
   215     val SOME tyco = inst_tyco thy (c, ty);
   216     val name_inst = AxClass.instance_name (tyco, class) ^ "_inst";
   217     val c' = NameSpace.base c ^ "_" ^ NameSpace.base tyco;
   218     val ty' = Type.strip_sorts ty;
   219   in
   220     thy
   221     |> Sign.sticky_prefix name_inst
   222     |> Sign.no_base_names
   223     |> Sign.declare_const [] (c', ty', NoSyn)
   224     |-> (fn const' as Const (c'', _) => Thm.add_def true
   225           (Thm.def_name c', Logic.mk_equals (Const (c, ty'), const'))
   226     #>> Thm.varifyT
   227     #-> (fn thm => add_inst (c, tyco) (c'', thm)
   228     #> primitive_note Thm.internalK (c', thm)
   229     #> snd
   230     #> Sign.restore_naming thy
   231     #> pair (Const (c, ty))))
   232   end;
   233 
   234 fun overloaded_def name (c, t) thy =
   235   let
   236     val ty = Term.fastype_of t;
   237     val SOME tyco = inst_tyco thy (c, ty);
   238     val (c', eq) = inst thy (c, tyco);
   239     val prop = Logic.mk_equals (Const (c', ty), t);
   240     val name' = Thm.def_name_optional
   241       (NameSpace.base c ^ "_" ^ NameSpace.base tyco) name;
   242   in
   243     thy
   244     |> Thm.add_def false (name', prop)
   245     |>> (fn thm =>  Drule.transitive_thm OF [eq, thm])
   246   end;
   247 
   248 
   249 (** class data **)
   250 
   251 datatype class_data = ClassData of {
   252   consts: (string * string) list
   253     (*locale parameter ~> constant name*),
   254   base_sort: sort,
   255   inst: term option list
   256     (*canonical interpretation*),
   257   morphism: morphism,
   258     (*partial morphism of canonical interpretation*)
   259   intro: thm,
   260   defs: thm list,
   261   operations: (string * (class * (typ * term))) list
   262 };
   263 
   264 fun rep_class_data (ClassData d) = d;
   265 fun mk_class_data ((consts, base_sort, inst, morphism, intro),
   266     (defs, operations)) =
   267   ClassData { consts = consts, base_sort = base_sort, inst = inst,
   268     morphism = morphism, intro = intro, defs = defs,
   269     operations = operations };
   270 fun map_class_data f (ClassData { consts, base_sort, inst, morphism, intro,
   271     defs, operations }) =
   272   mk_class_data (f ((consts, base_sort, inst, morphism, intro),
   273     (defs, operations)));
   274 fun merge_class_data _ (ClassData { consts = consts,
   275     base_sort = base_sort, inst = inst, morphism = morphism, intro = intro,
   276     defs = defs1, operations = operations1 },
   277   ClassData { consts = _, base_sort = _, inst = _, morphism = _, intro = _,
   278     defs = defs2, operations = operations2 }) =
   279   mk_class_data ((consts, base_sort, inst, morphism, intro),
   280     (Thm.merge_thms (defs1, defs2),
   281       AList.merge (op =) (K true) (operations1, operations2)));
   282 
   283 structure ClassData = TheoryDataFun
   284 (
   285   type T = class_data Graph.T
   286   val empty = Graph.empty;
   287   val copy = I;
   288   val extend = I;
   289   fun merge _ = Graph.join merge_class_data;
   290 );
   291 
   292 
   293 (* queries *)
   294 
   295 val lookup_class_data = Option.map rep_class_data oo try o Graph.get_node o ClassData.get;
   296 
   297 fun the_class_data thy class = case lookup_class_data thy class
   298  of NONE => error ("Undeclared class " ^ quote class)
   299   | SOME data => data;
   300 
   301 val is_class = is_some oo lookup_class_data;
   302 
   303 val ancestry = Graph.all_succs o ClassData.get;
   304 
   305 fun these_params thy =
   306   let
   307     fun params class =
   308       let
   309         val const_typs = (#params o AxClass.get_info thy) class;
   310         val const_names = (#consts o the_class_data thy) class;
   311       in
   312         (map o apsnd) (fn c => (c, (the o AList.lookup (op =) const_typs) c)) const_names
   313       end;
   314   in maps params o ancestry thy end;
   315 
   316 fun these_defs thy = maps (these o Option.map #defs o lookup_class_data thy) o ancestry thy;
   317 
   318 fun morphism thy = #morphism o the_class_data thy;
   319 
   320 fun these_intros thy =
   321   Graph.fold (fn (_, (data, _)) => insert Thm.eq_thm ((#intro o rep_class_data) data))
   322     (ClassData.get thy) [];
   323 
   324 fun these_operations thy =
   325   maps (#operations o the_class_data thy) o ancestry thy;
   326 
   327 fun print_classes thy =
   328   let
   329     val ctxt = ProofContext.init thy;
   330     val algebra = Sign.classes_of thy;
   331     val arities =
   332       Symtab.empty
   333       |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
   334            Symtab.map_default (class, []) (insert (op =) tyco)) arities)
   335              ((#arities o Sorts.rep_algebra) algebra);
   336     val the_arities = these o Symtab.lookup arities;
   337     fun mk_arity class tyco =
   338       let
   339         val Ss = Sorts.mg_domain algebra tyco [class];
   340       in Syntax.pretty_arity ctxt (tyco, Ss, [class]) end;
   341     fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
   342       ^ setmp show_sorts false (Syntax.string_of_typ ctxt o Type.strip_sorts) ty);
   343     fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
   344       (SOME o Pretty.str) ("class " ^ Sign.extern_class thy class ^ ":"),
   345       (SOME o Pretty.block) [Pretty.str "supersort: ",
   346         (Syntax.pretty_sort ctxt o Sign.minimize_sort thy o Sign.super_classes thy) class],
   347       if is_class thy class then (SOME o Pretty.str)
   348         ("locale: " ^ Locale.extern thy class) else NONE,
   349       ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks)
   350           (Pretty.str "parameters:" :: ps)) o map mk_param
   351         o these o Option.map #params o try (AxClass.get_info thy)) class,
   352       (SOME o Pretty.block o Pretty.breaks) [
   353         Pretty.str "instances:",
   354         Pretty.list "" "" (map (mk_arity class) (the_arities class))
   355       ]
   356     ]
   357   in
   358     (Pretty.writeln o Pretty.chunks o separate (Pretty.str "")
   359       o map mk_entry o Sorts.all_classes) algebra
   360   end;
   361 
   362 
   363 (* updaters *)
   364 
   365 fun add_class_data ((class, superclasses), (cs, base_sort, inst, phi, intro)) thy =
   366   let
   367     val operations = map (fn (v_ty as (_, ty), (c, _)) =>
   368       (c, (class, (ty, Free v_ty)))) cs;
   369     val cs = (map o pairself) fst cs;
   370     val add_class = Graph.new_node (class,
   371         mk_class_data ((cs, base_sort, map (SOME o Const) inst, phi, intro), ([], operations)))
   372       #> fold (curry Graph.add_edge class) superclasses;
   373   in
   374     ClassData.map add_class thy
   375   end;
   376 
   377 fun register_operation class (c, (t, some_def)) thy =
   378   let
   379     val base_sort = (#base_sort o the_class_data thy) class;
   380     val prep_typ = map_atyps
   381       (fn TVar (vi as (v, _), sort) => if Name.aT = v
   382         then TFree (v, base_sort) else TVar (vi, sort));
   383     val t' = map_types prep_typ t;
   384     val ty' = Term.fastype_of t';
   385   in
   386     thy
   387     |> (ClassData.map o Graph.map_node class o map_class_data o apsnd)
   388       (fn (defs, operations) =>
   389         (fold cons (the_list some_def) defs,
   390           (c, (class, (ty', t'))) :: operations))
   391   end;
   392 
   393 
   394 (** rule calculation, tactics and methods **)
   395 
   396 val class_prefix = Logic.const_of_class o Sign.base_name;
   397 
   398 fun calculate_morphism class cs =
   399   let
   400     val subst_typ = Term.map_type_tfree (fn var as (v, sort) =>
   401       if v = Name.aT then TVar ((v, 0), [class]) else TVar ((v, 0), sort));
   402     fun subst_aterm (t as Free (v, ty)) = (case AList.lookup (op =) cs v
   403          of SOME (c, _) => Const (c, ty)
   404           | NONE => t)
   405       | subst_aterm t = t;
   406     val subst_term = map_aterms subst_aterm #> map_types subst_typ;
   407   in
   408     Morphism.term_morphism subst_term
   409     $> Morphism.typ_morphism subst_typ
   410   end;
   411 
   412 fun class_intro thy class sups =
   413   let
   414     fun class_elim class =
   415       case (#axioms o AxClass.get_info thy) class
   416        of [thm] => SOME (Drule.unconstrainTs thm)
   417         | [] => NONE;
   418     val pred_intro = case Locale.intros thy class
   419      of ([ax_intro], [intro]) => intro |> OF_LAST ax_intro |> SOME
   420       | ([intro], []) => SOME intro
   421       | ([], [intro]) => SOME intro
   422       | _ => NONE;
   423     val pred_intro' = pred_intro
   424       |> Option.map (fn intro => intro OF map_filter class_elim sups);
   425     val class_intro = (#intro o AxClass.get_info thy) class;
   426     val raw_intro = case pred_intro'
   427      of SOME pred_intro => class_intro |> OF_LAST pred_intro
   428       | NONE => class_intro;
   429     val sort = Sign.super_classes thy class;
   430     val typ = TVar ((Name.aT, 0), sort);
   431     val defs = these_defs thy sups;
   432   in
   433     raw_intro
   434     |> Drule.instantiate' [SOME (Thm.ctyp_of thy typ)] []
   435     |> strip_all_ofclass thy sort
   436     |> Thm.strip_shyps
   437     |> MetaSimplifier.rewrite_rule defs
   438     |> Drule.unconstrainTs
   439   end;
   440 
   441 fun class_interpretation class facts defs thy =
   442   let
   443     val params = these_params thy [class];
   444     val inst = (#inst o the_class_data thy) class;
   445     val tac = ALLGOALS (ProofContext.fact_tac facts);
   446     val prfx = class_prefix class;
   447   in
   448     thy
   449     |> fold_map (get_remove_global_constraint o fst o snd) params
   450     ||> prove_interpretation tac ((false, prfx), []) (Locale.Locale class)
   451           (inst, map (fn def => (("", []), def)) defs)
   452     |-> (fn cs => fold (Sign.add_const_constraint o apsnd SOME) cs)
   453   end;
   454 
   455 fun intro_classes_tac facts st =
   456   let
   457     val thy = Thm.theory_of_thm st;
   458     val classes = Sign.all_classes thy;
   459     val class_trivs = map (Thm.class_triv thy) classes;
   460     val class_intros = these_intros thy;
   461     val axclass_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
   462   in
   463     Method.intros_tac (class_trivs @ class_intros @ axclass_intros) facts st
   464   end;
   465 
   466 fun default_intro_classes_tac [] = intro_classes_tac []
   467   | default_intro_classes_tac _ = no_tac;
   468 
   469 fun default_tac rules ctxt facts =
   470   HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
   471     default_intro_classes_tac facts;
   472 
   473 val _ = Context.add_setup (Method.add_methods
   474  [("intro_classes", Method.no_args (Method.METHOD intro_classes_tac),
   475     "back-chain introduction rules of classes"),
   476   ("default", Method.thms_ctxt_args (Method.METHOD oo default_tac),
   477     "apply some intro/elim rule")]);
   478 
   479 fun subclass_rule thy (sub, sup) =
   480   let
   481     val ctxt = Locale.init sub thy;
   482     val ctxt_thy = ProofContext.init thy;
   483     val props =
   484       Locale.global_asms_of thy sup
   485       |> maps snd
   486       |> map (ObjectLogic.ensure_propT thy);
   487     fun tac { prems, context } =
   488       Locale.intro_locales_tac true context prems
   489         ORELSE ALLGOALS assume_tac;
   490   in
   491     Goal.prove_multi ctxt [] [] props tac
   492     |> map (Assumption.export false ctxt ctxt_thy)
   493     |> Variable.export ctxt ctxt_thy
   494   end;
   495 
   496 fun prove_single_subclass (sub, sup) thms ctxt thy =
   497   let
   498     val ctxt_thy = ProofContext.init thy;
   499     val subclass_rule = Conjunction.intr_balanced thms
   500       |> Assumption.export false ctxt ctxt_thy
   501       |> singleton (Variable.export ctxt ctxt_thy);
   502     val sub_inst = Thm.ctyp_of thy (TVar ((Name.aT, 0), [sub]));
   503     val sub_ax = #axioms (AxClass.get_info thy sub);
   504     val classrel =
   505       #intro (AxClass.get_info thy sup)
   506       |> Drule.instantiate' [SOME sub_inst] []
   507       |> OF_LAST (subclass_rule OF sub_ax)
   508       |> strip_all_ofclass thy (Sign.super_classes thy sup)
   509       |> Thm.strip_shyps
   510   in
   511     thy
   512     |> AxClass.add_classrel classrel
   513     |> prove_interpretation_in (ALLGOALS (ProofContext.fact_tac thms))
   514          I (sub, Locale.Locale sup)
   515     |> ClassData.map (Graph.add_edge (sub, sup))
   516   end;
   517 
   518 fun prove_subclass (sub, sup) thms ctxt thy =
   519   let
   520     val classes = ClassData.get thy;
   521     val is_sup = not o null o curry (Graph.irreducible_paths classes) sub;
   522     val supclasses = Graph.all_succs classes [sup] |> filter_out is_sup;
   523     fun transform sup' = subclass_rule thy (sup, sup') |> map (fn thm => thm OF thms);
   524   in
   525     thy
   526     |> fold_rev (fn sup' => prove_single_subclass (sub, sup')
   527          (transform sup') ctxt) supclasses
   528  end;
   529 
   530 
   531 (** classes and class target **)
   532 
   533 (* class context syntax *)
   534 
   535 structure ClassSyntax = ProofDataFun(
   536   type T = {
   537     local_constraints: (string * typ) list,
   538     global_constraints: (string * typ) list,
   539     base_sort: sort,
   540     operations: (string * (typ * term)) list,
   541     unchecks: (term * term) list,
   542     passed: bool
   543   };
   544   fun init _ = {
   545     local_constraints = [],
   546     global_constraints = [],
   547     base_sort = [],
   548     operations = [],
   549     unchecks = [],
   550     passed = true
   551   };;
   552 );
   553 
   554 fun synchronize_syntax sups base_sort ctxt =
   555   let
   556     val thy = ProofContext.theory_of ctxt;
   557     fun subst_class_typ sort = map_atyps
   558       (fn TFree _ => TVar ((Name.aT, 0), sort) | ty' => ty');
   559     val operations = these_operations thy sups;
   560     val local_constraints =
   561       (map o apsnd) (subst_class_typ base_sort o fst o snd) operations;
   562     val global_constraints =
   563       (map o apsnd) (fn (class, (ty, _)) => subst_class_typ [class] ty) operations;
   564     fun declare_const (c, _) =
   565       let val b = Sign.base_name c
   566       in Sign.intern_const thy b = c ? Variable.declare_const (b, c) end;
   567     val unchecks = map (fn (c, (_, (ty, t))) => (t, Const (c, ty))) operations;
   568   in
   569     ctxt
   570     |> fold declare_const local_constraints
   571     |> fold (ProofContext.add_const_constraint o apsnd SOME) local_constraints
   572     |> ClassSyntax.put {
   573         local_constraints = local_constraints,
   574         global_constraints = global_constraints,
   575         base_sort = base_sort,
   576         operations = (map o apsnd) snd operations,
   577         unchecks = unchecks,
   578         passed = false
   579       }
   580   end;
   581 
   582 fun refresh_syntax class ctxt =
   583   let
   584     val thy = ProofContext.theory_of ctxt;
   585     val base_sort = (#base_sort o the_class_data thy) class;
   586   in synchronize_syntax [class] base_sort ctxt end;
   587 
   588 val mark_passed = ClassSyntax.map
   589   (fn { local_constraints, global_constraints, base_sort, operations, unchecks, passed } =>
   590     { local_constraints = local_constraints, global_constraints = global_constraints,
   591       base_sort = base_sort, operations = operations, unchecks = unchecks, passed = true });
   592 
   593 fun sort_term_check ts ctxt =
   594   let
   595     val { local_constraints, global_constraints, base_sort, operations, passed, ... } =
   596       ClassSyntax.get ctxt;
   597     fun check_improve (Const (c, ty)) = (case AList.lookup (op =) local_constraints c
   598          of SOME ty0 => (case try (Type.raw_match (ty0, ty)) Vartab.empty
   599              of SOME tyenv => (case Vartab.lookup tyenv (Name.aT, 0)
   600                  of SOME (_, TVar (tvar as (vi, _))) =>
   601                       if TypeInfer.is_param vi then cons tvar else I
   602                   | _ => I)
   603               | NONE => I)
   604           | NONE => I)
   605       | check_improve _ = I;
   606     val improvements = (fold o fold_aterms) check_improve ts [];
   607     val ts' = (map o map_types o map_atyps) (fn ty as TVar tvar =>
   608         if member (op =) improvements tvar
   609           then TFree (Name.aT, base_sort) else ty | ty => ty) ts;
   610     fun check t0 = Envir.expand_term (fn Const (c, ty) => (case AList.lookup (op =) operations c
   611          of SOME (ty0, t) =>
   612               if Type.typ_instance (ProofContext.tsig_of ctxt) (ty, ty0)
   613               then SOME (ty0, check t) else NONE
   614           | NONE => NONE)
   615       | _ => NONE) t0;
   616     val ts'' = map check ts';
   617   in if eq_list (op aconv) (ts, ts'') andalso passed then NONE
   618   else
   619     ctxt
   620     |> fold (ProofContext.add_const_constraint o apsnd SOME) global_constraints
   621     |> mark_passed
   622     |> pair ts''
   623     |> SOME
   624   end;
   625 
   626 fun sort_term_uncheck ts ctxt =
   627   let
   628     val thy = ProofContext.theory_of ctxt;
   629     val unchecks = (#unchecks o ClassSyntax.get) ctxt;
   630     val ts' = map (Pattern.rewrite_term thy unchecks []) ts;
   631   in if eq_list (op aconv) (ts, ts') then NONE else SOME (ts', ctxt) end;
   632 
   633 fun init_ctxt sups base_sort ctxt =
   634   ctxt
   635   |> Variable.declare_term
   636       (Logic.mk_type (TFree (Name.aT, base_sort)))
   637   |> synchronize_syntax sups base_sort
   638   |> Context.proof_map (
   639       Syntax.add_term_check 0 "class" sort_term_check
   640       #> Syntax.add_term_uncheck 0 "class" sort_term_uncheck)
   641 
   642 fun init class thy =
   643   thy
   644   |> Locale.init class
   645   |> init_ctxt [class] ((#base_sort o the_class_data thy) class);
   646 
   647 
   648 (* class definition *)
   649 
   650 local
   651 
   652 fun gen_class_spec prep_class prep_expr process_expr thy raw_supclasses raw_includes_elems =
   653   let
   654     val supclasses = map (prep_class thy) raw_supclasses;
   655     val sups = filter (is_class thy) supclasses;
   656     fun the_base_sort class = lookup_class_data thy class
   657       |> Option.map #base_sort
   658       |> the_default [class];
   659     val base_sort = Sign.minimize_sort thy (maps the_base_sort supclasses);
   660     val supsort = Sign.minimize_sort thy supclasses;
   661     val suplocales = map Locale.Locale sups;
   662     val (raw_elems, includes) = fold_rev (fn Locale.Elem e => apfst (cons e)
   663       | Locale.Expr i => apsnd (cons (prep_expr thy i))) raw_includes_elems ([], []);
   664     val supexpr = Locale.Merge suplocales;
   665     val supparams = (map fst o Locale.parameters_of_expr thy) supexpr;
   666     val supconsts = AList.make (the o AList.lookup (op =) (these_params thy sups))
   667       (map fst supparams);
   668     val mergeexpr = Locale.Merge (suplocales @ includes);
   669     val constrain = Element.Constrains ((map o apsnd o map_atyps)
   670       (fn TFree (_, sort) => TFree (Name.aT, sort)) supparams);
   671   in
   672     ProofContext.init thy
   673     |> Locale.cert_expr supexpr [constrain]
   674     |> snd
   675     |> init_ctxt sups base_sort
   676     |> process_expr Locale.empty raw_elems
   677     |> fst
   678     |> (fn elems => ((((sups, supconsts), (supsort, base_sort, mergeexpr)),
   679           (*FIXME*) if null includes then constrain :: elems else elems)))
   680   end;
   681 
   682 val read_class_spec = gen_class_spec Sign.intern_class Locale.intern_expr Locale.read_expr;
   683 val check_class_spec = gen_class_spec (K I) (K I) Locale.cert_expr;
   684 
   685 fun define_class_params (name, raw_superclasses) raw_consts raw_dep_axioms other_consts thy =
   686   let
   687     val superclasses = map (Sign.certify_class thy) raw_superclasses;
   688     val consts = (map o apfst o apsnd) (Sign.certify_typ thy) raw_consts;
   689     fun add_const ((c, ty), syn) =
   690       Sign.declare_const [] (c, Type.strip_sorts ty, syn) #>> Term.dest_Const;
   691     fun mk_axioms cs thy =
   692       raw_dep_axioms thy cs
   693       |> (map o apsnd o map) (Sign.cert_prop thy)
   694       |> rpair thy;
   695     fun constrain_typs class = (map o apsnd o Term.map_type_tfree)
   696       (fn (v, _) => TFree (v, [class]))
   697   in
   698     thy
   699     |> Sign.add_path (Logic.const_of_class name)
   700     |> fold_map add_const consts
   701     ||> Sign.restore_naming thy
   702     |-> (fn cs => mk_axioms cs
   703     #-> (fn axioms_prop => AxClass.define_class (name, superclasses)
   704            (map fst cs @ other_consts) axioms_prop
   705     #-> (fn class => `(fn _ => constrain_typs class cs)
   706     #-> (fn cs' => `(fn thy => AxClass.get_info thy class)
   707     #-> (fn {axioms, ...} => fold (Sign.add_const_constraint o apsnd SOME) cs'
   708     #> pair (class, (cs', axioms)))))))
   709   end;
   710 
   711 fun gen_class prep_spec prep_param bname
   712     raw_supclasses raw_includes_elems raw_other_consts thy =
   713   let
   714     val class = Sign.full_name thy bname;
   715     val (((sups, supconsts), (supsort, base_sort, mergeexpr)), elems_syn) =
   716       prep_spec thy raw_supclasses raw_includes_elems;
   717     val other_consts = map (tap (Sign.the_const_type thy) o prep_param thy) raw_other_consts;
   718     fun mk_inst class cs =
   719       (map o apsnd o Term.map_type_tfree) (fn (v, _) => TFree (v, [class])) cs;
   720     fun fork_syntax (Element.Fixes xs) =
   721           fold_map (fn (c, ty, syn) => cons (c, syn) #> pair (c, ty, NoSyn)) xs
   722           #>> Element.Fixes
   723       | fork_syntax x = pair x;
   724     val (elems, global_syn) = fold_map fork_syntax elems_syn [];
   725     fun globalize (c, ty) =
   726       ((c, Term.map_type_tfree (K (TFree (Name.aT, base_sort))) ty),
   727         (the_default NoSyn o AList.lookup (op =) global_syn) c);
   728     fun extract_params thy =
   729       let
   730         val params = map fst (Locale.parameters_of thy class);
   731       in
   732         (params, (map globalize o snd o chop (length supconsts)) params)
   733       end;
   734     fun extract_assumes params thy cs =
   735       let
   736         val consts = supconsts @ (map (fst o fst) params ~~ cs);
   737         fun subst (Free (c, ty)) =
   738               Const ((fst o the o AList.lookup (op =) consts) c, ty)
   739           | subst t = t;
   740         fun prep_asm ((name, atts), ts) =
   741           ((Sign.base_name name, map (Attrib.attribute_i thy) atts),
   742             (map o map_aterms) subst ts);
   743       in
   744         Locale.global_asms_of thy class
   745         |> map prep_asm
   746       end;
   747   in
   748     thy
   749     |> Locale.add_locale_i (SOME "") bname mergeexpr elems
   750     |> snd
   751     |> ProofContext.theory_of
   752     |> `extract_params
   753     |-> (fn (all_params, params) =>
   754         define_class_params (bname, supsort) params
   755           (extract_assumes params) other_consts
   756       #-> (fn (_, (consts, axioms)) =>
   757         `(fn thy => class_intro thy class sups)
   758       #-> (fn class_intro =>
   759         PureThy.note_thmss_qualified "" (NameSpace.append class classN)
   760           [((introN, []), [([class_intro], [])])]
   761       #-> (fn [(_, [class_intro])] =>
   762         add_class_data ((class, sups),
   763           (map fst params ~~ consts, base_sort,
   764             mk_inst class (map snd supconsts @ consts),
   765               calculate_morphism class (supconsts @ (map (fst o fst) params ~~ consts)), class_intro))
   766       #> class_interpretation class axioms []
   767       ))))
   768     |> init class
   769     |> pair class
   770   end;
   771 
   772 fun read_const thy = #1 o Term.dest_Const o ProofContext.read_const (ProofContext.init thy);
   773 
   774 in
   775 
   776 val class_cmd = gen_class read_class_spec read_const;
   777 val class = gen_class check_class_spec (K I);
   778 
   779 end; (*local*)
   780 
   781 
   782 (* class target *)
   783 
   784 fun logical_const class pos ((c, mx), dict) thy =
   785   let
   786     val prfx = class_prefix class;
   787     val thy' = thy |> Sign.add_path prfx;
   788     val phi = morphism thy' class;
   789 
   790     val c' = Sign.full_name thy' c;
   791     val dict' = Morphism.term phi dict;
   792     val dict_def = map_types Logic.unvarifyT dict';
   793     val ty' = Term.fastype_of dict_def;
   794     val ty'' = Type.strip_sorts ty';
   795     val def_eq = Logic.mk_equals (Const (c', ty'), dict_def);
   796   in
   797     thy'
   798     |> Sign.declare_const pos (c, ty'', mx) |> snd
   799     |> Thm.add_def false (c, def_eq)
   800     |>> Thm.symmetric
   801     |-> (fn def => class_interpretation class [def] [Thm.prop_of def]
   802           #> register_operation class (c', (dict', SOME (Thm.varifyT def))))
   803     |> Sign.restore_naming thy
   804     |> Sign.add_const_constraint (c', SOME ty')
   805   end;
   806 
   807 fun syntactic_const class prmode pos ((c, mx), rhs) thy =
   808   let
   809     val prfx = class_prefix class;
   810     val thy' = thy |> Sign.add_path prfx;
   811     val phi = morphism thy class;
   812 
   813     val c' = Sign.full_name thy' c;
   814     val rews = map (Logic.dest_equals o Thm.prop_of) (these_defs thy' [class])
   815     val rhs' = (Pattern.rewrite_term thy rews [] o Morphism.term phi) rhs;
   816     val ty' = Logic.unvarifyT (Term.fastype_of rhs');
   817   in
   818     thy'
   819     |> Sign.add_abbrev (#1 prmode) pos (c, map_types Type.strip_sorts rhs') |> snd
   820     |> Sign.add_const_constraint (c', SOME ty')
   821     |> Sign.notation true prmode [(Const (c', ty'), mx)]
   822     |> register_operation class (c', (rhs', NONE))
   823     |> Sign.restore_naming thy
   824   end;
   825 
   826 
   827 (** instantiation target **)
   828 
   829 (* bookkeeping *)
   830 
   831 datatype instantiation = Instantiation of {
   832   arities: arity list,
   833   params: ((string * string) * (string * typ)) list
   834 }
   835 
   836 structure Instantiation = ProofDataFun
   837 (
   838   type T = instantiation
   839   fun init _ = Instantiation { arities = [], params = [] };
   840 );
   841 
   842 fun mk_instantiation (arities, params) =
   843   Instantiation { arities = arities, params = params };
   844 fun get_instantiation lthy = case Instantiation.get (LocalTheory.target_of lthy)
   845  of Instantiation data => data;
   846 fun map_instantiation f = (LocalTheory.target o Instantiation.map)
   847   (fn Instantiation { arities, params } => mk_instantiation (f (arities, params)));
   848 
   849 fun the_instantiation lthy = case get_instantiation lthy
   850  of { arities = [], ... } => error "No instantiation target"
   851   | data => data;
   852 
   853 val instantiation_params = #params o get_instantiation;
   854 
   855 fun instantiation_param lthy v = instantiation_params lthy
   856   |> find_first (fn (_, (v', _)) => v = v')
   857   |> Option.map (fst o fst);
   858 
   859 fun confirm_declaration c = (map_instantiation o apsnd)
   860   (filter_out (fn (_, (c', _)) => c' = c));
   861 
   862 
   863 (* syntax *)
   864 
   865 fun inst_term_check ts lthy =
   866   let
   867     val params = instantiation_params lthy;
   868     val tsig = ProofContext.tsig_of lthy;
   869     val thy = ProofContext.theory_of lthy;
   870 
   871     fun check_improve (Const (c, ty)) = (case inst_tyco thy (c, ty)
   872          of SOME tyco => (case AList.lookup (op =) params (c, tyco)
   873              of SOME (_, ty') => perhaps (try (Type.typ_match tsig (ty, ty')))
   874               | NONE => I)
   875           | NONE => I)
   876       | check_improve _ = I;
   877     val improvement = (fold o fold_aterms) check_improve ts Vartab.empty;
   878     val ts' = (map o map_types) (Envir.typ_subst_TVars improvement) ts;
   879     val ts'' = (map o map_aterms) (fn t as Const (c, ty) => (case inst_tyco thy (c, ty)
   880          of SOME tyco => (case AList.lookup (op =) params (c, tyco)
   881              of SOME v_ty => Free v_ty
   882               | NONE => t)
   883           | NONE => t)
   884       | t => t) ts';
   885   in if eq_list (op aconv) (ts, ts'') then NONE else SOME (ts'', lthy) end;
   886 
   887 fun inst_term_uncheck ts lthy =
   888   let
   889     val params = instantiation_params lthy;
   890     val ts' = (map o map_aterms) (fn t as Free (v, ty) =>
   891        (case get_first (fn ((c, _), (v', _)) => if v = v' then SOME c else NONE) params
   892          of SOME c => Const (c, ty)
   893           | NONE => t)
   894       | t => t) ts;
   895   in if eq_list (op aconv) (ts, ts') then NONE else SOME (ts', lthy) end;
   896 
   897 
   898 (* target *)
   899 
   900 val sanatize_name = (*FIXME*)
   901   let
   902     fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s orelse s = "'";
   903     val is_junk = not o is_valid andf Symbol.is_regular;
   904     val junk = Scan.many is_junk;
   905     val scan_valids = Symbol.scanner "Malformed input"
   906       ((junk |--
   907         (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
   908         --| junk))
   909       -- Scan.repeat ((Scan.many1 is_valid >> implode) --| junk) >> op ::);
   910   in
   911     explode #> scan_valids #> implode
   912   end;
   913 
   914 
   915 fun init_instantiation arities thy =
   916   let
   917     val _ = if null arities then error "At least one arity must be given" else ();
   918     val _ = case (duplicates (op =) o map #1) arities
   919      of [] => ()
   920       | dupl_tycos => error ("Type constructors occur more than once in arities: "
   921           ^ commas_quote dupl_tycos);
   922     val _ = map (map (the_class_data thy) o #3) arities;
   923     val ty_insts = map (fn (tyco, sorts, _) =>
   924         (tyco, Type (tyco, map TFree (Name.names Name.context Name.aT sorts))))
   925       arities;
   926     val ty_inst = the o AList.lookup (op =) ty_insts;
   927     fun type_name "*" = "prod"
   928       | type_name "+" = "sum"
   929       | type_name s = sanatize_name (NameSpace.base s); (*FIXME*)
   930     fun get_param tyco sorts (param, (c, ty)) = if can (inst thy) (c, tyco)
   931       then NONE else SOME ((unoverload_const thy (c, ty), tyco),
   932         (param ^ "_" ^ type_name tyco, map_atyps (K (ty_inst tyco)) ty));
   933     fun get_params (tyco, sorts, sort) =
   934       map_filter (get_param tyco sorts) (these_params thy sort)
   935     val params = maps get_params arities;
   936   in
   937     thy
   938     |> ProofContext.init
   939     |> Instantiation.put (mk_instantiation (arities, params))
   940     |> fold (Variable.declare_term o Logic.mk_type o snd) ty_insts
   941     |> fold ProofContext.add_arity arities
   942     |> Context.proof_map (
   943         Syntax.add_term_check 0 "instance" inst_term_check
   944         #> Syntax.add_term_uncheck 0 "instance" inst_term_uncheck)
   945   end;
   946 
   947 fun gen_instantiation_instance do_proof after_qed lthy =
   948   let
   949     val arities = (#arities o the_instantiation) lthy;
   950     val arities_proof = maps Logic.mk_arities arities;
   951     fun after_qed' results =
   952       LocalTheory.theory (fold (AxClass.add_arity o Thm.varifyT) results)
   953       #> after_qed;
   954   in
   955     lthy
   956     |> do_proof after_qed' arities_proof
   957   end;
   958 
   959 val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
   960   Proof.theorem_i NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
   961 
   962 fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
   963   fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
   964     (fn {context, ...} => tac context)) ts) lthy) I;
   965 
   966 fun conclude_instantiation lthy =
   967   let
   968     val { arities, params } = the_instantiation lthy;
   969     val thy = ProofContext.theory_of lthy;
   970     (*val _ = map (fn (tyco, sorts, sort) =>
   971       if Sign.of_sort thy
   972         (Type (tyco, map TFree (Name.names Name.context Name.aT sorts)), sort)
   973       then () else error ("Missing instance proof for type " ^ quote (Sign.extern_type thy tyco)))
   974         arities; FIXME activate when old instance command is gone*)
   975     val params_of = maps (these o try (#params o AxClass.get_info thy))
   976       o Sign.complete_sort thy;
   977     val missing_params = arities
   978       |> maps (fn (tyco, _, sort) => params_of sort |> map (rpair tyco))
   979       |> filter_out (can (inst thy) o apfst fst);
   980     fun declare_missing ((c, ty0), tyco) thy =
   981     (*fun declare_missing ((c, tyco), (_, ty)) thy =*)
   982       let
   983         val SOME class = AxClass.class_of_param thy c;
   984         val name_inst = AxClass.instance_name (tyco, class) ^ "_inst";
   985         val c' = NameSpace.base c ^ "_" ^ NameSpace.base tyco;
   986         val vs = Name.names Name.context Name.aT (replicate (Sign.arity_number thy tyco) []);
   987         val ty = map_atyps (fn _ => Type (tyco, map TFree vs)) ty0;
   988       in
   989         thy
   990         |> Sign.sticky_prefix name_inst
   991         |> Sign.no_base_names
   992         |> Sign.declare_const [] (c', ty, NoSyn)
   993         |-> (fn const' as Const (c'', _) => Thm.add_def true
   994               (Thm.def_name c', Logic.mk_equals (const', Const (c, ty)))
   995         #>> Thm.varifyT
   996         #-> (fn thm => add_inst (c, tyco) (c'', Thm.symmetric thm)
   997         #> primitive_note Thm.internalK (c', thm)
   998         #> snd
   999         #> Sign.restore_naming thy))
  1000       end;
  1001   in
  1002     lthy
  1003     |> LocalTheory.theory (fold declare_missing missing_params)
  1004   end;
  1005 
  1006 end;