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