src/Pure/Isar/expression.ML
author wenzelm
Thu May 27 17:41:27 2010 +0200 (2010-05-27)
changeset 37145 01aa36932739
parent 36674 d95f39448121
child 37313 715d25555ca6
permissions -rw-r--r--
renamed structure TypeInfer to Type_Infer, keeping the old name as legacy alias for some time;
     1 (*  Title:      Pure/Isar/expression.ML
     2     Author:     Clemens Ballarin, TU Muenchen
     3 
     4 Locale expressions and user interface layer of locales.
     5 *)
     6 
     7 signature EXPRESSION =
     8 sig
     9   (* Locale expressions *)
    10   datatype 'term map = Positional of 'term option list | Named of (string * 'term) list
    11   type 'term 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 -> (((string * typ) * 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 -> (((string * typ) * 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 -> (((string * typ) * mixfix) list * (string * morphism) list
    31       * Element.context_i list) * ((string * typ) list * Proof.context)
    32   val add_locale: binding -> binding -> expression_i -> Element.context_i list ->
    33     theory -> string * local_theory
    34   val add_locale_cmd: binding -> binding -> 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 -> theory -> Proof.state
    45   val interpretation_cmd: expression -> (Attrib.binding * string) list -> theory -> Proof.state
    46   val interpret: expression_i -> bool -> Proof.state -> Proof.state
    47   val interpret_cmd: expression -> bool -> Proof.state -> Proof.state
    48 end;
    49 
    50 structure Expression : EXPRESSION =
    51 struct
    52 
    53 datatype ctxt = datatype Element.ctxt;
    54 
    55 
    56 (*** Expressions ***)
    57 
    58 datatype 'term map =
    59   Positional of 'term option list |
    60   Named of (string * 'term) list;
    61 
    62 type 'term expr = (string * ((string * bool) * 'term map)) list;
    63 
    64 type expression = string expr * (binding * string option * mixfix) list;
    65 type expression_i = term expr * (binding * typ option * mixfix) list;
    66 
    67 
    68 (** Internalise locale names in expr **)
    69 
    70 fun intern thy instances =  map (apfst (Locale.intern thy)) instances;
    71 
    72 
    73 (** Parameters of expression **)
    74 
    75 (*Sanity check of instantiations and extraction of implicit parameters.
    76   The latter only occurs iff strict = false.
    77   Positional instantiations are extended to match full length of parameter list
    78   of instantiated locale.*)
    79 
    80 fun parameters_of thy strict (expr, fixed) =
    81   let
    82     fun reject_dups message xs =
    83       (case duplicates (op =) xs of
    84         [] => ()
    85       | dups => error (message ^ commas dups));
    86 
    87     fun parm_eq ((p1: string, mx1: mixfix), (p2, mx2)) = p1 = p2 andalso
    88       (mx1 = mx2 orelse error ("Conflicting syntax for parameter " ^ quote p1 ^ " in expression"));
    89 
    90     fun params_loc loc = Locale.params_of thy loc |> map (apfst #1);
    91     fun params_inst (loc, (prfx, Positional insts)) =
    92           let
    93             val ps = params_loc loc;
    94             val d = length ps - length insts;
    95             val insts' =
    96               if d < 0 then error ("More arguments than parameters in instantiation of locale " ^
    97                 quote (Locale.extern thy loc))
    98               else insts @ replicate d NONE;
    99             val ps' = (ps ~~ insts') |>
   100               map_filter (fn (p, NONE) => SOME p | (_, SOME _) => NONE);
   101           in (ps', (loc, (prfx, Positional insts'))) end
   102       | params_inst (loc, (prfx, Named insts)) =
   103           let
   104             val _ = reject_dups "Duplicate instantiation of the following parameter(s): "
   105               (map fst insts);
   106             val ps' = (insts, params_loc loc) |-> fold (fn (p, _) => fn ps =>
   107               if AList.defined (op =) ps p then AList.delete (op =) p ps
   108               else error (quote p ^ " not a parameter of instantiated expression"));
   109           in (ps', (loc, (prfx, Named insts))) end;
   110     fun params_expr is =
   111       let
   112         val (is', ps') = fold_map (fn i => fn ps =>
   113           let
   114             val (ps', i') = params_inst i;
   115             val ps'' = distinct parm_eq (ps @ ps');
   116           in (i', ps'') end) is []
   117       in (ps', is') end;
   118 
   119     val (implicit, expr') = params_expr expr;
   120 
   121     val implicit' = map #1 implicit;
   122     val fixed' = map (#1 #> Name.of_binding) fixed;
   123     val _ = reject_dups "Duplicate fixed parameter(s): " fixed';
   124     val implicit'' =
   125       if strict then []
   126       else
   127         let val _ = reject_dups
   128           "Parameter(s) declared simultaneously in expression and for clause: " (implicit' @ fixed')
   129         in map (fn (x, mx) => (Binding.name x, NONE, mx)) implicit end;
   130 
   131   in (expr', implicit'' @ fixed) end;
   132 
   133 
   134 (** Read instantiation **)
   135 
   136 (* Parse positional or named instantiation *)
   137 
   138 local
   139 
   140 fun prep_inst prep_term ctxt parms (Positional insts) =
   141       (insts ~~ parms) |> map (fn
   142         (NONE, p) => Free (p, dummyT) |
   143         (SOME t, _) => prep_term ctxt t)
   144   | prep_inst prep_term ctxt parms (Named insts) =
   145       parms |> map (fn p => case AList.lookup (op =) insts p of
   146         SOME t => prep_term ctxt t |
   147         NONE => Free (p, dummyT));
   148 
   149 in
   150 
   151 fun parse_inst x = prep_inst Syntax.parse_term x;
   152 fun make_inst x = prep_inst (K I) x;
   153 
   154 end;
   155 
   156 
   157 (* Instantiation morphism *)
   158 
   159 fun inst_morph (parm_names, parm_types) ((prfx, mandatory), insts') ctxt =
   160   let
   161     (* parameters *)
   162     val type_parm_names = fold Term.add_tfreesT parm_types [] |> map fst;
   163 
   164     (* type inference and contexts *)
   165     val parm_types' = map (Type_Infer.paramify_vars o Logic.varifyT_global) parm_types;
   166     val type_parms = fold Term.add_tvarsT parm_types' [] |> map (Logic.mk_type o TVar);
   167     val arg = type_parms @ map2 Type_Infer.constrain parm_types' insts';
   168     val res = Syntax.check_terms ctxt arg;
   169     val ctxt' = ctxt |> fold Variable.auto_fixes res;
   170 
   171     (* instantiation *)
   172     val (type_parms'', res') = chop (length type_parms) res;
   173     val insts'' = (parm_names ~~ res') |> map_filter
   174       (fn inst as (x, Free (y, _)) => if x = y then NONE else SOME inst
   175         | inst => SOME inst);
   176     val instT = Symtab.make (type_parm_names ~~ map Logic.dest_type type_parms'');
   177     val inst = Symtab.make insts'';
   178   in
   179     (Element.inst_morphism (ProofContext.theory_of ctxt) (instT, inst) $>
   180       Morphism.binding_morphism (Binding.prefix mandatory prfx), ctxt')
   181   end;
   182 
   183 
   184 (*** Locale processing ***)
   185 
   186 (** Parsing **)
   187 
   188 fun parse_elem prep_typ prep_term ctxt =
   189   Element.map_ctxt
   190    {binding = I,
   191     typ = prep_typ ctxt,
   192     term = prep_term (ProofContext.set_mode ProofContext.mode_schematic ctxt),
   193     pattern = prep_term (ProofContext.set_mode ProofContext.mode_pattern ctxt),
   194     fact = I,
   195     attrib = I};
   196 
   197 fun parse_concl prep_term ctxt concl =
   198   (map o map) (fn (t, ps) =>
   199     (prep_term (ProofContext.set_mode ProofContext.mode_schematic ctxt) t,
   200       map (prep_term (ProofContext.set_mode ProofContext.mode_pattern ctxt)) ps)) concl;
   201 
   202 
   203 (** Simultaneous type inference: instantiations + elements + conclusion **)
   204 
   205 local
   206 
   207 fun mk_type T = (Logic.mk_type T, []);
   208 fun mk_term t = (t, []);
   209 fun mk_propp (p, pats) = (Syntax.type_constraint propT p, pats);
   210 
   211 fun dest_type (T, []) = Logic.dest_type T;
   212 fun dest_term (t, []) = t;
   213 fun dest_propp (p, pats) = (p, pats);
   214 
   215 fun extract_inst (_, (_, ts)) = map mk_term ts;
   216 fun restore_inst ((l, (p, _)), cs) = (l, (p, map dest_term cs));
   217 
   218 fun extract_elem (Fixes fixes) = map (#2 #> the_list #> map mk_type) fixes
   219   | extract_elem (Constrains csts) = map (#2 #> single #> map mk_type) csts
   220   | extract_elem (Assumes asms) = map (#2 #> map mk_propp) asms
   221   | extract_elem (Defines defs) = map (fn (_, (t, ps)) => [mk_propp (t, ps)]) defs
   222   | extract_elem (Notes _) = [];
   223 
   224 fun restore_elem (Fixes fixes, css) =
   225       (fixes ~~ css) |> map (fn ((x, _, mx), cs) =>
   226         (x, cs |> map dest_type |> try hd, mx)) |> Fixes
   227   | restore_elem (Constrains csts, css) =
   228       (csts ~~ css) |> map (fn ((x, _), cs) =>
   229         (x, cs |> map dest_type |> hd)) |> Constrains
   230   | restore_elem (Assumes asms, css) =
   231       (asms ~~ css) |> map (fn ((b, _), cs) => (b, map dest_propp cs)) |> Assumes
   232   | restore_elem (Defines defs, css) =
   233       (defs ~~ css) |> map (fn ((b, _), [c]) => (b, dest_propp c)) |> Defines
   234   | restore_elem (Notes notes, _) = Notes notes;
   235 
   236 fun check cs context =
   237   let
   238     fun prep (_, pats) (ctxt, t :: ts) =
   239       let val ctxt' = Variable.auto_fixes t ctxt
   240       in
   241         ((t, Syntax.check_props (ProofContext.set_mode ProofContext.mode_pattern ctxt') pats),
   242           (ctxt', ts))
   243       end;
   244     val (cs', (context', _)) = fold_map prep cs
   245       (context, Syntax.check_terms
   246         (ProofContext.set_mode ProofContext.mode_schematic context) (map fst cs));
   247   in (cs', context') end;
   248 
   249 in
   250 
   251 fun check_autofix insts elems concl ctxt =
   252   let
   253     val inst_cs = map extract_inst insts;
   254     val elem_css = map extract_elem elems;
   255     val concl_cs = (map o map) mk_propp concl;
   256     (* Type inference *)
   257     val (inst_cs' :: css', ctxt') =
   258       (fold_burrow o fold_burrow) check (inst_cs :: elem_css @ [concl_cs]) ctxt;
   259     val (elem_css', [concl_cs']) = chop (length elem_css) css';
   260   in
   261     (map restore_inst (insts ~~ inst_cs'),
   262       map restore_elem (elems ~~ elem_css'),
   263       concl_cs', ctxt')
   264   end;
   265 
   266 end;
   267 
   268 
   269 (** Prepare locale elements **)
   270 
   271 fun declare_elem prep_vars (Fixes fixes) ctxt =
   272       let val (vars, _) = prep_vars fixes ctxt
   273       in ctxt |> ProofContext.add_fixes vars |> snd end
   274   | declare_elem prep_vars (Constrains csts) ctxt =
   275       ctxt |> prep_vars (map (fn (x, T) => (Binding.name x, SOME T, NoSyn)) csts) |> snd
   276   | declare_elem _ (Assumes _) ctxt = ctxt
   277   | declare_elem _ (Defines _) ctxt = ctxt
   278   | declare_elem _ (Notes _) ctxt = ctxt;
   279 
   280 
   281 (** Finish locale elements **)
   282 
   283 fun closeup _ _ false elem = elem
   284   | closeup ctxt parms true elem =
   285       let
   286         (* FIXME consider closing in syntactic phase -- before type checking *)
   287         fun close_frees t =
   288           let
   289             val rev_frees =
   290               Term.fold_aterms (fn Free (x, T) =>
   291                 if AList.defined (op =) parms x then I else insert (op =) (x, T) | _ => I) t [];
   292           in fold (Logic.all o Free) rev_frees t end;
   293 
   294         fun no_binds [] = []
   295           | no_binds _ = error "Illegal term bindings in context element";
   296       in
   297         (case elem of
   298           Assumes asms => Assumes (asms |> map (fn (a, propps) =>
   299             (a, map (fn (t, ps) => (close_frees t, no_binds ps)) propps)))
   300         | Defines defs => Defines (defs |> map (fn ((name, atts), (t, ps)) =>
   301             let val ((c, _), t') = Local_Defs.cert_def ctxt (close_frees t)
   302             in ((Thm.def_binding_optional (Binding.name c) name, atts), (t', no_binds ps)) end))
   303         | e => e)
   304       end;
   305 
   306 fun finish_primitive parms _ (Fixes fixes) = Fixes (map (fn (binding, _, mx) =>
   307       let val x = Binding.name_of binding
   308       in (binding, AList.lookup (op =) parms x, mx) end) fixes)
   309   | finish_primitive _ _ (Constrains _) = Constrains []
   310   | finish_primitive _ close (Assumes asms) = close (Assumes asms)
   311   | finish_primitive _ close (Defines defs) = close (Defines defs)
   312   | finish_primitive _ _ (Notes facts) = Notes facts;
   313 
   314 fun finish_inst ctxt (loc, (prfx, inst)) =
   315   let
   316     val thy = ProofContext.theory_of ctxt;
   317     val (parm_names, parm_types) = Locale.params_of thy loc |> map #1 |> split_list;
   318     val (morph, _) = inst_morph (parm_names, parm_types) (prfx, inst) ctxt;
   319   in (loc, morph) end;
   320 
   321 fun finish_elem ctxt parms do_close elem =
   322   finish_primitive parms (closeup ctxt parms do_close) elem;
   323 
   324 fun finish ctxt parms do_close insts elems =
   325   let
   326     val deps = map (finish_inst ctxt) insts;
   327     val elems' = map (finish_elem ctxt parms do_close) elems;
   328   in (deps, elems') end;
   329 
   330 
   331 (** Process full context statement: instantiations + elements + conclusion **)
   332 
   333 (* Interleave incremental parsing and type inference over entire parsed stretch. *)
   334 
   335 local
   336 
   337 fun prep_full_context_statement parse_typ parse_prop prep_vars_elem prep_inst prep_vars_inst prep_expr
   338     {strict, do_close, fixed_frees} raw_import init_body raw_elems raw_concl ctxt1 =
   339   let
   340     val thy = ProofContext.theory_of ctxt1;
   341 
   342     val (raw_insts, fixed) = parameters_of thy strict (apfst (prep_expr thy) raw_import);
   343 
   344     fun prep_insts_cumulative (loc, (prfx, inst)) (i, insts, ctxt) =
   345       let
   346         val (parm_names, parm_types) = Locale.params_of thy loc |> map #1 |> split_list;
   347         val inst' = prep_inst ctxt parm_names inst;
   348         val parm_types' = map (Type_Infer.paramify_vars o
   349           Term.map_type_tvar (fn ((x, _), S) => TVar ((x, i), S)) o Logic.varifyT_global) parm_types;
   350         val inst'' = map2 Type_Infer.constrain parm_types' inst';
   351         val insts' = insts @ [(loc, (prfx, inst''))];
   352         val (insts'', _, _, ctxt' (* FIXME not used *) ) = check_autofix insts' [] [] ctxt;
   353         val inst''' = insts'' |> List.last |> snd |> snd;
   354         val (morph, _) = inst_morph (parm_names, parm_types) (prfx, inst''') ctxt;
   355         val ctxt'' = Locale.activate_declarations (loc, morph) ctxt;
   356       in (i + 1, insts', ctxt'') end;
   357 
   358     fun prep_elem insts raw_elem (elems, ctxt) =
   359       let
   360         val ctxt' = declare_elem prep_vars_elem raw_elem ctxt;
   361         val elems' = elems @ [parse_elem parse_typ parse_prop ctxt' raw_elem];
   362         val (_, _, _, ctxt'' (* FIXME not used *) ) = check_autofix insts elems' [] ctxt';
   363       in (elems', ctxt') end;
   364 
   365     fun prep_concl raw_concl (insts, elems, ctxt) =
   366       let
   367         val concl = parse_concl parse_prop ctxt raw_concl;
   368       in check_autofix insts elems concl ctxt end;
   369 
   370     val fors = prep_vars_inst fixed ctxt1 |> fst;
   371     val ctxt2 = ctxt1 |> ProofContext.add_fixes fors |> snd;
   372     val (_, insts', ctxt3) = fold prep_insts_cumulative raw_insts (0, [], ctxt2);
   373 
   374     val add_free = fold_aterms
   375       (fn Free (x, T) => not (Variable.is_fixed ctxt3 x) ? insert (op =) (x, T) | _ => I);
   376     val _ =
   377       if fixed_frees then ()
   378       else
   379         (case fold (fold add_free o snd o snd) insts' [] of
   380           [] => ()
   381         | frees => error ("Illegal free variables in expression: " ^
   382             commas_quote (map (Syntax.string_of_term ctxt3 o Free) (rev frees))));
   383 
   384     val ctxt4 = init_body ctxt3;
   385     val (elems, ctxt5) = fold (prep_elem insts') raw_elems ([], ctxt4);
   386     val (insts, elems', concl, ctxt6) = prep_concl raw_concl (insts', elems, ctxt5);
   387 
   388     (* Retrieve parameter types *)
   389     val xs = fold (fn Fixes fixes => (fn ps => ps @ map (Name.of_binding o #1) fixes)
   390       | _ => fn ps => ps) (Fixes fors :: elems') [];
   391     val (Ts, ctxt7) = fold_map ProofContext.inferred_param xs ctxt6;
   392     val parms = xs ~~ Ts;  (* params from expression and elements *)
   393 
   394     val Fixes fors' = finish_primitive parms I (Fixes fors);
   395     val fixed = map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fors';
   396     val (deps, elems'') = finish ctxt6 parms do_close insts elems';
   397 
   398   in ((fixed, deps, elems'', concl), (parms, ctxt7)) end
   399 
   400 in
   401 
   402 fun cert_full_context_statement x =
   403   prep_full_context_statement (K I) (K I) ProofContext.cert_vars
   404   make_inst ProofContext.cert_vars (K I) x;
   405 
   406 fun cert_read_full_context_statement x =
   407   prep_full_context_statement Syntax.parse_typ Syntax.parse_prop ProofContext.read_vars
   408   make_inst ProofContext.cert_vars (K I) x;
   409 
   410 fun read_full_context_statement x =
   411   prep_full_context_statement Syntax.parse_typ Syntax.parse_prop ProofContext.read_vars
   412   parse_inst ProofContext.read_vars intern x;
   413 
   414 end;
   415 
   416 
   417 (* Context statement: elements + conclusion *)
   418 
   419 local
   420 
   421 fun prep_statement prep activate raw_elems raw_concl context =
   422   let
   423      val ((_, _, elems, concl), _) =
   424        prep {strict = true, do_close = false, fixed_frees = true}
   425         ([], []) I raw_elems raw_concl context;
   426      val (_, context') = context |>
   427        ProofContext.set_stmt true |>
   428        fold_map activate elems;
   429   in (concl, context') end;
   430 
   431 in
   432 
   433 fun cert_statement x = prep_statement cert_full_context_statement Element.activate_i x;
   434 fun read_statement x = prep_statement read_full_context_statement Element.activate x;
   435 
   436 end;
   437 
   438 
   439 (* Locale declaration: import + elements *)
   440 
   441 fun fix_params params =
   442   ProofContext.add_fixes (map (fn ((x, T), mx) => (Binding.name x, SOME T, mx)) params) #> snd;
   443 
   444 local
   445 
   446 fun prep_declaration prep activate raw_import init_body raw_elems context =
   447   let
   448     val ((fixed, deps, elems, _), (parms, ctxt')) =
   449       prep {strict = false, do_close = true, fixed_frees = false}
   450         raw_import init_body raw_elems [] context;
   451     (* Declare parameters and imported facts *)
   452     val context' = context |>
   453       fix_params fixed |>
   454       fold (Context.proof_map o Locale.activate_facts) deps;
   455     val (elems', _) = context' |>
   456       ProofContext.set_stmt true |>
   457       fold_map 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 {strict = true, do_close = true, fixed_frees = true} expression I [] [] context;
   486     (* proof obligations *)
   487     val propss = map (props_of thy) deps;
   488 
   489     val goal_ctxt = context |>
   490       fix_params fixed |>
   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 = Term_Subst.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 _ = Local_Defs.cert_def ctxt eq;
   517     val ((y, T), b) = Local_Defs.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   eval_text ctxt true elem text;
   576 
   577 fun eval ctxt deps elems =
   578   let
   579     val text' = fold (eval_inst ctxt) deps ((([], []), ([], [])), ([], [], []));
   580     val ((spec, (_, _, defs))) = fold (eval_elem ctxt) elems text';
   581   in (spec, defs) end;
   582 
   583 (* axiomsN: name of theorem set with destruct rules for locale predicates,
   584      also name suffix of delta predicates and assumptions. *)
   585 
   586 val axiomsN = "axioms";
   587 
   588 local
   589 
   590 (* introN: name of theorems for introduction rules of locale and
   591      delta predicates *)
   592 
   593 val introN = "intro";
   594 
   595 fun atomize_spec thy ts =
   596   let
   597     val t = Logic.mk_conjunction_balanced ts;
   598     val body = Object_Logic.atomize_term thy t;
   599     val bodyT = Term.fastype_of body;
   600   in
   601     if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
   602     else (body, bodyT, Object_Logic.atomize (Thm.cterm_of thy t))
   603   end;
   604 
   605 (* achieve plain syntax for locale predicates (without "PROP") *)
   606 
   607 fun aprop_tr' n c = (Syntax.mark_const c, fn ctxt => fn args =>
   608   if length args = n then
   609     Syntax.const "_aprop" $   (* FIXME avoid old-style early externing (!??) *)
   610       Term.list_comb (Syntax.free (Consts.extern (ProofContext.consts_of ctxt) c), args)
   611   else raise Match);
   612 
   613 (* define one predicate including its intro rule and axioms
   614    - binding: predicate name
   615    - parms: locale parameters
   616    - defs: thms representing substitutions from defines elements
   617    - ts: terms representing locale assumptions (not normalised wrt. defs)
   618    - norm_ts: terms representing locale assumptions (normalised wrt. defs)
   619    - thy: the theory
   620 *)
   621 
   622 fun def_pred binding parms defs ts norm_ts thy =
   623   let
   624     val name = Sign.full_name thy binding;
   625 
   626     val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
   627     val env = Term.add_free_names body [];
   628     val xs = filter (member (op =) env o #1) parms;
   629     val Ts = map #2 xs;
   630     val extraTs =
   631       (subtract (op =) (fold Term.add_tfreesT Ts []) (Term.add_tfrees body []))
   632       |> Library.sort_wrt #1 |> map TFree;
   633     val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
   634 
   635     val args = map Logic.mk_type extraTs @ map Free xs;
   636     val head = Term.list_comb (Const (name, predT), args);
   637     val statement = Object_Logic.ensure_propT thy head;
   638 
   639     val ([pred_def], defs_thy) =
   640       thy
   641       |> bodyT = propT ? Sign.add_advanced_trfuns ([], [], [aprop_tr' (length args) name], [])
   642       |> Sign.declare_const ((Binding.conceal binding, predT), NoSyn) |> snd
   643       |> PureThy.add_defs false
   644         [((Binding.conceal (Thm.def_binding binding), Logic.mk_equals (head, body)), [])];
   645     val defs_ctxt = ProofContext.init_global defs_thy |> Variable.declare_term head;
   646 
   647     val cert = Thm.cterm_of defs_thy;
   648 
   649     val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
   650       MetaSimplifier.rewrite_goals_tac [pred_def] THEN
   651       Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
   652       Tactic.compose_tac (false,
   653         Conjunction.intr_balanced (map (Thm.assume o cert) norm_ts), 0) 1);
   654 
   655     val conjuncts =
   656       (Drule.equal_elim_rule2 OF [body_eq,
   657         MetaSimplifier.rewrite_rule [pred_def] (Thm.assume (cert statement))])
   658       |> Conjunction.elim_balanced (length ts);
   659     val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
   660       Element.prove_witness defs_ctxt t
   661        (MetaSimplifier.rewrite_goals_tac defs THEN
   662         Tactic.compose_tac (false, ax, 0) 1));
   663   in ((statement, intro, axioms), defs_thy) end;
   664 
   665 in
   666 
   667 (* main predicate definition function *)
   668 
   669 fun define_preds binding parms (((exts, exts'), (ints, ints')), defs) thy =
   670   let
   671     val defs' = map (cterm_of thy #> Assumption.assume #> Drule.abs_def) defs;
   672 
   673     val (a_pred, a_intro, a_axioms, thy'') =
   674       if null exts then (NONE, NONE, [], thy)
   675       else
   676         let
   677           val abinding = if null ints then binding else Binding.suffix_name ("_" ^ axiomsN) binding;
   678           val ((statement, intro, axioms), thy') =
   679             thy
   680             |> def_pred abinding parms defs' exts exts';
   681           val (_, thy'') =
   682             thy'
   683             |> Sign.qualified_path true abinding
   684             |> PureThy.note_thmss ""
   685               [((Binding.conceal (Binding.name introN), []), [([intro], [Locale.unfold_add])])]
   686             ||> Sign.restore_naming thy';
   687           in (SOME statement, SOME intro, axioms, thy'') end;
   688     val (b_pred, b_intro, b_axioms, thy'''') =
   689       if null ints then (NONE, NONE, [], thy'')
   690       else
   691         let
   692           val ((statement, intro, axioms), thy''') =
   693             thy''
   694             |> def_pred binding parms defs' (ints @ the_list a_pred) (ints' @ the_list a_pred);
   695           val (_, thy'''') =
   696             thy'''
   697             |> Sign.qualified_path true binding
   698             |> PureThy.note_thmss ""
   699                  [((Binding.conceal (Binding.name introN), []), [([intro], [Locale.intro_add])]),
   700                   ((Binding.conceal (Binding.name axiomsN), []),
   701                     [(map (Drule.export_without_context o Element.conclude_witness) axioms, [])])]
   702             ||> Sign.restore_naming thy''';
   703         in (SOME statement, SOME intro, axioms, thy'''') end;
   704   in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
   705 
   706 end;
   707 
   708 
   709 local
   710 
   711 fun assumes_to_notes (Assumes asms) axms =
   712       fold_map (fn (a, spec) => fn axs =>
   713           let val (ps, qs) = chop (length spec) axs
   714           in ((a, [(ps, [])]), qs) end) asms axms
   715       |> apfst (curry Notes "")
   716   | assumes_to_notes e axms = (e, axms);
   717 
   718 fun defines_to_notes thy (Defines defs) =
   719       Notes (Thm.definitionK, map (fn (a, (def, _)) =>
   720         (a, [([Assumption.assume (cterm_of thy def)],
   721           [(Attrib.internal o K) Locale.witness_add])])) defs)
   722   | defines_to_notes _ e = e;
   723 
   724 fun gen_add_locale prep_decl
   725     binding raw_predicate_binding raw_import raw_body thy =
   726   let
   727     val name = Sign.full_name thy binding;
   728     val _ = Locale.defined thy name andalso
   729       error ("Duplicate definition of locale " ^ quote name);
   730 
   731     val ((fixed, deps, body_elems), (parms, ctxt')) =
   732       prep_decl raw_import I raw_body (ProofContext.init_global thy);
   733     val text as (((_, exts'), _), defs) = eval ctxt' deps body_elems;
   734 
   735     val predicate_binding =
   736       if Binding.is_empty raw_predicate_binding then binding
   737       else raw_predicate_binding;
   738     val ((a_statement, a_intro, a_axioms), (b_statement, b_intro, b_axioms), thy') =
   739       define_preds predicate_binding parms text thy;
   740 
   741     val extraTs = subtract (op =) (fold Term.add_tfreesT (map snd parms) []) (fold Term.add_tfrees exts' []);
   742     val _ =
   743       if null extraTs then ()
   744       else warning ("Additional type variable(s) in locale specification " ^
   745         quote (Binding.str_of binding));
   746 
   747     val a_satisfy = Element.satisfy_morphism a_axioms;
   748     val b_satisfy = Element.satisfy_morphism b_axioms;
   749 
   750     val params = fixed @
   751       maps (fn Fixes fixes =>
   752         map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fixes | _ => []) body_elems;
   753     val asm = if is_some b_statement then b_statement else a_statement;
   754 
   755     val notes =
   756       if is_some asm then
   757         [("", [((Binding.conceal (Binding.suffix_name ("_" ^ axiomsN) binding), []),
   758           [([Assumption.assume (cterm_of thy' (the asm))],
   759             [(Attrib.internal o K) Locale.witness_add])])])]
   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 binding (extraTs, params)
   775           (asm, rev defs) (a_intro, b_intro) axioms [] (rev notes) (rev deps')
   776       |> Theory_Target.init (SOME name)
   777       |> fold (fn (kind, facts) => Local_Theory.notes_kind kind facts #> snd) notes';
   778 
   779   in (name, loc_ctxt) end;
   780 
   781 in
   782 
   783 val add_locale = gen_add_locale cert_declaration;
   784 val add_locale_cmd = gen_add_locale read_declaration;
   785 
   786 end;
   787 
   788 
   789 (*** Interpretation ***)
   790 
   791 (** Interpretation in theories **)
   792 
   793 local
   794 
   795 fun gen_interpretation prep_expr parse_prop prep_attr
   796     expression equations theory =
   797   let
   798     val ((propss, deps, export), expr_ctxt) = ProofContext.init_global theory
   799       |> prep_expr expression;
   800 
   801     val eqns = map (parse_prop expr_ctxt o snd) equations |> Syntax.check_terms expr_ctxt;
   802     val attrss = map ((apsnd o map) (prep_attr theory) o fst) equations;
   803     val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
   804     val export' = Variable.export_morphism goal_ctxt expr_ctxt;
   805 
   806     fun note_eqns raw_eqns thy =
   807       let
   808         val eqns = map (Morphism.thm (export' $> export)) raw_eqns;
   809         val eqn_attrss = map2 (fn attrs => fn eqn =>
   810           ((apsnd o map) (Attrib.attribute_i thy) attrs, [([eqn], [])])) attrss eqns;
   811         fun meta_rewrite thy =
   812           map (Local_Defs.meta_rewrite_rule (ProofContext.init_global thy) #> Drule.abs_def) o
   813             maps snd;
   814       in
   815         thy
   816         |> PureThy.note_thmss Thm.lemmaK eqn_attrss
   817         |-> (fn facts => `(fn thy => meta_rewrite thy facts))
   818       end;
   819 
   820     fun after_qed witss eqns = ProofContext.theory (note_eqns eqns
   821       #-> (fn eqns => fold (fn ((dep, morph), wits) =>
   822         fn thy => Locale.add_registration (dep, morph $> Element.satisfy_morphism
   823             (map (Element.morph_witness export') wits))
   824           (Element.eq_morphism thy eqns |> Option.map (rpair true))
   825           export thy) (deps ~~ witss)));
   826 
   827   in Element.witness_proof_eqs after_qed propss eqns goal_ctxt end;
   828 
   829 in
   830 
   831 fun interpretation x = gen_interpretation cert_goal_expression (K I) (K I) x;
   832 fun interpretation_cmd x = gen_interpretation read_goal_expression
   833   Syntax.parse_prop Attrib.intern_src x;
   834 
   835 end;
   836 
   837 
   838 (** Interpretation between locales: declaring sublocale relationships **)
   839 
   840 local
   841 
   842 fun gen_sublocale prep_expr intern raw_target expression thy =
   843   let
   844     val target = intern thy raw_target;
   845     val target_ctxt = Theory_Target.init (SOME target) thy;
   846     val ((propss, deps, export), goal_ctxt) = prep_expr expression target_ctxt;
   847     fun after_qed witss = ProofContext.theory
   848       (fold (fn ((dep, morph), wits) => Locale.add_dependency
   849         target (dep, morph $> Element.satisfy_morphism wits) export) (deps ~~ witss));
   850   in Element.witness_proof after_qed propss goal_ctxt end;
   851 
   852 in
   853 
   854 fun sublocale x = gen_sublocale cert_goal_expression (K I) x;
   855 fun sublocale_cmd x = gen_sublocale read_goal_expression Locale.intern x;
   856 
   857 end;
   858 
   859 
   860 (** Interpretation in proof contexts **)
   861 
   862 local
   863 
   864 fun gen_interpret prep_expr expression int state =
   865   let
   866     val _ = Proof.assert_forward_or_chain state;
   867     val ctxt = Proof.context_of state;
   868 
   869     val ((propss, regs, export), goal_ctxt) = prep_expr expression ctxt;
   870 
   871     fun store_reg (name, morph) thms =
   872       let
   873         val morph' = morph $> Element.satisfy_morphism thms $> export;
   874       in Context.proof_map (Locale.activate_facts (name, morph')) end;
   875 
   876     fun after_qed wits =
   877       Proof.map_context (fold2 store_reg regs wits);
   878   in
   879     state
   880     |> Element.witness_local_proof after_qed "interpret" propss goal_ctxt int
   881   end;
   882 
   883 in
   884 
   885 fun interpret x = gen_interpret cert_goal_expression x;
   886 fun interpret_cmd x = gen_interpret read_goal_expression x;
   887 
   888 end;
   889 
   890 end;
   891