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