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