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