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