src/Pure/Isar/expression.ML
author wenzelm
Fri Aug 16 20:58:15 2013 +0200 (2013-08-16)
changeset 53041 d51bac27d4a0
parent 52732 b4da1f2ec73f
child 54566 5f3e9baa8f13
permissions -rw-r--r--
more markup -- avoid old Locale.extern;
removed obsolete Locale.intern -- prefer Locale.check;
     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 ('name, 'term) expr = ('name * ((string * bool) * 'term map)) list
    12   type expression_i = (string, term) expr * (binding * typ option * mixfix) list
    13   type expression = (xstring * Position.T, string) expr * (binding * string option * mixfix) list
    14 
    15   (* Processing of context statements *)
    16   val cert_statement: Element.context_i list -> (term * term list) list list ->
    17     Proof.context -> (term * term list) list list * Proof.context
    18   val read_statement: Element.context list -> (string * string list) list list ->
    19     Proof.context -> (term * term list) list list * Proof.context
    20 
    21   (* Declaring locales *)
    22   val cert_declaration: expression_i -> (Proof.context -> Proof.context) -> Element.context_i list ->
    23     Proof.context -> (((string * typ) * mixfix) list * (string * morphism) list
    24       * Element.context_i list * Proof.context) * ((string * typ) list * Proof.context)
    25   val cert_read_declaration: expression_i -> (Proof.context -> Proof.context) -> Element.context list ->
    26     Proof.context -> (((string * typ) * mixfix) list * (string * morphism) list
    27       * Element.context_i list * Proof.context) * ((string * typ) list * Proof.context)
    28       (*FIXME*)
    29   val read_declaration: expression -> (Proof.context -> Proof.context) -> Element.context list ->
    30     Proof.context -> (((string * typ) * mixfix) list * (string * morphism) list
    31       * Element.context_i list * Proof.context) * ((string * typ) list * Proof.context)
    32   val add_locale: (local_theory -> local_theory) -> binding -> binding ->
    33     expression_i -> Element.context_i list -> theory -> string * local_theory
    34   val add_locale_cmd: (local_theory -> local_theory) -> binding -> binding ->
    35     expression -> Element.context list -> theory -> string * local_theory
    36 
    37   (* Interpretation *)
    38   val cert_goal_expression: expression_i -> Proof.context ->
    39     (term list list * (string * morphism) list * morphism) * Proof.context
    40   val read_goal_expression: expression -> Proof.context ->
    41     (term list list * (string * morphism) list * morphism) * Proof.context
    42   val permanent_interpretation: expression_i -> (Attrib.binding * term) list -> local_theory -> Proof.state
    43   val ephemeral_interpretation: expression_i -> (Attrib.binding * term) list -> local_theory -> Proof.state
    44   val interpret: expression_i -> (Attrib.binding * term) list -> bool -> Proof.state -> Proof.state
    45   val interpret_cmd: expression -> (Attrib.binding * string) list ->
    46     bool -> Proof.state -> Proof.state
    47   val interpretation: expression_i -> (Attrib.binding * term) list -> local_theory -> Proof.state
    48   val interpretation_cmd: expression -> (Attrib.binding * string) list -> local_theory -> Proof.state
    49   val sublocale: expression_i -> (Attrib.binding * term) list -> local_theory -> Proof.state
    50   val sublocale_cmd: expression -> (Attrib.binding * string) list -> local_theory -> Proof.state
    51   val sublocale_global: (local_theory -> local_theory) -> string -> expression_i ->
    52     (Attrib.binding * term) list -> theory -> Proof.state
    53   val sublocale_global_cmd: (local_theory -> local_theory) -> xstring * Position.T -> expression ->
    54     (Attrib.binding * string) list -> theory -> Proof.state
    55 
    56   (* Diagnostic *)
    57   val print_dependencies: Proof.context -> bool -> expression -> unit
    58 end;
    59 
    60 structure Expression : EXPRESSION =
    61 struct
    62 
    63 datatype ctxt = datatype Element.ctxt;
    64 
    65 
    66 (*** Expressions ***)
    67 
    68 datatype 'term map =
    69   Positional of 'term option list |
    70   Named of (string * 'term) list;
    71 
    72 type ('name, 'term) expr = ('name * ((string * bool) * 'term map)) list;
    73 
    74 type expression_i = (string, term) expr * (binding * typ option * mixfix) list;
    75 type expression = (xstring * Position.T, string) expr * (binding * string option * mixfix) list;
    76 
    77 
    78 (** Internalise locale names in expr **)
    79 
    80 fun check_expr thy instances = map (apfst (Locale.check thy)) instances;
    81 
    82 
    83 (** Parameters of expression **)
    84 
    85 (*Sanity check of instantiations and extraction of implicit parameters.
    86   The latter only occurs iff strict = false.
    87   Positional instantiations are extended to match full length of parameter list
    88   of instantiated locale.*)
    89 
    90 fun parameters_of thy strict (expr, fixed) =
    91   let
    92     val ctxt = Proof_Context.init_global thy;
    93 
    94     fun reject_dups message xs =
    95       (case duplicates (op =) xs of
    96         [] => ()
    97       | dups => error (message ^ commas dups));
    98 
    99     fun parm_eq ((p1: string, mx1: mixfix), (p2, mx2)) = p1 = p2 andalso
   100       (mx1 = mx2 orelse error ("Conflicting syntax for parameter " ^ quote p1 ^ " in expression"));
   101 
   102     fun params_loc loc = Locale.params_of thy loc |> map (apfst #1);
   103     fun params_inst (loc, (prfx, Positional insts)) =
   104           let
   105             val ps = params_loc loc;
   106             val d = length ps - length insts;
   107             val insts' =
   108               if d < 0 then
   109                 error ("More arguments than parameters in instantiation of locale " ^
   110                   quote (Locale.markup_name ctxt loc))
   111               else insts @ replicate d NONE;
   112             val ps' = (ps ~~ insts') |>
   113               map_filter (fn (p, NONE) => SOME p | (_, SOME _) => NONE);
   114           in (ps', (loc, (prfx, Positional insts'))) end
   115       | params_inst (loc, (prfx, Named insts)) =
   116           let
   117             val _ =
   118               reject_dups "Duplicate instantiation of the following parameter(s): "
   119                 (map fst insts);
   120             val ps' = (insts, params_loc loc) |-> fold (fn (p, _) => fn ps =>
   121               if AList.defined (op =) ps p then AList.delete (op =) p ps
   122               else error (quote p ^ " not a parameter of instantiated expression"));
   123           in (ps', (loc, (prfx, Named insts))) end;
   124     fun params_expr is =
   125       let
   126         val (is', ps') = fold_map (fn i => fn ps =>
   127           let
   128             val (ps', i') = params_inst i;
   129             val ps'' = distinct parm_eq (ps @ ps');
   130           in (i', ps'') end) is []
   131       in (ps', is') end;
   132 
   133     val (implicit, expr') = params_expr expr;
   134 
   135     val implicit' = map #1 implicit;
   136     val fixed' = map (Variable.check_name o #1) fixed;
   137     val _ = reject_dups "Duplicate fixed parameter(s): " fixed';
   138     val implicit'' =
   139       if strict then []
   140       else
   141         let val _ = reject_dups
   142           "Parameter(s) declared simultaneously in expression and for clause: " (implicit' @ fixed')
   143         in map (fn (x, mx) => (Binding.name x, NONE, mx)) implicit end;
   144 
   145   in (expr', implicit'' @ fixed) end;
   146 
   147 
   148 (** Read instantiation **)
   149 
   150 (* Parse positional or named instantiation *)
   151 
   152 local
   153 
   154 fun prep_inst prep_term ctxt parms (Positional insts) =
   155       (insts ~~ parms) |> map
   156         (fn (NONE, p) => Free (p, dummyT)
   157           | (SOME t, _) => prep_term ctxt t)
   158   | prep_inst prep_term ctxt parms (Named insts) =
   159       parms |> map (fn p =>
   160         (case AList.lookup (op =) insts p of
   161           SOME t => prep_term ctxt t |
   162           NONE => Free (p, dummyT)));
   163 
   164 in
   165 
   166 fun parse_inst x = prep_inst Syntax.parse_term x;
   167 fun make_inst x = prep_inst (K I) x;
   168 
   169 end;
   170 
   171 
   172 (* Instantiation morphism *)
   173 
   174 fun inst_morph (parm_names, parm_types) ((prfx, mandatory), insts') ctxt =
   175   let
   176     (* parameters *)
   177     val type_parm_names = fold Term.add_tfreesT parm_types [] |> map fst;
   178 
   179     (* type inference and contexts *)
   180     val parm_types' = map (Type_Infer.paramify_vars o Logic.varifyT_global) parm_types;
   181     val type_parms = fold Term.add_tvarsT parm_types' [] |> map (Logic.mk_type o TVar);
   182     val arg = type_parms @ map2 Type.constraint parm_types' insts';
   183     val res = Syntax.check_terms ctxt arg;
   184     val ctxt' = ctxt |> fold Variable.auto_fixes res;
   185 
   186     (* instantiation *)
   187     val (type_parms'', res') = chop (length type_parms) res;
   188     val insts'' = (parm_names ~~ res') |> map_filter
   189       (fn inst as (x, Free (y, _)) => if x = y then NONE else SOME inst
   190         | inst => SOME inst);
   191     val instT = Symtab.make (type_parm_names ~~ map Logic.dest_type type_parms'');
   192     val inst = Symtab.make insts'';
   193   in
   194     (Element.inst_morphism (Proof_Context.theory_of ctxt) (instT, inst) $>
   195       Morphism.binding_morphism (Binding.prefix mandatory prfx), ctxt')
   196   end;
   197 
   198 
   199 (*** Locale processing ***)
   200 
   201 (** Parsing **)
   202 
   203 fun parse_elem prep_typ prep_term ctxt =
   204   Element.map_ctxt
   205    {binding = I,
   206     typ = prep_typ ctxt,
   207     term = prep_term (Proof_Context.set_mode Proof_Context.mode_schematic ctxt),
   208     pattern = prep_term (Proof_Context.set_mode Proof_Context.mode_pattern ctxt),
   209     fact = I,
   210     attrib = I};
   211 
   212 fun parse_concl prep_term ctxt concl =
   213   (map o map) (fn (t, ps) =>
   214     (prep_term (Proof_Context.set_mode Proof_Context.mode_schematic ctxt) t,
   215       map (prep_term (Proof_Context.set_mode Proof_Context.mode_pattern ctxt)) ps)) concl;
   216 
   217 
   218 (** Simultaneous type inference: instantiations + elements + conclusion **)
   219 
   220 local
   221 
   222 fun mk_type T = (Logic.mk_type T, []);
   223 fun mk_term t = (t, []);
   224 fun mk_propp (p, pats) = (Type.constraint propT p, pats);
   225 
   226 fun dest_type (T, []) = Logic.dest_type T;
   227 fun dest_term (t, []) = t;
   228 fun dest_propp (p, pats) = (p, pats);
   229 
   230 fun extract_inst (_, (_, ts)) = map mk_term ts;
   231 fun restore_inst ((l, (p, _)), cs) = (l, (p, map dest_term cs));
   232 
   233 fun extract_elem (Fixes fixes) = map (#2 #> the_list #> map mk_type) fixes
   234   | extract_elem (Constrains csts) = map (#2 #> single #> map mk_type) csts
   235   | extract_elem (Assumes asms) = map (#2 #> map mk_propp) asms
   236   | extract_elem (Defines defs) = map (fn (_, (t, ps)) => [mk_propp (t, ps)]) defs
   237   | extract_elem (Notes _) = [];
   238 
   239 fun restore_elem (Fixes fixes, css) =
   240       (fixes ~~ css) |> map (fn ((x, _, mx), cs) =>
   241         (x, cs |> map dest_type |> try hd, mx)) |> Fixes
   242   | restore_elem (Constrains csts, css) =
   243       (csts ~~ css) |> map (fn ((x, _), cs) =>
   244         (x, cs |> map dest_type |> hd)) |> Constrains
   245   | restore_elem (Assumes asms, css) =
   246       (asms ~~ css) |> map (fn ((b, _), cs) => (b, map dest_propp cs)) |> Assumes
   247   | restore_elem (Defines defs, css) =
   248       (defs ~~ css) |> map (fn ((b, _), [c]) => (b, dest_propp c)) |> Defines
   249   | restore_elem (Notes notes, _) = Notes notes;
   250 
   251 fun check cs context =
   252   let
   253     fun prep (_, pats) (ctxt, t :: ts) =
   254       let val ctxt' = Variable.auto_fixes t ctxt
   255       in
   256         ((t, Syntax.check_props (Proof_Context.set_mode Proof_Context.mode_pattern ctxt') pats),
   257           (ctxt', ts))
   258       end;
   259     val (cs', (context', _)) = fold_map prep cs
   260       (context, Syntax.check_terms
   261         (Proof_Context.set_mode Proof_Context.mode_schematic context) (map fst cs));
   262   in (cs', context') end;
   263 
   264 in
   265 
   266 fun check_autofix insts elems concl ctxt =
   267   let
   268     val inst_cs = map extract_inst insts;
   269     val elem_css = map extract_elem elems;
   270     val concl_cs = (map o map) mk_propp concl;
   271     (* Type inference *)
   272     val (inst_cs' :: css', ctxt') =
   273       (fold_burrow o fold_burrow) check (inst_cs :: elem_css @ [concl_cs]) ctxt;
   274     val (elem_css', [concl_cs']) = chop (length elem_css) css';
   275   in
   276     (map restore_inst (insts ~~ inst_cs'),
   277       map restore_elem (elems ~~ elem_css'),
   278       concl_cs', ctxt')
   279   end;
   280 
   281 end;
   282 
   283 
   284 (** Prepare locale elements **)
   285 
   286 fun declare_elem prep_vars (Fixes fixes) ctxt =
   287       let val (vars, _) = prep_vars fixes ctxt
   288       in ctxt |> Proof_Context.add_fixes vars |> snd end
   289   | declare_elem prep_vars (Constrains csts) ctxt =
   290       ctxt |> prep_vars (map (fn (x, T) => (Binding.name x, SOME T, NoSyn)) csts) |> snd
   291   | declare_elem _ (Assumes _) ctxt = ctxt
   292   | declare_elem _ (Defines _) ctxt = ctxt
   293   | declare_elem _ (Notes _) ctxt = ctxt;
   294 
   295 
   296 (** Finish locale elements **)
   297 
   298 fun finish_inst ctxt (loc, (prfx, inst)) =
   299   let
   300     val thy = Proof_Context.theory_of ctxt;
   301     val (parm_names, parm_types) = Locale.params_of thy loc |> map #1 |> split_list;
   302     val (morph, _) = inst_morph (parm_names, parm_types) (prfx, inst) ctxt;
   303   in (loc, morph) end;
   304 
   305 fun finish_fixes (parms: (string * typ) list) = map (fn (binding, _, mx) =>
   306   let val x = Binding.name_of binding
   307   in (binding, AList.lookup (op =) parms x, mx) end);
   308 
   309 local
   310 
   311 fun closeup _ _ false elem = elem
   312   | closeup (outer_ctxt, ctxt) parms true elem =
   313       let
   314         (* FIXME consider closing in syntactic phase -- before type checking *)
   315         fun close_frees t =
   316           let
   317             val rev_frees =
   318               Term.fold_aterms (fn Free (x, T) =>
   319                 if Variable.is_fixed outer_ctxt x orelse AList.defined (op =) parms x then I
   320                 else insert (op =) (x, T) | _ => I) t [];
   321           in fold (Logic.all o Free) rev_frees t end;
   322 
   323         fun no_binds [] = []
   324           | no_binds _ = error "Illegal term bindings in context element";
   325       in
   326         (case elem of
   327           Assumes asms => Assumes (asms |> map (fn (a, propps) =>
   328             (a, map (fn (t, ps) => (close_frees t, no_binds ps)) propps)))
   329         | Defines defs => Defines (defs |> map (fn ((name, atts), (t, ps)) =>
   330             let val ((c, _), t') = Local_Defs.cert_def ctxt (close_frees t)
   331             in ((Thm.def_binding_optional (Binding.name c) name, atts), (t', no_binds ps)) end))
   332         | e => e)
   333       end;
   334 
   335 in
   336 
   337 fun finish_elem _ parms _ (Fixes fixes) = Fixes (finish_fixes parms fixes)
   338   | finish_elem _ _ _ (Constrains _) = Constrains []
   339   | finish_elem ctxts parms do_close (Assumes asms) = closeup ctxts parms do_close (Assumes asms)
   340   | finish_elem ctxts parms do_close (Defines defs) = closeup ctxts parms do_close (Defines defs)
   341   | finish_elem _ _ _ (Notes facts) = Notes facts;
   342 
   343 end;
   344 
   345 
   346 (** Process full context statement: instantiations + elements + conclusion **)
   347 
   348 (* Interleave incremental parsing and type inference over entire parsed stretch. *)
   349 
   350 local
   351 
   352 fun prep_full_context_statement
   353     parse_typ parse_prop prep_vars_elem prep_inst prep_vars_inst prep_expr
   354     {strict, do_close, fixed_frees} raw_import init_body raw_elems raw_concl ctxt1 =
   355   let
   356     val thy = Proof_Context.theory_of ctxt1;
   357 
   358     val (raw_insts, fixed) = parameters_of thy strict (apfst (prep_expr thy) raw_import);
   359 
   360     fun prep_insts_cumulative (loc, (prfx, inst)) (i, insts, ctxt) =
   361       let
   362         val (parm_names, parm_types) = Locale.params_of thy loc |> map #1 |> split_list;
   363         val inst' = prep_inst ctxt parm_names inst;
   364         val parm_types' = parm_types
   365           |> map (Type_Infer.paramify_vars o
   366               Term.map_type_tvar (fn ((x, _), S) => TVar ((x, i), S)) o Logic.varifyT_global);
   367         val inst'' = map2 Type.constraint parm_types' inst';
   368         val insts' = insts @ [(loc, (prfx, inst''))];
   369         val (insts'', _, _, _) = check_autofix insts' [] [] ctxt;
   370         val inst''' = insts'' |> List.last |> snd |> snd;
   371         val (morph, _) = inst_morph (parm_names, parm_types) (prfx, inst''') ctxt;
   372         val ctxt'' = Locale.activate_declarations (loc, morph) ctxt;
   373       in (i + 1, insts', ctxt'') end;
   374 
   375     fun prep_elem raw_elem ctxt =
   376       let
   377         val ctxt' = ctxt
   378           |> Context_Position.set_visible false
   379           |> declare_elem prep_vars_elem raw_elem
   380           |> Context_Position.restore_visible ctxt;
   381         val elems' = parse_elem parse_typ parse_prop ctxt' raw_elem;
   382       in (elems', ctxt') end;
   383 
   384     fun prep_concl raw_concl (insts, elems, ctxt) =
   385       let
   386         val concl = parse_concl parse_prop ctxt raw_concl;
   387       in check_autofix insts elems concl ctxt end;
   388 
   389     val fors = prep_vars_inst fixed ctxt1 |> fst;
   390     val ctxt2 = ctxt1 |> Proof_Context.add_fixes fors |> snd;
   391     val (_, insts', ctxt3) = fold prep_insts_cumulative raw_insts (0, [], ctxt2);
   392 
   393     val _ =
   394       if fixed_frees then ()
   395       else
   396         (case fold (fold (Variable.add_frees ctxt3) o snd o snd) insts' [] of
   397           [] => ()
   398         | frees => error ("Illegal free variables in expression: " ^
   399             commas_quote (map (Syntax.string_of_term ctxt3 o Free) (rev frees))));
   400 
   401     val ctxt4 = init_body ctxt3;
   402     val (elems, ctxt5) = fold_map prep_elem raw_elems ctxt4;
   403     val (insts, elems', concl, ctxt6) = prep_concl raw_concl (insts', elems, ctxt5);
   404 
   405     (* Retrieve parameter types *)
   406     val xs = fold (fn Fixes fixes => (fn ps => ps @ map (Variable.check_name o #1) fixes)
   407       | _ => fn ps => ps) (Fixes fors :: elems') [];
   408     val (Ts, ctxt7) = fold_map Proof_Context.inferred_param xs ctxt6;
   409     val parms = xs ~~ Ts;  (* params from expression and elements *)
   410 
   411     val fors' = finish_fixes parms fors;
   412     val fixed = map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fors';
   413     val deps = map (finish_inst ctxt6) insts;
   414     val elems'' = map (finish_elem (ctxt1, ctxt6) parms do_close) elems';
   415 
   416   in ((fixed, deps, elems'', concl), (parms, ctxt7)) end
   417 
   418 in
   419 
   420 fun cert_full_context_statement x =
   421   prep_full_context_statement (K I) (K I) Proof_Context.cert_vars
   422   make_inst Proof_Context.cert_vars (K I) x;
   423 
   424 fun cert_read_full_context_statement x =
   425   prep_full_context_statement Syntax.parse_typ Syntax.parse_prop Proof_Context.read_vars
   426   make_inst Proof_Context.cert_vars (K I) x;
   427 
   428 fun read_full_context_statement x =
   429   prep_full_context_statement Syntax.parse_typ Syntax.parse_prop Proof_Context.read_vars
   430   parse_inst Proof_Context.read_vars check_expr x;
   431 
   432 end;
   433 
   434 
   435 (* Context statement: elements + conclusion *)
   436 
   437 local
   438 
   439 fun prep_statement prep activate raw_elems raw_concl context =
   440   let
   441     val ((_, _, elems, concl), _) =
   442       prep {strict = true, do_close = false, fixed_frees = true}
   443         ([], []) I raw_elems raw_concl context;
   444     val (_, context') = context
   445       |> Proof_Context.set_stmt true
   446       |> fold_map activate elems;
   447   in (concl, context') end;
   448 
   449 in
   450 
   451 fun cert_statement x = prep_statement cert_full_context_statement Element.activate_i x;
   452 fun read_statement x = prep_statement read_full_context_statement Element.activate x;
   453 
   454 end;
   455 
   456 
   457 (* Locale declaration: import + elements *)
   458 
   459 fun fix_params params =
   460   Proof_Context.add_fixes (map (fn ((x, T), mx) => (Binding.name x, SOME T, mx)) params) #> snd;
   461 
   462 local
   463 
   464 fun prep_declaration prep activate raw_import init_body raw_elems context =
   465   let
   466     val ((fixed, deps, elems, _), (parms, ctxt')) =
   467       prep {strict = false, do_close = true, fixed_frees = false}
   468         raw_import init_body raw_elems [] context;
   469     (* Declare parameters and imported facts *)
   470     val context' = context |>
   471       fix_params fixed |>
   472       fold (Context.proof_map o Locale.activate_facts NONE) deps;
   473     val (elems', context'') = context' |>
   474       Proof_Context.set_stmt true |>
   475       fold_map activate elems;
   476   in ((fixed, deps, elems', context''), (parms, ctxt')) end;
   477 
   478 in
   479 
   480 fun cert_declaration x = prep_declaration cert_full_context_statement Element.activate_i x;
   481 fun cert_read_declaration x = prep_declaration cert_read_full_context_statement Element.activate x;
   482 fun read_declaration x = prep_declaration read_full_context_statement Element.activate x;
   483 
   484 end;
   485 
   486 
   487 (* Locale expression to set up a goal *)
   488 
   489 local
   490 
   491 fun props_of thy (name, morph) =
   492   let
   493     val (asm, defs) = Locale.specification_of thy name;
   494   in
   495     (case asm of NONE => defs | SOME asm => asm :: defs) |> map (Morphism.term morph)
   496   end;
   497 
   498 fun prep_goal_expression prep expression context =
   499   let
   500     val thy = Proof_Context.theory_of context;
   501 
   502     val ((fixed, deps, _, _), _) =
   503       prep {strict = true, do_close = true, fixed_frees = true} expression I [] [] context;
   504     (* proof obligations *)
   505     val propss = map (props_of thy) deps;
   506 
   507     val goal_ctxt = context |>
   508       fix_params fixed |>
   509       (fold o fold) Variable.auto_fixes propss;
   510 
   511     val export = Variable.export_morphism goal_ctxt context;
   512     val exp_fact = Drule.zero_var_indexes_list o map Thm.strip_shyps o Morphism.fact export;
   513     val exp_term = Term_Subst.zero_var_indexes o Morphism.term export;
   514     val exp_typ = Logic.type_map exp_term;
   515     val export' =
   516       Morphism.morphism {binding = [], typ = [exp_typ], term = [exp_term], fact = [exp_fact]};
   517   in ((propss, deps, export'), goal_ctxt) end;
   518 
   519 in
   520 
   521 fun cert_goal_expression x = prep_goal_expression cert_full_context_statement x;
   522 fun read_goal_expression x = prep_goal_expression read_full_context_statement x;
   523 
   524 end;
   525 
   526 
   527 (*** Locale declarations ***)
   528 
   529 (* extract specification text *)
   530 
   531 val norm_term = Envir.beta_norm oo Term.subst_atomic;
   532 
   533 fun bind_def ctxt eq (xs, env, eqs) =
   534   let
   535     val _ = Local_Defs.cert_def ctxt eq;
   536     val ((y, T), b) = Local_Defs.abs_def eq;
   537     val b' = norm_term env b;
   538     fun err msg = error (msg ^ ": " ^ quote y);
   539   in
   540     (case filter (fn (Free (y', _), _) => y = y' | _ => false) env of
   541       [] => (Term.add_frees b' xs, (Free (y, T), b') :: env, eq :: eqs)
   542     | dups =>
   543         if forall (fn (_, b'') => b' aconv b'') dups then (xs, env, eqs)
   544         else err "Attempt to redefine variable")
   545   end;
   546 
   547 (* text has the following structure:
   548        (((exts, exts'), (ints, ints')), (xs, env, defs))
   549    where
   550      exts: external assumptions (terms in assumes elements)
   551      exts': dito, normalised wrt. env
   552      ints: internal assumptions (terms in assumptions from insts)
   553      ints': dito, normalised wrt. env
   554      xs: the free variables in exts' and ints' and rhss of definitions,
   555        this includes parameters except defined parameters
   556      env: list of term pairs encoding substitutions, where the first term
   557        is a free variable; substitutions represent defines elements and
   558        the rhs is normalised wrt. the previous env
   559      defs: the equations from the defines elements
   560    *)
   561 
   562 fun eval_text _ _ (Fixes _) text = text
   563   | eval_text _ _ (Constrains _) text = text
   564   | eval_text _ is_ext (Assumes asms)
   565         (((exts, exts'), (ints, ints')), (xs, env, defs)) =
   566       let
   567         val ts = maps (map #1 o #2) asms;
   568         val ts' = map (norm_term env) ts;
   569         val spec' =
   570           if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
   571           else ((exts, exts'), (ints @ ts, ints' @ ts'));
   572       in (spec', (fold Term.add_frees ts' xs, env, defs)) end
   573   | eval_text ctxt _ (Defines defs) (spec, binds) =
   574       (spec, fold (bind_def ctxt o #1 o #2) defs binds)
   575   | eval_text _ _ (Notes _) text = text;
   576 
   577 fun eval_inst ctxt (loc, morph) text =
   578   let
   579     val thy = Proof_Context.theory_of ctxt;
   580     val (asm, defs) = Locale.specification_of thy loc;
   581     val asm' = Option.map (Morphism.term morph) asm;
   582     val defs' = map (Morphism.term morph) defs;
   583     val text' = text |>
   584       (if is_some asm
   585         then eval_text ctxt false (Assumes [(Attrib.empty_binding, [(the asm', [])])])
   586         else I) |>
   587       (if not (null defs)
   588         then eval_text ctxt false (Defines (map (fn def => (Attrib.empty_binding, (def, []))) defs'))
   589         else I)
   590 (* FIXME clone from locale.ML *)
   591   in text' end;
   592 
   593 fun eval_elem ctxt elem text =
   594   eval_text ctxt true elem text;
   595 
   596 fun eval ctxt deps elems =
   597   let
   598     val text' = fold (eval_inst ctxt) deps ((([], []), ([], [])), ([], [], []));
   599     val ((spec, (_, _, defs))) = fold (eval_elem ctxt) elems text';
   600   in (spec, defs) end;
   601 
   602 (* axiomsN: name of theorem set with destruct rules for locale predicates,
   603      also name suffix of delta predicates and assumptions. *)
   604 
   605 val axiomsN = "axioms";
   606 
   607 local
   608 
   609 (* introN: name of theorems for introduction rules of locale and
   610      delta predicates *)
   611 
   612 val introN = "intro";
   613 
   614 fun atomize_spec thy ts =
   615   let
   616     val t = Logic.mk_conjunction_balanced ts;
   617     val body = Object_Logic.atomize_term thy t;
   618     val bodyT = Term.fastype_of body;
   619   in
   620     if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
   621     else (body, bodyT, Object_Logic.atomize (Thm.cterm_of thy t))
   622   end;
   623 
   624 (* achieve plain syntax for locale predicates (without "PROP") *)
   625 
   626 fun aprop_tr' n c =
   627   let
   628     val c' = Lexicon.mark_const c;
   629     fun tr' (_: Proof.context) T args =
   630       if T <> dummyT andalso length args = n
   631       then Syntax.const "_aprop" $ Term.list_comb (Syntax.const c', args)
   632       else raise Match;
   633   in (c', tr') end;
   634 
   635 (* define one predicate including its intro rule and axioms
   636    - binding: predicate name
   637    - parms: locale parameters
   638    - defs: thms representing substitutions from defines elements
   639    - ts: terms representing locale assumptions (not normalised wrt. defs)
   640    - norm_ts: terms representing locale assumptions (normalised wrt. defs)
   641    - thy: the theory
   642 *)
   643 
   644 fun def_pred binding parms defs ts norm_ts thy =
   645   let
   646     val name = Sign.full_name thy binding;
   647 
   648     val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
   649     val env = Term.add_free_names body [];
   650     val xs = filter (member (op =) env o #1) parms;
   651     val Ts = map #2 xs;
   652     val extraTs =
   653       (subtract (op =) (fold Term.add_tfreesT Ts []) (Term.add_tfrees body []))
   654       |> Library.sort_wrt #1 |> map TFree;
   655     val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
   656 
   657     val args = map Logic.mk_type extraTs @ map Free xs;
   658     val head = Term.list_comb (Const (name, predT), args);
   659     val statement = Object_Logic.ensure_propT thy head;
   660 
   661     val ([pred_def], defs_thy) =
   662       thy
   663       |> bodyT = propT ? Sign.typed_print_translation [aprop_tr' (length args) name]
   664       |> Sign.declare_const_global ((Binding.conceal binding, predT), NoSyn) |> snd
   665       |> Global_Theory.add_defs false
   666         [((Binding.conceal (Thm.def_binding binding), Logic.mk_equals (head, body)), [])];
   667     val defs_ctxt = Proof_Context.init_global defs_thy |> Variable.declare_term head;
   668 
   669     val cert = Thm.cterm_of defs_thy;
   670 
   671     val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
   672       rewrite_goals_tac [pred_def] THEN
   673       compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
   674       compose_tac (false, Conjunction.intr_balanced (map (Thm.assume o cert) norm_ts), 0) 1);
   675 
   676     val conjuncts =
   677       (Drule.equal_elim_rule2 OF [body_eq, rewrite_rule [pred_def] (Thm.assume (cert statement))])
   678       |> Conjunction.elim_balanced (length ts);
   679     val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
   680       Element.prove_witness defs_ctxt t
   681        (rewrite_goals_tac defs THEN compose_tac (false, ax, 0) 1));
   682   in ((statement, intro, axioms), defs_thy) end;
   683 
   684 in
   685 
   686 (* main predicate definition function *)
   687 
   688 fun define_preds binding parms (((exts, exts'), (ints, ints')), defs) thy =
   689   let
   690     val defs' = map (cterm_of thy #> Assumption.assume #> Drule.abs_def) defs;
   691 
   692     val (a_pred, a_intro, a_axioms, thy'') =
   693       if null exts then (NONE, NONE, [], thy)
   694       else
   695         let
   696           val abinding = if null ints then binding else Binding.suffix_name ("_" ^ axiomsN) binding;
   697           val ((statement, intro, axioms), thy') =
   698             thy
   699             |> def_pred abinding parms defs' exts exts';
   700           val (_, thy'') =
   701             thy'
   702             |> Sign.qualified_path true abinding
   703             |> Global_Theory.note_thmss ""
   704               [((Binding.conceal (Binding.name introN), []), [([intro], [Locale.unfold_add])])]
   705             ||> Sign.restore_naming thy';
   706           in (SOME statement, SOME intro, axioms, thy'') end;
   707     val (b_pred, b_intro, b_axioms, thy'''') =
   708       if null ints then (NONE, NONE, [], thy'')
   709       else
   710         let
   711           val ((statement, intro, axioms), thy''') =
   712             thy''
   713             |> def_pred binding parms defs' (ints @ the_list a_pred) (ints' @ the_list a_pred);
   714           val (_, thy'''') =
   715             thy'''
   716             |> Sign.qualified_path true binding
   717             |> Global_Theory.note_thmss ""
   718                  [((Binding.conceal (Binding.name introN), []), [([intro], [Locale.intro_add])]),
   719                   ((Binding.conceal (Binding.name axiomsN), []),
   720                     [(map (Drule.export_without_context o Element.conclude_witness) axioms, [])])]
   721             ||> Sign.restore_naming thy''';
   722         in (SOME statement, SOME intro, axioms, thy'''') end;
   723   in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
   724 
   725 end;
   726 
   727 
   728 local
   729 
   730 fun assumes_to_notes (Assumes asms) axms =
   731       fold_map (fn (a, spec) => fn axs =>
   732           let val (ps, qs) = chop (length spec) axs
   733           in ((a, [(ps, [])]), qs) end) asms axms
   734       |> apfst (curry Notes "")
   735   | assumes_to_notes e axms = (e, axms);
   736 
   737 fun defines_to_notes thy (Defines defs) =
   738       Notes ("", map (fn (a, (def, _)) =>
   739         (a, [([Assumption.assume (cterm_of thy def)],
   740           [(Attrib.internal o K) Locale.witness_add])])) defs)
   741   | defines_to_notes _ e = e;
   742 
   743 fun gen_add_locale prep_decl
   744     before_exit binding raw_predicate_binding raw_import raw_body thy =
   745   let
   746     val name = Sign.full_name thy binding;
   747     val _ = Locale.defined thy name andalso
   748       error ("Duplicate definition of locale " ^ quote name);
   749 
   750     val ((fixed, deps, body_elems, _), (parms, ctxt')) =
   751       prep_decl raw_import I raw_body (Proof_Context.init_global thy);
   752     val text as (((_, exts'), _), defs) = eval ctxt' deps body_elems;
   753 
   754     val extraTs =
   755       subtract (op =) (fold Term.add_tfreesT (map snd parms) []) (fold Term.add_tfrees exts' []);
   756     val _ =
   757       if null extraTs then ()
   758       else warning ("Additional type variable(s) in locale specification " ^
   759           Binding.print binding ^ ": " ^
   760           commas (map (Syntax.string_of_typ ctxt' o TFree) (sort_wrt #1 extraTs)));
   761 
   762     val predicate_binding =
   763       if Binding.is_empty raw_predicate_binding then binding
   764       else raw_predicate_binding;
   765     val ((a_statement, a_intro, a_axioms), (b_statement, b_intro, b_axioms), thy') =
   766       define_preds predicate_binding parms text thy;
   767 
   768     val a_satisfy = Element.satisfy_morphism a_axioms;
   769     val b_satisfy = Element.satisfy_morphism b_axioms;
   770 
   771     val params = fixed @
   772       maps (fn Fixes fixes =>
   773         map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fixes | _ => []) body_elems;
   774     val asm = if is_some b_statement then b_statement else a_statement;
   775 
   776     val notes =
   777       if is_some asm then
   778         [("", [((Binding.conceal (Binding.suffix_name ("_" ^ axiomsN) binding), []),
   779           [([Assumption.assume (cterm_of thy' (the asm))],
   780             [(Attrib.internal o K) Locale.witness_add])])])]
   781       else [];
   782 
   783     val notes' = body_elems |>
   784       map (defines_to_notes thy') |>
   785       map (Element.transform_ctxt a_satisfy) |>
   786       (fn elems => fold_map assumes_to_notes elems (map Element.conclude_witness a_axioms)) |>
   787       fst |>
   788       map (Element.transform_ctxt b_satisfy) |>
   789       map_filter (fn Notes notes => SOME notes | _ => NONE);
   790 
   791     val deps' = map (fn (l, morph) => (l, morph $> b_satisfy)) deps;
   792     val axioms = map Element.conclude_witness b_axioms;
   793 
   794     val loc_ctxt = thy'
   795       |> Locale.register_locale binding (extraTs, params)
   796           (asm, rev defs) (a_intro, b_intro) axioms [] (rev notes) (rev deps')
   797       |> Named_Target.init before_exit name
   798       |> fold (fn (kind, facts) => Local_Theory.notes_kind kind facts #> snd) notes';
   799 
   800   in (name, loc_ctxt) end;
   801 
   802 in
   803 
   804 val add_locale = gen_add_locale cert_declaration;
   805 val add_locale_cmd = gen_add_locale read_declaration;
   806 
   807 end;
   808 
   809 
   810 (*** Interpretation ***)
   811 
   812 local
   813 
   814 (* reading *)
   815 
   816 fun read_with_extended_syntax prep_prop deps ctxt props =
   817   let
   818     val deps_ctxt = fold Locale.activate_declarations deps ctxt;
   819   in
   820     map (prep_prop deps_ctxt o snd) props |> Syntax.check_terms deps_ctxt
   821       |> Variable.export_terms deps_ctxt ctxt
   822   end;
   823 
   824 fun read_interpretation prep_expr prep_prop prep_attr expression raw_eqns initial_ctxt =
   825   let
   826     val ((propss, deps, export), expr_ctxt) = prep_expr expression initial_ctxt;
   827     val eqns = read_with_extended_syntax prep_prop deps expr_ctxt raw_eqns;
   828     val attrss = map (apsnd (map (prep_attr (Proof_Context.theory_of initial_ctxt))) o fst) raw_eqns;
   829     val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
   830     val export' = Variable.export_morphism goal_ctxt expr_ctxt;
   831   in (((propss, deps, export, export'), (eqns, attrss)), goal_ctxt) end;
   832 
   833 
   834 (* generic interpretation machinery *)
   835 
   836 fun meta_rewrite eqns ctxt = (map (Local_Defs.meta_rewrite_rule ctxt #> Drule.abs_def) (maps snd eqns), ctxt);
   837 
   838 fun note_eqns_register note activate deps witss eqns attrss export export' ctxt =
   839   let
   840     val facts = map2 (fn attrs => fn eqn =>
   841       (attrs, [([Morphism.thm (export' $> export) eqn], [])])) attrss eqns;
   842     val (eqns', ctxt') = ctxt
   843       |> note Thm.lemmaK facts
   844       |-> meta_rewrite;
   845     val dep_morphs = map2 (fn (dep, morph) => fn wits =>
   846       (dep, morph $> Element.satisfy_morphism (map (Element.transform_witness export') wits))) deps witss;
   847     fun activate' dep_morph ctxt = activate dep_morph
   848       (Option.map (rpair true) (Element.eq_morphism (Proof_Context.theory_of ctxt) eqns')) export ctxt;
   849   in
   850     ctxt'
   851     |> fold activate' dep_morphs
   852   end;
   853 
   854 fun generic_interpretation prep_expr prep_prop prep_attr setup_proof note activate
   855     expression raw_eqns initial_ctxt = 
   856   let
   857     val (((propss, deps, export, export'), (eqns, attrss)), goal_ctxt) = 
   858       read_interpretation prep_expr prep_prop prep_attr expression raw_eqns initial_ctxt;
   859     fun after_qed witss eqns =
   860       note_eqns_register note activate deps witss eqns attrss export export';
   861   in setup_proof after_qed propss eqns goal_ctxt end;
   862 
   863 
   864 (* various flavours of interpretation *)
   865 
   866 fun assert_not_theory lthy = if Named_Target.is_theory lthy
   867   then error "Not possible on level of global theory" else ();
   868 
   869 fun gen_interpret prep_expr prep_prop prep_attr expression raw_eqns int state =
   870   let
   871     val _ = Proof.assert_forward_or_chain state;
   872     val ctxt = Proof.context_of state;
   873     fun lift_after_qed after_qed witss eqns = Proof.map_context (after_qed witss eqns) #> Proof.reset_facts;
   874     fun setup_proof after_qed propss eqns goal_ctxt = 
   875       Element.witness_local_proof_eqs (lift_after_qed after_qed) "interpret" propss eqns goal_ctxt int state;
   876   in
   877     generic_interpretation prep_expr prep_prop prep_attr setup_proof
   878       Attrib.local_notes (Context.proof_map ooo Locale.add_registration) expression raw_eqns ctxt
   879   end;
   880 
   881 fun gen_interpretation prep_expr prep_prop prep_attr expression raw_eqns lthy =
   882   if Named_Target.is_theory lthy
   883   then 
   884     lthy
   885     |> generic_interpretation prep_expr prep_prop prep_attr Element.witness_proof_eqs
   886         Local_Theory.notes_kind Generic_Target.theory_registration expression raw_eqns
   887   else
   888     lthy
   889     |> generic_interpretation prep_expr prep_prop prep_attr Element.witness_proof_eqs
   890         Local_Theory.notes_kind Local_Theory.activate expression raw_eqns;
   891 
   892 fun gen_sublocale prep_expr prep_prop prep_attr expression raw_eqns lthy =
   893   let
   894     val _ = assert_not_theory lthy;
   895     val locale = Named_Target.the_name lthy;
   896   in
   897     lthy
   898     |> generic_interpretation prep_expr prep_prop prep_attr Element.witness_proof_eqs
   899         Local_Theory.notes_kind (Generic_Target.locale_dependency locale) expression raw_eqns
   900   end;
   901   
   902 fun gen_sublocale_global prep_expr prep_loc prep_prop prep_attr before_exit raw_locale expression raw_eqns thy =
   903   let
   904     val locale = prep_loc thy raw_locale;
   905     val add_dependency_global = Proof_Context.background_theory ooo Locale.add_dependency locale;
   906   in
   907     thy
   908     |> Named_Target.init before_exit locale
   909     |> generic_interpretation prep_expr prep_prop prep_attr Element.witness_proof_eqs
   910         Local_Theory.notes_kind add_dependency_global expression raw_eqns
   911   end;
   912 
   913 in
   914 
   915 fun permanent_interpretation expression raw_eqns lthy =
   916   let
   917     val _ = Local_Theory.assert_bottom true lthy;
   918     val target = Named_Target.the_name lthy;
   919     val subscribe = if target = "" then Generic_Target.theory_registration
   920       else Generic_Target.locale_dependency target;
   921   in
   922     lthy
   923     |> generic_interpretation cert_goal_expression (K I) (K I) Element.witness_proof_eqs
   924         Local_Theory.notes_kind subscribe expression raw_eqns
   925   end;
   926 
   927 fun ephemeral_interpretation expression raw_eqns lthy =
   928   let
   929     val _ = assert_not_theory lthy;
   930   in
   931     lthy
   932     |> generic_interpretation cert_goal_expression (K I) (K I) Element.witness_proof_eqs
   933         Local_Theory.notes_kind Local_Theory.activate expression raw_eqns
   934   end;
   935 
   936 fun interpret x = gen_interpret cert_goal_expression (K I) (K I) x;
   937 fun interpret_cmd x =
   938   gen_interpret read_goal_expression Syntax.parse_prop Attrib.intern_src x;
   939 
   940 fun interpretation x = gen_interpretation cert_goal_expression (K I) (K I) x;
   941 fun interpretation_cmd x =
   942   gen_interpretation read_goal_expression Syntax.parse_prop Attrib.intern_src x;
   943 
   944 fun sublocale x = gen_sublocale cert_goal_expression (K I) (K I) x;
   945 fun sublocale_cmd x =
   946   gen_sublocale read_goal_expression Syntax.parse_prop Attrib.intern_src x;
   947 
   948 fun sublocale_global x = gen_sublocale_global cert_goal_expression (K I) (K I) (K I) x;
   949 fun sublocale_global_cmd x =
   950   gen_sublocale_global read_goal_expression Locale.check Syntax.parse_prop Attrib.intern_src x;
   951 
   952 end;
   953 
   954 
   955 (** Print the instances that would be activated by an interpretation
   956   of the expression in the current context (clean = false) or in an
   957   empty context (clean = true). **)
   958 
   959 fun print_dependencies ctxt clean expression =
   960   let
   961     val ((_, deps, export), expr_ctxt) = read_goal_expression expression ctxt;
   962     val export' = if clean then Morphism.identity else export;
   963   in
   964     Locale.print_dependencies expr_ctxt clean export' deps
   965   end;
   966 
   967 end;