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