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