1 (* Title: Pure/Isar/expression.ML
2 Author: Clemens Ballarin, TU Muenchen
4 Locale expressions and user interface layer of locales.
9 (* Locale expressions *)
10 datatype 'term map = Positional of 'term option list | Named of (string * 'term) list
11 type 'term rewrites = (Attrib.binding * 'term) list
12 type ('name, 'term) expr = ('name * ((string * bool) * ('term map * 'term rewrites))) list
13 type expression_i = (string, term) expr * (binding * typ option * mixfix) list
14 type expression = (xstring * Position.T, string) expr * (binding * string option * mixfix) list
16 (* Processing of context statements *)
17 val cert_statement: Element.context_i list -> Element.statement_i ->
18 Proof.context -> (Attrib.binding * (term * term list) list) list * Proof.context
19 val read_statement: Element.context list -> Element.statement ->
20 Proof.context -> (Attrib.binding * (term * term list) list) list * Proof.context
22 (* Declaring locales *)
23 val cert_declaration: expression_i -> (Proof.context -> Proof.context) ->
24 Element.context_i list ->
25 Proof.context -> (((string * typ) * mixfix) list * (string * morphism) list
26 * Element.context_i list * Proof.context) * ((string * typ) list * Proof.context)
27 val cert_read_declaration: expression_i -> (Proof.context -> Proof.context) ->
28 Element.context list ->
29 Proof.context -> (((string * typ) * mixfix) list * (string * morphism) list
30 * Element.context_i list * Proof.context) * ((string * typ) list * Proof.context)
32 val read_declaration: expression -> (Proof.context -> Proof.context) -> Element.context list ->
33 Proof.context -> (((string * typ) * mixfix) list * (string * morphism) list
34 * Element.context_i list * Proof.context) * ((string * typ) list * Proof.context)
35 val add_locale: binding -> binding ->
36 expression_i -> Element.context_i list -> theory -> string * local_theory
37 val add_locale_cmd: binding -> binding ->
38 expression -> Element.context list -> theory -> string * local_theory
40 (* Processing of locale expressions *)
41 val cert_goal_expression: expression_i -> Proof.context ->
42 (term list list * term list list * (string * morphism) list * (Attrib.binding * term) list list * morphism) * Proof.context
43 val read_goal_expression: expression -> Proof.context ->
44 (term list list * term list list * (string * morphism) list * (Attrib.binding * term) list list * morphism) * Proof.context
47 structure Expression (**): EXPRESSION(**) =
50 datatype ctxt = datatype Element.ctxt;
56 Positional of 'term option list |
57 Named of (string * 'term) list;
59 type 'term rewrites = (Attrib.binding * 'term) list;
61 type ('name, 'term) expr = ('name * ((string * bool) * ('term map * 'term rewrites))) list;
63 type expression_i = (string, term) expr * (binding * typ option * mixfix) list;
64 type expression = (xstring * Position.T, string) expr * (binding * string option * mixfix) list;
67 (** Internalise locale names in expr **)
69 fun check_expr thy instances = map (apfst (Locale.check thy)) instances;
72 (** Parameters of expression **)
74 (*Sanity check of instantiations and extraction of implicit parameters.
75 The latter only occurs iff strict = false.
76 Positional instantiations are extended to match full length of parameter list
77 of instantiated locale.*)
79 fun parameters_of thy strict (expr, fixed) =
81 val ctxt = Proof_Context.init_global thy;
83 fun reject_dups message xs =
84 (case duplicates (op =) xs of
86 | dups => error (message ^ commas dups));
88 fun parm_eq ((p1, mx1), (p2, mx2)) =
90 (Mixfix.equal (mx1, mx2) orelse
91 error ("Conflicting syntax for parameter " ^ quote p1 ^ " in expression" ^
92 Position.here_list [Mixfix.pos_of mx1, Mixfix.pos_of mx2]));
94 fun params_loc loc = Locale.params_of thy loc |> map (apfst #1);
95 fun params_inst (loc, (prfx, (Positional insts, eqns))) =
97 val ps = params_loc loc;
98 val d = length ps - length insts;
101 error ("More arguments than parameters in instantiation of locale " ^
102 quote (Locale.markup_name ctxt loc))
103 else insts @ replicate d NONE;
104 val ps' = (ps ~~ insts') |>
105 map_filter (fn (p, NONE) => SOME p | (_, SOME _) => NONE);
106 in (ps', (loc, (prfx, (Positional insts', eqns)))) end
107 | params_inst (loc, (prfx, (Named insts, eqns))) =
110 reject_dups "Duplicate instantiation of the following parameter(s): "
112 val ps' = (insts, params_loc loc) |-> fold (fn (p, _) => fn ps =>
113 if AList.defined (op =) ps p then AList.delete (op =) p ps
114 else error (quote p ^ " not a parameter of instantiated expression"));
115 in (ps', (loc, (prfx, (Named insts, eqns)))) end;
118 val (is', ps') = fold_map (fn i => fn ps =>
120 val (ps', i') = params_inst i;
121 val ps'' = distinct parm_eq (ps @ ps');
122 in (i', ps'') end) is []
125 val (implicit, expr') = params_expr expr;
127 val implicit' = map #1 implicit;
128 val fixed' = map (Variable.check_name o #1) fixed;
129 val _ = reject_dups "Duplicate fixed parameter(s): " fixed';
136 "Parameter(s) declared simultaneously in expression and for clause: "
137 (implicit' @ fixed');
138 in map (fn (x, mx) => (Binding.name x, NONE, mx)) implicit end;
140 in (expr', implicit'' @ fixed) end;
143 (** Read instantiation **)
145 (* Parse positional or named instantiation *)
149 fun prep_inst prep_term ctxt parms (Positional insts) =
150 (insts ~~ parms) |> map
151 (fn (NONE, p) => Free (p, dummyT)
152 | (SOME t, _) => prep_term ctxt t)
153 | prep_inst prep_term ctxt parms (Named insts) =
154 parms |> map (fn p =>
155 (case AList.lookup (op =) insts p of
156 SOME t => prep_term ctxt t |
157 NONE => Free (p, dummyT)));
161 fun parse_inst x = prep_inst Syntax.parse_term x;
162 fun make_inst x = prep_inst (K I) x;
167 (* Instantiation morphism *)
169 (*val inst_morphism: (string * typ) list -> (string * bool) * term list -> Proof.context ->
170 morphism * Proof.context*)
171 fun inst_morphism params ((prfx, mandatory), insts') ctxt =
173 (** )val _ = writeln "#### Expression.inst_morphism";( **)
175 val parm_types = map #2 (params: (string * typ) list);
176 val type_parms = fold Term.add_tfreesT parm_types [];
179 val parm_types' = map (Type_Infer.paramify_vars o Logic.varifyT_global) parm_types;
180 val type_parms' = fold Term.add_tvarsT parm_types' [];
182 (map (Logic.mk_type o TVar) type_parms' @ map2 Type.constraint parm_types' insts')
183 |> Syntax.check_terms (Config.put Type_Infer.object_logic false ctxt)
184 val (type_parms'', insts'') = chop (length type_parms') checked;
187 val ctxt' = fold Proof_Context.augment checked ctxt;
188 val certT = Thm.trim_context_ctyp o Thm.ctyp_of ctxt';
189 val cert = Thm.trim_context_cterm o Thm.cterm_of ctxt';
193 (type_parms ~~ map Logic.dest_type type_parms'')
194 |> map_filter (fn (v, T) => if TFree v = T then NONE else SOME (v, T));
196 ((map #1 params ~~ map (Term_Subst.instantiateT_frees instT) parm_types) ~~ insts'')
197 |> map_filter (fn (v, t) => if Free v = t then NONE else SOME (v, cert t));
199 (Element.instantiate_normalize_morphism (map (apsnd certT) instT, cert_inst) $>
200 Morphism.binding_morphism "Expression.inst" (Binding.prefix mandatory prfx), ctxt')
204 (*** Locale processing ***)
208 fun parse_elem prep_typ prep_term ctxt =
212 term = prep_term (Proof_Context.set_mode Proof_Context.mode_schematic ctxt),
213 pattern = prep_term (Proof_Context.set_mode Proof_Context.mode_pattern ctxt),
217 fun prepare_stmt prep_prop prep_obtains ctxt stmt =
219 Element.Shows raw_shows =>
220 raw_shows |> (map o apsnd o map) (fn (t, ps) =>
221 (prep_prop (Proof_Context.set_mode Proof_Context.mode_schematic ctxt) t,
222 map (prep_prop (Proof_Context.set_mode Proof_Context.mode_pattern ctxt)) ps))
223 | Element.Obtains raw_obtains =>
225 val ((_, thesis), thesis_ctxt) = Obtain.obtain_thesis ctxt;
226 val obtains = prep_obtains thesis_ctxt thesis raw_obtains;
227 in map (fn (b, t) => ((b, []), [(t, [])])) obtains end);
230 (** Simultaneous type inference: instantiations + elements + statement **)
234 fun mk_type T = (Logic.mk_type T, []);
235 fun mk_term t = (t, []);
236 fun mk_propp (p, pats) = (Type.constraint propT p, pats);
238 fun dest_type (T, []) = Logic.dest_type T;
239 fun dest_term (t, []) = t;
240 fun dest_propp (p, pats) = (p, pats);
242 fun extract_inst (_, (_, ts)) = map mk_term ts;
243 fun restore_inst ((l, (p, _)), cs) = (l, (p, map dest_term cs));
245 fun extract_eqns es = map (mk_term o snd) es;
246 fun restore_eqns (es, cs) = map2 (fn (b, _) => fn c => (b, dest_term c)) es cs;
248 fun extract_elem (Fixes fixes) = map (#2 #> the_list #> map mk_type) fixes
249 | extract_elem (Constrains csts) = map (#2 #> single #> map mk_type) csts
250 | extract_elem (Assumes asms) = map (#2 #> map mk_propp) asms
251 | extract_elem (Defines defs) = map (fn (_, (t, ps)) => [mk_propp (t, ps)]) defs
252 | extract_elem (Notes _) = []
253 | extract_elem (Lazy_Notes _) = [];
255 fun restore_elem (Fixes fixes, css) =
256 (fixes ~~ css) |> map (fn ((x, _, mx), cs) =>
257 (x, cs |> map dest_type |> try hd, mx)) |> Fixes
258 | restore_elem (Constrains csts, css) =
259 (csts ~~ css) |> map (fn ((x, _), cs) =>
260 (x, cs |> map dest_type |> hd)) |> Constrains
261 | restore_elem (Assumes asms, css) =
262 (asms ~~ css) |> map (fn ((b, _), cs) => (b, map dest_propp cs)) |> Assumes
263 | restore_elem (Defines defs, css) =
264 (defs ~~ css) |> map (fn ((b, _), [c]) => (b, dest_propp c)) |> Defines
265 | restore_elem (elem as Notes _, _) = elem
266 | restore_elem (elem as Lazy_Notes _, _) = elem;
268 fun prep (_, pats) (ctxt, t :: ts) =
270 (** )val _ = writeln "##### Expression.prep";((**)**)
271 val ctxt' = Proof_Context.augment t ctxt
273 ((t, Syntax.check_props (Proof_Context.set_mode Proof_Context.mode_pattern ctxt') pats),
277 (* val check: (term * term list) list -> Proof.context ->
278 (term * term list) list * Proof.context *)
281 val (cs', (ctxt', _)) = fold_map prep cs
282 (ctxt, Syntax.check_terms
283 (Proof_Context.set_mode Proof_Context.mode_schematic ctxt) (map fst cs));
288 fun check_autofix insts eqnss elems concl ctxt =
290 (** )val _ = writeln "##### Expression.check_autofix";( **)
291 val inst_cs = map extract_inst insts;
292 val eqns_cs = map extract_eqns eqnss;
293 val elem_css = map extract_elem elems;
294 val concl_cs = (map o map) mk_propp (map snd concl);
296 val (inst_cs' :: eqns_cs' :: css', ctxt') =
297 (fold_burrow o fold_burrow) check (inst_cs :: eqns_cs :: elem_css @ [concl_cs]) ctxt;
298 val (elem_css', [concl_cs']) = chop (length elem_css) css';
300 ((map restore_inst (insts ~~ inst_cs'),
301 map restore_eqns (eqnss ~~ eqns_cs'),
302 map restore_elem (elems ~~ elem_css'),
303 map fst concl ~~ concl_cs'), ctxt')
309 (** Prepare locale elements **)
311 fun declare_elem prep_var (Fixes fixes) ctxt =
312 let val (vars, _) = fold_map prep_var fixes ctxt
313 in ctxt |> Proof_Context.add_fixes vars |> snd end
314 | declare_elem prep_var (Constrains csts) ctxt =
315 ctxt |> fold_map (fn (x, T) => prep_var (Binding.name x, SOME T, NoSyn)) csts |> snd
316 | declare_elem _ (Assumes _) ctxt = ctxt
317 | declare_elem _ (Defines _) ctxt = ctxt
318 | declare_elem _ (Notes _) ctxt = ctxt
319 | declare_elem _ (Lazy_Notes _) ctxt = ctxt;
322 (** Finish locale elements **)
324 fun finish_inst ctxt (loc, (prfx, inst)) =
326 val thy = Proof_Context.theory_of ctxt;
327 val (morph, _) = inst_morphism (map #1 (Locale.params_of thy loc)) (prfx, inst) ctxt;
330 fun finish_fixes (parms: (string * typ) list) = map (fn (binding, _, mx) =>
331 let val x = Binding.name_of binding
332 in (binding, AList.lookup (op =) parms x, mx) end);
336 fun closeup _ _ false elem = elem
337 | closeup (outer_ctxt, ctxt) parms true elem =
339 (* FIXME consider closing in syntactic phase -- before type checking *)
343 Term.fold_aterms (fn Free (x, T) =>
344 if Variable.is_fixed outer_ctxt x orelse AList.defined (op =) parms x then I
345 else insert (op =) (x, T) | _ => I) t [];
346 in fold (Logic.all o Free) rev_frees t end;
349 | no_binds _ = error "Illegal term bindings in context element";
352 Assumes asms => Assumes (asms |> map (fn (a, propps) =>
353 (a, map (fn (t, ps) => (close_frees t, no_binds ps)) propps)))
354 | Defines defs => Defines (defs |> map (fn ((name, atts), (t, ps)) =>
355 let val ((c, _), t') = Local_Defs.cert_def ctxt (K []) (close_frees t)
356 in ((Thm.def_binding_optional (Binding.name c) name, atts), (t', no_binds ps)) end))
362 fun finish_elem _ parms _ (Fixes fixes) = Fixes (finish_fixes parms fixes)
363 | finish_elem _ _ _ (Constrains _) = Constrains []
364 | finish_elem ctxts parms do_close (Assumes asms) = closeup ctxts parms do_close (Assumes asms)
365 | finish_elem ctxts parms do_close (Defines defs) = closeup ctxts parms do_close (Defines defs)
366 | finish_elem _ _ _ (elem as Notes _) = elem
367 | finish_elem _ _ _ (elem as Lazy_Notes _) = elem;
372 (** Process full context statement: instantiations + elements + statement **)
374 (* Interleave incremental parsing and type inference over entire parsed stretch. *)
379 Thm.cterm_of ctxt #> Assumption.assume ctxt #> Local_Defs.abs_def_rule ctxt #> Thm.prop_of;
381 fun prep_full_context_statement
382 parse_typ parse_prop prep_obtains prep_var_elem prep_inst prep_eqns prep_attr prep_var_inst prep_expr
383 {strict, do_close, fixed_frees} raw_import init_body raw_elems raw_stmt ctxt1 =
385 val thy = Proof_Context.theory_of ctxt1;
387 val (raw_insts, fixed) = parameters_of thy strict (apfst (prep_expr thy) raw_import);
389 fun prep_insts_cumulative (loc, (prfx, (inst, eqns))) (i, insts, eqnss, ctxt) =
391 val params = map #1 (Locale.params_of thy loc);
392 val inst' = prep_inst ctxt (map #1 params) inst;
394 params |> map (#2 #> Logic.varifyT_global #>
395 Term.map_type_tvar (fn ((x, _), S) => TVar ((x, i), S)) #>
396 Type_Infer.paramify_vars);
397 val inst'' = map2 Type.constraint parm_types' inst';
398 val insts' = insts @ [(loc, (prfx, inst''))];
399 val ((insts'', _, _, _), ctxt2) = check_autofix insts' [] [] [] ctxt;
400 val inst''' = insts'' |> List.last |> snd |> snd;
401 val (inst_morph, _) = inst_morphism params (prfx, inst''') ctxt;
402 val ctxt' = Locale.activate_declarations (loc, inst_morph) ctxt2
403 handle ERROR msg => if null eqns then error msg else
404 (Locale.tracing ctxt1
405 (msg ^ "\nFalling back to reading rewrites clause before activation.");
408 val attrss = map (apsnd (map (prep_attr ctxt)) o fst) eqns;
409 val eqns' = (prep_eqns ctxt' o map snd) eqns;
410 val eqnss' = [attrss ~~ eqns'];
411 val ((_, [eqns''], _, _), _) = check_autofix insts'' eqnss' [] [] ctxt';
412 val rewrite_morph = eqns'
413 |> map (abs_def ctxt')
414 |> Variable.export_terms ctxt' ctxt
415 |> Element.eq_term_morphism (Proof_Context.theory_of ctxt)
416 |> the_default Morphism.identity;
417 val ctxt'' = Locale.activate_declarations (loc, inst_morph $> rewrite_morph) ctxt;
418 val eqnss' = eqnss @ [attrss ~~ Variable.export_terms ctxt' ctxt eqns'];
419 in (i + 1, insts', eqnss', ctxt'') end;
421 fun prep_elem raw_elem ctxt =
424 |> Context_Position.set_visible false
425 |> declare_elem prep_var_elem raw_elem
426 |> Context_Position.restore_visible ctxt;
427 val elems' = parse_elem parse_typ parse_prop ctxt' raw_elem;
428 in (elems', ctxt') end;
430 val fors = fold_map prep_var_inst fixed ctxt1 |> fst;
431 val ctxt2 = ctxt1 |> Proof_Context.add_fixes fors |> snd;
432 val (_, insts', eqnss', ctxt3) = fold prep_insts_cumulative raw_insts (0, [], [], ctxt2);
434 fun prep_stmt elems ctxt =
435 check_autofix insts' [] elems (prepare_stmt parse_prop prep_obtains ctxt raw_stmt) ctxt;
438 if fixed_frees then ()
440 (case fold (fold (Variable.add_frees ctxt3) o snd o snd) insts' [] of
442 | frees => error ("Illegal free variables in expression: " ^
443 commas_quote (map (Syntax.string_of_term ctxt3 o Free) (rev frees))));
445 val ((insts, _, elems', concl), ctxt4) = ctxt3
447 |> fold_map prep_elem raw_elems
451 (* parameters from expression and elements *)
453 val xs = maps (fn Fixes fixes => map (Variable.check_name o #1) fixes | _ => [])
454 (Fixes fors :: elems');
455 val (parms, ctxt5) = fold_map Proof_Context.inferred_param xs ctxt4;
457 val fors' = finish_fixes parms fors;
458 val fixed = map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fors';
459 val deps = map (finish_inst ctxt5) insts;
460 val elems'' = map (finish_elem (ctxt1, ctxt5) parms do_close) elems';
462 in ((fixed, deps, eqnss', elems'', concl), (parms, ctxt5)) end;
466 fun cert_full_context_statement x =
467 ((** )writeln "##### Expression.cert_full_context_statement";( **)
468 prep_full_context_statement (K I) (K I) Obtain.cert_obtains
469 Proof_Context.cert_var make_inst Syntax.check_props (K I) Proof_Context.cert_var (K I) x);
471 fun cert_read_full_context_statement x =
472 ((** )writeln "##### Expression.cert_read_full_context_statement";( **)
473 prep_full_context_statement Syntax.parse_typ Syntax.parse_prop Obtain.parse_obtains
474 Proof_Context.read_var make_inst Syntax.check_props (K I) Proof_Context.cert_var (K I) x);
476 fun read_full_context_statement x =
477 ((**)writeln "##### Expression.read_full_context_statement";(**)
478 prep_full_context_statement Syntax.parse_typ Syntax.parse_prop Obtain.parse_obtains
479 Proof_Context.read_var parse_inst Syntax.read_props Attrib.check_src
480 Proof_Context.read_var check_expr x);
485 (* Context statement: elements + statement *)
489 fun prep_statement prep activate raw_elems raw_stmt ctxt =
491 val ((_, _, _, elems, concl), _) =
492 prep {strict = true, do_close = false, fixed_frees = true}
493 ([], []) I raw_elems raw_stmt ctxt;
495 |> Proof_Context.set_stmt true
496 |> fold_map activate elems |> #2
497 |> Proof_Context.restore_stmt ctxt;
498 in (concl, ctxt') end;
502 fun cert_statement x = prep_statement cert_full_context_statement Element.activate_i x;
503 fun read_statement x = prep_statement read_full_context_statement Element.activate x;
508 (* Locale declaration: import + elements *)
510 fun fix_params params =
511 Proof_Context.add_fixes (map (fn ((x, T), mx) => (Binding.name x, SOME T, mx)) params) #> snd;
515 fun prep_declaration prep activate raw_import init_body raw_elems ctxt =
517 val ((fixed, deps, eqnss, elems, _), (parms, ctxt0)) =
518 prep {strict = false, do_close = true, fixed_frees = false}
519 raw_import init_body raw_elems (Element.Shows []) ctxt;
520 val _ = null (flat eqnss) orelse error "Illegal rewrites clause(s) in declaration of locale";
521 (* Declare parameters and imported facts *)
524 |> fold (Context.proof_map o Locale.activate_facts NONE) deps;
525 val (elems', ctxt'') = ctxt'
526 |> Proof_Context.set_stmt true
527 |> fold_map activate elems
528 ||> Proof_Context.restore_stmt ctxt';
529 in ((fixed, deps, elems', ctxt''), (parms, ctxt0)) end;
533 fun cert_declaration x = prep_declaration cert_full_context_statement Element.activate_i x;
534 fun cert_read_declaration x = prep_declaration cert_read_full_context_statement Element.activate x;
535 fun read_declaration x = prep_declaration read_full_context_statement Element.activate x;
540 (* Locale expression to set up a goal *)
544 fun props_of thy (name, morph) =
545 let val (asm, defs) = Locale.specification_of thy name
546 in map (Morphism.term morph) (the_list asm @ defs) end;
548 fun prep_goal_expression prep expression ctxt =
550 val thy = Proof_Context.theory_of ctxt;
552 val ((fixed, deps, eqnss, _, _), _) =
553 prep {strict = true, do_close = true, fixed_frees = true} expression I []
554 (Element.Shows []) ctxt;
555 (* proof obligations *)
556 val propss = map (props_of thy) deps;
557 val eq_propss = (map o map) snd eqnss;
561 |> (fold o fold) Proof_Context.augment (propss @ eq_propss);
563 val export = Proof_Context.export_morphism goal_ctxt ctxt;
564 val exp_fact = Drule.zero_var_indexes_list o map Thm.strip_shyps o Morphism.fact export;
565 val exp_term = Term_Subst.zero_var_indexes o Morphism.term export;
566 val exp_typ = Logic.type_map exp_term;
568 Morphism.morphism "Expression.prep_goal"
569 {binding = [], typ = [exp_typ], term = [exp_term], fact = [exp_fact]};
570 in ((propss, eq_propss, deps, eqnss, export'), goal_ctxt) end;
574 fun cert_goal_expression x = prep_goal_expression cert_full_context_statement x;
575 fun read_goal_expression x = prep_goal_expression read_full_context_statement x;
580 (*** Locale declarations ***)
582 (* extract specification text *)
584 val norm_term = Envir.beta_norm oo Term.subst_atomic;
586 fun bind_def ctxt eq (xs, env, eqs) =
588 val _ = Local_Defs.cert_def ctxt (K []) eq;
589 val ((y, T), b) = Local_Defs.abs_def eq;
590 val b' = norm_term env b;
591 fun err msg = error (msg ^ ": " ^ quote y);
593 (case filter (fn (Free (y', _), _) => y = y' | _ => false) env of
594 [] => (Term.add_frees b' xs, (Free (y, T), b') :: env, eq :: eqs)
596 if forall (fn (_, b'') => b' aconv b'') dups then (xs, env, eqs)
597 else err "Attempt to redefine variable")
600 (* text has the following structure:
601 (((exts, exts'), (ints, ints')), (xs, env, defs))
603 exts: external assumptions (terms in assumes elements)
604 exts': dito, normalised wrt. env
605 ints: internal assumptions (terms in assumptions from insts)
606 ints': dito, normalised wrt. env
607 xs: the free variables in exts' and ints' and rhss of definitions,
608 this includes parameters except defined parameters
609 env: list of term pairs encoding substitutions, where the first term
610 is a free variable; substitutions represent defines elements and
611 the rhs is normalised wrt. the previous env
612 defs: the equations from the defines elements
615 fun eval_text _ _ (Fixes _) text = text
616 | eval_text _ _ (Constrains _) text = text
617 | eval_text _ is_ext (Assumes asms)
618 (((exts, exts'), (ints, ints')), (xs, env, defs)) =
620 val ts = maps (map #1 o #2) asms;
621 val ts' = map (norm_term env) ts;
623 if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
624 else ((exts, exts'), (ints @ ts, ints' @ ts'));
625 in (spec', (fold Term.add_frees ts' xs, env, defs)) end
626 | eval_text ctxt _ (Defines defs) (spec, binds) =
627 (spec, fold (bind_def ctxt o #1 o #2) defs binds)
628 | eval_text _ _ (Notes _) text = text
629 | eval_text _ _ (Lazy_Notes _) text = text;
631 fun eval_inst ctxt (loc, morph) text =
633 val thy = Proof_Context.theory_of ctxt;
634 val (asm, defs) = Locale.specification_of thy loc;
635 val asm' = Option.map (Morphism.term morph) asm;
636 val defs' = map (Morphism.term morph) defs;
640 eval_text ctxt false (Assumes [(Binding.empty_atts, [(the asm', [])])])
642 (if not (null defs) then
643 eval_text ctxt false (Defines (map (fn def => (Binding.empty_atts, (def, []))) defs'))
645 (* FIXME clone from locale.ML *)
648 fun eval_elem ctxt elem text =
649 eval_text ctxt true elem text;
651 fun eval ctxt deps elems =
653 val text' = fold (eval_inst ctxt) deps ((([], []), ([], [])), ([], [], []));
654 val ((spec, (_, _, defs))) = fold (eval_elem ctxt) elems text';
657 (* axiomsN: name of theorem set with destruct rules for locale predicates,
658 also name suffix of delta predicates and assumptions. *)
660 val axiomsN = "axioms";
664 (* introN: name of theorems for introduction rules of locale and
667 val introN = "intro";
669 fun atomize_spec ctxt ts =
671 val t = Logic.mk_conjunction_balanced ts;
672 val body = Object_Logic.atomize_term ctxt t;
673 val bodyT = Term.fastype_of body;
676 then (t, propT, Thm.reflexive (Thm.cterm_of ctxt t))
677 else (body, bodyT, Object_Logic.atomize ctxt (Thm.cterm_of ctxt t))
680 (* achieve plain syntax for locale predicates (without "PROP") *)
684 val c' = Lexicon.mark_const c;
685 fun tr' (_: Proof.context) T args =
686 if T <> dummyT andalso length args = n
687 then Syntax.const "_aprop" $ Term.list_comb (Syntax.const c', args)
691 (* define one predicate including its intro rule and axioms
692 - binding: predicate name
693 - parms: locale parameters
694 - defs: thms representing substitutions from defines elements
695 - ts: terms representing locale assumptions (not normalised wrt. defs)
696 - norm_ts: terms representing locale assumptions (normalised wrt. defs)
700 fun def_pred binding parms defs ts norm_ts thy =
702 val name = Sign.full_name thy binding;
704 val thy_ctxt = Proof_Context.init_global thy;
706 val (body, bodyT, body_eq) = atomize_spec thy_ctxt norm_ts;
707 val env = Term.add_free_names body [];
708 val xs = filter (member (op =) env o #1) parms;
711 (subtract (op =) (fold Term.add_tfreesT Ts []) (Term.add_tfrees body []))
712 |> sort_by #1 |> map TFree;
713 val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
715 val args = map Logic.mk_type extraTs @ map Free xs;
716 val head = Term.list_comb (Const (name, predT), args);
717 val statement = Object_Logic.ensure_propT thy_ctxt head;
719 val ([pred_def], defs_thy) =
721 |> bodyT = propT ? Sign.typed_print_translation [aprop_tr' (length args) name]
722 |> Sign.declare_const_global ((binding, predT), NoSyn) |> snd
723 |> Global_Theory.add_defs false [((Thm.def_binding binding, Logic.mk_equals (head, body)), [])];
724 val defs_ctxt = Proof_Context.init_global defs_thy |> Variable.declare_term head;
726 val intro = Goal.prove_global defs_thy [] norm_ts statement
727 (fn {context = ctxt, ...} =>
728 rewrite_goals_tac ctxt [pred_def] THEN
729 compose_tac defs_ctxt (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
730 compose_tac defs_ctxt
732 Conjunction.intr_balanced (map (Thm.assume o Thm.cterm_of defs_ctxt) norm_ts), 0) 1);
735 (Drule.equal_elim_rule2 OF
736 [body_eq, rewrite_rule defs_ctxt [pred_def] (Thm.assume (Thm.cterm_of defs_ctxt statement))])
737 |> Conjunction.elim_balanced (length ts);
739 val (_, axioms_ctxt) = defs_ctxt
740 |> Assumption.add_assumes (maps Thm.chyps_of (defs @ conjuncts));
741 val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
742 Element.prove_witness axioms_ctxt t
743 (rewrite_goals_tac axioms_ctxt defs THEN compose_tac axioms_ctxt (false, ax, 0) 1));
744 in ((statement, intro, axioms), defs_thy) end;
748 (* main predicate definition function *)
750 fun define_preds binding parms (((exts, exts'), (ints, ints')), defs) thy =
752 val ctxt = Proof_Context.init_global thy;
753 val defs' = map (Thm.cterm_of ctxt #> Assumption.assume ctxt #> Drule.abs_def) defs;
755 val (a_pred, a_intro, a_axioms, thy'') =
756 if null exts then (NONE, NONE, [], thy)
760 if null ints then binding else Binding.suffix_name ("_" ^ axiomsN) binding;
761 val ((statement, intro, axioms), thy') =
763 |> def_pred abinding parms defs' exts exts';
764 val ((_, [intro']), thy'') =
766 |> Sign.qualified_path true abinding
767 |> Global_Theory.note_thms ""
768 ((Binding.name introN, []), [([intro], [Locale.unfold_add])])
769 ||> Sign.restore_naming thy';
770 in (SOME statement, SOME intro', axioms, thy'') end;
771 val (b_pred, b_intro, b_axioms, thy'''') =
772 if null ints then (NONE, NONE, [], thy'')
775 val ((statement, intro, axioms), thy''') =
777 |> def_pred binding parms defs' (ints @ the_list a_pred) (ints' @ the_list a_pred);
778 val ctxt''' = Proof_Context.init_global thy''';
779 val ([(_, [intro']), _], thy'''') =
781 |> Sign.qualified_path true binding
782 |> Global_Theory.note_thmss ""
783 [((Binding.name introN, []), [([intro], [Locale.intro_add])]),
784 ((Binding.name axiomsN, []),
785 [(map (Drule.export_without_context o Element.conclude_witness ctxt''') axioms,
787 ||> Sign.restore_naming thy''';
788 in (SOME statement, SOME intro', axioms, thy'''') end;
789 in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
796 fun assumes_to_notes (Assumes asms) axms =
797 fold_map (fn (a, spec) => fn axs =>
798 let val (ps, qs) = chop (length spec) axs
799 in ((a, [(ps, [])]), qs) end) asms axms
800 |> apfst (curry Notes "")
801 | assumes_to_notes e axms = (e, axms);
803 fun defines_to_notes ctxt (Defines defs) =
804 Notes ("", map (fn (a, (def, _)) =>
805 (a, [([Assumption.assume ctxt (Thm.cterm_of ctxt def)],
806 [(Attrib.internal o K) Locale.witness_add])])) defs)
807 | defines_to_notes _ e = e;
809 val is_hyp = fn Assumes _ => true | Defines _ => true | _ => false;
811 fun gen_add_locale prep_decl
812 binding raw_predicate_binding raw_import raw_body thy =
814 val name = Sign.full_name thy binding;
815 val _ = Locale.defined thy name andalso
816 error ("Duplicate definition of locale " ^ quote name);
818 val ((fixed, deps, body_elems, _), (parms, ctxt')) =
819 prep_decl raw_import I raw_body (Proof_Context.init_global thy);
820 val text as (((_, exts'), _), defs) = eval ctxt' deps body_elems;
824 (fold Term.add_tfreesT (map snd parms) [])
825 (fold Term.add_tfrees exts' []);
827 if null extraTs then ()
828 else warning ("Additional type variable(s) in locale specification " ^
829 Binding.print binding ^ ": " ^
830 commas (map (Syntax.string_of_typ ctxt' o TFree) (sort_by #1 extraTs)));
832 val predicate_binding =
833 if Binding.is_empty raw_predicate_binding then binding
834 else raw_predicate_binding;
835 val ((a_statement, a_intro, a_axioms), (b_statement, b_intro, b_axioms), thy') =
836 define_preds predicate_binding parms text thy;
837 val pred_ctxt = Proof_Context.init_global thy';
839 val a_satisfy = Element.satisfy_morphism a_axioms;
840 val b_satisfy = Element.satisfy_morphism b_axioms;
843 maps (fn Fixes fixes =>
844 map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fixes | _ => []) body_elems;
845 val asm = if is_some b_statement then b_statement else a_statement;
847 val hyp_spec = filter is_hyp body_elems;
851 [("", [((Binding.suffix_name ("_" ^ axiomsN) binding, []),
852 [([Assumption.assume pred_ctxt (Thm.cterm_of pred_ctxt (the asm))],
853 [(Attrib.internal o K) Locale.witness_add])])])]
858 |> map (defines_to_notes pred_ctxt)
859 |> map (Element.transform_ctxt a_satisfy)
861 fold_map assumes_to_notes elems (map (Element.conclude_witness pred_ctxt) a_axioms))
863 |> map (Element.transform_ctxt b_satisfy)
864 |> map_filter (fn Notes notes => SOME notes | _ => NONE);
866 val deps' = map (fn (l, morph) => (l, morph $> b_satisfy)) deps;
867 val axioms = map (Element.conclude_witness pred_ctxt) b_axioms;
870 |> Locale.register_locale binding (extraTs, params)
871 (asm, rev defs) (a_intro, b_intro) axioms hyp_spec [] (rev notes) (rev deps')
872 |> Named_Target.init name
873 |> fold (fn (kind, facts) => Local_Theory.notes_kind kind facts #> snd) notes';
875 in (name, loc_ctxt) end;
879 val add_locale = gen_add_locale cert_declaration;
880 val add_locale_cmd = gen_add_locale read_declaration;