src/Pure/Isar/expression.ML
author Walther Neuper <walther.neuper@jku.at>
Mon, 21 Dec 2020 15:13:49 +0100
changeset 60140 8bb9b4a2f575
parent 60139 c3cb65678c47
child 60141 538e96acb633
permissions -rw-r--r--
step 4.6: two gaps in trace on SPARK

note: no caller found for "Syntax.read_props" and "Proof.have"
     1 (*  Title:      Pure/Isar/expression.ML
     2     Author:     Clemens Ballarin, TU Muenchen
     3 
     4 Locale expressions and user interface layer of locales.
     5 *)
     6 
     7 signature EXPRESSION =
     8 sig
     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
    15 
    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
    21 
    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)
    31       (*FIXME*)
    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
    39 
    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
    45 end;
    46 
    47 structure Expression (**): EXPRESSION(**) =
    48 struct
    49 
    50 datatype ctxt = datatype Element.ctxt;
    51 
    52 
    53 (*** Expressions ***)
    54 
    55 datatype 'term map =
    56   Positional of 'term option list |
    57   Named of (string * 'term) list;
    58 
    59 type 'term rewrites = (Attrib.binding * 'term) list;
    60 
    61 type ('name, 'term) expr = ('name * ((string * bool) * ('term map * 'term rewrites))) list;
    62 
    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;
    65 
    66 
    67 (** Internalise locale names in expr **)
    68 
    69 fun check_expr thy instances = map (apfst (Locale.check thy)) instances;
    70 
    71 
    72 (** Parameters of expression **)
    73 
    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.*)
    78 
    79 fun parameters_of thy strict (expr, fixed) =
    80   let
    81     val ctxt = Proof_Context.init_global thy;
    82 
    83     fun reject_dups message xs =
    84       (case duplicates (op =) xs of
    85         [] => ()
    86       | dups => error (message ^ commas dups));
    87 
    88     fun parm_eq ((p1, mx1), (p2, mx2)) =
    89       p1 = p2 andalso
    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]));
    93 
    94     fun params_loc loc = Locale.params_of thy loc |> map (apfst #1);
    95     fun params_inst (loc, (prfx, (Positional insts, eqns))) =
    96           let
    97             val ps = params_loc loc;
    98             val d = length ps - length insts;
    99             val insts' =
   100               if d < 0 then
   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))) =
   108           let
   109             val _ =
   110               reject_dups "Duplicate instantiation of the following parameter(s): "
   111                 (map fst insts);
   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;
   116     fun params_expr is =
   117       let
   118         val (is', ps') = fold_map (fn i => fn ps =>
   119           let
   120             val (ps', i') = params_inst i;
   121             val ps'' = distinct parm_eq (ps @ ps');
   122           in (i', ps'') end) is []
   123       in (ps', is') end;
   124 
   125     val (implicit, expr') = params_expr expr;
   126 
   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';
   130     val implicit'' =
   131       if strict then []
   132       else
   133         let
   134           val _ =
   135             reject_dups
   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;
   139 
   140   in (expr', implicit'' @ fixed) end;
   141 
   142 
   143 (** Read instantiation **)
   144 
   145 (* Parse positional or named instantiation *)
   146 
   147 (*1*)local(*1*)
   148 
   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)));
   158 
   159 (*1*)in(*1*)
   160 
   161 fun parse_inst x = prep_inst Syntax.parse_term x;
   162 fun make_inst x = prep_inst (K I) x;
   163 
   164 (*1*)end;(*1*)
   165 
   166 
   167 (* Instantiation morphism *)
   168 
   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 =
   172   let
   173 (** )val _ = writeln "#### Expression.inst_morphism";( **)
   174     (* parameters *)
   175     val parm_types = map #2 (params: (string * typ) list);
   176     val type_parms = fold Term.add_tfreesT parm_types [];
   177 
   178     (* type inference *)
   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' [];
   181     val checked =
   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;
   185 
   186     (* context *)
   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';
   190 
   191     (* instantiation *)
   192     val instT =
   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));
   195     val cert_inst =
   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));
   198   in
   199     (Element.instantiate_normalize_morphism (map (apsnd certT) instT, cert_inst) $>
   200       Morphism.binding_morphism "Expression.inst" (Binding.prefix mandatory prfx), ctxt')
   201   end;
   202 
   203 
   204 (*** Locale processing ***)
   205 
   206 (** Parsing **)
   207 
   208 fun parse_elem prep_typ prep_term ctxt =
   209   Element.map_ctxt
   210    {binding = I,
   211     typ = prep_typ 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),
   214     fact = I,
   215     attrib = I};
   216 
   217 fun prepare_stmt prep_prop prep_obtains ctxt stmt =
   218   (case stmt of
   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 =>
   224       let
   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);
   228 
   229 
   230 (** Simultaneous type inference: instantiations + elements + statement **)
   231 
   232 (*2*)local(*2*)
   233 
   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);
   237 
   238 fun dest_type (T, []) = Logic.dest_type T;
   239 fun dest_term (t, []) = t;
   240 fun dest_propp (p, pats) = (p, pats);
   241 
   242 fun extract_inst (_, (_, ts)) = map mk_term ts;
   243 fun restore_inst ((l, (p, _)), cs) = (l, (p, map dest_term cs));
   244 
   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;
   247 
   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 _) = [];
   254 
   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;
   267 
   268 fun prep (_, pats) (ctxt, t :: ts) =
   269   let
   270 (** )val _ = writeln "##### Expression.prep";((**)**)
   271     val ctxt' = Proof_Context.augment t ctxt
   272   in
   273     ((t, Syntax.check_props (Proof_Context.set_mode Proof_Context.mode_pattern ctxt') pats),
   274       (ctxt', ts))
   275   end;
   276 
   277 (* val check: (term * term list) list -> Proof.context ->
   278       (term * term list) list * Proof.context *)
   279 fun check cs ctxt =
   280   let
   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));
   284   in (cs', ctxt') end;
   285 
   286 (*2*)in(*2*)
   287 
   288 fun check_autofix insts eqnss elems concl ctxt =
   289   let
   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);
   295     (* Type inference *)
   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';
   299   in
   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')
   304   end;
   305 
   306 (*2*)end;(*2*)
   307 
   308 
   309 (** Prepare locale elements **)
   310 
   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;
   320 
   321 
   322 (** Finish locale elements **)
   323 
   324 fun finish_inst ctxt (loc, (prfx, inst)) =
   325   let
   326     val thy = Proof_Context.theory_of ctxt;
   327     val (morph, _) = inst_morphism (map #1 (Locale.params_of thy loc)) (prfx, inst) ctxt;
   328   in (loc, morph) end;
   329 
   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);
   333 
   334 (*3*)local(*3*)
   335 
   336 fun closeup _ _ false elem = elem
   337   | closeup (outer_ctxt, ctxt) parms true elem =
   338       let
   339         (* FIXME consider closing in syntactic phase -- before type checking *)
   340         fun close_frees t =
   341           let
   342             val rev_frees =
   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;
   347 
   348         fun no_binds [] = []
   349           | no_binds _ = error "Illegal term bindings in context element";
   350       in
   351         (case elem of
   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))
   357         | e => e)
   358       end;
   359 
   360 (*3*)in(*3*)
   361 
   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;
   368 
   369 (*3*)end;(*3*)
   370 
   371 
   372 (** Process full context statement: instantiations + elements + statement **)
   373 
   374 (* Interleave incremental parsing and type inference over entire parsed stretch. *)
   375 
   376 (*4*)local(*4*)
   377 
   378 fun abs_def ctxt =
   379   Thm.cterm_of ctxt #> Assumption.assume ctxt #> Local_Defs.abs_def_rule ctxt #> Thm.prop_of;
   380 
   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 =
   384   let
   385     val thy = Proof_Context.theory_of ctxt1;
   386 
   387     val (raw_insts, fixed) = parameters_of thy strict (apfst (prep_expr thy) raw_import);
   388 
   389     fun prep_insts_cumulative (loc, (prfx, (inst, eqns))) (i, insts, eqnss, ctxt) =
   390       let
   391         val params = map #1 (Locale.params_of thy loc);
   392         val inst' = prep_inst ctxt (map #1 params) inst;
   393         val parm_types' =
   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.");
   406              ctxt2);
   407 
   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;
   420 
   421     fun prep_elem raw_elem ctxt =
   422       let
   423         val ctxt' = 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;
   429 
   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);
   433 
   434     fun prep_stmt elems ctxt =
   435       check_autofix insts' [] elems (prepare_stmt parse_prop prep_obtains ctxt raw_stmt) ctxt;
   436 
   437     val _ =
   438       if fixed_frees then ()
   439       else
   440         (case fold (fold (Variable.add_frees ctxt3) o snd o snd) insts' [] of
   441           [] => ()
   442         | frees => error ("Illegal free variables in expression: " ^
   443             commas_quote (map (Syntax.string_of_term ctxt3 o Free) (rev frees))));
   444 
   445     val ((insts, _, elems', concl), ctxt4) = ctxt3
   446       |> init_body
   447       |> fold_map prep_elem raw_elems
   448       |-> prep_stmt;
   449 
   450 
   451     (* parameters from expression and elements *)
   452 
   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;
   456 
   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';
   461 
   462   in ((fixed, deps, eqnss', elems'', concl), (parms, ctxt5)) end;
   463 
   464 (*4*)in(*4*)
   465 
   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);
   470 
   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);
   475 
   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);
   481 
   482 (*4*)end;(*4*)
   483 
   484 
   485 (* Context statement: elements + statement *)
   486 
   487 (*5*)local(*5*)
   488 
   489 fun prep_statement prep activate raw_elems raw_stmt ctxt =
   490   let
   491     val ((_, _, _, elems, concl), _) =
   492       prep {strict = true, do_close = false, fixed_frees = true}
   493         ([], []) I raw_elems raw_stmt ctxt;
   494     val ctxt' = ctxt
   495       |> Proof_Context.set_stmt true
   496       |> fold_map activate elems |> #2
   497       |> Proof_Context.restore_stmt ctxt;
   498   in (concl, ctxt') end;
   499 
   500 (*5*)in(*5*)
   501 
   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;
   504 
   505 (*5*)end;(*5*)
   506 
   507 
   508 (* Locale declaration: import + elements *)
   509 
   510 fun fix_params params =
   511   Proof_Context.add_fixes (map (fn ((x, T), mx) => (Binding.name x, SOME T, mx)) params) #> snd;
   512 
   513 (*6*)local(*6*)
   514 
   515 fun prep_declaration prep activate raw_import init_body raw_elems ctxt =
   516   let
   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 *)
   522     val ctxt' = ctxt
   523       |> fix_params fixed
   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;
   530 
   531 (*6*)in(*6*)
   532 
   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;
   536 
   537 (*6*)end;(*6*)
   538 
   539 
   540 (* Locale expression to set up a goal *)
   541 
   542 (*7*)local(*7*)
   543 
   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;
   547 
   548 fun prep_goal_expression prep expression ctxt =
   549   let
   550     val thy = Proof_Context.theory_of ctxt;
   551 
   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;
   558 
   559     val goal_ctxt = ctxt
   560       |> fix_params fixed
   561       |> (fold o fold) Proof_Context.augment (propss @ eq_propss);
   562 
   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;
   567     val export' =
   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;
   571 
   572 (*7*)in(*7*)
   573 
   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;
   576 
   577 (*7*)end;(*7*)
   578 
   579 
   580 (*** Locale declarations ***)
   581 
   582 (* extract specification text *)
   583 
   584 val norm_term = Envir.beta_norm oo Term.subst_atomic;
   585 
   586 fun bind_def ctxt eq (xs, env, eqs) =
   587   let
   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);
   592   in
   593     (case filter (fn (Free (y', _), _) => y = y' | _ => false) env of
   594       [] => (Term.add_frees b' xs, (Free (y, T), b') :: env, eq :: eqs)
   595     | dups =>
   596         if forall (fn (_, b'') => b' aconv b'') dups then (xs, env, eqs)
   597         else err "Attempt to redefine variable")
   598   end;
   599 
   600 (* text has the following structure:
   601        (((exts, exts'), (ints, ints')), (xs, env, defs))
   602    where
   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
   613    *)
   614 
   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)) =
   619       let
   620         val ts = maps (map #1 o #2) asms;
   621         val ts' = map (norm_term env) ts;
   622         val spec' =
   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;
   630 
   631 fun eval_inst ctxt (loc, morph) text =
   632   let
   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;
   637     val text' =
   638       text |>
   639        (if is_some asm then
   640           eval_text ctxt false (Assumes [(Binding.empty_atts, [(the asm', [])])])
   641         else I) |>
   642        (if not (null defs) then
   643           eval_text ctxt false (Defines (map (fn def => (Binding.empty_atts, (def, []))) defs'))
   644         else I)
   645 (* FIXME clone from locale.ML *)
   646   in text' end;
   647 
   648 fun eval_elem ctxt elem text =
   649   eval_text ctxt true elem text;
   650 
   651 fun eval ctxt deps elems =
   652   let
   653     val text' = fold (eval_inst ctxt) deps ((([], []), ([], [])), ([], [], []));
   654     val ((spec, (_, _, defs))) = fold (eval_elem ctxt) elems text';
   655   in (spec, defs) end;
   656 
   657 (* axiomsN: name of theorem set with destruct rules for locale predicates,
   658      also name suffix of delta predicates and assumptions. *)
   659 
   660 val axiomsN = "axioms";
   661 
   662 (*8*)local(*8*)
   663 
   664 (* introN: name of theorems for introduction rules of locale and
   665      delta predicates *)
   666 
   667 val introN = "intro";
   668 
   669 fun atomize_spec ctxt ts =
   670   let
   671     val t = Logic.mk_conjunction_balanced ts;
   672     val body = Object_Logic.atomize_term ctxt t;
   673     val bodyT = Term.fastype_of body;
   674   in
   675     if bodyT = propT
   676     then (t, propT, Thm.reflexive (Thm.cterm_of ctxt t))
   677     else (body, bodyT, Object_Logic.atomize ctxt (Thm.cterm_of ctxt t))
   678   end;
   679 
   680 (* achieve plain syntax for locale predicates (without "PROP") *)
   681 
   682 fun aprop_tr' n c =
   683   let
   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)
   688       else raise Match;
   689   in (c', tr') end;
   690 
   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)
   697    - thy: the theory
   698 *)
   699 
   700 fun def_pred binding parms defs ts norm_ts thy =
   701   let
   702     val name = Sign.full_name thy binding;
   703 
   704     val thy_ctxt = Proof_Context.init_global thy;
   705 
   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;
   709     val Ts = map #2 xs;
   710     val extraTs =
   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;
   714 
   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;
   718 
   719     val ([pred_def], defs_thy) =
   720       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;
   725 
   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
   731           (false,
   732             Conjunction.intr_balanced (map (Thm.assume o Thm.cterm_of defs_ctxt) norm_ts), 0) 1);
   733 
   734     val conjuncts =
   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);
   738 
   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;
   745 
   746 (*8*)in(*8*)
   747 
   748 (* main predicate definition function *)
   749 
   750 fun define_preds binding parms (((exts, exts'), (ints, ints')), defs) thy =
   751   let
   752     val ctxt = Proof_Context.init_global thy;
   753     val defs' = map (Thm.cterm_of ctxt #> Assumption.assume ctxt #> Drule.abs_def) defs;
   754 
   755     val (a_pred, a_intro, a_axioms, thy'') =
   756       if null exts then (NONE, NONE, [], thy)
   757       else
   758         let
   759           val abinding =
   760             if null ints then binding else Binding.suffix_name ("_" ^ axiomsN) binding;
   761           val ((statement, intro, axioms), thy') =
   762             thy
   763             |> def_pred abinding parms defs' exts exts';
   764           val ((_, [intro']), thy'') =
   765             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'')
   773       else
   774         let
   775           val ((statement, intro, axioms), thy''') =
   776             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'''') =
   780             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,
   786                       [])])]
   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;
   790 
   791 (*8*)end;(*8*)
   792 
   793 
   794 (*9*)local(*9*)
   795 
   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);
   802 
   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;
   808 
   809 val is_hyp = fn Assumes _ => true | Defines _ => true | _ => false;
   810 
   811 fun gen_add_locale prep_decl
   812     binding raw_predicate_binding raw_import raw_body thy =
   813   let
   814     val name = Sign.full_name thy binding;
   815     val _ = Locale.defined thy name andalso
   816       error ("Duplicate definition of locale " ^ quote name);
   817 
   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;
   821 
   822     val extraTs =
   823       subtract (op =)
   824         (fold Term.add_tfreesT (map snd parms) [])
   825         (fold Term.add_tfrees exts' []);
   826     val _ =
   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)));
   831 
   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';
   838 
   839     val a_satisfy = Element.satisfy_morphism a_axioms;
   840     val b_satisfy = Element.satisfy_morphism b_axioms;
   841 
   842     val params = fixed @
   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;
   846 
   847     val hyp_spec = filter is_hyp body_elems;
   848 
   849     val notes =
   850       if is_some asm then
   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])])])]
   854       else [];
   855 
   856     val notes' =
   857       body_elems
   858       |> map (defines_to_notes pred_ctxt)
   859       |> map (Element.transform_ctxt a_satisfy)
   860       |> (fn elems =>
   861         fold_map assumes_to_notes elems (map (Element.conclude_witness pred_ctxt) a_axioms))
   862       |> fst
   863       |> map (Element.transform_ctxt b_satisfy)
   864       |> map_filter (fn Notes notes => SOME notes | _ => NONE);
   865 
   866     val deps' = map (fn (l, morph) => (l, morph $> b_satisfy)) deps;
   867     val axioms = map (Element.conclude_witness pred_ctxt) b_axioms;
   868 
   869     val loc_ctxt = thy'
   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';
   874 
   875   in (name, loc_ctxt) end;
   876 
   877 (*9*)in(*9*)
   878 
   879 val add_locale = gen_add_locale cert_declaration;
   880 val add_locale_cmd = gen_add_locale read_declaration;
   881 
   882 (*9*)end;(*9*)
   883 
   884 end;