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