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