src/Pure/Isar/class.ML
author wenzelm
Sat Mar 07 11:32:31 2009 +0100 (2009-03-07)
changeset 30335 b3ef64cadcad
parent 30242 aea5d7fa7ef5
child 30344 10a67c5ddddb
permissions -rw-r--r--
Binding.str_of: removed verbose feature, include qualifier in output;
renamed Binding.add_prefix to Binding.prefix;
     1 (*  Title:      Pure/Isar/ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Type classes derived from primitive axclasses and locales - interfaces.
     5 *)
     6 
     7 signature CLASS =
     8 sig
     9   include CLASS_TARGET
    10     (*FIXME the split into class_target.ML, theory_target.ML and
    11       class.ML is artificial*)
    12 
    13   val class: bstring -> class list -> Element.context_i list
    14     -> theory -> string * local_theory
    15   val class_cmd: bstring -> xstring list -> Element.context list
    16     -> theory -> string * local_theory
    17   val prove_subclass: tactic -> class -> local_theory -> local_theory
    18   val subclass: class -> local_theory -> Proof.state
    19   val subclass_cmd: xstring -> local_theory -> Proof.state
    20 end;
    21 
    22 structure Class : CLASS =
    23 struct
    24 
    25 open Class_Target;
    26 
    27 (** class definitions **)
    28 
    29 local
    30 
    31 (* calculating class-related rules including canonical interpretation *)
    32 
    33 fun calculate thy class sups base_sort param_map assm_axiom =
    34   let
    35     val empty_ctxt = ProofContext.init thy;
    36 
    37     (* instantiation of canonical interpretation *)
    38     val aT = TFree (Name.aT, base_sort);
    39     val param_map_const = (map o apsnd) Const param_map;
    40     val param_map_inst = (map o apsnd)
    41       (Const o apsnd (map_atyps (K aT))) param_map;
    42     val const_morph = Element.inst_morphism thy
    43       (Symtab.empty, Symtab.make param_map_inst);
    44     val typ_morph = Element.inst_morphism thy
    45       (Symtab.empty |> Symtab.update (Name.aT, TFree (Name.aT, [class])), Symtab.empty);
    46     val (([raw_props], [(_, raw_inst_morph)], export_morph), _) = empty_ctxt
    47       |> Expression.cert_goal_expression ([(class, (("", false),
    48            Expression.Named param_map_const))], []);
    49     val (props, inst_morph) = if null param_map
    50       then (raw_props |> map (Morphism.term typ_morph),
    51         raw_inst_morph $> typ_morph)
    52       else (raw_props, raw_inst_morph); (*FIXME proper handling in
    53         locale.ML / expression.ML would be desirable*)
    54 
    55     (* witness for canonical interpretation *)
    56     val prop = try the_single props;
    57     val wit = Option.map (fn prop => let
    58         val sup_axioms = map_filter (fst o rules thy) sups;
    59         val loc_intro_tac = case Locale.intros_of thy class
    60           of (_, NONE) => all_tac
    61            | (_, SOME intro) => ALLGOALS (Tactic.rtac intro);
    62         val tac = loc_intro_tac
    63           THEN ALLGOALS (ProofContext.fact_tac (sup_axioms @ the_list assm_axiom))
    64       in Element.prove_witness empty_ctxt prop tac end) prop;
    65     val axiom = Option.map Element.conclude_witness wit;
    66 
    67     (* canonical interpretation *)
    68     val base_morph = inst_morph
    69       $> Morphism.binding_morphism (Binding.prefix false (class_prefix class))
    70       $> Element.satisfy_morphism (the_list wit);
    71     val defs = these_defs thy sups;
    72     val eq_morph = Element.eq_morphism thy defs;
    73     val morph = base_morph $> eq_morph;
    74 
    75     (* assm_intro *)
    76     fun prove_assm_intro thm = 
    77       let
    78         val ((_, [thm']), _) = Variable.import_thms true [thm] empty_ctxt;
    79         val thm'' = Morphism.thm (const_morph $> eq_morph) thm';
    80         val tac = ALLGOALS (ProofContext.fact_tac [thm'']);
    81       in Goal.prove_global thy [] [] (Thm.prop_of thm'') (K tac) end;
    82     val assm_intro = Option.map prove_assm_intro
    83       (fst (Locale.intros_of thy class));
    84 
    85     (* of_class *)
    86     val of_class_prop_concl = Logic.mk_inclass (aT, class);
    87     val of_class_prop = case prop of NONE => of_class_prop_concl
    88       | SOME prop => Logic.mk_implies (Morphism.term const_morph
    89           ((map_types o map_atyps) (K aT) prop), of_class_prop_concl);
    90     val sup_of_classes = map (snd o rules thy) sups;
    91     val loc_axiom_intros = map Drule.standard' (Locale.axioms_of thy class);
    92     val axclass_intro = #intro (AxClass.get_info thy class);
    93     val base_sort_trivs = Drule.sort_triv thy (aT, base_sort);
    94     val tac = REPEAT (SOMEGOAL
    95       (Tactic.match_tac (axclass_intro :: sup_of_classes
    96          @ loc_axiom_intros @ base_sort_trivs)
    97            ORELSE' Tactic.assume_tac));
    98     val of_class = Goal.prove_global thy [] [] of_class_prop (K tac);
    99 
   100   in (base_morph, morph, export_morph, axiom, assm_intro, of_class) end;
   101 
   102 
   103 (* reading and processing class specifications *)
   104 
   105 fun prep_class_elems prep_decl thy supexpr sups proto_base_sort raw_elems =
   106   let
   107 
   108     (* user space type system: only permits 'a type variable, improves towards 'a *)
   109     val base_constraints = (map o apsnd)
   110       (map_type_tfree (K (TVar ((Name.aT, 0), proto_base_sort))) o fst o snd)
   111         (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 thy algebra 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) => curry (Sorts.inter_sort algebra) 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 Sorts.inter_sort algebra (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 add_typ_check level name f = Context.proof_map (Syntax.add_typ_check level name (fn xs => fn ctxt =>
   134       let val xs' = f xs in if eq_list (op =) (xs, xs') then NONE else SOME (xs', ctxt) end));
   135 
   136     (* preprocessing elements, retrieving base sort from type-checked elements *)
   137     val init_class_body = fold (ProofContext.add_const_constraint o apsnd SOME) base_constraints
   138       #> redeclare_operations thy sups
   139       #> add_typ_check 10 "reject_bcd_etc" reject_bcd_etc
   140       #> add_typ_check ~10 "singleton_fixate" (singleton_fixate thy (Sign.classes_of thy));
   141     val ((_, _, inferred_elems), _) = ProofContext.init thy
   142       |> prep_decl supexpr init_class_body raw_elems;
   143     fun fold_element_types f (Element.Fixes fxs) = fold (fn (_, SOME T, _) => f T) fxs
   144       | fold_element_types f (Element.Constrains cnstrs) = fold (f o snd) cnstrs
   145       | fold_element_types f (Element.Assumes assms) = fold (fold (fn (t, ts) =>
   146           fold_types f t #> (fold o fold_types) f ts) o snd) assms
   147       | fold_element_types f (Element.Defines _) =
   148           error ("\"defines\" element not allowed in class specification.")
   149       | fold_element_types f (Element.Notes _) =
   150           error ("\"notes\" element not allowed in class specification.");
   151     val base_sort = if null inferred_elems then proto_base_sort else
   152       case (fold o fold_element_types) Term.add_tfreesT inferred_elems []
   153        of [] => error "No type variable in class specification"
   154         | [(_, sort)] => sort
   155         | _ => error "Multiple type variables in class specification"
   156 
   157   in (base_sort, inferred_elems) end;
   158 
   159 val cert_class_elems = prep_class_elems Expression.cert_declaration;
   160 val read_class_elems = prep_class_elems Expression.cert_read_declaration;
   161 
   162 fun prep_class_spec prep_class prep_class_elems thy raw_supclasses raw_elems =
   163   let
   164 
   165     (* prepare import *)
   166     val inter_sort = curry (Sorts.inter_sort (Sign.classes_of thy));
   167     val sups = map (prep_class thy) raw_supclasses
   168       |> Sign.minimize_sort thy;
   169     val _ = case filter_out (is_class thy) sups
   170      of [] => ()
   171       | no_classes => error ("No (proper) classes: " ^ commas (map quote no_classes));
   172           val supparams = (map o apsnd) (snd o snd) (these_params thy sups);
   173     val supparam_names = map fst supparams;
   174     val _ = if has_duplicates (op =) supparam_names
   175       then error ("Duplicate parameter(s) in superclasses: "
   176         ^ (commas o map quote o duplicates (op =)) supparam_names)
   177       else ();
   178     val supexpr = (map (fn sup => (sup, (("", false), Expression.Positional [])))
   179       sups, []);
   180     val given_basesort = fold inter_sort (map (base_sort thy) sups) [];
   181 
   182     (* infer types and base sort *)
   183     val (base_sort, inferred_elems) = prep_class_elems thy supexpr sups
   184       given_basesort raw_elems;
   185     val sup_sort = inter_sort base_sort sups
   186 
   187     (* process elements as class specification *)
   188     val class_ctxt = begin sups base_sort (ProofContext.init thy)
   189     val ((_, _, syntax_elems), _) = class_ctxt
   190       |> Expression.cert_declaration supexpr I inferred_elems;
   191     fun check_vars e vs = if null vs
   192       then error ("No type variable in part of specification element "
   193         ^ (Pretty.output o Pretty.chunks) (Element.pretty_ctxt class_ctxt e))
   194       else ();
   195     fun check_element (e as Element.Fixes fxs) =
   196           map (fn (_, SOME T, _) => check_vars e (Term.add_tfreesT T [])) fxs
   197       | check_element (e as Element.Assumes assms) =
   198           maps (fn (_, ts_pss) => map
   199             (fn (t, _) => check_vars e (Term.add_tfrees t [])) ts_pss) assms
   200       | check_element e = [()];
   201     val _ = map check_element syntax_elems;
   202     fun fork_syn (Element.Fixes xs) =
   203           fold_map (fn (c, ty, syn) => cons (Binding.name_of c, syn) #> pair (c, ty, NoSyn)) xs
   204           #>> Element.Fixes
   205       | fork_syn x = pair x;
   206     val (elems, global_syntax) = fold_map fork_syn syntax_elems [];
   207     val constrain = Element.Constrains ((map o apsnd o map_atyps)
   208       (K (TFree (Name.aT, base_sort))) supparams);
   209       (*FIXME perhaps better: control type variable by explicit
   210       parameter instantiation of import expression*)
   211 
   212   in (((sups, supparam_names), (sup_sort, base_sort, supexpr)), (constrain :: elems, global_syntax)) end;
   213 
   214 val cert_class_spec = prep_class_spec (K I) cert_class_elems;
   215 val read_class_spec = prep_class_spec Sign.intern_class read_class_elems;
   216 
   217 
   218 (* class establishment *)
   219 
   220 fun add_consts bname class base_sort sups supparams global_syntax thy =
   221   let
   222     (*FIXME simplify*)
   223     val supconsts = supparams
   224       |> AList.make (snd o the o AList.lookup (op =) (these_params thy sups))
   225       |> (map o apsnd o apsnd o map_atyps o K o TFree) (Name.aT, [class]);
   226     val all_params = Locale.params_of thy class;
   227     val raw_params = (snd o chop (length supparams)) all_params;
   228     fun add_const (b, SOME raw_ty, _) thy =
   229       let
   230         val v = Binding.name_of b;
   231         val c = Sign.full_bname thy v;
   232         val ty = map_atyps (K (TFree (Name.aT, base_sort))) raw_ty;
   233         val ty0 = Type.strip_sorts ty;
   234         val ty' = map_atyps (K (TFree (Name.aT, [class]))) ty0;
   235         val syn = (the_default NoSyn o AList.lookup (op =) global_syntax) v;
   236       in
   237         thy
   238         |> Sign.declare_const [] ((Binding.name v, ty0), syn)
   239         |> snd
   240         |> pair ((v, ty), (c, ty'))
   241       end;
   242   in
   243     thy
   244     |> Sign.add_path (class_prefix class)
   245     |> fold_map add_const raw_params
   246     ||> Sign.restore_naming thy
   247     |-> (fn params => pair (supconsts @ (map o apfst) fst params, params))
   248   end;
   249 
   250 fun adjungate_axclass bname class base_sort sups supsort supparams global_syntax thy =
   251   let
   252     (*FIXME simplify*)
   253     fun globalize param_map = map_aterms
   254       (fn Free (v, ty) => Const ((fst o the o AList.lookup (op =) param_map) v, ty)
   255         | t => t);
   256     val raw_pred = Locale.intros_of thy class
   257       |> fst
   258       |> Option.map (Logic.unvarify o Logic.strip_imp_concl o Thm.prop_of);
   259     fun get_axiom thy = case (#axioms o AxClass.get_info thy) class
   260      of [] => NONE
   261       | [thm] => SOME thm;
   262   in
   263     thy
   264     |> add_consts bname class base_sort sups supparams global_syntax
   265     |-> (fn (param_map, params) => AxClass.define_class (bname, supsort)
   266           (map (fst o snd) params)
   267           [(Thm.empty_binding, Option.map (globalize param_map) raw_pred |> the_list)]
   268     #> snd
   269     #> `get_axiom
   270     #-> (fn assm_axiom => fold (Sign.add_const_constraint o apsnd SOME o snd) params
   271     #> pair (param_map, params, assm_axiom)))
   272   end;
   273 
   274 fun gen_class prep_spec bname raw_supclasses raw_elems thy =
   275   let
   276     val class = Sign.full_bname thy bname;
   277     val (((sups, supparams), (supsort, base_sort, supexpr)), (elems, global_syntax)) =
   278       prep_spec thy raw_supclasses raw_elems;
   279   in
   280     thy
   281     |> Expression.add_locale bname "" supexpr elems
   282     |> snd |> LocalTheory.exit_global
   283     |> adjungate_axclass bname class base_sort sups supsort supparams global_syntax
   284     |-> (fn (param_map, params, assm_axiom) =>
   285        `(fn thy => calculate thy class sups base_sort param_map assm_axiom)
   286     #-> (fn (base_morph, morph, export_morph, axiom, assm_intro, of_class) =>
   287        Locale.add_registration (class, (morph, export_morph))
   288     #> Locale.activate_global_facts (class, morph $> export_morph)
   289     #> register class sups params base_sort base_morph axiom assm_intro of_class))
   290     |> TheoryTarget.init (SOME class)
   291     |> pair class
   292   end;
   293 
   294 in
   295 
   296 val class = gen_class cert_class_spec;
   297 val class_cmd = gen_class read_class_spec;
   298 
   299 end; (*local*)
   300 
   301 
   302 (** subclass relations **)
   303 
   304 local
   305 
   306 fun gen_subclass prep_class do_proof raw_sup lthy =
   307   let
   308     val thy = ProofContext.theory_of lthy;
   309     val proto_sup = prep_class thy raw_sup;
   310     val proto_sub = case TheoryTarget.peek lthy
   311      of {is_class = false, ...} => error "Not in a class context"
   312       | {target, ...} => target;
   313     val (sub, sup) = AxClass.cert_classrel thy (proto_sub, proto_sup)
   314 
   315     val expr = ([(sup, (("", false), Expression.Positional []))], []);
   316     val (([props], deps, export), goal_ctxt) =
   317       Expression.cert_goal_expression expr lthy;
   318     val some_prop = try the_single props;
   319     val some_dep_morph = try the_single (map snd deps);
   320     fun after_qed some_wit =
   321       ProofContext.theory (register_subclass (sub, sup)
   322         some_dep_morph some_wit export)
   323       #> ProofContext.theory_of #> TheoryTarget.init (SOME sub);
   324   in do_proof after_qed some_prop goal_ctxt end;
   325 
   326 fun user_proof after_qed some_prop =
   327   Element.witness_proof (after_qed o try the_single o the_single)
   328     [the_list some_prop];
   329 
   330 fun tactic_proof tac after_qed some_prop ctxt =
   331   after_qed (Option.map
   332     (fn prop => Element.prove_witness ctxt prop tac) some_prop) ctxt;
   333 
   334 in
   335 
   336 val subclass = gen_subclass (K I) user_proof;
   337 fun prove_subclass tac = gen_subclass (K I) (tactic_proof tac);
   338 val subclass_cmd = gen_subclass Sign.read_class user_proof;
   339 
   340 end; (*local*)
   341 
   342 end;