src/Pure/Isar/expression.ML
author wenzelm
Thu, 26 Aug 2010 15:48:08 +0200
changeset 39032 2b3e054ae6fc
parent 39031 d07959fabde6
child 39541 f1ae2493d93f
permissions -rw-r--r--
renamed Local_Theory.theory(_result) to Local_Theory.background_theory(_result) to emphasize that this belongs to the infrastructure and is rarely appropriate in user-space tools;
     1 (*  Title:      Pure/Isar/expression.ML
     2     Author:     Clemens Ballarin, TU Muenchen
     3 
     4 Locale expressions and user interface layer of locales.
     5 *)
     6 
     7 signature EXPRESSION =
     8 sig
     9   (* Locale expressions *)
    10   datatype 'term map = Positional of 'term option list | Named of (string * 'term) list
    11   type '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 -> (Attrib.binding * term) list -> bool -> Proof.state -> Proof.state
    47   val interpret_cmd: expression -> (Attrib.binding * string) list -> 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 (Type_Infer.paramify_vars o Logic.varifyT_global) parm_types;
   166     val type_parms = fold Term.add_tvarsT parm_types' [] |> map (Logic.mk_type o TVar);
   167     val arg = type_parms @ map2 Type_Infer.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') = Local_Defs.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 (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) 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, fixed_frees} 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 (Type_Infer.paramify_vars o
   349           Term.map_type_tvar (fn ((x, _), S) => TVar ((x, i), S)) o Logic.varifyT_global) parm_types;
   350         val inst'' = map2 Type_Infer.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 
   374     val add_free = fold_aterms
   375       (fn Free (x, T) => not (Variable.is_fixed ctxt3 x) ? insert (op =) (x, T) | _ => I);
   376     val _ =
   377       if fixed_frees then ()
   378       else
   379         (case fold (fold add_free o snd o snd) insts' [] of
   380           [] => ()
   381         | frees => error ("Illegal free variables in expression: " ^
   382             commas_quote (map (Syntax.string_of_term ctxt3 o Free) (rev frees))));
   383 
   384     val ctxt4 = init_body ctxt3;
   385     val (elems, ctxt5) = fold (prep_elem insts') raw_elems ([], ctxt4);
   386     val (insts, elems', concl, ctxt6) = prep_concl raw_concl (insts', elems, ctxt5);
   387 
   388     (* Retrieve parameter types *)
   389     val xs = fold (fn Fixes fixes => (fn ps => ps @ map (Name.of_binding o #1) fixes)
   390       | _ => fn ps => ps) (Fixes fors :: elems') [];
   391     val (Ts, ctxt7) = fold_map ProofContext.inferred_param xs ctxt6;
   392     val parms = xs ~~ Ts;  (* params from expression and elements *)
   393 
   394     val Fixes fors' = finish_primitive parms I (Fixes fors);
   395     val fixed = map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fors';
   396     val (deps, elems'') = finish ctxt6 parms do_close insts elems';
   397 
   398   in ((fixed, deps, elems'', concl), (parms, ctxt7)) end
   399 
   400 in
   401 
   402 fun cert_full_context_statement x =
   403   prep_full_context_statement (K I) (K I) ProofContext.cert_vars
   404   make_inst ProofContext.cert_vars (K I) x;
   405 
   406 fun cert_read_full_context_statement x =
   407   prep_full_context_statement Syntax.parse_typ Syntax.parse_prop ProofContext.read_vars
   408   make_inst ProofContext.cert_vars (K I) x;
   409 
   410 fun read_full_context_statement x =
   411   prep_full_context_statement Syntax.parse_typ Syntax.parse_prop ProofContext.read_vars
   412   parse_inst ProofContext.read_vars intern x;
   413 
   414 end;
   415 
   416 
   417 (* Context statement: elements + conclusion *)
   418 
   419 local
   420 
   421 fun prep_statement prep activate raw_elems raw_concl context =
   422   let
   423      val ((_, _, elems, concl), _) =
   424        prep {strict = true, do_close = false, fixed_frees = true}
   425         ([], []) I raw_elems raw_concl context;
   426      val (_, context') = context |>
   427        ProofContext.set_stmt true |>
   428        fold_map activate elems;
   429   in (concl, context') end;
   430 
   431 in
   432 
   433 fun cert_statement x = prep_statement cert_full_context_statement Element.activate_i x;
   434 fun read_statement x = prep_statement read_full_context_statement Element.activate x;
   435 
   436 end;
   437 
   438 
   439 (* Locale declaration: import + elements *)
   440 
   441 fun fix_params params =
   442   ProofContext.add_fixes (map (fn ((x, T), mx) => (Binding.name x, SOME T, mx)) params) #> snd;
   443 
   444 local
   445 
   446 fun prep_declaration prep activate raw_import init_body raw_elems context =
   447   let
   448     val ((fixed, deps, elems, _), (parms, ctxt')) =
   449       prep {strict = false, do_close = true, fixed_frees = false}
   450         raw_import init_body raw_elems [] context;
   451     (* Declare parameters and imported facts *)
   452     val context' = context |>
   453       fix_params fixed |>
   454       fold (Context.proof_map o Locale.activate_facts NONE) deps;
   455     val (elems', _) = context' |>
   456       ProofContext.set_stmt true |>
   457       fold_map activate elems;
   458   in ((fixed, deps, elems'), (parms, ctxt')) end;
   459 
   460 in
   461 
   462 fun cert_declaration x = prep_declaration cert_full_context_statement Element.activate_i x;
   463 fun cert_read_declaration x = prep_declaration cert_read_full_context_statement Element.activate x;
   464 fun read_declaration x = prep_declaration read_full_context_statement Element.activate x;
   465 
   466 end;
   467 
   468 
   469 (* Locale expression to set up a goal *)
   470 
   471 local
   472 
   473 fun props_of thy (name, morph) =
   474   let
   475     val (asm, defs) = Locale.specification_of thy name;
   476   in
   477     (case asm of NONE => defs | SOME asm => asm :: defs) |> map (Morphism.term morph)
   478   end;
   479 
   480 fun prep_goal_expression prep expression context =
   481   let
   482     val thy = ProofContext.theory_of context;
   483 
   484     val ((fixed, deps, _, _), _) =
   485       prep {strict = true, do_close = true, fixed_frees = true} expression I [] [] context;
   486     (* proof obligations *)
   487     val propss = map (props_of thy) deps;
   488 
   489     val goal_ctxt = context |>
   490       fix_params fixed |>
   491       (fold o fold) Variable.auto_fixes propss;
   492 
   493     val export = Variable.export_morphism goal_ctxt context;
   494     val exp_fact = Drule.zero_var_indexes_list o map Thm.strip_shyps o Morphism.fact export;
   495     val exp_term = Term_Subst.zero_var_indexes o Morphism.term export;
   496     val exp_typ = Logic.type_map exp_term;
   497     val export' = Morphism.morphism {binding = I, typ = exp_typ, term = exp_term, fact = exp_fact};
   498   in ((propss, deps, export'), goal_ctxt) end;
   499 
   500 in
   501 
   502 fun cert_goal_expression x = prep_goal_expression cert_full_context_statement x;
   503 fun read_goal_expression x = prep_goal_expression read_full_context_statement x;
   504 
   505 end;
   506 
   507 
   508 (*** Locale declarations ***)
   509 
   510 (* extract specification text *)
   511 
   512 val norm_term = Envir.beta_norm oo Term.subst_atomic;
   513 
   514 fun bind_def ctxt eq (xs, env, eqs) =
   515   let
   516     val _ = Local_Defs.cert_def ctxt eq;
   517     val ((y, T), b) = Local_Defs.abs_def eq;
   518     val b' = norm_term env b;
   519     fun err msg = error (msg ^ ": " ^ quote y);
   520   in
   521     case filter (fn (Free (y', _), _) => y = y' | _ => false) env of
   522       [] => (Term.add_frees b' xs, (Free (y, T), b') :: env, eq :: eqs) |
   523       dups => if forall (fn (_, b'') => b' aconv b'') dups
   524         then (xs, env, eqs)
   525         else err "Attempt to redefine variable"
   526   end;
   527 
   528 (* text has the following structure:
   529        (((exts, exts'), (ints, ints')), (xs, env, defs))
   530    where
   531      exts: external assumptions (terms in assumes elements)
   532      exts': dito, normalised wrt. env
   533      ints: internal assumptions (terms in assumptions from insts)
   534      ints': dito, normalised wrt. env
   535      xs: the free variables in exts' and ints' and rhss of definitions,
   536        this includes parameters except defined parameters
   537      env: list of term pairs encoding substitutions, where the first term
   538        is a free variable; substitutions represent defines elements and
   539        the rhs is normalised wrt. the previous env
   540      defs: the equations from the defines elements
   541    *)
   542 
   543 fun eval_text _ _ (Fixes _) text = text
   544   | eval_text _ _ (Constrains _) text = text
   545   | eval_text _ is_ext (Assumes asms)
   546         (((exts, exts'), (ints, ints')), (xs, env, defs)) =
   547       let
   548         val ts = maps (map #1 o #2) asms;
   549         val ts' = map (norm_term env) ts;
   550         val spec' =
   551           if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
   552           else ((exts, exts'), (ints @ ts, ints' @ ts'));
   553       in (spec', (fold Term.add_frees ts' xs, env, defs)) end
   554   | eval_text ctxt _ (Defines defs) (spec, binds) =
   555       (spec, fold (bind_def ctxt o #1 o #2) defs binds)
   556   | eval_text _ _ (Notes _) text = text;
   557 
   558 fun eval_inst ctxt (loc, morph) text =
   559   let
   560     val thy = ProofContext.theory_of ctxt;
   561     val (asm, defs) = Locale.specification_of thy loc;
   562     val asm' = Option.map (Morphism.term morph) asm;
   563     val defs' = map (Morphism.term morph) defs;
   564     val text' = text |>
   565       (if is_some asm
   566         then eval_text ctxt false (Assumes [(Attrib.empty_binding, [(the asm', [])])])
   567         else I) |>
   568       (if not (null defs)
   569         then eval_text ctxt false (Defines (map (fn def => (Attrib.empty_binding, (def, []))) defs'))
   570         else I)
   571 (* FIXME clone from locale.ML *)
   572   in text' end;
   573 
   574 fun eval_elem ctxt elem text =
   575   eval_text ctxt true elem text;
   576 
   577 fun eval ctxt deps elems =
   578   let
   579     val text' = fold (eval_inst ctxt) deps ((([], []), ([], [])), ([], [], []));
   580     val ((spec, (_, _, defs))) = fold (eval_elem ctxt) elems text';
   581   in (spec, defs) end;
   582 
   583 (* axiomsN: name of theorem set with destruct rules for locale predicates,
   584      also name suffix of delta predicates and assumptions. *)
   585 
   586 val axiomsN = "axioms";
   587 
   588 local
   589 
   590 (* introN: name of theorems for introduction rules of locale and
   591      delta predicates *)
   592 
   593 val introN = "intro";
   594 
   595 fun atomize_spec thy ts =
   596   let
   597     val t = Logic.mk_conjunction_balanced ts;
   598     val body = Object_Logic.atomize_term thy t;
   599     val bodyT = Term.fastype_of body;
   600   in
   601     if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
   602     else (body, bodyT, Object_Logic.atomize (Thm.cterm_of thy t))
   603   end;
   604 
   605 (* achieve plain syntax for locale predicates (without "PROP") *)
   606 
   607 fun aprop_tr' n c = (Syntax.mark_const c, fn ctxt => fn args =>
   608   if length args = n then
   609     Syntax.const "_aprop" $   (* FIXME avoid old-style early externing (!??) *)
   610       Term.list_comb (Syntax.free (Consts.extern (ProofContext.consts_of ctxt) c), args)
   611   else raise Match);
   612 
   613 (* define one predicate including its intro rule and axioms
   614    - binding: predicate name
   615    - parms: locale parameters
   616    - defs: thms representing substitutions from defines elements
   617    - ts: terms representing locale assumptions (not normalised wrt. defs)
   618    - norm_ts: terms representing locale assumptions (normalised wrt. defs)
   619    - thy: the theory
   620 *)
   621 
   622 fun def_pred binding parms defs ts norm_ts thy =
   623   let
   624     val name = Sign.full_name thy binding;
   625 
   626     val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
   627     val env = Term.add_free_names body [];
   628     val xs = filter (member (op =) env o #1) parms;
   629     val Ts = map #2 xs;
   630     val extraTs =
   631       (subtract (op =) (fold Term.add_tfreesT Ts []) (Term.add_tfrees body []))
   632       |> Library.sort_wrt #1 |> map TFree;
   633     val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
   634 
   635     val args = map Logic.mk_type extraTs @ map Free xs;
   636     val head = Term.list_comb (Const (name, predT), args);
   637     val statement = Object_Logic.ensure_propT thy head;
   638 
   639     val ([pred_def], defs_thy) =
   640       thy
   641       |> bodyT = propT ? Sign.add_advanced_trfuns ([], [], [aprop_tr' (length args) name], [])
   642       |> Sign.declare_const ((Binding.conceal binding, predT), NoSyn) |> snd
   643       |> PureThy.add_defs false
   644         [((Binding.conceal (Thm.def_binding binding), Logic.mk_equals (head, body)), [])];
   645     val defs_ctxt = ProofContext.init_global defs_thy |> Variable.declare_term head;
   646 
   647     val cert = Thm.cterm_of defs_thy;
   648 
   649     val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
   650       MetaSimplifier.rewrite_goals_tac [pred_def] THEN
   651       Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
   652       Tactic.compose_tac (false,
   653         Conjunction.intr_balanced (map (Thm.assume o cert) norm_ts), 0) 1);
   654 
   655     val conjuncts =
   656       (Drule.equal_elim_rule2 OF [body_eq,
   657         MetaSimplifier.rewrite_rule [pred_def] (Thm.assume (cert statement))])
   658       |> Conjunction.elim_balanced (length ts);
   659     val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
   660       Element.prove_witness defs_ctxt t
   661        (MetaSimplifier.rewrite_goals_tac defs THEN
   662         Tactic.compose_tac (false, ax, 0) 1));
   663   in ((statement, intro, axioms), defs_thy) end;
   664 
   665 in
   666 
   667 (* main predicate definition function *)
   668 
   669 fun define_preds binding parms (((exts, exts'), (ints, ints')), defs) thy =
   670   let
   671     val defs' = map (cterm_of thy #> Assumption.assume #> Drule.abs_def) defs;
   672 
   673     val (a_pred, a_intro, a_axioms, thy'') =
   674       if null exts then (NONE, NONE, [], thy)
   675       else
   676         let
   677           val abinding = if null ints then binding else Binding.suffix_name ("_" ^ axiomsN) binding;
   678           val ((statement, intro, axioms), thy') =
   679             thy
   680             |> def_pred abinding parms defs' exts exts';
   681           val (_, thy'') =
   682             thy'
   683             |> Sign.qualified_path true abinding
   684             |> PureThy.note_thmss ""
   685               [((Binding.conceal (Binding.name introN), []), [([intro], [Locale.unfold_add])])]
   686             ||> Sign.restore_naming thy';
   687           in (SOME statement, SOME intro, axioms, thy'') end;
   688     val (b_pred, b_intro, b_axioms, thy'''') =
   689       if null ints then (NONE, NONE, [], thy'')
   690       else
   691         let
   692           val ((statement, intro, axioms), thy''') =
   693             thy''
   694             |> def_pred binding parms defs' (ints @ the_list a_pred) (ints' @ the_list a_pred);
   695           val (_, thy'''') =
   696             thy'''
   697             |> Sign.qualified_path true binding
   698             |> PureThy.note_thmss ""
   699                  [((Binding.conceal (Binding.name introN), []), [([intro], [Locale.intro_add])]),
   700                   ((Binding.conceal (Binding.name axiomsN), []),
   701                     [(map (Drule.export_without_context o Element.conclude_witness) axioms, [])])]
   702             ||> Sign.restore_naming thy''';
   703         in (SOME statement, SOME intro, axioms, thy'''') end;
   704   in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
   705 
   706 end;
   707 
   708 
   709 local
   710 
   711 fun assumes_to_notes (Assumes asms) axms =
   712       fold_map (fn (a, spec) => fn axs =>
   713           let val (ps, qs) = chop (length spec) axs
   714           in ((a, [(ps, [])]), qs) end) asms axms
   715       |> apfst (curry Notes "")
   716   | assumes_to_notes e axms = (e, axms);
   717 
   718 fun defines_to_notes thy (Defines defs) =
   719       Notes (Thm.definitionK, map (fn (a, (def, _)) =>
   720         (a, [([Assumption.assume (cterm_of thy def)],
   721           [(Attrib.internal o K) Locale.witness_add])])) defs)
   722   | defines_to_notes _ e = e;
   723 
   724 fun gen_add_locale prep_decl
   725     binding raw_predicate_binding raw_import raw_body thy =
   726   let
   727     val name = Sign.full_name thy binding;
   728     val _ = Locale.defined thy name andalso
   729       error ("Duplicate definition of locale " ^ quote name);
   730 
   731     val ((fixed, deps, body_elems), (parms, ctxt')) =
   732       prep_decl raw_import I raw_body (ProofContext.init_global thy);
   733     val text as (((_, exts'), _), defs) = eval ctxt' deps body_elems;
   734 
   735     val extraTs =
   736       subtract (op =) (fold Term.add_tfreesT (map snd parms) []) (fold Term.add_tfrees exts' []);
   737     val _ =
   738       if null extraTs then ()
   739       else warning ("Additional type variable(s) in locale specification " ^
   740         quote (Binding.str_of binding) ^ ": " ^
   741           commas (map (Syntax.string_of_typ ctxt' o TFree) (sort_wrt #1 extraTs)));
   742 
   743     val predicate_binding =
   744       if Binding.is_empty raw_predicate_binding then binding
   745       else raw_predicate_binding;
   746     val ((a_statement, a_intro, a_axioms), (b_statement, b_intro, b_axioms), thy') =
   747       define_preds predicate_binding parms text thy;
   748 
   749     val a_satisfy = Element.satisfy_morphism a_axioms;
   750     val b_satisfy = Element.satisfy_morphism b_axioms;
   751 
   752     val params = fixed @
   753       maps (fn Fixes fixes =>
   754         map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fixes | _ => []) body_elems;
   755     val asm = if is_some b_statement then b_statement else a_statement;
   756 
   757     val notes =
   758       if is_some asm then
   759         [("", [((Binding.conceal (Binding.suffix_name ("_" ^ axiomsN) binding), []),
   760           [([Assumption.assume (cterm_of thy' (the asm))],
   761             [(Attrib.internal o K) Locale.witness_add])])])]
   762       else [];
   763 
   764     val notes' = body_elems |>
   765       map (defines_to_notes thy') |>
   766       map (Element.morph_ctxt a_satisfy) |>
   767       (fn elems => fold_map assumes_to_notes elems (map Element.conclude_witness a_axioms)) |>
   768       fst |>
   769       map (Element.morph_ctxt b_satisfy) |>
   770       map_filter (fn Notes notes => SOME notes | _ => NONE);
   771 
   772     val deps' = map (fn (l, morph) => (l, morph $> b_satisfy)) deps;
   773     val axioms = map Element.conclude_witness b_axioms;
   774 
   775     val loc_ctxt = thy'
   776       |> Locale.register_locale binding (extraTs, params)
   777           (asm, rev defs) (a_intro, b_intro) axioms [] (rev notes) (rev deps')
   778       |> Named_Target.init name
   779       |> fold (fn (kind, facts) => Local_Theory.notes_kind kind facts #> snd) notes';
   780 
   781   in (name, loc_ctxt) end;
   782 
   783 in
   784 
   785 val add_locale = gen_add_locale cert_declaration;
   786 val add_locale_cmd = gen_add_locale read_declaration;
   787 
   788 end;
   789 
   790 
   791 (*** Interpretation ***)
   792 
   793 (** Interpretation in theories and proof contexts **)
   794 
   795 local
   796 
   797 fun note_eqns_register deps witss attrss eqns export export' context =
   798   let
   799     fun meta_rewrite context =
   800       map (Local_Defs.meta_rewrite_rule (Context.proof_of context) #> Drule.abs_def) o
   801         maps snd;
   802   in
   803     context
   804     |> Element.generic_note_thmss Thm.lemmaK
   805       (attrss ~~ map (fn eqn => [([Morphism.thm (export' $> export) eqn],[])]) eqns)
   806     |-> (fn facts => `(fn context => meta_rewrite context facts))
   807     |-> (fn eqns => fold (fn ((dep, morph), wits) =>
   808       fn context =>
   809         Locale.add_registration (dep, morph $> Element.satisfy_morphism
   810             (map (Element.morph_witness export') wits))
   811           (Element.eq_morphism (Context.theory_of context) eqns |>
   812             Option.map (rpair true))
   813           export context) (deps ~~ witss))
   814   end;
   815 
   816 fun gen_interpretation prep_expr parse_prop prep_attr
   817     expression equations theory =
   818   let
   819     val ((propss, deps, export), expr_ctxt) = ProofContext.init_global theory
   820       |> prep_expr expression;
   821 
   822     val eqns = map (parse_prop expr_ctxt o snd) equations |> Syntax.check_terms expr_ctxt;
   823     val attrss = map ((apsnd o map) (prep_attr theory) o fst) equations;
   824     val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
   825     val export' = Variable.export_morphism goal_ctxt expr_ctxt;
   826 
   827     fun after_qed witss eqns =
   828       (ProofContext.background_theory o Context.theory_map)
   829         (note_eqns_register deps witss attrss eqns export export');
   830 
   831   in Element.witness_proof_eqs after_qed propss eqns goal_ctxt end;
   832 
   833 fun gen_interpret prep_expr parse_prop prep_attr
   834     expression equations int state =
   835   let
   836     val _ = Proof.assert_forward_or_chain state;
   837     val ctxt = Proof.context_of state;
   838     val theory = ProofContext.theory_of ctxt;
   839 
   840     val ((propss, deps, export), expr_ctxt) = prep_expr expression ctxt;
   841 
   842     val eqns = map (parse_prop expr_ctxt o snd) equations |> Syntax.check_terms expr_ctxt;
   843     val attrss = map ((apsnd o map) (prep_attr theory) o fst) equations;
   844     val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
   845     val export' = Variable.export_morphism goal_ctxt expr_ctxt;
   846 
   847     fun after_qed witss eqns = (Proof.map_context o Context.proof_map)
   848       (note_eqns_register deps witss attrss eqns export export');
   849   in
   850     state
   851     |> Element.witness_local_proof_eqs after_qed "interpret" propss eqns goal_ctxt int
   852   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 fun interpret x = gen_interpret cert_goal_expression (K I) (K I) x;
   861 fun interpret_cmd x = gen_interpret read_goal_expression
   862   Syntax.parse_prop Attrib.intern_src x;
   863 
   864 end;
   865 
   866 
   867 (** Interpretation between locales: declaring sublocale relationships **)
   868 
   869 local
   870 
   871 fun gen_sublocale prep_expr intern raw_target expression thy =
   872   let
   873     val target = intern thy raw_target;
   874     val target_ctxt = Named_Target.init target thy;
   875     val ((propss, deps, export), goal_ctxt) = prep_expr expression target_ctxt;
   876     fun after_qed witss = ProofContext.background_theory
   877       (fold (fn ((dep, morph), wits) => Locale.add_dependency
   878         target (dep, morph $> Element.satisfy_morphism wits) export) (deps ~~ witss));
   879   in Element.witness_proof after_qed propss goal_ctxt end;
   880 
   881 in
   882 
   883 fun sublocale x = gen_sublocale cert_goal_expression (K I) x;
   884 fun sublocale_cmd x = gen_sublocale read_goal_expression Locale.intern x;
   885 
   886 end;
   887 
   888 end;
   889