src/Pure/Isar/class_declaration.ML
author wenzelm
Sun Apr 17 19:54:04 2011 +0200 (2011-04-17)
changeset 42375 774df7c59508
parent 42360 da8817d01e7c
child 42402 c7139609b67d
permissions -rw-r--r--
report Name_Space.declare/define, relatively to context;
added "global" variants of context-dependent declarations;
     1 (*  Title:      Pure/Isar/class_declaration.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Declaring classes and subclass relations.
     5 *)
     6 
     7 signature CLASS_DECLARATION =
     8 sig
     9   val class: (local_theory -> local_theory) -> binding -> class list ->
    10     Element.context_i list -> theory -> string * local_theory
    11   val class_cmd: (local_theory -> local_theory) -> binding -> xstring list ->
    12     Element.context list -> theory -> string * local_theory
    13   val prove_subclass: (local_theory -> local_theory) -> tactic -> class ->
    14     local_theory -> local_theory
    15   val subclass: (local_theory -> local_theory) -> class -> local_theory -> Proof.state
    16   val subclass_cmd: (local_theory -> local_theory) -> xstring -> local_theory -> Proof.state
    17 end;
    18 
    19 structure Class_Declaration: CLASS_DECLARATION =
    20 struct
    21 
    22 (** class definitions **)
    23 
    24 local
    25 
    26 (* calculating class-related rules including canonical interpretation *)
    27 
    28 fun calculate thy class sups base_sort param_map assm_axiom =
    29   let
    30     val empty_ctxt = Proof_Context.init_global thy;
    31 
    32     (* instantiation of canonical interpretation *)
    33     val aT = TFree (Name.aT, base_sort);
    34     val param_map_const = (map o apsnd) Const param_map;
    35     val param_map_inst = (map o apsnd)
    36       (Const o apsnd (map_atyps (K aT))) param_map;
    37     val const_morph = Element.inst_morphism thy
    38       (Symtab.empty, Symtab.make param_map_inst);
    39     val typ_morph = Element.inst_morphism thy
    40       (Symtab.empty |> Symtab.update (Name.aT, TFree (Name.aT, [class])), Symtab.empty);
    41     val (([raw_props], [(_, raw_inst_morph)], export_morph), _) = empty_ctxt
    42       |> Expression.cert_goal_expression ([(class, (("", false),
    43            Expression.Named param_map_const))], []);
    44     val (props, inst_morph) = if null param_map
    45       then (raw_props |> map (Morphism.term typ_morph),
    46         raw_inst_morph $> typ_morph)
    47       else (raw_props, raw_inst_morph); (*FIXME proper handling in
    48         locale.ML / expression.ML would be desirable*)
    49 
    50     (* witness for canonical interpretation *)
    51     val prop = try the_single props;
    52     val wit = Option.map (fn prop => let
    53         val sup_axioms = map_filter (fst o Class.rules thy) sups;
    54         val loc_intro_tac = case Locale.intros_of thy class
    55           of (_, NONE) => all_tac
    56            | (_, SOME intro) => ALLGOALS (Tactic.rtac intro);
    57         val tac = loc_intro_tac
    58           THEN ALLGOALS (Proof_Context.fact_tac (sup_axioms @ the_list assm_axiom))
    59       in Element.prove_witness empty_ctxt prop tac end) prop;
    60     val axiom = Option.map Element.conclude_witness wit;
    61 
    62     (* canonical interpretation *)
    63     val base_morph = inst_morph
    64       $> Morphism.binding_morphism (Binding.prefix false (Class.class_prefix class))
    65       $> Element.satisfy_morphism (the_list wit);
    66     val eq_morph = Element.eq_morphism thy (Class.these_defs thy sups);
    67 
    68     (* assm_intro *)
    69     fun prove_assm_intro thm =
    70       let
    71         val ((_, [thm']), _) = Variable.import true [thm] empty_ctxt;
    72         val const_eq_morph = case eq_morph
    73          of SOME eq_morph => const_morph $> eq_morph
    74           | NONE => const_morph
    75         val thm'' = Morphism.thm const_eq_morph thm';
    76         val tac = ALLGOALS (Proof_Context.fact_tac [thm'']);
    77       in Skip_Proof.prove_global thy [] [] (Thm.prop_of thm'') (K tac) end;
    78     val assm_intro = Option.map prove_assm_intro
    79       (fst (Locale.intros_of thy class));
    80 
    81     (* of_class *)
    82     val of_class_prop_concl = Logic.mk_of_class (aT, class);
    83     val of_class_prop = case prop of NONE => of_class_prop_concl
    84       | SOME prop => Logic.mk_implies (Morphism.term const_morph
    85           ((map_types o map_atyps) (K aT) prop), of_class_prop_concl);
    86     val sup_of_classes = map (snd o Class.rules thy) sups;
    87     val loc_axiom_intros = map Drule.export_without_context_open (Locale.axioms_of thy class);
    88     val axclass_intro = #intro (AxClass.get_info thy class);
    89     val base_sort_trivs = Thm.of_sort (Thm.ctyp_of thy aT, base_sort);
    90     val tac = REPEAT (SOMEGOAL
    91       (Tactic.match_tac (axclass_intro :: sup_of_classes
    92          @ loc_axiom_intros @ base_sort_trivs)
    93            ORELSE' Tactic.assume_tac));
    94     val of_class = Skip_Proof.prove_global thy [] [] of_class_prop (K tac);
    95 
    96   in (base_morph, eq_morph, export_morph, axiom, assm_intro, of_class) end;
    97 
    98 
    99 (* reading and processing class specifications *)
   100 
   101 fun prep_class_elems prep_decl thy sups raw_elems =
   102   let
   103 
   104     (* user space type system: only permits 'a type variable, improves towards 'a *)
   105     val algebra = Sign.classes_of thy;
   106     val inter_sort = curry (Sorts.inter_sort algebra);
   107     val proto_base_sort = if null sups then Sign.defaultS thy
   108       else fold inter_sort (map (Class.base_sort thy) sups) [];
   109     val base_constraints = (map o apsnd)
   110       (map_type_tfree (K (TVar ((Name.aT, 0), proto_base_sort))) o fst o snd)
   111         (Class.these_operations thy sups);
   112     val reject_bcd_etc = (map o map_atyps) (fn T as TFree (v, sort) =>
   113           if v = Name.aT then T
   114           else error ("No type variable other than " ^ Name.aT ^ " allowed in class specification")
   115       | T => T);
   116     fun singleton_fixate Ts =
   117       let
   118         fun extract f = (fold o fold_atyps) f Ts [];
   119         val tfrees = extract
   120           (fn TFree (v, sort) => insert (op =) (v, sort) | _ => I);
   121         val inferred_sort = extract
   122           (fn TVar (_, sort) => inter_sort sort | _ => I);
   123         val fixate_sort = if null tfrees then inferred_sort
   124           else case tfrees
   125            of [(_, a_sort)] => if Sorts.sort_le algebra (a_sort, inferred_sort)
   126                 then inter_sort a_sort inferred_sort
   127                 else error ("Type inference imposes additional sort constraint "
   128                   ^ Syntax.string_of_sort_global thy inferred_sort
   129                   ^ " of type parameter " ^ Name.aT ^ " of sort "
   130                   ^ Syntax.string_of_sort_global thy a_sort)
   131             | _ => error "Multiple type variables in class specification";
   132       in (map o map_atyps) (K (TFree (Name.aT, fixate_sort))) Ts end;
   133     fun after_infer_fixate Ts =
   134       let
   135         val sort' = (fold o fold_atyps) (fn T as TFree _ => I | T as TVar (vi, sort) =>
   136           if Type_Infer.is_param vi then inter_sort sort else I) Ts [];
   137       in
   138         (map o map_atyps)
   139           (fn T as TFree _ => T | T as TVar (vi, _) =>
   140             if Type_Infer.is_param vi then Type_Infer.param 0 (Name.aT, sort') else T) Ts
   141       end;
   142     fun add_typ_check level name f = Context.proof_map
   143       (Syntax.add_typ_check level name (fn Ts => fn ctxt =>
   144         let val Ts' = f Ts in if eq_list (op =) (Ts, Ts') then NONE else SOME (Ts', ctxt) end));
   145 
   146     (* preprocessing elements, retrieving base sort from type-checked elements *)
   147     val raw_supexpr = (map (fn sup => (sup, (("", false),
   148       Expression.Positional []))) sups, []);
   149     val init_class_body = fold (Proof_Context.add_const_constraint o apsnd SOME) base_constraints
   150       #> Class.redeclare_operations thy sups
   151       #> add_typ_check 10 "reject_bcd_etc" reject_bcd_etc
   152       #> add_typ_check ~10 "singleton_fixate" singleton_fixate;
   153     val ((raw_supparams, _, raw_inferred_elems), _) = Proof_Context.init_global thy
   154       |> add_typ_check 5 "after_infer_fixate" after_infer_fixate
   155       |> prep_decl raw_supexpr init_class_body raw_elems;
   156     fun filter_element (Element.Fixes []) = NONE
   157       | filter_element (e as Element.Fixes _) = SOME e
   158       | filter_element (Element.Constrains []) = NONE
   159       | filter_element (e as Element.Constrains _) = SOME e
   160       | filter_element (Element.Assumes []) = NONE
   161       | filter_element (e as Element.Assumes _) = SOME e
   162       | filter_element (Element.Defines _) = error ("\"defines\" element not allowed in class specification.")
   163       | filter_element (Element.Notes _) = error ("\"notes\" element not allowed in class specification.");
   164     val inferred_elems = map_filter filter_element raw_inferred_elems;
   165     fun fold_element_types f (Element.Fixes fxs) = fold (fn (_, SOME T, _) => f T) fxs
   166       | fold_element_types f (Element.Constrains cnstrs) = fold (f o snd) cnstrs
   167       | fold_element_types f (Element.Assumes assms) = fold (fold (fn (t, ts) =>
   168           fold_types f t #> (fold o fold_types) f ts) o snd) assms
   169     val base_sort = if null inferred_elems then proto_base_sort else
   170       case (fold o fold_element_types) Term.add_tfreesT inferred_elems []
   171        of [] => error "No type variable in class specification"
   172         | [(_, sort)] => sort
   173         | _ => error "Multiple type variables in class specification";
   174     val supparams = map (fn ((c, T), _) =>
   175       (c, map_atyps (K (TFree (Name.aT, base_sort))) T)) raw_supparams;
   176     val supparam_names = map fst supparams;
   177     fun mk_param ((c, _), _) = Free (c, (the o AList.lookup (op =) supparams) c);
   178     val supexpr = (map (fn sup => (sup, (("", false),
   179       Expression.Positional (map (SOME o mk_param) (Locale.params_of thy sup))))) sups,
   180         map (fn (c, T) => (Binding.name c, SOME T, NoSyn)) supparams);
   181 
   182   in (base_sort, supparam_names, supexpr, inferred_elems) end;
   183 
   184 val cert_class_elems = prep_class_elems Expression.cert_declaration;
   185 val read_class_elems = prep_class_elems Expression.cert_read_declaration;
   186 
   187 fun prep_class_spec prep_class prep_class_elems thy raw_supclasses raw_elems =
   188   let
   189 
   190     (* prepare import *)
   191     val inter_sort = curry (Sorts.inter_sort (Sign.classes_of thy));
   192     val sups = map (prep_class thy) raw_supclasses
   193       |> Sign.minimize_sort thy;
   194     val _ = case filter_out (Class.is_class thy) sups
   195      of [] => ()
   196       | no_classes => error ("No (proper) classes: " ^ commas (map quote no_classes));
   197     val raw_supparams = (map o apsnd) (snd o snd) (Class.these_params thy sups);
   198     val raw_supparam_names = map fst raw_supparams;
   199     val _ = if has_duplicates (op =) raw_supparam_names
   200       then error ("Duplicate parameter(s) in superclasses: "
   201         ^ (commas o map quote o duplicates (op =)) raw_supparam_names)
   202       else ();
   203 
   204     (* infer types and base sort *)
   205     val (base_sort, supparam_names, supexpr, inferred_elems) =
   206       prep_class_elems thy sups raw_elems;
   207     val sup_sort = inter_sort base_sort sups;
   208 
   209     (* process elements as class specification *)
   210     val class_ctxt = Class.begin sups base_sort (Proof_Context.init_global thy);
   211     val ((_, _, syntax_elems), _) = class_ctxt
   212       |> Expression.cert_declaration supexpr I inferred_elems;
   213     fun check_vars e vs = if null vs
   214       then error ("No type variable in part of specification element "
   215         ^ (Pretty.string_of o Pretty.chunks) (Element.pretty_ctxt class_ctxt e))
   216       else ();
   217     fun check_element (e as Element.Fixes fxs) =
   218           map (fn (_, SOME T, _) => check_vars e (Term.add_tfreesT T [])) fxs
   219       | check_element (e as Element.Assumes assms) =
   220           maps (fn (_, ts_pss) => map
   221             (fn (t, _) => check_vars e (Term.add_tfrees t [])) ts_pss) assms
   222       | check_element e = [()];
   223     val _ = map check_element syntax_elems;
   224     fun fork_syn (Element.Fixes xs) =
   225           fold_map (fn (c, ty, syn) => cons (c, syn) #> pair (c, ty, NoSyn)) xs
   226           #>> Element.Fixes
   227       | fork_syn x = pair x;
   228     val (elems, global_syntax) = fold_map fork_syn syntax_elems [];
   229 
   230   in (((sups, supparam_names), (sup_sort, base_sort, supexpr)), (elems, global_syntax)) end;
   231 
   232 val cert_class_spec = prep_class_spec (K I) cert_class_elems;
   233 val read_class_spec = prep_class_spec Sign.intern_class read_class_elems;
   234 
   235 
   236 (* class establishment *)
   237 
   238 fun add_consts class base_sort sups supparam_names global_syntax thy =
   239   let
   240     (*FIXME simplify*)
   241     val supconsts = supparam_names
   242       |> AList.make (snd o the o AList.lookup (op =) (Class.these_params thy sups))
   243       |> (map o apsnd o apsnd o map_atyps o K o TFree) (Name.aT, [class]);
   244     val all_params = Locale.params_of thy class;
   245     val raw_params = (snd o chop (length supparam_names)) all_params;
   246     fun add_const ((raw_c, raw_ty), _) thy =
   247       let
   248         val b = Binding.name raw_c;
   249         val c = Sign.full_name thy b;
   250         val ty = map_atyps (K (TFree (Name.aT, base_sort))) raw_ty;
   251         val ty0 = Type.strip_sorts ty;
   252         val ty' = map_atyps (K (TFree (Name.aT, [class]))) ty0;
   253         val syn = (the_default NoSyn o AList.lookup Binding.eq_name global_syntax) b;
   254       in
   255         thy
   256         |> Sign.declare_const_global ((b, ty0), syn)
   257         |> snd
   258         |> pair ((Variable.name b, ty), (c, ty'))
   259       end;
   260   in
   261     thy
   262     |> Sign.add_path (Class.class_prefix class)
   263     |> fold_map add_const raw_params
   264     ||> Sign.restore_naming thy
   265     |-> (fn params => pair (supconsts @ (map o apfst) fst params, params))
   266   end;
   267 
   268 fun adjungate_axclass bname class base_sort sups supsort supparam_names global_syntax thy =
   269   let
   270     (*FIXME simplify*)
   271     fun globalize param_map = map_aterms
   272       (fn Free (v, ty) => Const ((fst o the o AList.lookup (op =) param_map) v, ty)
   273         | t => t);
   274     val raw_pred = Locale.intros_of thy class
   275       |> fst
   276       |> Option.map (Logic.unvarify_global o Logic.strip_imp_concl o Thm.prop_of);
   277     fun get_axiom thy = case (#axioms o AxClass.get_info thy) class
   278      of [] => NONE
   279       | [thm] => SOME thm;
   280   in
   281     thy
   282     |> add_consts class base_sort sups supparam_names global_syntax
   283     |-> (fn (param_map, params) => AxClass.define_class (bname, supsort)
   284           (map (fst o snd) params)
   285           [(Thm.empty_binding, Option.map (globalize param_map) raw_pred |> the_list)]
   286     #> snd
   287     #> `get_axiom
   288     #-> (fn assm_axiom => fold (Sign.add_const_constraint o apsnd SOME o snd) params
   289     #> pair (param_map, params, assm_axiom)))
   290   end;
   291 
   292 fun gen_class prep_class_spec before_exit b raw_supclasses raw_elems thy =
   293   let
   294     val class = Sign.full_name thy b;
   295     val (((sups, supparam_names), (supsort, base_sort, supexpr)), (elems, global_syntax)) =
   296       prep_class_spec thy raw_supclasses raw_elems;
   297   in
   298     thy
   299     |> Expression.add_locale I b (Binding.qualify true "class" b) supexpr elems
   300     |> snd |> Local_Theory.exit_global
   301     |> adjungate_axclass b class base_sort sups supsort supparam_names global_syntax
   302     ||> Theory.checkpoint
   303     |-> (fn (param_map, params, assm_axiom) =>
   304        `(fn thy => calculate thy class sups base_sort param_map assm_axiom)
   305     #-> (fn (base_morph, eq_morph, export_morph, axiom, assm_intro, of_class) =>
   306        Context.theory_map (Locale.add_registration (class, base_morph)
   307          (Option.map (rpair true) eq_morph) export_morph)
   308     #> Class.register class sups params base_sort base_morph export_morph axiom assm_intro of_class))
   309     |> Named_Target.init before_exit class
   310     |> pair class
   311   end;
   312 
   313 in
   314 
   315 val class = gen_class cert_class_spec;
   316 val class_cmd = gen_class read_class_spec;
   317 
   318 end; (*local*)
   319 
   320 
   321 (** subclass relations **)
   322 
   323 local
   324 
   325 fun gen_subclass prep_class do_proof before_exit raw_sup lthy =
   326   let
   327     val thy = Proof_Context.theory_of lthy;
   328     val proto_sup = prep_class thy raw_sup;
   329     val proto_sub = case Named_Target.peek lthy
   330      of SOME {target, is_class = true, ...} => target
   331       | _ => error "Not in a class target";
   332     val (sub, sup) = AxClass.cert_classrel thy (proto_sub, proto_sup);
   333 
   334     val expr = ([(sup, (("", false), Expression.Positional []))], []);
   335     val (([props], deps, export), goal_ctxt) =
   336       Expression.cert_goal_expression expr lthy;
   337     val some_prop = try the_single props;
   338     val some_dep_morph = try the_single (map snd deps);
   339     fun after_qed some_wit =
   340       Proof_Context.background_theory (Class.register_subclass (sub, sup)
   341         some_dep_morph some_wit export)
   342       #> Proof_Context.theory_of #> Named_Target.init before_exit sub;
   343   in do_proof after_qed some_prop goal_ctxt end;
   344 
   345 fun user_proof after_qed some_prop =
   346   Element.witness_proof (after_qed o try the_single o the_single)
   347     [the_list some_prop];
   348 
   349 fun tactic_proof tac after_qed some_prop ctxt =
   350   after_qed (Option.map
   351     (fn prop => Element.prove_witness ctxt prop tac) some_prop) ctxt;
   352 
   353 in
   354 
   355 val subclass = gen_subclass (K I) user_proof;
   356 fun prove_subclass before_exit tac = gen_subclass (K I) (tactic_proof tac) before_exit;
   357 val subclass_cmd = gen_subclass (Proof_Context.read_class o Proof_Context.init_global) user_proof;
   358 
   359 end; (*local*)
   360 
   361 end;