src/Pure/Isar/class_declaration.ML
changeset 38379 67d71449e85b
parent 38376 dc67291d590b
child 38384 07c33be08476
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/Pure/Isar/class_declaration.ML	Wed Aug 11 16:02:03 2010 +0200
     1.3 @@ -0,0 +1,345 @@
     1.4 +(*  Title:      Pure/Isar/class_declaration.ML
     1.5 +    Author:     Florian Haftmann, TU Muenchen
     1.6 +
     1.7 +Declaring classes and subclass relations.
     1.8 +*)
     1.9 +
    1.10 +signature CLASS_DECLARATION =
    1.11 +sig
    1.12 +  val class: binding -> class list -> Element.context_i list
    1.13 +    -> theory -> string * local_theory
    1.14 +  val class_cmd: binding -> xstring list -> Element.context list
    1.15 +    -> theory -> string * local_theory
    1.16 +  val prove_subclass: tactic -> class -> local_theory -> local_theory
    1.17 +  val subclass: class -> local_theory -> Proof.state
    1.18 +  val subclass_cmd: xstring -> local_theory -> Proof.state
    1.19 +end;
    1.20 +
    1.21 +structure Class_Declaration: CLASS_DECLARATION =
    1.22 +struct
    1.23 +
    1.24 +(** class definitions **)
    1.25 +
    1.26 +local
    1.27 +
    1.28 +(* calculating class-related rules including canonical interpretation *)
    1.29 +
    1.30 +fun calculate thy class sups base_sort param_map assm_axiom =
    1.31 +  let
    1.32 +    val empty_ctxt = ProofContext.init_global thy;
    1.33 +
    1.34 +    (* instantiation of canonical interpretation *)
    1.35 +    val aT = TFree (Name.aT, base_sort);
    1.36 +    val param_map_const = (map o apsnd) Const param_map;
    1.37 +    val param_map_inst = (map o apsnd)
    1.38 +      (Const o apsnd (map_atyps (K aT))) param_map;
    1.39 +    val const_morph = Element.inst_morphism thy
    1.40 +      (Symtab.empty, Symtab.make param_map_inst);
    1.41 +    val typ_morph = Element.inst_morphism thy
    1.42 +      (Symtab.empty |> Symtab.update (Name.aT, TFree (Name.aT, [class])), Symtab.empty);
    1.43 +    val (([raw_props], [(_, raw_inst_morph)], export_morph), _) = empty_ctxt
    1.44 +      |> Expression.cert_goal_expression ([(class, (("", false),
    1.45 +           Expression.Named param_map_const))], []);
    1.46 +    val (props, inst_morph) = if null param_map
    1.47 +      then (raw_props |> map (Morphism.term typ_morph),
    1.48 +        raw_inst_morph $> typ_morph)
    1.49 +      else (raw_props, raw_inst_morph); (*FIXME proper handling in
    1.50 +        locale.ML / expression.ML would be desirable*)
    1.51 +
    1.52 +    (* witness for canonical interpretation *)
    1.53 +    val prop = try the_single props;
    1.54 +    val wit = Option.map (fn prop => let
    1.55 +        val sup_axioms = map_filter (fst o Class.rules thy) sups;
    1.56 +        val loc_intro_tac = case Locale.intros_of thy class
    1.57 +          of (_, NONE) => all_tac
    1.58 +           | (_, SOME intro) => ALLGOALS (Tactic.rtac intro);
    1.59 +        val tac = loc_intro_tac
    1.60 +          THEN ALLGOALS (ProofContext.fact_tac (sup_axioms @ the_list assm_axiom))
    1.61 +      in Element.prove_witness empty_ctxt prop tac end) prop;
    1.62 +    val axiom = Option.map Element.conclude_witness wit;
    1.63 +
    1.64 +    (* canonical interpretation *)
    1.65 +    val base_morph = inst_morph
    1.66 +      $> Morphism.binding_morphism (Binding.prefix false (Class.class_prefix class))
    1.67 +      $> Element.satisfy_morphism (the_list wit);
    1.68 +    val eq_morph = Element.eq_morphism thy (Class.these_defs thy sups);
    1.69 +
    1.70 +    (* assm_intro *)
    1.71 +    fun prove_assm_intro thm =
    1.72 +      let
    1.73 +        val ((_, [thm']), _) = Variable.import true [thm] empty_ctxt;
    1.74 +        val const_eq_morph = case eq_morph
    1.75 +         of SOME eq_morph => const_morph $> eq_morph
    1.76 +          | NONE => const_morph
    1.77 +        val thm'' = Morphism.thm const_eq_morph thm';
    1.78 +        val tac = ALLGOALS (ProofContext.fact_tac [thm'']);
    1.79 +      in Skip_Proof.prove_global thy [] [] (Thm.prop_of thm'') (K tac) end;
    1.80 +    val assm_intro = Option.map prove_assm_intro
    1.81 +      (fst (Locale.intros_of thy class));
    1.82 +
    1.83 +    (* of_class *)
    1.84 +    val of_class_prop_concl = Logic.mk_of_class (aT, class);
    1.85 +    val of_class_prop = case prop of NONE => of_class_prop_concl
    1.86 +      | SOME prop => Logic.mk_implies (Morphism.term const_morph
    1.87 +          ((map_types o map_atyps) (K aT) prop), of_class_prop_concl);
    1.88 +    val sup_of_classes = map (snd o Class.rules thy) sups;
    1.89 +    val loc_axiom_intros = map Drule.export_without_context_open (Locale.axioms_of thy class);
    1.90 +    val axclass_intro = #intro (AxClass.get_info thy class);
    1.91 +    val base_sort_trivs = Thm.of_sort (Thm.ctyp_of thy aT, base_sort);
    1.92 +    val tac = REPEAT (SOMEGOAL
    1.93 +      (Tactic.match_tac (axclass_intro :: sup_of_classes
    1.94 +         @ loc_axiom_intros @ base_sort_trivs)
    1.95 +           ORELSE' Tactic.assume_tac));
    1.96 +    val of_class = Skip_Proof.prove_global thy [] [] of_class_prop (K tac);
    1.97 +
    1.98 +  in (base_morph, eq_morph, export_morph, axiom, assm_intro, of_class) end;
    1.99 +
   1.100 +
   1.101 +(* reading and processing class specifications *)
   1.102 +
   1.103 +fun prep_class_elems prep_decl thy sups raw_elems =
   1.104 +  let
   1.105 +
   1.106 +    (* user space type system: only permits 'a type variable, improves towards 'a *)
   1.107 +    val algebra = Sign.classes_of thy;
   1.108 +    val inter_sort = curry (Sorts.inter_sort algebra);
   1.109 +    val proto_base_sort = if null sups then Sign.defaultS thy
   1.110 +      else fold inter_sort (map (Class.base_sort thy) sups) [];
   1.111 +    val base_constraints = (map o apsnd)
   1.112 +      (map_type_tfree (K (TVar ((Name.aT, 0), proto_base_sort))) o fst o snd)
   1.113 +        (Class.these_operations thy sups);
   1.114 +    val reject_bcd_etc = (map o map_atyps) (fn T as TFree (v, sort) =>
   1.115 +          if v = Name.aT then T
   1.116 +          else error ("No type variable other than " ^ Name.aT ^ " allowed in class specification")
   1.117 +      | T => T);
   1.118 +    fun singleton_fixate Ts =
   1.119 +      let
   1.120 +        fun extract f = (fold o fold_atyps) f Ts [];
   1.121 +        val tfrees = extract
   1.122 +          (fn TFree (v, sort) => insert (op =) (v, sort) | _ => I);
   1.123 +        val inferred_sort = extract
   1.124 +          (fn TVar (_, sort) => inter_sort sort | _ => I);
   1.125 +        val fixate_sort = if null tfrees then inferred_sort
   1.126 +          else case tfrees
   1.127 +           of [(_, a_sort)] => if Sorts.sort_le algebra (a_sort, inferred_sort)
   1.128 +                then inter_sort a_sort inferred_sort
   1.129 +                else error ("Type inference imposes additional sort constraint "
   1.130 +                  ^ Syntax.string_of_sort_global thy inferred_sort
   1.131 +                  ^ " of type parameter " ^ Name.aT ^ " of sort "
   1.132 +                  ^ Syntax.string_of_sort_global thy a_sort ^ ".")
   1.133 +            | _ => error "Multiple type variables in class specification.";
   1.134 +      in (map o map_atyps) (K (TFree (Name.aT, fixate_sort))) Ts end;
   1.135 +    fun add_typ_check level name f = Context.proof_map
   1.136 +      (Syntax.add_typ_check level name (fn xs => fn ctxt =>
   1.137 +        let val xs' = f xs in if eq_list (op =) (xs, xs') then NONE else SOME (xs', ctxt) end));
   1.138 +
   1.139 +    (* preprocessing elements, retrieving base sort from type-checked elements *)
   1.140 +    val init_class_body = fold (ProofContext.add_const_constraint o apsnd SOME) base_constraints
   1.141 +      #> Class.redeclare_operations thy sups
   1.142 +      #> add_typ_check 10 "reject_bcd_etc" reject_bcd_etc
   1.143 +      #> add_typ_check ~10 "singleton_fixate" singleton_fixate;
   1.144 +    val raw_supexpr = (map (fn sup => (sup, (("", false),
   1.145 +      Expression.Positional []))) sups, []);
   1.146 +    val ((raw_supparams, _, inferred_elems), _) = ProofContext.init_global thy
   1.147 +      |> prep_decl raw_supexpr init_class_body raw_elems;
   1.148 +    fun fold_element_types f (Element.Fixes fxs) = fold (fn (_, SOME T, _) => f T) fxs
   1.149 +      | fold_element_types f (Element.Constrains cnstrs) = fold (f o snd) cnstrs
   1.150 +      | fold_element_types f (Element.Assumes assms) = fold (fold (fn (t, ts) =>
   1.151 +          fold_types f t #> (fold o fold_types) f ts) o snd) assms
   1.152 +      | fold_element_types f (Element.Defines _) =
   1.153 +          error ("\"defines\" element not allowed in class specification.")
   1.154 +      | fold_element_types f (Element.Notes _) =
   1.155 +          error ("\"notes\" element not allowed in class specification.");
   1.156 +    val base_sort = if null inferred_elems then proto_base_sort else
   1.157 +      case (fold o fold_element_types) Term.add_tfreesT inferred_elems []
   1.158 +       of [] => error "No type variable in class specification"
   1.159 +        | [(_, sort)] => sort
   1.160 +        | _ => error "Multiple type variables in class specification";
   1.161 +    val supparams = map (fn ((c, T), _) =>
   1.162 +      (c, map_atyps (K (TFree (Name.aT, base_sort))) T)) raw_supparams;
   1.163 +    val supparam_names = map fst supparams;
   1.164 +    fun mk_param ((c, _), _) = Free (c, (the o AList.lookup (op =) supparams) c);
   1.165 +    val supexpr = (map (fn sup => (sup, (("", false),
   1.166 +      Expression.Positional (map (SOME o mk_param) (Locale.params_of thy sup))))) sups,
   1.167 +        map (fn (c, T) => (Binding.name c, SOME T, NoSyn)) supparams);
   1.168 +
   1.169 +  in (base_sort, supparam_names, supexpr, inferred_elems) end;
   1.170 +
   1.171 +val cert_class_elems = prep_class_elems Expression.cert_declaration;
   1.172 +val read_class_elems = prep_class_elems Expression.cert_read_declaration;
   1.173 +
   1.174 +fun prep_class_spec prep_class prep_class_elems thy raw_supclasses raw_elems =
   1.175 +  let
   1.176 +
   1.177 +    (* prepare import *)
   1.178 +    val inter_sort = curry (Sorts.inter_sort (Sign.classes_of thy));
   1.179 +    val sups = map (prep_class thy) raw_supclasses
   1.180 +      |> Sign.minimize_sort thy;
   1.181 +    val _ = case filter_out (Class.is_class thy) sups
   1.182 +     of [] => ()
   1.183 +      | no_classes => error ("No (proper) classes: " ^ commas (map quote no_classes));
   1.184 +    val raw_supparams = (map o apsnd) (snd o snd) (Class.these_params thy sups);
   1.185 +    val raw_supparam_names = map fst raw_supparams;
   1.186 +    val _ = if has_duplicates (op =) raw_supparam_names
   1.187 +      then error ("Duplicate parameter(s) in superclasses: "
   1.188 +        ^ (commas o map quote o duplicates (op =)) raw_supparam_names)
   1.189 +      else ();
   1.190 +
   1.191 +    (* infer types and base sort *)
   1.192 +    val (base_sort, supparam_names, supexpr, inferred_elems) =
   1.193 +      prep_class_elems thy sups raw_elems;
   1.194 +    val sup_sort = inter_sort base_sort sups;
   1.195 +
   1.196 +    (* process elements as class specification *)
   1.197 +    val class_ctxt = Class.begin sups base_sort (ProofContext.init_global thy);
   1.198 +    val ((_, _, syntax_elems), _) = class_ctxt
   1.199 +      |> Expression.cert_declaration supexpr I inferred_elems;
   1.200 +    fun check_vars e vs = if null vs
   1.201 +      then error ("No type variable in part of specification element "
   1.202 +        ^ (Pretty.string_of o Pretty.chunks) (Element.pretty_ctxt class_ctxt e))
   1.203 +      else ();
   1.204 +    fun check_element (e as Element.Fixes fxs) =
   1.205 +          map (fn (_, SOME T, _) => check_vars e (Term.add_tfreesT T [])) fxs
   1.206 +      | check_element (e as Element.Assumes assms) =
   1.207 +          maps (fn (_, ts_pss) => map
   1.208 +            (fn (t, _) => check_vars e (Term.add_tfrees t [])) ts_pss) assms
   1.209 +      | check_element e = [()];
   1.210 +    val _ = map check_element syntax_elems;
   1.211 +    fun fork_syn (Element.Fixes xs) =
   1.212 +          fold_map (fn (c, ty, syn) => cons (c, syn) #> pair (c, ty, NoSyn)) xs
   1.213 +          #>> Element.Fixes
   1.214 +      | fork_syn x = pair x;
   1.215 +    val (elems, global_syntax) = fold_map fork_syn syntax_elems [];
   1.216 +
   1.217 +  in (((sups, supparam_names), (sup_sort, base_sort, supexpr)), (elems, global_syntax)) end;
   1.218 +
   1.219 +val cert_class_spec = prep_class_spec (K I) cert_class_elems;
   1.220 +val read_class_spec = prep_class_spec Sign.intern_class read_class_elems;
   1.221 +
   1.222 +
   1.223 +(* class establishment *)
   1.224 +
   1.225 +fun add_consts class base_sort sups supparam_names global_syntax thy =
   1.226 +  let
   1.227 +    (*FIXME simplify*)
   1.228 +    val supconsts = supparam_names
   1.229 +      |> AList.make (snd o the o AList.lookup (op =) (Class.these_params thy sups))
   1.230 +      |> (map o apsnd o apsnd o map_atyps o K o TFree) (Name.aT, [class]);
   1.231 +    val all_params = Locale.params_of thy class;
   1.232 +    val raw_params = (snd o chop (length supparam_names)) all_params;
   1.233 +    fun add_const ((raw_c, raw_ty), _) thy =
   1.234 +      let
   1.235 +        val b = Binding.name raw_c;
   1.236 +        val c = Sign.full_name thy b;
   1.237 +        val ty = map_atyps (K (TFree (Name.aT, base_sort))) raw_ty;
   1.238 +        val ty0 = Type.strip_sorts ty;
   1.239 +        val ty' = map_atyps (K (TFree (Name.aT, [class]))) ty0;
   1.240 +        val syn = (the_default NoSyn o AList.lookup Binding.eq_name global_syntax) b;
   1.241 +      in
   1.242 +        thy
   1.243 +        |> Sign.declare_const ((b, ty0), syn)
   1.244 +        |> snd
   1.245 +        |> pair ((Name.of_binding b, ty), (c, ty'))
   1.246 +      end;
   1.247 +  in
   1.248 +    thy
   1.249 +    |> Sign.add_path (Class.class_prefix class)
   1.250 +    |> fold_map add_const raw_params
   1.251 +    ||> Sign.restore_naming thy
   1.252 +    |-> (fn params => pair (supconsts @ (map o apfst) fst params, params))
   1.253 +  end;
   1.254 +
   1.255 +fun adjungate_axclass bname class base_sort sups supsort supparam_names global_syntax thy =
   1.256 +  let
   1.257 +    (*FIXME simplify*)
   1.258 +    fun globalize param_map = map_aterms
   1.259 +      (fn Free (v, ty) => Const ((fst o the o AList.lookup (op =) param_map) v, ty)
   1.260 +        | t => t);
   1.261 +    val raw_pred = Locale.intros_of thy class
   1.262 +      |> fst
   1.263 +      |> Option.map (Logic.unvarify_global o Logic.strip_imp_concl o Thm.prop_of);
   1.264 +    fun get_axiom thy = case (#axioms o AxClass.get_info thy) class
   1.265 +     of [] => NONE
   1.266 +      | [thm] => SOME thm;
   1.267 +  in
   1.268 +    thy
   1.269 +    |> add_consts class base_sort sups supparam_names global_syntax
   1.270 +    |-> (fn (param_map, params) => AxClass.define_class (bname, supsort)
   1.271 +          (map (fst o snd) params)
   1.272 +          [(Thm.empty_binding, Option.map (globalize param_map) raw_pred |> the_list)]
   1.273 +    #> snd
   1.274 +    #> `get_axiom
   1.275 +    #-> (fn assm_axiom => fold (Sign.add_const_constraint o apsnd SOME o snd) params
   1.276 +    #> pair (param_map, params, assm_axiom)))
   1.277 +  end;
   1.278 +
   1.279 +fun gen_class prep_class_spec b raw_supclasses raw_elems thy =
   1.280 +  let
   1.281 +    val class = Sign.full_name thy b;
   1.282 +    val (((sups, supparam_names), (supsort, base_sort, supexpr)), (elems, global_syntax)) =
   1.283 +      prep_class_spec thy raw_supclasses raw_elems;
   1.284 +  in
   1.285 +    thy
   1.286 +    |> Expression.add_locale b (Binding.qualify true "class" b) supexpr elems
   1.287 +    |> snd |> Local_Theory.exit_global
   1.288 +    |> adjungate_axclass b class base_sort sups supsort supparam_names global_syntax
   1.289 +    ||> Theory.checkpoint
   1.290 +    |-> (fn (param_map, params, assm_axiom) =>
   1.291 +       `(fn thy => calculate thy class sups base_sort param_map assm_axiom)
   1.292 +    #-> (fn (base_morph, eq_morph, export_morph, axiom, assm_intro, of_class) =>
   1.293 +       Context.theory_map (Locale.add_registration (class, base_morph)
   1.294 +         (Option.map (rpair true) eq_morph) export_morph)
   1.295 +    #> Class.register class sups params base_sort base_morph export_morph axiom assm_intro of_class))
   1.296 +    |> Named_Target.init (SOME class)
   1.297 +    |> pair class
   1.298 +  end;
   1.299 +
   1.300 +in
   1.301 +
   1.302 +val class = gen_class cert_class_spec;
   1.303 +val class_cmd = gen_class read_class_spec;
   1.304 +
   1.305 +end; (*local*)
   1.306 +
   1.307 +
   1.308 +(** subclass relations **)
   1.309 +
   1.310 +local
   1.311 +
   1.312 +fun gen_subclass prep_class do_proof raw_sup lthy =
   1.313 +  let
   1.314 +    val thy = ProofContext.theory_of lthy;
   1.315 +    val proto_sup = prep_class thy raw_sup;
   1.316 +    val proto_sub = case Named_Target.peek lthy
   1.317 +     of {is_class = false, ...} => error "Not in a class context"
   1.318 +      | {target, ...} => target;
   1.319 +    val (sub, sup) = AxClass.cert_classrel thy (proto_sub, proto_sup);
   1.320 +
   1.321 +    val expr = ([(sup, (("", false), Expression.Positional []))], []);
   1.322 +    val (([props], deps, export), goal_ctxt) =
   1.323 +      Expression.cert_goal_expression expr lthy;
   1.324 +    val some_prop = try the_single props;
   1.325 +    val some_dep_morph = try the_single (map snd deps);
   1.326 +    fun after_qed some_wit =
   1.327 +      ProofContext.theory (Class.register_subclass (sub, sup)
   1.328 +        some_dep_morph some_wit export)
   1.329 +      #> ProofContext.theory_of #> Named_Target.init (SOME sub);
   1.330 +  in do_proof after_qed some_prop goal_ctxt end;
   1.331 +
   1.332 +fun user_proof after_qed some_prop =
   1.333 +  Element.witness_proof (after_qed o try the_single o the_single)
   1.334 +    [the_list some_prop];
   1.335 +
   1.336 +fun tactic_proof tac after_qed some_prop ctxt =
   1.337 +  after_qed (Option.map
   1.338 +    (fn prop => Element.prove_witness ctxt prop tac) some_prop) ctxt;
   1.339 +
   1.340 +in
   1.341 +
   1.342 +val subclass = gen_subclass (K I) user_proof;
   1.343 +fun prove_subclass tac = gen_subclass (K I) (tactic_proof tac);
   1.344 +val subclass_cmd = gen_subclass (ProofContext.read_class o ProofContext.init_global) user_proof;
   1.345 +
   1.346 +end; (*local*)
   1.347 +
   1.348 +end;