src/Pure/Isar/class_declaration.ML
author wenzelm
Thu Oct 30 16:20:46 2014 +0100 (2014-10-30)
changeset 58837 e84d900cd287
parent 58319 9228350683d0
child 58957 c9e744ea8a38
permissions -rw-r--r--
eliminated aliases;
     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: binding -> class list ->
    10     Element.context_i list -> theory -> string * local_theory
    11   val class_cmd: binding -> xstring list ->
    12     Element.context list -> theory -> string * local_theory
    13   val prove_subclass: tactic -> class ->
    14     local_theory -> local_theory
    15   val subclass: class -> local_theory -> Proof.state
    16   val subclass_cmd: 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) =
    45       if null param_map
    46       then (raw_props |> map (Morphism.term typ_morph),
    47         raw_inst_morph $> typ_morph)
    48       else (raw_props, raw_inst_morph); (*FIXME proper handling in
    49         locale.ML / expression.ML would be desirable*)
    50 
    51     (* witness for canonical interpretation *)
    52     val some_prop = try the_single props;
    53     val some_witn = Option.map (fn prop =>
    54       let
    55         val sup_axioms = map_filter (fst o Class.rules thy) sups;
    56         val loc_intro_tac =
    57           (case Locale.intros_of thy class of
    58             (_, NONE) => all_tac
    59           | (_, SOME intro) => ALLGOALS (resolve_tac [intro]));
    60         val tac = loc_intro_tac
    61           THEN ALLGOALS (Proof_Context.fact_tac empty_ctxt (sup_axioms @ the_list assm_axiom));
    62       in Element.prove_witness empty_ctxt prop tac end) some_prop;
    63     val some_axiom = Option.map (Element.conclude_witness empty_ctxt) some_witn;
    64 
    65     (* canonical interpretation *)
    66     val base_morph = inst_morph
    67       $> Morphism.binding_morphism "class_binding" (Binding.prefix false (Class.class_prefix class))
    68       $> Element.satisfy_morphism (the_list some_witn);
    69     val eq_morph = Element.eq_morphism thy (Class.these_defs thy sups);
    70 
    71     (* assm_intro *)
    72     fun prove_assm_intro thm =
    73       let
    74         val ((_, [thm']), _) = Variable.import true [thm] empty_ctxt;
    75         val const_eq_morph =
    76           (case eq_morph of
    77             SOME eq_morph => const_morph $> eq_morph
    78           | NONE => const_morph);
    79         val thm'' = Morphism.thm const_eq_morph thm';
    80       in
    81         Goal.prove_sorry_global thy [] [] (Thm.prop_of thm'')
    82           (fn {context = ctxt, ...} => ALLGOALS (Proof_Context.fact_tac ctxt [thm'']))
    83       end;
    84     val some_assm_intro = Option.map prove_assm_intro (fst (Locale.intros_of thy class));
    85 
    86     (* of_class *)
    87     val of_class_prop_concl = Logic.mk_of_class (aT, class);
    88     val of_class_prop =
    89       (case some_prop of
    90         NONE => of_class_prop_concl
    91       | SOME prop => Logic.mk_implies (Morphism.term const_morph
    92           ((map_types o map_atyps) (K aT) prop), of_class_prop_concl));
    93     val sup_of_classes = map (snd o Class.rules thy) sups;
    94     val loc_axiom_intros = map Drule.export_without_context_open (Locale.axioms_of thy class);
    95     val axclass_intro = #intro (Axclass.get_info thy class);
    96     val base_sort_trivs = Thm.of_sort (Thm.ctyp_of thy aT, base_sort);
    97     val tac =
    98       REPEAT (SOMEGOAL
    99         (match_tac (axclass_intro :: sup_of_classes @ loc_axiom_intros @ base_sort_trivs)
   100           ORELSE' assume_tac));
   101     val of_class = Goal.prove_sorry_global thy [] [] of_class_prop (K tac);
   102 
   103   in (base_morph, eq_morph, export_morph, some_axiom, some_assm_intro, of_class) end;
   104 
   105 
   106 (* reading and processing class specifications *)
   107 
   108 fun prep_class_elems prep_decl thy sups raw_elems =
   109   let
   110 
   111     (* user space type system: only permits 'a type variable, improves towards 'a *)
   112     val algebra = Sign.classes_of thy;
   113     val inter_sort = curry (Sorts.inter_sort algebra);
   114     val proto_base_sort =
   115       if null sups then Sign.defaultS thy
   116       else fold inter_sort (map (Class.base_sort thy) sups) [];
   117     val is_param = member (op =) (map fst (Class.these_params thy sups));
   118     val base_constraints = (map o apsnd)
   119       (map_type_tfree (K (TVar ((Name.aT, 0), proto_base_sort))) o fst o snd)
   120         (Class.these_operations thy sups);
   121     fun singleton_fixateT Ts =
   122       let
   123         val tfrees = fold Term.add_tfreesT Ts [];
   124         val inferred_sort =
   125           (fold o fold_atyps) (fn TVar (_, S) => inter_sort S | _ => I) Ts [];
   126         val fixate_sort =
   127           (case tfrees of
   128             [] => inferred_sort
   129           | [(a, S)] =>
   130               if a <> Name.aT then
   131                 error ("No type variable other than " ^ Name.aT ^ " allowed in class specification")
   132               else if Sorts.sort_le algebra (S, inferred_sort) then S
   133               else
   134                 error ("Type inference imposes additional sort constraint " ^
   135                   Syntax.string_of_sort_global thy inferred_sort ^
   136                   " of type parameter " ^ Name.aT ^ " of sort " ^
   137                   Syntax.string_of_sort_global thy S)
   138           | _ => error "Multiple type variables in class specification");
   139         val fixateT = TFree (Name.aT, fixate_sort);
   140       in
   141         (map o map_atyps)
   142           (fn T as TVar (xi, _) => if Type_Infer.is_param xi then fixateT else T | T => T) Ts
   143       end;
   144     fun singleton_fixate _ ts = burrow_types singleton_fixateT ts;
   145     fun unify_params ctxt ts =
   146       let
   147         val param_Ts = (fold o fold_aterms)
   148           (fn Free (v, T) => if is_param v then fold_atyps (insert (op =)) T else I | _ => I) ts [];
   149         val param_namesT = map_filter (try (fst o dest_TVar)) param_Ts;
   150         val param_T = if null param_namesT then NONE
   151           else SOME (case get_first (try dest_TFree) param_Ts of
   152             SOME v_sort => TFree v_sort |
   153             NONE => TVar (hd param_namesT, proto_base_sort));
   154       in case param_T of
   155         NONE => ts |
   156         SOME T => map (subst_TVars (map (rpair T) param_namesT)) ts
   157       end;
   158 
   159     (* preprocessing elements, retrieving base sort from type-checked elements *)
   160     val raw_supexpr =
   161       (map (fn sup => (sup, (("", false), Expression.Positional []))) sups, []);
   162     val init_class_body =
   163       fold (Proof_Context.add_const_constraint o apsnd SOME) base_constraints
   164       #> Class.redeclare_operations thy sups
   165       #> Context.proof_map (Syntax_Phases.term_check 0 "singleton_fixate" singleton_fixate);
   166     val ((raw_supparams, _, raw_inferred_elems, _), _) =
   167       Proof_Context.init_global thy
   168       |> Context.proof_map (Syntax_Phases.term_check 0 "unify_params" unify_params)
   169       |> prep_decl raw_supexpr init_class_body raw_elems;
   170     fun filter_element (Element.Fixes []) = NONE
   171       | filter_element (e as Element.Fixes _) = SOME e
   172       | filter_element (Element.Constrains []) = NONE
   173       | filter_element (e as Element.Constrains _) = SOME e
   174       | filter_element (Element.Assumes []) = NONE
   175       | filter_element (e as Element.Assumes _) = SOME e
   176       | filter_element (Element.Defines _) =
   177           error ("\"defines\" element not allowed in class specification.")
   178       | filter_element (Element.Notes _) =
   179           error ("\"notes\" element not allowed in class specification.");
   180     val inferred_elems = map_filter filter_element raw_inferred_elems;
   181     fun fold_element_types f (Element.Fixes fxs) = fold (fn (_, SOME T, _) => f T) fxs
   182       | fold_element_types f (Element.Constrains cnstrs) = fold (f o snd) cnstrs
   183       | fold_element_types f (Element.Assumes assms) = fold (fold (fn (t, ts) =>
   184           fold_types f t #> (fold o fold_types) f ts) o snd) assms;
   185     val base_sort =
   186       if null inferred_elems then proto_base_sort
   187       else
   188         (case (fold o fold_element_types) Term.add_tfreesT inferred_elems [] of
   189           [] => error "No type variable in class specification"
   190         | [(_, sort)] => sort
   191         | _ => error "Multiple type variables in class specification");
   192     val supparams = map (fn ((c, T), _) =>
   193       (c, map_atyps (K (TFree (Name.aT, base_sort))) T)) raw_supparams;
   194     val supparam_names = map fst supparams;
   195     fun mk_param ((c, _), _) = Free (c, (the o AList.lookup (op =) supparams) c);
   196     val supexpr = (map (fn sup => (sup, (("", false),
   197       Expression.Positional (map (SOME o mk_param) (Locale.params_of thy sup))))) sups,
   198         map (fn (c, T) => (Binding.name c, SOME T, NoSyn)) supparams);
   199 
   200   in (base_sort, supparam_names, supexpr, inferred_elems) end;
   201 
   202 val cert_class_elems = prep_class_elems Expression.cert_declaration;
   203 val read_class_elems = prep_class_elems Expression.cert_read_declaration;
   204 
   205 fun prep_class_spec prep_class prep_class_elems thy raw_supclasses raw_elems =
   206   let
   207     val thy_ctxt = Proof_Context.init_global thy;
   208 
   209     (* prepare import *)
   210     val inter_sort = curry (Sorts.inter_sort (Sign.classes_of thy));
   211     val sups = Sign.minimize_sort thy (map (prep_class thy_ctxt) raw_supclasses);
   212     val _ =
   213       (case filter_out (Class.is_class thy) sups of
   214         [] => ()
   215       | no_classes => error ("No (proper) classes: " ^ commas_quote no_classes));
   216     val raw_supparams = (map o apsnd) (snd o snd) (Class.these_params thy sups);
   217     val raw_supparam_names = map fst raw_supparams;
   218     val _ =
   219       if has_duplicates (op =) raw_supparam_names then
   220         error ("Duplicate parameter(s) in superclasses: " ^
   221           (commas_quote (duplicates (op =) raw_supparam_names)))
   222       else ();
   223 
   224     (* infer types and base sort *)
   225     val (base_sort, supparam_names, supexpr, inferred_elems) = prep_class_elems thy sups raw_elems;
   226     val sup_sort = inter_sort base_sort sups;
   227 
   228     (* process elements as class specification *)
   229     val class_ctxt = Class.begin sups base_sort thy_ctxt;
   230     val ((_, _, syntax_elems, _), _) = class_ctxt
   231       |> Expression.cert_declaration supexpr I inferred_elems;
   232     fun check_vars e vs =
   233       if null vs then
   234         error ("No type variable in part of specification element " ^
   235           Pretty.string_of (Pretty.chunks (Element.pretty_ctxt class_ctxt e)))
   236       else ();
   237     fun check_element (e as Element.Fixes fxs) =
   238           List.app (fn (_, SOME T, _) => check_vars e (Term.add_tfreesT T [])) fxs
   239       | check_element (e as Element.Assumes assms) =
   240           List.app (fn (_, ts_pss) =>
   241             List.app (fn (t, _) => check_vars e (Term.add_tfrees t [])) ts_pss) assms
   242       | check_element _ = ();
   243     val _ = List.app check_element syntax_elems;
   244     fun fork_syn (Element.Fixes xs) =
   245           fold_map (fn (c, ty, syn) => cons (c, syn) #> pair (c, ty, NoSyn)) xs
   246           #>> Element.Fixes
   247       | fork_syn x = pair x;
   248     val (elems, global_syntax) = fold_map fork_syn syntax_elems [];
   249 
   250   in (((sups, supparam_names), (sup_sort, base_sort, supexpr)), (elems, global_syntax)) end;
   251 
   252 val cert_class_spec = prep_class_spec (K I) cert_class_elems;
   253 val read_class_spec = prep_class_spec Proof_Context.read_class read_class_elems;
   254 
   255 
   256 (* class establishment *)
   257 
   258 fun add_consts class base_sort sups supparam_names global_syntax thy =
   259   let
   260     (*FIXME simplify*)
   261     val supconsts = supparam_names
   262       |> AList.make (snd o the o AList.lookup (op =) (Class.these_params thy sups))
   263       |> (map o apsnd o apsnd o map_atyps o K o TFree) (Name.aT, [class]);
   264     val all_params = Locale.params_of thy class;
   265     val raw_params = (snd o chop (length supparam_names)) all_params;
   266     fun add_const ((raw_c, raw_ty), _) thy =
   267       let
   268         val b = Binding.name raw_c;
   269         val c = Sign.full_name thy b;
   270         val ty = map_atyps (K (TFree (Name.aT, base_sort))) raw_ty;
   271         val ty0 = Type.strip_sorts ty;
   272         val ty' = map_atyps (K (TFree (Name.aT, [class]))) ty0;
   273         val syn = (the_default NoSyn o AList.lookup Binding.eq_name global_syntax) b;
   274       in
   275         thy
   276         |> Sign.declare_const_global ((b, ty0), syn)
   277         |> snd
   278         |> pair ((Variable.check_name b, ty), (c, ty'))
   279       end;
   280   in
   281     thy
   282     |> Sign.add_path (Class.class_prefix class)
   283     |> fold_map add_const raw_params
   284     ||> Sign.restore_naming thy
   285     |-> (fn params => pair (supconsts @ (map o apfst) fst params, params))
   286   end;
   287 
   288 fun adjungate_axclass bname class base_sort sups supsort supparam_names global_syntax thy =
   289   let
   290     (*FIXME simplify*)
   291     fun globalize param_map = map_aterms
   292       (fn Free (v, ty) => Const ((fst o the o AList.lookup (op =) param_map) v, ty)
   293         | t => t);
   294     val raw_pred = Locale.intros_of thy class
   295       |> fst
   296       |> Option.map (Logic.unvarify_global o Logic.strip_imp_concl o Thm.prop_of);
   297     fun get_axiom thy =
   298       (case #axioms (Axclass.get_info thy class) of
   299          [] => NONE
   300       | [thm] => SOME thm);
   301   in
   302     thy
   303     |> add_consts class base_sort sups supparam_names global_syntax
   304     |-> (fn (param_map, params) => Axclass.define_class (bname, supsort)
   305           (map (fst o snd) params)
   306           [(Thm.empty_binding, Option.map (globalize param_map) raw_pred |> the_list)]
   307     #> snd
   308     #> `get_axiom
   309     #-> (fn assm_axiom => fold (Sign.add_const_constraint o apsnd SOME o snd) params
   310     #> pair (param_map, params, assm_axiom)))
   311   end;
   312 
   313 fun gen_class prep_class_spec b raw_supclasses raw_elems thy =
   314   let
   315     val class = Sign.full_name thy b;
   316     val prefix = Binding.qualify true "class";
   317     val (((sups, supparam_names), (supsort, base_sort, supexpr)), (elems, global_syntax)) =
   318       prep_class_spec thy raw_supclasses raw_elems;
   319   in
   320     thy
   321     |> Expression.add_locale b (prefix b) supexpr elems
   322     |> snd |> Local_Theory.exit_global
   323     |> adjungate_axclass b class base_sort sups supsort supparam_names global_syntax
   324     |-> (fn (param_map, params, assm_axiom) =>
   325        `(fn thy => calculate thy class sups base_sort param_map assm_axiom)
   326     #-> (fn (base_morph, eq_morph, export_morph, some_axiom, some_assm_intro, of_class) =>
   327        Context.theory_map (Locale.add_registration (class, base_morph)
   328          (Option.map (rpair true) eq_morph) export_morph)
   329     #> Class.register class sups params base_sort base_morph export_morph some_axiom some_assm_intro of_class
   330     #> Global_Theory.store_thm (prefix (Binding.qualified_name (class ^ ".of_class.intro")), of_class)))
   331     |> snd
   332     |> Named_Target.init class
   333     |> pair class
   334   end;
   335 
   336 in
   337 
   338 val class = gen_class cert_class_spec;
   339 val class_cmd = gen_class read_class_spec;
   340 
   341 end; (*local*)
   342 
   343 
   344 
   345 (** subclass relations **)
   346 
   347 local
   348 
   349 fun gen_subclass prep_class do_proof raw_sup lthy =
   350   let
   351     val thy = Proof_Context.theory_of lthy;
   352     val proto_sup = prep_class thy raw_sup;
   353     val proto_sub = case Named_Target.class_of lthy of
   354         SOME class => class
   355       | NONE => error "Not in a class target";
   356     val (sub, sup) = Axclass.cert_classrel thy (proto_sub, proto_sup);
   357 
   358     val expr = ([(sup, (("", false), Expression.Positional []))], []);
   359     val (([props], deps, export), goal_ctxt) =
   360       Expression.cert_goal_expression expr lthy;
   361     val some_prop = try the_single props;
   362     val some_dep_morph = try the_single (map snd deps);
   363     fun after_qed some_wit =
   364       Class.register_subclass (sub, sup) some_dep_morph some_wit export;
   365   in do_proof after_qed some_prop goal_ctxt end;
   366 
   367 fun user_proof after_qed some_prop =
   368   Element.witness_proof (after_qed o try the_single o the_single)
   369     [the_list some_prop];
   370 
   371 fun tactic_proof tac after_qed some_prop ctxt =
   372   after_qed (Option.map
   373     (fn prop => Element.prove_witness ctxt prop tac) some_prop) ctxt;
   374 
   375 in
   376 
   377 fun prove_subclass tac = gen_subclass (K I) (tactic_proof tac);
   378 
   379 fun subclass x = gen_subclass (K I) user_proof x;
   380 fun subclass_cmd x =
   381   gen_subclass (Proof_Context.read_class o Proof_Context.init_global) user_proof x;
   382 
   383 end; (*local*)
   384 
   385 end;