src/Pure/Isar/locale.ML
author wenzelm
Thu Nov 23 00:52:23 2006 +0100 (2006-11-23)
changeset 21483 e4be91feca50
parent 21441 940ef3e85c5a
child 21499 fbd6422a847a
permissions -rw-r--r--
replaced Args.map_values/Element.map_ctxt_values by general morphism application;
wenzelm@12014
     1
(*  Title:      Pure/Isar/locale.ML
wenzelm@11896
     2
    ID:         $Id$
ballarin@15206
     3
    Author:     Clemens Ballarin, TU Muenchen; Markus Wenzel, LMU/TU Muenchen
wenzelm@11896
     4
wenzelm@12058
     5
Locales -- Isar proof contexts as meta-level predicates, with local
wenzelm@12529
     6
syntax and implicit structures.
wenzelm@12529
     7
ballarin@19942
     8
Draws basic ideas from Florian Kammueller's original version of
wenzelm@12529
     9
locales, but uses the richer infrastructure of Isar instead of the raw
ballarin@20035
    10
meta-logic.  Furthermore, structured import of contexts (with merge
ballarin@20035
    11
and rename operations) are provided, as well as type-inference of the
wenzelm@13375
    12
signature parts, and predicate definitions of the specification text.
ballarin@14446
    13
ballarin@17437
    14
Interpretation enables the reuse of theorems of locales in other
ballarin@17437
    15
contexts, namely those defined by theories, structured proofs and
ballarin@17437
    16
locales themselves.
ballarin@17437
    17
ballarin@14446
    18
See also:
ballarin@14446
    19
ballarin@14446
    20
[1] Clemens Ballarin. Locales and Locale Expressions in Isabelle/Isar.
ballarin@14446
    21
    In Stefano Berardi et al., Types for Proofs and Programs: International
ballarin@15099
    22
    Workshop, TYPES 2003, Torino, Italy, LNCS 3085, pages 34-50, 2004.
ballarin@19942
    23
[2] Clemens Ballarin. Interpretation of Locales in Isabelle: Managing
ballarin@19942
    24
    Dependencies between Locales. Technical Report TUM-I0607, Technische
ballarin@19942
    25
    Universitaet Muenchen, 2006.
ballarin@19942
    26
[3] Clemens Ballarin. Interpretation of Locales in Isabelle: Theories and
ballarin@19942
    27
    Proof Contexts. In J.M. Borwein and W.M. Farmer, MKM 2006, LNAI 4108,
ballarin@19942
    28
    pages 31-43, 2006.
wenzelm@11896
    29
*)
wenzelm@11896
    30
ballarin@16169
    31
(* TODO:
ballarin@16169
    32
- beta-eta normalisation of interpretation parameters
ballarin@16169
    33
- dangling type frees in locales
ballarin@16620
    34
- test subsumption of interpretations when merging theories
ballarin@16169
    35
*)
ballarin@16169
    36
wenzelm@11896
    37
signature LOCALE =
wenzelm@11896
    38
sig
wenzelm@12273
    39
  datatype expr =
wenzelm@12273
    40
    Locale of string |
ballarin@16102
    41
    Rename of expr * (string * mixfix option) option list |
wenzelm@12273
    42
    Merge of expr list
wenzelm@12273
    43
  val empty: expr
wenzelm@18137
    44
  datatype 'a element = Elem of 'a | Expr of expr
wenzelm@21035
    45
  val map_elem: ('a -> 'b) -> 'a element -> 'b element
ballarin@15206
    46
wenzelm@16458
    47
  val intern: theory -> xstring -> string
wenzelm@16458
    48
  val extern: theory -> string -> xstring
ballarin@19991
    49
  val init: string -> theory -> Proof.context
ballarin@15206
    50
ballarin@18795
    51
  (* The specification of a locale *)
ballarin@18795
    52
ballarin@18795
    53
  val parameters_of: theory -> string ->
haftmann@18917
    54
    ((string * typ) * mixfix) list
ballarin@19276
    55
  val parameters_of_expr: theory -> expr ->
ballarin@19276
    56
    ((string * typ) * mixfix) list
ballarin@18795
    57
  val local_asms_of: theory -> string ->
ballarin@18795
    58
    ((string * Attrib.src list) * term list) list
ballarin@18795
    59
  val global_asms_of: theory -> string ->
ballarin@18795
    60
    ((string * Attrib.src list) * term list) list
ballarin@18795
    61
wenzelm@18899
    62
  (* Processing of locale statements *)
wenzelm@18137
    63
  val read_context_statement: xstring option -> Element.context element list ->
wenzelm@19585
    64
    (string * string list) list list -> Proof.context ->
ballarin@19991
    65
    string option * Proof.context * Proof.context * (term * term list) list list
wenzelm@21035
    66
  val read_context_statement_i: string option -> Element.context element list ->
wenzelm@21035
    67
    (string * string list) list list -> Proof.context ->
wenzelm@21035
    68
    string option * Proof.context * Proof.context * (term * term list) list list
wenzelm@18137
    69
  val cert_context_statement: string option -> Element.context_i element list ->
wenzelm@19585
    70
    (term * term list) list list -> Proof.context ->
ballarin@19991
    71
    string option * Proof.context * Proof.context * (term * term list) list list
wenzelm@19780
    72
  val read_expr: expr -> Element.context list -> Proof.context ->
wenzelm@19780
    73
    Element.context_i list * Proof.context
wenzelm@19780
    74
  val cert_expr: expr -> Element.context_i list -> Proof.context ->
wenzelm@19780
    75
    Element.context_i list * Proof.context
ballarin@15596
    76
ballarin@15596
    77
  (* Diagnostic functions *)
wenzelm@12758
    78
  val print_locales: theory -> unit
wenzelm@18137
    79
  val print_locale: theory -> bool -> expr -> Element.context list -> unit
ballarin@17138
    80
  val print_global_registrations: bool -> string -> theory -> unit
wenzelm@18617
    81
  val print_local_registrations': bool -> string -> Proof.context -> unit
wenzelm@18617
    82
  val print_local_registrations: bool -> string -> Proof.context -> unit
wenzelm@18137
    83
haftmann@18917
    84
  val add_locale: bool -> bstring -> expr -> Element.context list -> theory
wenzelm@20965
    85
    -> string * Proof.context
haftmann@18917
    86
  val add_locale_i: bool -> bstring -> expr -> Element.context_i list -> theory
wenzelm@20965
    87
    -> string * Proof.context
ballarin@15596
    88
schirmer@21225
    89
  (* Tactics *)
schirmer@21225
    90
  val intro_locales_tac: bool -> Proof.context -> thm list -> tactic
schirmer@21225
    91
ballarin@15696
    92
  (* Storing results *)
wenzelm@18806
    93
  val add_thmss: string -> string ->
wenzelm@18806
    94
    ((string * Attrib.src list) * (thm list * Attrib.src list) list) list ->
wenzelm@20911
    95
    Proof.context -> (string * thm list) list * Proof.context
ballarin@20037
    96
  val add_term_syntax: string -> (Proof.context -> Proof.context) -> Proof.context -> Proof.context
wenzelm@18137
    97
wenzelm@21005
    98
  val interpretation: (Proof.context -> Proof.context) ->
wenzelm@21005
    99
    string * Attrib.src list -> expr -> string option list ->
wenzelm@21005
   100
    theory -> Proof.state
wenzelm@21005
   101
  val interpretation_in_locale: (Proof.context -> Proof.context) ->
wenzelm@21005
   102
    xstring * expr -> theory -> Proof.state
wenzelm@21005
   103
  val interpret: (Proof.state -> Proof.state Seq.seq) ->
wenzelm@21005
   104
    string * Attrib.src list -> expr -> string option list ->
wenzelm@21005
   105
    bool -> Proof.state -> Proof.state
wenzelm@11896
   106
end;
wenzelm@12839
   107
wenzelm@12289
   108
structure Locale: LOCALE =
wenzelm@11896
   109
struct
wenzelm@11896
   110
ballarin@19931
   111
fun legacy_unvarifyT thm =
ballarin@19931
   112
  let
ballarin@19931
   113
    val cT = Thm.ctyp_of (Thm.theory_of_thm thm);
wenzelm@20307
   114
    val tvars = rev (Drule.fold_terms Term.add_tvars thm []);
wenzelm@20307
   115
    val tfrees = map (fn ((x, _), S) => SOME (cT (TFree (x, S)))) tvars;
ballarin@19931
   116
  in Drule.instantiate' tfrees [] thm end;
ballarin@19931
   117
ballarin@19931
   118
fun legacy_unvarify raw_thm =
ballarin@19931
   119
  let
ballarin@19931
   120
    val thm = legacy_unvarifyT raw_thm;
ballarin@19931
   121
    val ct = Thm.cterm_of (Thm.theory_of_thm thm);
wenzelm@20307
   122
    val vars = rev (Drule.fold_terms Term.add_vars thm []);
wenzelm@20307
   123
    val frees = map (fn ((x, _), T) => SOME (ct (Free (x, T)))) vars;
ballarin@19931
   124
  in Drule.instantiate' [] frees thm end;
wenzelm@19780
   125
wenzelm@20307
   126
wenzelm@12273
   127
(** locale elements and expressions **)
wenzelm@11896
   128
wenzelm@18137
   129
datatype ctxt = datatype Element.ctxt;
wenzelm@17355
   130
wenzelm@12273
   131
datatype expr =
wenzelm@12273
   132
  Locale of string |
ballarin@16102
   133
  Rename of expr * (string * mixfix option) option list |
wenzelm@12273
   134
  Merge of expr list;
wenzelm@11896
   135
wenzelm@12273
   136
val empty = Merge [];
wenzelm@12273
   137
wenzelm@18137
   138
datatype 'a element =
ballarin@15206
   139
  Elem of 'a | Expr of expr;
wenzelm@12273
   140
wenzelm@18137
   141
fun map_elem f (Elem e) = Elem (f e)
wenzelm@18137
   142
  | map_elem _ (Expr e) = Expr e;
wenzelm@18137
   143
wenzelm@12070
   144
type locale =
ballarin@19931
   145
 {axiom: Element.witness list,
ballarin@19942
   146
    (* For locales that define predicates this is [A [A]], where A is the locale
ballarin@20317
   147
       specification.  Otherwise [].
ballarin@20317
   148
       Only required to generate the right witnesses for locales with predicates. *)
wenzelm@19018
   149
  import: expr,                                                     (*dynamic import*)
ballarin@19783
   150
  elems: (Element.context_i * stamp) list,
ballarin@19783
   151
    (* Static content, neither Fixes nor Constrains elements *)
ballarin@19278
   152
  params: ((string * typ) * mixfix) list,                           (*all params*)
ballarin@19931
   153
  lparams: string list,                                             (*local params*)
wenzelm@19662
   154
  term_syntax: ((Proof.context -> Proof.context) * stamp) list, (* FIXME depend on morphism *)
ballarin@19931
   155
  regs: ((string * string list) * Element.witness list) list,
wenzelm@19780
   156
    (* Registrations: indentifiers and witnesses of locales interpreted in the locale. *)
ballarin@19931
   157
  intros: thm list * thm list}
ballarin@19931
   158
    (* Introduction rules: of delta predicate and locale predicate. *)
wenzelm@11896
   159
wenzelm@15703
   160
(* CB: an internal (Int) locale element was either imported or included,
wenzelm@15703
   161
   an external (Ext) element appears directly in the locale text. *)
wenzelm@15703
   162
wenzelm@15703
   163
datatype ('a, 'b) int_ext = Int of 'a | Ext of 'b;
wenzelm@15703
   164
wenzelm@15703
   165
wenzelm@15703
   166
ballarin@16736
   167
(** management of registrations in theories and proof contexts **)
wenzelm@11896
   168
ballarin@15837
   169
structure Registrations :
ballarin@15837
   170
  sig
ballarin@15837
   171
    type T
ballarin@15837
   172
    val empty: T
ballarin@15837
   173
    val join: T * T -> T
ballarin@20069
   174
    val dest: theory -> T ->
ballarin@20069
   175
      (term list * ((string * Attrib.src list) * Element.witness list)) list
wenzelm@16458
   176
    val lookup: theory -> T * term list ->
wenzelm@19780
   177
      ((string * Attrib.src list) * Element.witness list) option
wenzelm@16458
   178
    val insert: theory -> term list * (string * Attrib.src list) -> T ->
wenzelm@19780
   179
      T * (term list * ((string * Attrib.src list) * Element.witness list)) list
wenzelm@19780
   180
    val add_witness: term list -> Element.witness -> T -> T
ballarin@15837
   181
  end =
ballarin@15837
   182
struct
ballarin@20069
   183
  (* a registration consists of theorems (actually, witnesses) instantiating locale
ballarin@20069
   184
     assumptions and prefix and attributes, indexed by parameter instantiation *)
wenzelm@19780
   185
  type T = ((string * Attrib.src list) * Element.witness list) Termtab.table;
ballarin@15837
   186
ballarin@15837
   187
  val empty = Termtab.empty;
ballarin@15837
   188
ballarin@15837
   189
  (* term list represented as single term, for simultaneous matching *)
ballarin@15837
   190
  fun termify ts =
wenzelm@18343
   191
    Term.list_comb (Const ("", map fastype_of ts ---> propT), ts);
ballarin@15837
   192
  fun untermify t =
ballarin@15837
   193
    let fun ut (Const _) ts = ts
ballarin@15837
   194
          | ut (s $ t) ts = ut s (t::ts)
ballarin@15837
   195
    in ut t [] end;
ballarin@15837
   196
ballarin@16620
   197
  (* joining of registrations: prefix and attributes of left theory,
ballarin@15837
   198
     thms are equal, no attempt to subsumption testing *)
wenzelm@19025
   199
  fun join (r1, r2) = Termtab.join (fn _ => fn (reg, _) => reg) (r1, r2);
ballarin@15837
   200
ballarin@20069
   201
  fun dest_transfer thy regs =
ballarin@20069
   202
    Termtab.dest regs |> map (apsnd (apsnd (map (Element.transfer_witness thy))));
ballarin@20069
   203
ballarin@20069
   204
  fun dest thy regs = dest_transfer thy regs |> map (apfst untermify);
ballarin@15837
   205
ballarin@15837
   206
  (* registrations that subsume t *)
wenzelm@17203
   207
  fun subsumers thy t regs =
ballarin@20069
   208
    filter (fn (t', _) => Pattern.matches thy (t', t)) (dest_transfer thy regs);
ballarin@15837
   209
ballarin@15837
   210
  (* look up registration, pick one that subsumes the query *)
wenzelm@19780
   211
  fun lookup thy (regs, ts) =
ballarin@15837
   212
    let
ballarin@15837
   213
      val t = termify ts;
wenzelm@19780
   214
      val subs = subsumers thy t regs;
wenzelm@21483
   215
    in
wenzelm@21483
   216
      (case subs of
ballarin@15837
   217
        [] => NONE
wenzelm@21483
   218
      | ((t', (attn, thms)) :: _) =>
wenzelm@21483
   219
          let
wenzelm@19780
   220
            val (tinst, inst) = Pattern.match thy (t', t) (Vartab.empty, Vartab.empty);
ballarin@15837
   221
            (* thms contain Frees, not Vars *)
wenzelm@21483
   222
            val tinst' = tinst |> Vartab.dest   (* FIXME Symtab.map (!?) *)
wenzelm@19810
   223
                 |> map (fn ((x, 0), (_, T)) => (x, Logic.legacy_unvarifyT T))
ballarin@15837
   224
                 |> Symtab.make;
ballarin@15837
   225
            val inst' = inst |> Vartab.dest
wenzelm@19810
   226
                 |> map (fn ((x, 0), (_, t)) => (x, Logic.legacy_unvarify t))
ballarin@15837
   227
                 |> Symtab.make;
wenzelm@21483
   228
            val inst_witness = Element.morph_witness (Element.inst_morphism thy (tinst', inst'));
wenzelm@21483
   229
          in SOME (attn, map inst_witness thms) end)
ballarin@15837
   230
    end;
ballarin@15837
   231
ballarin@15837
   232
  (* add registration if not subsumed by ones already present,
ballarin@15837
   233
     additionally returns registrations that are strictly subsumed *)
ballarin@20069
   234
  fun insert thy (ts, attn) regs =
ballarin@15837
   235
    let
ballarin@15837
   236
      val t = termify ts;
ballarin@20069
   237
      val subs = subsumers thy t regs ;
ballarin@15837
   238
    in (case subs of
ballarin@15837
   239
        [] => let
ballarin@15837
   240
                val sups =
ballarin@20069
   241
                  filter (fn (t', _) => Pattern.matches thy (t, t')) (dest_transfer thy regs);
ballarin@15837
   242
                val sups' = map (apfst untermify) sups
wenzelm@17412
   243
              in (Termtab.update (t, (attn, [])) regs, sups') end
ballarin@15837
   244
      | _ => (regs, []))
ballarin@15837
   245
    end;
ballarin@15837
   246
ballarin@15837
   247
  (* add witness theorem to registration,
ballarin@16169
   248
     only if instantiation is exact, otherwise exception Option raised *)
ballarin@15837
   249
  fun add_witness ts thm regs =
ballarin@15837
   250
    let
ballarin@15837
   251
      val t = termify ts;
wenzelm@18343
   252
      val (x, thms) = the (Termtab.lookup regs t);
ballarin@15837
   253
    in
wenzelm@17412
   254
      Termtab.update (t, (x, thm::thms)) regs
ballarin@15837
   255
    end;
ballarin@15837
   256
end;
ballarin@15837
   257
ballarin@16736
   258
ballarin@15837
   259
(** theory data **)
ballarin@15596
   260
wenzelm@16458
   261
structure GlobalLocalesData = TheoryDataFun
wenzelm@16458
   262
(struct
wenzelm@12014
   263
  val name = "Isar/locales";
ballarin@15837
   264
  type T = NameSpace.T * locale Symtab.table * Registrations.T Symtab.table;
ballarin@15596
   265
    (* 1st entry: locale namespace,
ballarin@15596
   266
       2nd entry: locales of the theory,
ballarin@15837
   267
       3rd entry: registrations, indexed by locale name *)
wenzelm@11896
   268
ballarin@15596
   269
  val empty = (NameSpace.empty, Symtab.empty, Symtab.empty);
wenzelm@12063
   270
  val copy = I;
wenzelm@16458
   271
  val extend = I;
wenzelm@12289
   272
ballarin@19931
   273
  fun join_locs _ ({axiom, import, elems, params, lparams, term_syntax, regs, intros}: locale,
wenzelm@19662
   274
      {elems = elems', term_syntax = term_syntax', regs = regs', ...}: locale) =
ballarin@19931
   275
     {axiom = axiom,
wenzelm@19018
   276
      import = import,
haftmann@17496
   277
      elems = gen_merge_lists (eq_snd (op =)) elems elems',
ballarin@16736
   278
      params = params,
ballarin@19278
   279
      lparams = lparams,
wenzelm@19662
   280
      term_syntax = Library.merge (eq_snd (op =)) (term_syntax, term_syntax'),
ballarin@19931
   281
      regs = merge_alists regs regs',
ballarin@19931
   282
      intros = intros};
wenzelm@16458
   283
  fun merge _ ((space1, locs1, regs1), (space2, locs2, regs2)) =
ballarin@15596
   284
    (NameSpace.merge (space1, space2), Symtab.join join_locs (locs1, locs2),
wenzelm@19025
   285
     Symtab.join (K Registrations.join) (regs1, regs2));
wenzelm@12289
   286
ballarin@15596
   287
  fun print _ (space, locs, _) =
wenzelm@16346
   288
    Pretty.strs ("locales:" :: map #1 (NameSpace.extern_table (space, locs)))
wenzelm@12014
   289
    |> Pretty.writeln;
wenzelm@16458
   290
end);
wenzelm@11896
   291
wenzelm@18708
   292
val _ = Context.add_setup GlobalLocalesData.init;
wenzelm@15801
   293
wenzelm@15801
   294
ballarin@15624
   295
ballarin@15624
   296
(** context data **)
wenzelm@11896
   297
wenzelm@16458
   298
structure LocalLocalesData = ProofDataFun
wenzelm@16458
   299
(struct
ballarin@15624
   300
  val name = "Isar/locales";
ballarin@15837
   301
  type T = Registrations.T Symtab.table;
ballarin@15837
   302
    (* registrations, indexed by locale name *)
ballarin@15624
   303
  fun init _ = Symtab.empty;
ballarin@15624
   304
  fun print _ _ = ();
wenzelm@16458
   305
end);
ballarin@15624
   306
wenzelm@18708
   307
val _ = Context.add_setup LocalLocalesData.init;
wenzelm@12289
   308
wenzelm@12277
   309
wenzelm@12277
   310
(* access locales *)
wenzelm@12277
   311
ballarin@15624
   312
val print_locales = GlobalLocalesData.print;
ballarin@15624
   313
wenzelm@16458
   314
val intern = NameSpace.intern o #1 o GlobalLocalesData.get;
wenzelm@16458
   315
val extern = NameSpace.extern o #1 o GlobalLocalesData.get;
ballarin@15624
   316
wenzelm@16144
   317
fun declare_locale name thy =
wenzelm@16144
   318
  thy |> GlobalLocalesData.map (fn (space, locs, regs) =>
wenzelm@16458
   319
    (Sign.declare_name thy name space, locs, regs));
wenzelm@11896
   320
ballarin@15596
   321
fun put_locale name loc =
ballarin@15624
   322
  GlobalLocalesData.map (fn (space, locs, regs) =>
wenzelm@17412
   323
    (space, Symtab.update (name, loc) locs, regs));
wenzelm@17412
   324
wenzelm@17412
   325
fun get_locale thy name = Symtab.lookup (#2 (GlobalLocalesData.get thy)) name;
wenzelm@11896
   326
wenzelm@12014
   327
fun the_locale thy name =
wenzelm@12014
   328
  (case get_locale thy name of
skalberg@15531
   329
    SOME loc => loc
skalberg@15531
   330
  | NONE => error ("Unknown locale " ^ quote name));
wenzelm@11896
   331
wenzelm@18806
   332
fun change_locale name f thy =
wenzelm@18806
   333
  let
ballarin@19931
   334
    val {axiom, import, elems, params, lparams, term_syntax, regs, intros} =
ballarin@19931
   335
        the_locale thy name;
ballarin@19931
   336
    val (axiom', import', elems', params', lparams', term_syntax', regs', intros') =
ballarin@19931
   337
      f (axiom, import, elems, params, lparams, term_syntax, regs, intros);
wenzelm@18806
   338
  in
ballarin@19931
   339
    put_locale name {axiom = axiom', import = import', elems = elems',
ballarin@19931
   340
      params = params', lparams = lparams', term_syntax = term_syntax', regs = regs',
ballarin@19931
   341
      intros = intros'} thy
wenzelm@18806
   342
  end;
wenzelm@18806
   343
wenzelm@12046
   344
ballarin@15596
   345
(* access registrations *)
ballarin@15596
   346
ballarin@15696
   347
(* Ids of global registrations are varified,
ballarin@15696
   348
   Ids of local registrations are not.
ballarin@15696
   349
   Thms of registrations are never varified. *)
ballarin@15696
   350
ballarin@15624
   351
(* retrieve registration from theory or context *)
ballarin@15624
   352
ballarin@20069
   353
fun gen_get_registrations get thy_of thy_ctxt name =
wenzelm@17412
   354
  case Symtab.lookup (get thy_ctxt) name of
ballarin@15696
   355
      NONE => []
ballarin@20069
   356
    | SOME reg => Registrations.dest (thy_of thy_ctxt) reg;
ballarin@15696
   357
ballarin@15696
   358
val get_global_registrations =
ballarin@20069
   359
     gen_get_registrations (#3 o GlobalLocalesData.get) I;
ballarin@15696
   360
val get_local_registrations =
ballarin@20069
   361
     gen_get_registrations LocalLocalesData.get ProofContext.theory_of;
ballarin@15696
   362
wenzelm@16458
   363
fun gen_get_registration get thy_of thy_ctxt (name, ps) =
wenzelm@17412
   364
  case Symtab.lookup (get thy_ctxt) name of
ballarin@15624
   365
      NONE => NONE
wenzelm@16458
   366
    | SOME reg => Registrations.lookup (thy_of thy_ctxt) (reg, ps);
ballarin@15624
   367
ballarin@15624
   368
val get_global_registration =
wenzelm@16458
   369
     gen_get_registration (#3 o GlobalLocalesData.get) I;
ballarin@15624
   370
val get_local_registration =
wenzelm@16458
   371
     gen_get_registration LocalLocalesData.get ProofContext.theory_of;
ballarin@15596
   372
wenzelm@18343
   373
val test_global_registration = is_some oo get_global_registration;
wenzelm@18343
   374
val test_local_registration = is_some oo get_local_registration;
ballarin@15624
   375
fun smart_test_registration ctxt id =
ballarin@15624
   376
  let
ballarin@15624
   377
    val thy = ProofContext.theory_of ctxt;
ballarin@15624
   378
  in
ballarin@15624
   379
    test_global_registration thy id orelse test_local_registration ctxt id
ballarin@15624
   380
  end;
ballarin@15624
   381
ballarin@15624
   382
ballarin@15837
   383
(* add registration to theory or context, ignored if subsumed *)
ballarin@15624
   384
wenzelm@16458
   385
fun gen_put_registration map_data thy_of (name, ps) attn thy_ctxt =
ballarin@15837
   386
  map_data (fn regs =>
ballarin@15837
   387
    let
wenzelm@16458
   388
      val thy = thy_of thy_ctxt;
wenzelm@18343
   389
      val reg = the_default Registrations.empty (Symtab.lookup regs name);
wenzelm@16458
   390
      val (reg', sups) = Registrations.insert thy (ps, attn) reg;
ballarin@15837
   391
      val _ = if not (null sups) then warning
ballarin@15837
   392
                ("Subsumed interpretation(s) of locale " ^
wenzelm@16458
   393
                 quote (extern thy name) ^
ballarin@15837
   394
                 "\nby interpretation(s) with the following prefix(es):\n" ^
ballarin@15837
   395
                  commas_quote (map (fn (_, ((s, _), _)) => s) sups))
ballarin@15837
   396
              else ();
wenzelm@17412
   397
    in Symtab.update (name, reg') regs end) thy_ctxt;
ballarin@15624
   398
ballarin@15624
   399
val put_global_registration =
ballarin@15624
   400
     gen_put_registration (fn f =>
wenzelm@16458
   401
       GlobalLocalesData.map (fn (space, locs, regs) => (space, locs, f regs))) I;
ballarin@15837
   402
val put_local_registration =
wenzelm@16458
   403
     gen_put_registration LocalLocalesData.map ProofContext.theory_of;
ballarin@15596
   404
wenzelm@18806
   405
fun put_registration_in_locale name id =
ballarin@19931
   406
  change_locale name (fn (axiom, import, elems, params, lparams, term_syntax, regs, intros) =>
ballarin@19931
   407
    (axiom, import, elems, params, lparams, term_syntax, regs @ [(id, [])], intros));
ballarin@17000
   408
ballarin@15624
   409
ballarin@15624
   410
(* add witness theorem to registration in theory or context,
ballarin@15596
   411
   ignored if registration not present *)
ballarin@15596
   412
wenzelm@18123
   413
fun add_witness (name, ps) thm =
wenzelm@18123
   414
  Symtab.map_entry name (Registrations.add_witness ps thm);
wenzelm@18123
   415
wenzelm@18123
   416
fun add_global_witness id thm =
wenzelm@18123
   417
  GlobalLocalesData.map (fn (space, locs, regs) => (space, locs, add_witness id thm regs));
wenzelm@18123
   418
wenzelm@18123
   419
val add_local_witness = LocalLocalesData.map oo add_witness;
ballarin@15596
   420
wenzelm@18806
   421
fun add_witness_in_locale name id thm =
ballarin@19931
   422
  change_locale name (fn (axiom, import, elems, params, lparams, term_syntax, regs, intros) =>
ballarin@17000
   423
    let
ballarin@17000
   424
      fun add (id', thms) =
wenzelm@18806
   425
        if id = id' then (id', thm :: thms) else (id', thms);
ballarin@19931
   426
    in (axiom, import, elems, params, lparams, term_syntax, map add regs, intros) end);
ballarin@15596
   427
ballarin@14215
   428
ballarin@15624
   429
(* printing of registrations *)
ballarin@15596
   430
ballarin@17138
   431
fun gen_print_registrations get_regs mk_ctxt msg show_wits loc thy_ctxt =
ballarin@15596
   432
  let
wenzelm@15703
   433
    val ctxt = mk_ctxt thy_ctxt;
wenzelm@15703
   434
    val thy = ProofContext.theory_of ctxt;
wenzelm@15703
   435
wenzelm@15703
   436
    val prt_term = Pretty.quote o ProofContext.pretty_term ctxt;
ballarin@17096
   437
    fun prt_inst ts =
ballarin@17096
   438
        Pretty.enclose "(" ")" (Pretty.breaks (map prt_term ts));
ballarin@17096
   439
    fun prt_attn (prfx, atts) =
wenzelm@21035
   440
        Pretty.breaks (Pretty.str prfx :: Attrib.pretty_attribs ctxt atts);
wenzelm@19780
   441
    fun prt_witns witns = Pretty.enclose "[" "]"
wenzelm@19780
   442
      (Pretty.breaks (map (prt_term o Element.witness_prop) witns));
wenzelm@19780
   443
    fun prt_reg (ts, (("", []), witns)) =
ballarin@17138
   444
        if show_wits
wenzelm@19780
   445
          then Pretty.block [prt_inst ts, Pretty.fbrk, prt_witns witns]
ballarin@17096
   446
          else prt_inst ts
wenzelm@19780
   447
      | prt_reg (ts, (attn, witns)) =
ballarin@17138
   448
        if show_wits
ballarin@17096
   449
          then Pretty.block ((prt_attn attn @
ballarin@17096
   450
            [Pretty.str ":", Pretty.brk 1, prt_inst ts, Pretty.fbrk,
wenzelm@19780
   451
              prt_witns witns]))
ballarin@17096
   452
          else Pretty.block ((prt_attn attn @
ballarin@17096
   453
            [Pretty.str ":", Pretty.brk 1, prt_inst ts]));
wenzelm@15703
   454
wenzelm@16458
   455
    val loc_int = intern thy loc;
ballarin@15624
   456
    val regs = get_regs thy_ctxt;
wenzelm@17412
   457
    val loc_regs = Symtab.lookup regs loc_int;
ballarin@15596
   458
  in
ballarin@15596
   459
    (case loc_regs of
wenzelm@17355
   460
        NONE => Pretty.str ("no interpretations in " ^ msg)
ballarin@15763
   461
      | SOME r => let
ballarin@20069
   462
            val r' = Registrations.dest thy r;
ballarin@15763
   463
            val r'' = Library.sort_wrt (fn (_, ((prfx, _), _)) => prfx) r';
wenzelm@17355
   464
          in Pretty.big_list ("interpretations in " ^ msg ^ ":")
ballarin@17096
   465
            (map prt_reg r'')
ballarin@15763
   466
          end)
ballarin@15596
   467
    |> Pretty.writeln
ballarin@15596
   468
  end;
ballarin@15596
   469
ballarin@15624
   470
val print_global_registrations =
ballarin@15624
   471
     gen_print_registrations (#3 o GlobalLocalesData.get)
wenzelm@15703
   472
       ProofContext.init "theory";
ballarin@15624
   473
val print_local_registrations' =
ballarin@15624
   474
     gen_print_registrations LocalLocalesData.get
wenzelm@15703
   475
       I "context";
ballarin@17138
   476
fun print_local_registrations show_wits loc ctxt =
ballarin@17138
   477
  (print_global_registrations show_wits loc (ProofContext.theory_of ctxt);
ballarin@17138
   478
   print_local_registrations' show_wits loc ctxt);
ballarin@15624
   479
ballarin@15596
   480
wenzelm@12277
   481
(* diagnostics *)
wenzelm@12273
   482
wenzelm@12277
   483
fun err_in_locale ctxt msg ids =
wenzelm@12277
   484
  let
wenzelm@16458
   485
    val thy = ProofContext.theory_of ctxt;
wenzelm@12529
   486
    fun prt_id (name, parms) =
wenzelm@16458
   487
      [Pretty.block (Pretty.breaks (map Pretty.str (extern thy name :: parms)))];
wenzelm@19482
   488
    val prt_ids = flat (separate [Pretty.str " +", Pretty.brk 1] (map prt_id ids));
wenzelm@12502
   489
    val err_msg =
wenzelm@12529
   490
      if forall (equal "" o #1) ids then msg
wenzelm@12502
   491
      else msg ^ "\n" ^ Pretty.string_of (Pretty.block
wenzelm@12502
   492
        (Pretty.str "The error(s) above occurred in locale:" :: Pretty.brk 1 :: prt_ids));
wenzelm@18678
   493
  in error err_msg end;
wenzelm@12063
   494
ballarin@15206
   495
fun err_in_locale' ctxt msg ids' = err_in_locale ctxt msg (map fst ids');
wenzelm@12277
   496
wenzelm@12277
   497
ballarin@19783
   498
fun pretty_ren NONE = Pretty.str "_"
ballarin@19783
   499
  | pretty_ren (SOME (x, NONE)) = Pretty.str x
ballarin@19783
   500
  | pretty_ren (SOME (x, SOME syn)) =
ballarin@19783
   501
      Pretty.block [Pretty.str x, Pretty.brk 1, Syntax.pretty_mixfix syn];
ballarin@19783
   502
ballarin@19783
   503
fun pretty_expr thy (Locale name) = Pretty.str (extern thy name)
ballarin@19783
   504
  | pretty_expr thy (Rename (expr, xs)) =
ballarin@19783
   505
      Pretty.block [pretty_expr thy expr, Pretty.brk 1, Pretty.block (map pretty_ren xs |> Pretty.breaks)]
ballarin@19783
   506
  | pretty_expr thy (Merge es) =
ballarin@19783
   507
      Pretty.separate "+" (map (pretty_expr thy) es) |> Pretty.block;
ballarin@19783
   508
ballarin@19783
   509
fun err_in_expr _ msg (Merge []) = error msg
ballarin@19783
   510
  | err_in_expr ctxt msg expr =
ballarin@19783
   511
    error (msg ^ "\n" ^ Pretty.string_of (Pretty.block
ballarin@19783
   512
      [Pretty.str "The error(s) above occured in locale expression:", Pretty.brk 1,
ballarin@19783
   513
       pretty_expr (ProofContext.theory_of ctxt) expr]));
ballarin@19783
   514
wenzelm@12046
   515
wenzelm@12529
   516
(** structured contexts: rename + merge + implicit type instantiation **)
wenzelm@12529
   517
wenzelm@12529
   518
(* parameter types *)
wenzelm@12529
   519
wenzelm@12529
   520
fun frozen_tvars ctxt Ts =
wenzelm@19914
   521
  #1 (Variable.importT_inst (map Logic.mk_type Ts) ctxt)
wenzelm@19900
   522
  |> map (fn ((xi, S), T) => (xi, (S, T)));
wenzelm@12529
   523
wenzelm@12529
   524
fun unify_frozen ctxt maxidx Ts Us =
wenzelm@12529
   525
  let
wenzelm@18343
   526
    fun paramify NONE i = (NONE, i)
wenzelm@18343
   527
      | paramify (SOME T) i = apfst SOME (TypeInfer.paramify_dummies T i);
wenzelm@12529
   528
wenzelm@18343
   529
    val (Ts', maxidx') = fold_map paramify Ts maxidx;
wenzelm@18343
   530
    val (Us', maxidx'') = fold_map paramify Us maxidx';
wenzelm@16947
   531
    val thy = ProofContext.theory_of ctxt;
ballarin@14215
   532
wenzelm@18190
   533
    fun unify (SOME T, SOME U) env = (Sign.typ_unify thy (U, T) env
wenzelm@18190
   534
          handle Type.TUNIFY => raise TYPE ("unify_frozen: failed to unify types", [U, T], []))
wenzelm@18190
   535
      | unify _ env = env;
wenzelm@18190
   536
    val (unifier, _) = fold unify (Ts' ~~ Us') (Vartab.empty, maxidx'');
skalberg@15570
   537
    val Vs = map (Option.map (Envir.norm_type unifier)) Us';
wenzelm@19482
   538
    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (map_filter I Vs));
skalberg@15570
   539
  in map (Option.map (Envir.norm_type unifier')) Vs end;
wenzelm@12529
   540
haftmann@19932
   541
fun params_of elemss = distinct (eq_fst (op = : string * string -> bool)) (maps (snd o fst) elemss);
haftmann@19932
   542
fun params_of' elemss = distinct (eq_fst (op = : string * string -> bool)) (maps (snd o fst o fst) elemss);
ballarin@16102
   543
ballarin@14508
   544
ballarin@14508
   545
(* CB: param_types has the following type:
skalberg@15531
   546
  ('a * 'b option) list -> ('a * 'b) list *)
wenzelm@19482
   547
fun param_types ps = map_filter (fn (_, NONE) => NONE | (x, SOME T) => SOME (x, T)) ps;
wenzelm@12529
   548
wenzelm@12529
   549
haftmann@19932
   550
fun merge_syntax ctxt ids ss = Symtab.merge (op = : mixfix * mixfix -> bool) ss
ballarin@16102
   551
  handle Symtab.DUPS xs => err_in_locale ctxt
ballarin@16105
   552
    ("Conflicting syntax for parameter(s): " ^ commas_quote xs) (map fst ids);
ballarin@16102
   553
ballarin@16102
   554
ballarin@17000
   555
(* Distinction of assumed vs. derived identifiers.
ballarin@17000
   556
   The former may have axioms relating assumptions of the context to
ballarin@17000
   557
   assumptions of the specification fragment (for locales with
wenzelm@19780
   558
   predicates).  The latter have witnesses relating assumptions of the
ballarin@17000
   559
   specification fragment to assumptions of other (assumed) specification
ballarin@17000
   560
   fragments. *)
ballarin@17000
   561
ballarin@17000
   562
datatype 'a mode = Assumed of 'a | Derived of 'a;
ballarin@17000
   563
ballarin@17000
   564
fun map_mode f (Assumed x) = Assumed (f x)
ballarin@17000
   565
  | map_mode f (Derived x) = Derived (f x);
ballarin@17000
   566
wenzelm@18123
   567
wenzelm@12529
   568
(* flatten expressions *)
wenzelm@11896
   569
wenzelm@12510
   570
local
wenzelm@12502
   571
wenzelm@18137
   572
fun unify_parms ctxt fixed_parms raw_parmss =
wenzelm@12502
   573
  let
wenzelm@16458
   574
    val thy = ProofContext.theory_of ctxt;
wenzelm@12502
   575
    val maxidx = length raw_parmss;
wenzelm@12502
   576
    val idx_parmss = (0 upto maxidx - 1) ~~ raw_parmss;
wenzelm@12502
   577
wenzelm@12502
   578
    fun varify i = Term.map_type_tfree (fn (a, S) => TVar ((a, i), S));
wenzelm@12529
   579
    fun varify_parms (i, ps) = map (apsnd (varify i)) (param_types ps);
wenzelm@19482
   580
    val parms = fixed_parms @ maps varify_parms idx_parmss;
wenzelm@12502
   581
wenzelm@18137
   582
    fun unify T U envir = Sign.typ_unify thy (U, T) envir
ballarin@15206
   583
      handle Type.TUNIFY =>
wenzelm@18137
   584
        let val prt = Sign.string_of_typ thy in
wenzelm@18137
   585
          raise TYPE ("unify_parms: failed to unify types " ^
wenzelm@18137
   586
            prt U ^ " and " ^ prt T, [U, T], [])
wenzelm@18137
   587
        end;
wenzelm@18137
   588
    fun unify_list (T :: Us) = fold (unify T) Us
wenzelm@18137
   589
      | unify_list [] = I;
wenzelm@18952
   590
    val (unifier, _) = fold unify_list (map #2 (Symtab.dest (Symtab.make_list parms)))
wenzelm@18137
   591
      (Vartab.empty, maxidx);
wenzelm@12502
   592
wenzelm@19061
   593
    val parms' = map (apsnd (Envir.norm_type unifier)) (distinct (eq_fst (op =)) parms);
wenzelm@12502
   594
    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (map #2 parms'));
wenzelm@12502
   595
wenzelm@12502
   596
    fun inst_parms (i, ps) =
wenzelm@19482
   597
      foldr Term.add_typ_tfrees [] (map_filter snd ps)
wenzelm@19482
   598
      |> map_filter (fn (a, S) =>
wenzelm@12502
   599
          let val T = Envir.norm_type unifier' (TVar ((a, i), S))
wenzelm@18137
   600
          in if T = TFree (a, S) then NONE else SOME (a, T) end)
wenzelm@18137
   601
      |> Symtab.make;
wenzelm@18137
   602
  in map inst_parms idx_parmss end;
wenzelm@12502
   603
wenzelm@12529
   604
in
wenzelm@12502
   605
wenzelm@12529
   606
fun unify_elemss _ _ [] = []
wenzelm@12529
   607
  | unify_elemss _ [] [elems] = [elems]
wenzelm@12529
   608
  | unify_elemss ctxt fixed_parms elemss =
wenzelm@12502
   609
      let
wenzelm@18137
   610
        val thy = ProofContext.theory_of ctxt;
wenzelm@21483
   611
        val phis = unify_parms ctxt fixed_parms (map (snd o fst o fst) elemss)
wenzelm@21483
   612
          |> map (Element.instT_morphism thy);
wenzelm@21483
   613
        fun inst ((((name, ps), mode), elems), phi) =
wenzelm@21483
   614
          (((name, map (apsnd (Option.map (Morphism.typ phi))) ps),
wenzelm@21483
   615
              map_mode (map (Element.morph_witness phi)) mode),
wenzelm@21483
   616
            map (Element.morph_ctxt phi) elems);
wenzelm@21483
   617
      in map inst (elemss ~~ phis) end;
wenzelm@12502
   618
ballarin@17000
   619
wenzelm@19810
   620
fun renaming xs parms = zip_options parms xs
wenzelm@19810
   621
  handle Library.UnequalLengths =>
wenzelm@19810
   622
    error ("Too many arguments in renaming: " ^
wenzelm@19810
   623
      commas (map (fn NONE => "_" | SOME x => quote (fst x)) xs));
wenzelm@19810
   624
wenzelm@19810
   625
ballarin@19783
   626
(* params_of_expr:
ballarin@19783
   627
   Compute parameters (with types and syntax) of locale expression.
ballarin@19783
   628
*)
ballarin@19783
   629
ballarin@19783
   630
fun params_of_expr ctxt fixed_params expr (prev_parms, prev_types, prev_syn) =
ballarin@19783
   631
  let
ballarin@19783
   632
    val thy = ProofContext.theory_of ctxt;
ballarin@19783
   633
ballarin@19783
   634
    fun merge_tenvs fixed tenv1 tenv2 =
ballarin@19783
   635
        let
ballarin@19783
   636
          val [env1, env2] = unify_parms ctxt fixed
ballarin@19783
   637
                [tenv1 |> Symtab.dest |> map (apsnd SOME),
ballarin@19783
   638
                 tenv2 |> Symtab.dest |> map (apsnd SOME)]
ballarin@19783
   639
        in
ballarin@19783
   640
          Symtab.merge (op =) (Symtab.map (Element.instT_type env1) tenv1,
ballarin@19783
   641
            Symtab.map (Element.instT_type env2) tenv2)
ballarin@19783
   642
        end;
ballarin@19783
   643
ballarin@19783
   644
    fun merge_syn expr syn1 syn2 =
haftmann@19932
   645
        Symtab.merge (op = : mixfix * mixfix -> bool) (syn1, syn2)
ballarin@19783
   646
        handle Symtab.DUPS xs => err_in_expr ctxt
ballarin@19783
   647
          ("Conflicting syntax for parameter(s): " ^ commas_quote xs) expr;
wenzelm@20366
   648
ballarin@19783
   649
    fun params_of (expr as Locale name) =
ballarin@19783
   650
          let
ballarin@19783
   651
            val {import, params, ...} = the_locale thy name;
ballarin@19783
   652
            val parms = map (fst o fst) params;
ballarin@19783
   653
            val (parms', types', syn') = params_of import;
ballarin@19783
   654
            val all_parms = merge_lists parms' parms;
ballarin@19783
   655
            val all_types = merge_tenvs [] types' (params |> map fst |> Symtab.make);
ballarin@19783
   656
            val all_syn = merge_syn expr syn' (params |> map (apfst fst) |> Symtab.make);
ballarin@19783
   657
          in (all_parms, all_types, all_syn) end
ballarin@19783
   658
      | params_of (expr as Rename (e, xs)) =
ballarin@19783
   659
          let
ballarin@19783
   660
            val (parms', types', syn') = params_of e;
ballarin@19783
   661
            val ren = renaming xs parms';
ballarin@19783
   662
            (* renaming may reduce number of parameters *)
ballarin@19783
   663
            val new_parms = map (Element.rename ren) parms' |> distinct (op =);
ballarin@19783
   664
            val ren_syn = syn' |> Symtab.dest |> map (Element.rename_var ren);
ballarin@19783
   665
            val new_syn = fold (Symtab.insert (op =)) ren_syn Symtab.empty
ballarin@19783
   666
                handle Symtab.DUP x =>
ballarin@19783
   667
                  err_in_expr ctxt ("Conflicting syntax for parameter: " ^ quote x) expr;
ballarin@19783
   668
            val syn_types = map (apsnd (fn mx => SOME (Type.freeze_type (#1 (TypeInfer.paramify_dummies (TypeInfer.mixfixT mx) 0))))) (Symtab.dest new_syn);
ballarin@19783
   669
            val ren_types = types' |> Symtab.dest |> map (apfst (Element.rename ren));
wenzelm@20366
   670
            val (env :: _) = unify_parms ctxt []
ballarin@19783
   671
                ((ren_types |> map (apsnd SOME)) :: map single syn_types);
ballarin@19783
   672
            val new_types = fold (Symtab.insert (op =))
ballarin@19783
   673
                (map (apsnd (Element.instT_type env)) ren_types) Symtab.empty;
ballarin@19783
   674
          in (new_parms, new_types, new_syn) end
ballarin@19783
   675
      | params_of (Merge es) =
ballarin@19783
   676
          fold (fn e => fn (parms, types, syn) =>
ballarin@19783
   677
                   let
ballarin@19783
   678
                     val (parms', types', syn') = params_of e
ballarin@19783
   679
                   in
ballarin@19783
   680
                     (merge_lists parms parms', merge_tenvs [] types types',
ballarin@19783
   681
                      merge_syn e syn syn')
ballarin@19783
   682
                   end)
ballarin@19783
   683
            es ([], Symtab.empty, Symtab.empty)
ballarin@19783
   684
ballarin@19783
   685
      val (parms, types, syn) = params_of expr;
ballarin@19783
   686
    in
ballarin@19783
   687
      (merge_lists prev_parms parms, merge_tenvs fixed_params prev_types types,
ballarin@19783
   688
       merge_syn expr prev_syn syn)
ballarin@19783
   689
    end;
ballarin@19783
   690
ballarin@19783
   691
fun make_params_ids params = [(("", params), ([], Assumed []))];
ballarin@19783
   692
fun make_raw_params_elemss (params, tenv, syn) =
ballarin@19783
   693
    [((("", map (fn p => (p, Symtab.lookup tenv p)) params), Assumed []),
ballarin@19783
   694
      Int [Fixes (map (fn p =>
ballarin@19783
   695
        (p, Symtab.lookup tenv p, Symtab.lookup syn p |> the)) params)])];
ballarin@19783
   696
ballarin@19783
   697
ballarin@15596
   698
(* flatten_expr:
ballarin@15596
   699
   Extend list of identifiers by those new in locale expression expr.
ballarin@15596
   700
   Compute corresponding list of lists of locale elements (one entry per
ballarin@15596
   701
   identifier).
ballarin@15596
   702
ballarin@15596
   703
   Identifiers represent locale fragments and are in an extended form:
ballarin@15596
   704
     ((name, ps), (ax_ps, axs))
ballarin@15596
   705
   (name, ps) is the locale name with all its parameters.
ballarin@15596
   706
   (ax_ps, axs) is the locale axioms with its parameters;
ballarin@15596
   707
     axs are always taken from the top level of the locale hierarchy,
ballarin@15596
   708
     hence axioms may contain additional parameters from later fragments:
ballarin@15596
   709
     ps subset of ax_ps.  axs is either singleton or empty.
ballarin@15596
   710
ballarin@15596
   711
   Elements are enriched by identifier-like information:
ballarin@15596
   712
     (((name, ax_ps), axs), elems)
ballarin@15596
   713
   The parameters in ax_ps are the axiom parameters, but enriched by type
ballarin@15596
   714
   info: now each entry is a pair of string and typ option.  Axioms are
ballarin@15596
   715
   type-instantiated.
ballarin@15596
   716
ballarin@15596
   717
*)
ballarin@15596
   718
ballarin@16102
   719
fun flatten_expr ctxt ((prev_idents, prev_syntax), expr) =
wenzelm@12014
   720
  let
wenzelm@12014
   721
    val thy = ProofContext.theory_of ctxt;
wenzelm@12263
   722
ballarin@17000
   723
    fun rename_parms top ren ((name, ps), (parms, mode)) =
ballarin@19783
   724
        ((name, map (Element.rename ren) ps),
ballarin@19783
   725
         if top
ballarin@19783
   726
         then (map (Element.rename ren) parms,
wenzelm@21483
   727
               map_mode (map (Element.morph_witness (Element.rename_morphism ren))) mode)
ballarin@19783
   728
         else (parms, mode));
wenzelm@12263
   729
ballarin@20167
   730
    (* add (name, ps) and its registrations, recursively; adjust hyps of witnesses *)
ballarin@17000
   731
ballarin@20167
   732
    fun add_with_regs ((name, pTs), mode) (wits, ids, visited) =
ballarin@20167
   733
        if member (fn (a, (b, _)) => a = b) visited (name, map #1 pTs)
ballarin@20167
   734
        then (wits, ids, visited)
ballarin@20167
   735
        else
wenzelm@20366
   736
          let
wenzelm@20366
   737
            val {params, regs, ...} = the_locale thy name;
wenzelm@20366
   738
            val pTs' = map #1 params;
wenzelm@20366
   739
            val ren = map #1 pTs' ~~ map (fn (x, _) => (x, NONE)) pTs;
wenzelm@20366
   740
              (* dummy syntax, since required by rename *)
wenzelm@20366
   741
            val pTs'' = map (fn ((p, _), (_, T)) => (p, T)) (pTs ~~ pTs');
wenzelm@20366
   742
            val [env] = unify_parms ctxt pTs [map (apsnd SOME) pTs''];
wenzelm@20366
   743
              (* propagate parameter types, to keep them consistent *)
wenzelm@20366
   744
            val regs' = map (fn ((name, ps), wits) =>
wenzelm@20366
   745
                ((name, map (Element.rename ren) ps),
wenzelm@20366
   746
                 map (Element.transfer_witness thy) wits)) regs;
wenzelm@20366
   747
            val new_regs = regs';
wenzelm@20366
   748
            val new_ids = map fst new_regs;
wenzelm@21483
   749
            val new_idTs =
wenzelm@21483
   750
              map (apsnd (map (fn p => (p, (the o AList.lookup (op =) pTs) p)))) new_ids;
ballarin@17096
   751
wenzelm@20366
   752
            val new_wits = new_regs |> map (#2 #> map
wenzelm@21483
   753
              (Element.morph_witness
wenzelm@21483
   754
                (Element.instT_morphism thy env $>
wenzelm@21483
   755
                  Element.rename_morphism ren $>
wenzelm@21483
   756
                  Element.satisfy_morphism wits)));
wenzelm@20366
   757
            val new_ids' = map (fn (id, wits) =>
wenzelm@20366
   758
                (id, ([], Derived wits))) (new_ids ~~ new_wits);
wenzelm@20366
   759
            val new_idTs' = map (fn ((n, pTs), (_, ([], mode))) =>
wenzelm@20366
   760
                ((n, pTs), mode)) (new_idTs ~~ new_ids');
wenzelm@20366
   761
            val new_id = ((name, map #1 pTs), ([], mode));
wenzelm@20366
   762
            val (wits', ids', visited') = fold add_with_regs new_idTs'
ballarin@20167
   763
              (wits @ flat new_wits, ids, visited @ [new_id]);
wenzelm@20366
   764
          in
wenzelm@20366
   765
            (wits', ids' @ [new_id], visited')
wenzelm@20366
   766
          end;
ballarin@17000
   767
ballarin@17000
   768
    (* distribute top-level axioms over assumed ids *)
ballarin@17000
   769
ballarin@17000
   770
    fun axiomify all_ps ((name, parms), (_, Assumed _)) axioms =
ballarin@17000
   771
        let
ballarin@17000
   772
          val {elems, ...} = the_locale thy name;
wenzelm@19482
   773
          val ts = maps
wenzelm@19482
   774
            (fn (Assumes asms, _) => maps (map #1 o #2) asms
ballarin@17000
   775
              | _ => [])
wenzelm@19482
   776
            elems;
wenzelm@19018
   777
          val (axs1, axs2) = chop (length ts) axioms;
ballarin@17000
   778
        in (((name, parms), (all_ps, Assumed axs1)), axs2) end
ballarin@17000
   779
      | axiomify all_ps (id, (_, Derived ths)) axioms =
ballarin@17000
   780
          ((id, (all_ps, Derived ths)), axioms);
ballarin@17000
   781
ballarin@17096
   782
    (* identifiers of an expression *)
ballarin@17096
   783
ballarin@15206
   784
    fun identify top (Locale name) =
ballarin@15596
   785
    (* CB: ids_ax is a list of tuples of the form ((name, ps), axs),
ballarin@15206
   786
       where name is a locale name, ps a list of parameter names and axs
ballarin@15206
   787
       a list of axioms relating to the identifier, axs is empty unless
ballarin@15206
   788
       identify at top level (top = true);
ballarin@14215
   789
       parms is accumulated list of parameters *)
wenzelm@12289
   790
          let
ballarin@20035
   791
            val {axiom, import, params, ...} = the_locale thy name;
ballarin@19278
   792
            val ps = map (#1 o #1) params;
ballarin@20035
   793
            val (ids', parms') = identify false import;
ballarin@15206
   794
                (* acyclic import dependencies *)
ballarin@19931
   795
ballarin@20167
   796
            val (_, ids'', _) = add_with_regs ((name, map #1 params), Assumed []) ([], ids', ids');
ballarin@20167
   797
            val ids_ax = if top then fst (fold_map (axiomify ps) ids'' axiom) else ids'';
ballarin@20035
   798
            in (ids_ax, merge_lists parms' ps) end
ballarin@15206
   799
      | identify top (Rename (e, xs)) =
wenzelm@12273
   800
          let
ballarin@20035
   801
            val (ids', parms') = identify top e;
wenzelm@12839
   802
            val ren = renaming xs parms'
wenzelm@18678
   803
              handle ERROR msg => err_in_locale' ctxt msg ids';
ballarin@17096
   804
wenzelm@19061
   805
            val ids'' = distinct (eq_fst (op =)) (map (rename_parms top ren) ids');
wenzelm@19482
   806
            val parms'' = distinct (op =) (maps (#2 o #1) ids'');
ballarin@20035
   807
          in (ids'', parms'') end
ballarin@15206
   808
      | identify top (Merge es) =
ballarin@20035
   809
          fold (fn e => fn (ids, parms) =>
ballarin@17000
   810
                   let
ballarin@20035
   811
                     val (ids', parms') = identify top e
ballarin@17000
   812
                   in
ballarin@20035
   813
                     (merge_alists ids ids', merge_lists parms parms')
ballarin@17000
   814
                   end)
ballarin@20035
   815
            es ([], []);
ballarin@15206
   816
ballarin@20035
   817
    fun inst_wit all_params (t, th) = let
ballarin@15206
   818
         val {hyps, prop, ...} = Thm.rep_thm th;
wenzelm@16861
   819
         val ps = map (apsnd SOME) (fold Term.add_frees (prop :: hyps) []);
ballarin@15206
   820
         val [env] = unify_parms ctxt all_params [ps];
wenzelm@18137
   821
         val t' = Element.instT_term env t;
wenzelm@18137
   822
         val th' = Element.instT_thm thy env th;
wenzelm@18123
   823
       in (t', th') end;
ballarin@17000
   824
ballarin@20035
   825
    fun eval all_params tenv syn ((name, params), (locale_params, mode)) =
ballarin@20035
   826
      let
ballarin@20035
   827
        val {params = ps_mx, elems = elems_stamped, ...} = the_locale thy name;
ballarin@20035
   828
        val elems = map fst elems_stamped;
ballarin@20035
   829
        val ps = map fst ps_mx;
ballarin@20035
   830
        fun lookup_syn x = (case Symtab.lookup syn x of SOME Structure => NONE | opt => opt);
ballarin@20035
   831
        val locale_params' = map (fn p => (p, Symtab.lookup tenv p |> the)) locale_params;
ballarin@20035
   832
        val mode' = map_mode (map (Element.map_witness (inst_wit all_params))) mode;
ballarin@20035
   833
        val ren = map fst ps ~~ map (fn p => (p, lookup_syn p)) params;
ballarin@20035
   834
        val [env] = unify_parms ctxt all_params [map (apfst (Element.rename ren) o apsnd SOME) ps];
wenzelm@21483
   835
        val eval_elem =
wenzelm@21483
   836
           Element.morph_ctxt (Element.rename_morphism ren) #>
wenzelm@21483
   837
           Element.map_ctxt {var = I, typ = I, term = I, fact = I, attrib = I,
wenzelm@21483
   838
             name = NameSpace.qualified (space_implode "_" params)} #>
wenzelm@21483
   839
           Element.morph_ctxt (Element.instT_morphism thy env);
wenzelm@21483
   840
      in (((name, map (apsnd SOME) locale_params'), mode'), map eval_elem elems) end;
ballarin@20035
   841
ballarin@20035
   842
    (* parameters, their types and syntax *)
ballarin@20035
   843
    val (all_params', tenv, syn) = params_of_expr ctxt [] expr ([], Symtab.empty, Symtab.empty);
ballarin@20035
   844
    val all_params = map (fn p => (p, Symtab.lookup tenv p |> the)) all_params';
ballarin@20035
   845
    (* compute identifiers and syntax, merge with previous ones *)
ballarin@20035
   846
    val (ids, _) = identify true expr;
haftmann@20951
   847
    val idents = subtract (eq_fst (op =)) prev_idents ids;
ballarin@20035
   848
    val syntax = merge_syntax ctxt ids (syn, prev_syntax);
ballarin@20035
   849
    (* type-instantiate elements *)
ballarin@20035
   850
    val final_elemss = map (eval all_params tenv syntax) idents;
ballarin@16102
   851
  in ((prev_idents @ idents, syntax), final_elemss) end;
wenzelm@12046
   852
wenzelm@12510
   853
end;
wenzelm@12510
   854
wenzelm@12070
   855
wenzelm@12529
   856
(* activate elements *)
wenzelm@12273
   857
wenzelm@12510
   858
local
wenzelm@12510
   859
wenzelm@18671
   860
fun axioms_export axs _ hyps =
wenzelm@19780
   861
  Element.satisfy_thm axs
wenzelm@20307
   862
  #> Drule.implies_intr_list (Library.drop (length axs, hyps));
wenzelm@12263
   863
ballarin@17000
   864
ballarin@17000
   865
(* NB: derived ids contain only facts at this stage *)
ballarin@17000
   866
ballarin@19931
   867
fun activate_elem _ _ ((ctxt, mode), Fixes fixes) =
wenzelm@18671
   868
      ((ctxt |> ProofContext.add_fixes_i fixes |> snd, mode), [])
ballarin@19931
   869
  | activate_elem _ _ ((ctxt, mode), Constrains _) =
ballarin@17000
   870
      ((ctxt, mode), [])
ballarin@19931
   871
  | activate_elem ax_in_ctxt _ ((ctxt, Assumed axs), Assumes asms) =
wenzelm@13399
   872
      let
wenzelm@18728
   873
        val asms' = Attrib.map_specs (Attrib.attribute_i (ProofContext.theory_of ctxt)) asms;
wenzelm@19482
   874
        val ts = maps (map #1 o #2) asms';
wenzelm@19018
   875
        val (ps, qs) = chop (length ts) axs;
wenzelm@17856
   876
        val (_, ctxt') =
wenzelm@21370
   877
          ctxt |> fold Variable.auto_fixes ts
ballarin@19931
   878
          |> ProofContext.add_assms_i (axioms_export (if ax_in_ctxt then ps else [])) asms';
ballarin@17000
   879
      in ((ctxt', Assumed qs), []) end
ballarin@19931
   880
  | activate_elem _ _ ((ctxt, Derived ths), Assumes asms) =
ballarin@17000
   881
      ((ctxt, Derived ths), [])
ballarin@19931
   882
  | activate_elem _ _ ((ctxt, Assumed axs), Defines defs) =
ballarin@15596
   883
      let
wenzelm@18728
   884
        val defs' = Attrib.map_specs (Attrib.attribute_i (ProofContext.theory_of ctxt)) defs;
wenzelm@19732
   885
        val asms = defs' |> map (fn ((name, atts), (t, ps)) =>
wenzelm@19732
   886
            let val ((c, _), t') = LocalDefs.cert_def ctxt t
wenzelm@20872
   887
            in (t', ((Thm.def_name_optional c name, atts), [(t', ps)])) end);
wenzelm@17856
   888
        val (_, ctxt') =
wenzelm@21370
   889
          ctxt |> fold (Variable.auto_fixes o #1) asms
wenzelm@19732
   890
          |> ProofContext.add_assms_i LocalDefs.def_export (map #2 asms);
ballarin@17000
   891
      in ((ctxt', Assumed axs), []) end
ballarin@19931
   892
  | activate_elem _ _ ((ctxt, Derived ths), Defines defs) =
ballarin@17000
   893
      ((ctxt, Derived ths), [])
wenzelm@21441
   894
  | activate_elem _ is_ext ((ctxt, mode), Notes (kind, facts)) =
ballarin@15596
   895
      let
wenzelm@18728
   896
        val facts' = Attrib.map_facts (Attrib.attribute_i (ProofContext.theory_of ctxt)) facts;
wenzelm@21441
   897
        val (res, ctxt') = ctxt |> ProofContext.note_thmss_i kind facts';
ballarin@17000
   898
      in ((ctxt', mode), if is_ext then res else []) end;
wenzelm@12502
   899
ballarin@19931
   900
fun activate_elems ax_in_ctxt (((name, ps), mode), elems) ctxt =
ballarin@17033
   901
  let
wenzelm@18123
   902
    val thy = ProofContext.theory_of ctxt;
ballarin@17033
   903
    val ((ctxt', _), res) =
wenzelm@21441
   904
      foldl_map (activate_elem ax_in_ctxt (name = ""))
wenzelm@21441
   905
        ((ProofContext.qualified_names ctxt, mode), elems)
wenzelm@21441
   906
      handle ERROR msg => err_in_locale ctxt msg [(name, map fst ps)];
ballarin@15696
   907
    val ctxt'' = if name = "" then ctxt'
ballarin@15696
   908
          else let
ballarin@15696
   909
              val ps' = map (fn (n, SOME T) => Free (n, T)) ps;
ballarin@15696
   910
              val ctxt'' = put_local_registration (name, ps') ("", []) ctxt'
ballarin@17000
   911
            in case mode of
wenzelm@18123
   912
                Assumed axs =>
wenzelm@19780
   913
                  fold (add_local_witness (name, ps') o
wenzelm@19780
   914
                    Element.assume_witness thy o Element.witness_prop) axs ctxt''
wenzelm@18123
   915
              | Derived ths => fold (add_local_witness (name, ps')) ths ctxt''
ballarin@15696
   916
            end
wenzelm@16144
   917
  in (ProofContext.restore_naming ctxt ctxt'', res) end;
wenzelm@13399
   918
ballarin@19931
   919
fun activate_elemss ax_in_ctxt prep_facts =
ballarin@17000
   920
    fold_map (fn (((name, ps), mode), raw_elems) => fn ctxt =>
ballarin@17000
   921
      let
ballarin@17000
   922
        val elems = map (prep_facts ctxt) raw_elems;
wenzelm@19482
   923
        val (ctxt', res) = apsnd flat
ballarin@19931
   924
            (activate_elems ax_in_ctxt (((name, ps), mode), elems) ctxt);
wenzelm@18137
   925
        val elems' = elems |> map (Element.map_ctxt
wenzelm@18137
   926
          {name = I, var = I, typ = I, term = I, fact = I, attrib = Args.closure});
ballarin@19931
   927
      in (((((name, ps), mode), elems'), res), ctxt') end);
wenzelm@12834
   928
wenzelm@12546
   929
in
wenzelm@12546
   930
ballarin@15206
   931
(* CB: activate_facts prep_facts (ctxt, elemss),
ballarin@15206
   932
   where elemss is a list of pairs consisting of identifiers and
ballarin@15206
   933
   context elements, extends ctxt by the context elements yielding
ballarin@15206
   934
   ctxt' and returns (ctxt', (elemss', facts)).
ballarin@15206
   935
   Identifiers in the argument are of the form ((name, ps), axs) and
ballarin@15206
   936
   assumptions use the axioms in the identifiers to set up exporters
ballarin@15206
   937
   in ctxt'.  elemss' does not contain identifiers and is obtained
ballarin@15206
   938
   from elemss and the intermediate context with prep_facts.
wenzelm@15703
   939
   If read_facts or cert_facts is used for prep_facts, these also remove
ballarin@14508
   940
   the internal/external markers from elemss. *)
ballarin@14508
   941
ballarin@19931
   942
fun activate_facts ax_in_ctxt prep_facts (ctxt, args) =
ballarin@19931
   943
  let val ((elemss, factss), ctxt') = activate_elemss ax_in_ctxt prep_facts args ctxt |>> split_list
wenzelm@19482
   944
  in (ctxt', (elemss, flat factss)) end;
wenzelm@15703
   945
wenzelm@12510
   946
end;
wenzelm@12510
   947
wenzelm@12307
   948
ballarin@15696
   949
wenzelm@18137
   950
(** prepare locale elements **)
wenzelm@12529
   951
wenzelm@12529
   952
(* expressions *)
wenzelm@12529
   953
wenzelm@16458
   954
fun intern_expr thy (Locale xname) = Locale (intern thy xname)
wenzelm@16458
   955
  | intern_expr thy (Merge exprs) = Merge (map (intern_expr thy) exprs)
wenzelm@16458
   956
  | intern_expr thy (Rename (expr, xs)) = Rename (intern_expr thy expr, xs);
wenzelm@12529
   957
wenzelm@12529
   958
wenzelm@12529
   959
(* propositions and bindings *)
wenzelm@12529
   960
ballarin@17000
   961
(* flatten (ctxt, prep_expr) ((ids, syn), expr)
ballarin@17000
   962
   normalises expr (which is either a locale
ballarin@14508
   963
   expression or a single context element) wrt.
ballarin@14508
   964
   to the list ids of already accumulated identifiers.
ballarin@19783
   965
   It returns ((ids', syn'), elemss) where ids' is an extension of ids
ballarin@14508
   966
   with identifiers generated for expr, and elemss is the list of
ballarin@16102
   967
   context elements generated from expr.
ballarin@16102
   968
   syn and syn' are symtabs mapping parameter names to their syntax.  syn'
ballarin@16102
   969
   is an extension of syn.
ballarin@16102
   970
   For details, see flatten_expr.
ballarin@16102
   971
ballarin@15596
   972
   Additionally, for a locale expression, the elems are grouped into a single
ballarin@15596
   973
   Int; individual context elements are marked Ext.  In this case, the
ballarin@15596
   974
   identifier-like information of the element is as follows:
ballarin@15596
   975
   - for Fixes: (("", ps), []) where the ps have type info NONE
ballarin@15596
   976
   - for other elements: (("", []), []).
ballarin@15206
   977
   The implementation of activate_facts relies on identifier names being
ballarin@15206
   978
   empty strings for external elements.
ballarin@15596
   979
*)
ballarin@14508
   980
ballarin@16102
   981
fun flatten (ctxt, _) ((ids, syn), Elem (Fixes fixes)) = let
wenzelm@18137
   982
        val ids' = ids @ [(("", map #1 fixes), ([], Assumed []))]
ballarin@16102
   983
      in
wenzelm@18137
   984
        ((ids',
wenzelm@18137
   985
         merge_syntax ctxt ids'
wenzelm@18137
   986
           (syn, Symtab.make (map (fn fx => (#1 fx, #3 fx)) fixes))
wenzelm@18137
   987
           handle Symtab.DUPS xs => err_in_locale ctxt
ballarin@19931
   988
             ("Conflicting syntax for parameters: " ^ commas_quote xs)
ballarin@16102
   989
             (map #1 ids')),
wenzelm@18137
   990
         [((("", map (rpair NONE o #1) fixes), Assumed []), Ext (Fixes fixes))])
ballarin@16102
   991
      end
ballarin@16102
   992
  | flatten _ ((ids, syn), Elem elem) =
ballarin@17000
   993
      ((ids @ [(("", []), ([], Assumed []))], syn), [((("", []), Assumed []), Ext elem)])
ballarin@16102
   994
  | flatten (ctxt, prep_expr) ((ids, syn), Expr expr) =
ballarin@16102
   995
      apsnd (map (apsnd Int)) (flatten_expr ctxt ((ids, syn), prep_expr expr));
ballarin@14508
   996
wenzelm@12529
   997
local
wenzelm@12529
   998
wenzelm@12839
   999
local
wenzelm@12839
  1000
wenzelm@12727
  1001
fun declare_int_elem (ctxt, Fixes fixes) =
wenzelm@18671
  1002
      (ctxt |> ProofContext.add_fixes_i (map (fn (x, T, mx) =>
wenzelm@18671
  1003
        (x, Option.map (Term.map_type_tfree (TypeInfer.param 0)) T, mx)) fixes) |> snd, [])
wenzelm@12727
  1004
  | declare_int_elem (ctxt, _) = (ctxt, []);
wenzelm@12529
  1005
wenzelm@18671
  1006
fun declare_ext_elem prep_vars (ctxt, Fixes fixes) =
wenzelm@18671
  1007
      let val (vars, _) = prep_vars fixes ctxt
wenzelm@18671
  1008
      in (ctxt |> ProofContext.add_fixes_i vars |> snd, []) end
wenzelm@18671
  1009
  | declare_ext_elem prep_vars (ctxt, Constrains csts) =
wenzelm@18671
  1010
      let val (_, ctxt') = prep_vars (map (fn (x, T) => (x, SOME T, NoSyn)) csts) ctxt
wenzelm@18671
  1011
      in (ctxt', []) end
wenzelm@12529
  1012
  | declare_ext_elem _ (ctxt, Assumes asms) = (ctxt, map #2 asms)
wenzelm@19585
  1013
  | declare_ext_elem _ (ctxt, Defines defs) = (ctxt, map (fn (_, (t, ps)) => [(t, ps)]) defs)
wenzelm@21441
  1014
  | declare_ext_elem _ (ctxt, Notes _) = (ctxt, []);
wenzelm@12529
  1015
wenzelm@18671
  1016
fun declare_elems prep_vars (ctxt, (((name, ps), Assumed _), elems)) =
ballarin@17000
  1017
    let val (ctxt', propps) =
ballarin@17000
  1018
      (case elems of
ballarin@17000
  1019
        Int es => foldl_map declare_int_elem (ctxt, es)
wenzelm@18671
  1020
      | Ext e => foldl_map (declare_ext_elem prep_vars) (ctxt, [e]))
wenzelm@18678
  1021
      handle ERROR msg => err_in_locale ctxt msg [(name, map fst ps)]
ballarin@17000
  1022
    in (ctxt', propps) end
ballarin@17000
  1023
  | declare_elems _ (ctxt, ((_, Derived _), elems)) = (ctxt, []);
wenzelm@12727
  1024
wenzelm@12839
  1025
in
wenzelm@12839
  1026
wenzelm@18671
  1027
fun declare_elemss prep_vars fixed_params raw_elemss ctxt =
wenzelm@12727
  1028
  let
ballarin@14215
  1029
    (* CB: fix of type bug of goal in target with context elements.
ballarin@14215
  1030
       Parameters new in context elements must receive types that are
ballarin@14215
  1031
       distinct from types of parameters in target (fixed_params).  *)
ballarin@14215
  1032
    val ctxt_with_fixed =
wenzelm@19900
  1033
      fold Variable.declare_term (map Free fixed_params) ctxt;
wenzelm@12727
  1034
    val int_elemss =
wenzelm@12727
  1035
      raw_elemss
wenzelm@19482
  1036
      |> map_filter (fn (id, Int es) => SOME (id, es) | _ => NONE)
ballarin@14215
  1037
      |> unify_elemss ctxt_with_fixed fixed_params;
wenzelm@12727
  1038
    val (_, raw_elemss') =
wenzelm@12727
  1039
      foldl_map (fn ((_, es) :: elemss, (id, Int _)) => (elemss, (id, Int es)) | x => x)
wenzelm@12727
  1040
        (int_elemss, raw_elemss);
wenzelm@18671
  1041
  in foldl_map (declare_elems prep_vars) (ctxt, raw_elemss') end;
wenzelm@12529
  1042
wenzelm@12839
  1043
end;
wenzelm@12529
  1044
wenzelm@12839
  1045
local
wenzelm@12839
  1046
wenzelm@12839
  1047
val norm_term = Envir.beta_norm oo Term.subst_atomic;
wenzelm@12839
  1048
wenzelm@16458
  1049
fun abstract_thm thy eq =
wenzelm@16458
  1050
  Thm.assume (Thm.cterm_of thy eq) |> Drule.gen_all |> Drule.abs_def;
wenzelm@12502
  1051
wenzelm@18190
  1052
fun bind_def ctxt (name, ps) eq (xs, env, ths) =
wenzelm@12839
  1053
  let
wenzelm@18831
  1054
    val ((y, T), b) = LocalDefs.abs_def eq;
wenzelm@13308
  1055
    val b' = norm_term env b;
wenzelm@16458
  1056
    val th = abstract_thm (ProofContext.theory_of ctxt) eq;
wenzelm@13308
  1057
    fun err msg = err_in_locale ctxt (msg ^ ": " ^ quote y) [(name, map fst ps)];
wenzelm@12839
  1058
  in
wenzelm@13308
  1059
    conditional (exists (equal y o #1) xs) (fn () =>
wenzelm@13308
  1060
      err "Attempt to define previously specified variable");
wenzelm@13308
  1061
    conditional (exists (fn (Free (y', _), _) => y = y' | _ => false) env) (fn () =>
wenzelm@13308
  1062
      err "Attempt to redefine variable");
wenzelm@16861
  1063
    (Term.add_frees b' xs, (Free (y, T), b') :: env, th :: ths)
wenzelm@12839
  1064
  end;
wenzelm@12575
  1065
ballarin@17000
  1066
ballarin@17000
  1067
(* CB: for finish_elems (Int and Ext),
ballarin@17000
  1068
   extracts specification, only of assumed elements *)
ballarin@15206
  1069
wenzelm@18190
  1070
fun eval_text _ _ _ (Fixes _) text = text
wenzelm@18190
  1071
  | eval_text _ _ _ (Constrains _) text = text
wenzelm@18190
  1072
  | eval_text _ (_, Assumed _) is_ext (Assumes asms)
wenzelm@18190
  1073
        (((exts, exts'), (ints, ints')), (xs, env, defs)) =
wenzelm@13394
  1074
      let
wenzelm@19482
  1075
        val ts = maps (map #1 o #2) asms;
wenzelm@13394
  1076
        val ts' = map (norm_term env) ts;
wenzelm@13394
  1077
        val spec' =
wenzelm@13394
  1078
          if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
wenzelm@13394
  1079
          else ((exts, exts'), (ints @ ts, ints' @ ts'));
wenzelm@16861
  1080
      in (spec', (fold Term.add_frees ts' xs, env, defs)) end
wenzelm@18190
  1081
  | eval_text _ (_, Derived _) _ (Assumes _) text = text
wenzelm@18190
  1082
  | eval_text ctxt (id, Assumed _) _ (Defines defs) (spec, binds) =
wenzelm@18190
  1083
      (spec, fold (bind_def ctxt id o #1 o #2) defs binds)
wenzelm@18190
  1084
  | eval_text _ (_, Derived _) _ (Defines _) text = text
wenzelm@18190
  1085
  | eval_text _ _ _ (Notes _) text = text;
wenzelm@13308
  1086
ballarin@17000
  1087
ballarin@17000
  1088
(* for finish_elems (Int),
ballarin@17000
  1089
   remove redundant elements of derived identifiers,
ballarin@17000
  1090
   turn assumptions and definitions into facts,
wenzelm@21483
  1091
   satisfy hypotheses of facts *)
ballarin@17000
  1092
ballarin@17096
  1093
fun finish_derived _ _ (Assumed _) (Fixes fixes) = SOME (Fixes fixes)
ballarin@17096
  1094
  | finish_derived _ _ (Assumed _) (Constrains csts) = SOME (Constrains csts)
ballarin@17096
  1095
  | finish_derived _ _ (Assumed _) (Assumes asms) = SOME (Assumes asms)
ballarin@17096
  1096
  | finish_derived _ _ (Assumed _) (Defines defs) = SOME (Defines defs)
ballarin@17096
  1097
ballarin@17000
  1098
  | finish_derived _ _ (Derived _) (Fixes _) = NONE
ballarin@17000
  1099
  | finish_derived _ _ (Derived _) (Constrains _) = NONE
wenzelm@21483
  1100
  | finish_derived sign satisfy (Derived _) (Assumes asms) = asms
ballarin@17096
  1101
      |> map (apsnd (map (fn (a, _) => ([Thm.assume (cterm_of sign a)], []))))
wenzelm@21441
  1102
      |> pair Thm.assumptionK |> Notes
wenzelm@21483
  1103
      |> Element.morph_ctxt satisfy |> SOME
wenzelm@21483
  1104
  | finish_derived sign satisfy (Derived _) (Defines defs) = defs
ballarin@17096
  1105
      |> map (apsnd (fn (d, _) => [([Thm.assume (cterm_of sign d)], [])]))
wenzelm@21441
  1106
      |> pair Thm.definitionK |> Notes
wenzelm@21483
  1107
      |> Element.morph_ctxt satisfy |> SOME
ballarin@17000
  1108
wenzelm@21483
  1109
  | finish_derived _ satisfy _ (Notes facts) = Notes facts
wenzelm@21483
  1110
      |> Element.morph_ctxt satisfy |> SOME;
ballarin@17000
  1111
ballarin@15206
  1112
(* CB: for finish_elems (Ext) *)
ballarin@15206
  1113
wenzelm@13308
  1114
fun closeup _ false elem = elem
wenzelm@13308
  1115
  | closeup ctxt true elem =
wenzelm@12839
  1116
      let
wenzelm@13308
  1117
        fun close_frees t =
wenzelm@19900
  1118
          let val frees = rev (filter_out (Variable.is_fixed ctxt o #1) (Term.add_frees t []))
wenzelm@13308
  1119
          in Term.list_all_free (frees, t) end;
wenzelm@13308
  1120
wenzelm@13308
  1121
        fun no_binds [] = []
wenzelm@18678
  1122
          | no_binds _ = error "Illegal term bindings in locale element";
wenzelm@13308
  1123
      in
wenzelm@13308
  1124
        (case elem of
wenzelm@13308
  1125
          Assumes asms => Assumes (asms |> map (fn (a, propps) =>
wenzelm@19585
  1126
            (a, map (fn (t, ps) => (close_frees t, no_binds ps)) propps)))
wenzelm@13308
  1127
        | Defines defs => Defines (defs |> map (fn (a, (t, ps)) =>
wenzelm@18831
  1128
            (a, (close_frees (#2 (LocalDefs.cert_def ctxt t)), no_binds ps))))
wenzelm@13308
  1129
        | e => e)
wenzelm@13308
  1130
      end;
wenzelm@12839
  1131
wenzelm@12502
  1132
wenzelm@12839
  1133
fun finish_ext_elem parms _ (Fixes fixes, _) = Fixes (map (fn (x, _, mx) =>
haftmann@17271
  1134
      (x, AList.lookup (op =) parms x, mx)) fixes)
wenzelm@18899
  1135
  | finish_ext_elem parms _ (Constrains _, _) = Constrains []
wenzelm@12839
  1136
  | finish_ext_elem _ close (Assumes asms, propp) =
wenzelm@12839
  1137
      close (Assumes (map #1 asms ~~ propp))
wenzelm@12839
  1138
  | finish_ext_elem _ close (Defines defs, propp) =
wenzelm@19585
  1139
      close (Defines (map #1 defs ~~ map (fn [(t, ps)] => (t, ps)) propp))
wenzelm@12839
  1140
  | finish_ext_elem _ _ (Notes facts, _) = Notes facts;
wenzelm@12839
  1141
ballarin@17000
  1142
ballarin@15206
  1143
(* CB: finish_parms introduces type info from parms to identifiers *)
skalberg@15531
  1144
(* CB: only needed for types that have been NONE so far???
ballarin@15206
  1145
   If so, which are these??? *)
ballarin@15206
  1146
ballarin@17000
  1147
fun finish_parms parms (((name, ps), mode), elems) =
haftmann@19932
  1148
  (((name, map (fn (x, _) => (x, AList.lookup (op = : string * string -> bool) parms x)) ps), mode), elems);
wenzelm@12839
  1149
ballarin@17000
  1150
fun finish_elems ctxt parms _ ((text, wits), ((id, Int e), _)) =
wenzelm@12839
  1151
      let
ballarin@17000
  1152
        val [(id' as (_, mode), es)] = unify_elemss ctxt parms [(id, e)];
ballarin@17000
  1153
        val wits' = case mode of Assumed _ => wits | Derived ths => wits @ ths;
wenzelm@18190
  1154
        val text' = fold (eval_text ctxt id' false) es text;
wenzelm@19482
  1155
        val es' = map_filter
wenzelm@21483
  1156
          (finish_derived (ProofContext.theory_of ctxt) (Element.satisfy_morphism wits') mode) es;
ballarin@17000
  1157
      in ((text', wits'), (id', map Int es')) end
ballarin@17000
  1158
  | finish_elems ctxt parms do_close ((text, wits), ((id, Ext e), [propp])) =
wenzelm@13308
  1159
      let
wenzelm@13308
  1160
        val e' = finish_ext_elem parms (closeup ctxt do_close) (e, propp);
wenzelm@18190
  1161
        val text' = eval_text ctxt id true e' text;
ballarin@17000
  1162
      in ((text', wits), (id, [Ext e'])) end
wenzelm@12839
  1163
wenzelm@12839
  1164
in
wenzelm@12510
  1165
ballarin@15206
  1166
(* CB: only called by prep_elemss *)
ballarin@15206
  1167
wenzelm@13375
  1168
fun finish_elemss ctxt parms do_close =
wenzelm@13375
  1169
  foldl_map (apsnd (finish_parms parms) o finish_elems ctxt parms do_close);
wenzelm@12839
  1170
wenzelm@12839
  1171
end;
wenzelm@12839
  1172
ballarin@16736
  1173
ballarin@19942
  1174
(* Remove duplicate Defines elements: temporary workaround to fix Afp/Category. *)
ballarin@19942
  1175
ballarin@19942
  1176
fun defs_ord (defs1, defs2) =
ballarin@19942
  1177
    list_ord (fn ((_, (d1, _)), (_, (d2, _))) =>
ballarin@19942
  1178
      Term.fast_term_ord (d1, d2)) (defs1, defs2);
ballarin@19942
  1179
structure Defstab =
ballarin@19942
  1180
    TableFun(type key = ((string * Attrib.src list) * (term * term list)) list
ballarin@19942
  1181
        val ord = defs_ord);
ballarin@19942
  1182
ballarin@19942
  1183
fun rem_dup_defs es ds =
ballarin@19942
  1184
    fold_map (fn e as (Defines defs) => (fn ds =>
ballarin@19942
  1185
                 if Defstab.defined ds defs
ballarin@19942
  1186
                 then (Defines [], ds)
ballarin@19942
  1187
                 else (e, Defstab.update (defs, ()) ds))
ballarin@19942
  1188
               | e => (fn ds => (e, ds))) es ds;
ballarin@19942
  1189
fun rem_dup_elemss (Int es) ds = apfst Int (rem_dup_defs es ds)
ballarin@19942
  1190
  | rem_dup_elemss (Ext e) ds = (Ext e, ds);
ballarin@19942
  1191
fun rem_dup_defines raw_elemss =
ballarin@19942
  1192
    fold_map (fn (id as (_, (Assumed _)), es) => (fn ds =>
ballarin@19942
  1193
                     apfst (pair id) (rem_dup_elemss es ds))
ballarin@19942
  1194
               | (id as (_, (Derived _)), es) => (fn ds =>
ballarin@19942
  1195
                     ((id, es), ds))) raw_elemss Defstab.empty |> #1;
ballarin@19942
  1196
ballarin@16736
  1197
(* CB: type inference and consistency checks for locales.
ballarin@16736
  1198
ballarin@16736
  1199
   Works by building a context (through declare_elemss), extracting the
ballarin@16736
  1200
   required information and adjusting the context elements (finish_elemss).
ballarin@16736
  1201
   Can also universally close free vars in assms and defs.  This is only
ballarin@17000
  1202
   needed for Ext elements and controlled by parameter do_close.
ballarin@17000
  1203
ballarin@17000
  1204
   Only elements of assumed identifiers are considered.
ballarin@16736
  1205
*)
ballarin@15127
  1206
wenzelm@18671
  1207
fun prep_elemss prep_vars prepp do_close context fixed_params raw_elemss raw_concl =
wenzelm@12529
  1208
  let
ballarin@15127
  1209
    (* CB: contexts computed in the course of this function are discarded.
ballarin@15127
  1210
       They are used for type inference and consistency checks only. *)
ballarin@15206
  1211
    (* CB: fixed_params are the parameters (with types) of the target locale,
ballarin@15206
  1212
       empty list if there is no target. *)
ballarin@14508
  1213
    (* CB: raw_elemss are list of pairs consisting of identifiers and
ballarin@14508
  1214
       context elements, the latter marked as internal or external. *)
ballarin@19942
  1215
    val raw_elemss = rem_dup_defines raw_elemss;
wenzelm@18671
  1216
    val (raw_ctxt, raw_proppss) = declare_elemss prep_vars fixed_params raw_elemss context;
ballarin@14508
  1217
    (* CB: raw_ctxt is context with additional fixed variables derived from
ballarin@14508
  1218
       the fixes elements in raw_elemss,
ballarin@14508
  1219
       raw_proppss contains assumptions and definitions from the
ballarin@15206
  1220
       external elements in raw_elemss. *)
haftmann@18550
  1221
    fun prep_prop raw_propp (raw_ctxt, raw_concl)  =
haftmann@18450
  1222
      let
haftmann@18450
  1223
        (* CB: add type information from fixed_params to context (declare_term) *)
haftmann@18450
  1224
        (* CB: process patterns (conclusion and external elements only) *)
haftmann@18450
  1225
        val (ctxt, all_propp) =
wenzelm@19900
  1226
          prepp (fold Variable.declare_term (map Free fixed_params) raw_ctxt, raw_concl @ raw_propp);
haftmann@18450
  1227
        (* CB: add type information from conclusion and external elements to context *)
wenzelm@19900
  1228
        val ctxt = fold Variable.declare_term (maps (map fst) all_propp) ctxt;
haftmann@18450
  1229
        (* CB: resolve schematic variables (patterns) in conclusion and external elements. *)
haftmann@18450
  1230
        val all_propp' = map2 (curry (op ~~))
haftmann@18450
  1231
          (#1 (#2 (ProofContext.bind_propp_schematic_i (ctxt, all_propp)))) (map (map snd) all_propp);
wenzelm@19018
  1232
        val (concl, propp) = chop (length raw_concl) all_propp';
haftmann@18550
  1233
      in (propp, (ctxt, concl)) end
ballarin@15206
  1234
haftmann@18550
  1235
    val (proppss, (ctxt, concl)) =
haftmann@18550
  1236
      (fold_burrow o fold_burrow) prep_prop raw_proppss (raw_ctxt, raw_concl);
wenzelm@12502
  1237
ballarin@15206
  1238
    (* CB: obtain all parameters from identifier part of raw_elemss *)
ballarin@15206
  1239
    val xs = map #1 (params_of' raw_elemss);
wenzelm@12727
  1240
    val typing = unify_frozen ctxt 0
wenzelm@19900
  1241
      (map (Variable.default_type raw_ctxt) xs)
wenzelm@19900
  1242
      (map (Variable.default_type ctxt) xs);
wenzelm@12529
  1243
    val parms = param_types (xs ~~ typing);
ballarin@14508
  1244
    (* CB: parms are the parameters from raw_elemss, with correct typing. *)
wenzelm@12273
  1245
ballarin@14508
  1246
    (* CB: extract information from assumes and defines elements
ballarin@16169
  1247
       (fixes, constrains and notes in raw_elemss don't have an effect on
ballarin@16169
  1248
       text and elemss), compute final form of context elements. *)
ballarin@17000
  1249
    val ((text, _), elemss) = finish_elemss ctxt parms do_close
ballarin@17000
  1250
      ((((([], []), ([], [])), ([], [], [])), []), raw_elemss ~~ proppss);
ballarin@14508
  1251
    (* CB: text has the following structure:
ballarin@14508
  1252
           (((exts, exts'), (ints, ints')), (xs, env, defs))
ballarin@14508
  1253
       where
ballarin@14508
  1254
         exts: external assumptions (terms in external assumes elements)
ballarin@14508
  1255
         exts': dito, normalised wrt. env
ballarin@14508
  1256
         ints: internal assumptions (terms in internal assumes elements)
ballarin@14508
  1257
         ints': dito, normalised wrt. env
ballarin@14508
  1258
         xs: the free variables in exts' and ints' and rhss of definitions,
ballarin@14508
  1259
           this includes parameters except defined parameters
ballarin@14508
  1260
         env: list of term pairs encoding substitutions, where the first term
ballarin@14508
  1261
           is a free variable; substitutions represent defines elements and
ballarin@14508
  1262
           the rhs is normalised wrt. the previous env
ballarin@14508
  1263
         defs: theorems representing the substitutions from defines elements
ballarin@14508
  1264
           (thms are normalised wrt. env).
ballarin@14508
  1265
       elemss is an updated version of raw_elemss:
ballarin@16169
  1266
         - type info added to Fixes and modified in Constrains
ballarin@14508
  1267
         - axiom and definition statement replaced by corresponding one
ballarin@14508
  1268
           from proppss in Assumes and Defines
ballarin@14508
  1269
         - Facts unchanged
ballarin@14508
  1270
       *)
wenzelm@13308
  1271
  in ((parms, elemss, concl), text) end;
wenzelm@12502
  1272
wenzelm@12502
  1273
in
wenzelm@12502
  1274
wenzelm@18671
  1275
fun read_elemss x = prep_elemss ProofContext.read_vars ProofContext.read_propp_schematic x;
wenzelm@18671
  1276
fun cert_elemss x = prep_elemss ProofContext.cert_vars ProofContext.cert_propp_schematic x;
wenzelm@12529
  1277
wenzelm@12529
  1278
end;
wenzelm@12529
  1279
wenzelm@12529
  1280
wenzelm@15703
  1281
(* facts and attributes *)
wenzelm@12529
  1282
wenzelm@12529
  1283
local
wenzelm@12529
  1284
wenzelm@20965
  1285
fun check_name name =
wenzelm@18678
  1286
  if NameSpace.is_qualified name then error ("Illegal qualified name: " ^ quote name)
wenzelm@15703
  1287
  else name;
wenzelm@12529
  1288
wenzelm@20965
  1289
fun prep_facts _ _ _ ctxt (Int elem) =
wenzelm@21483
  1290
      Element.morph_ctxt (Morphism.transfer (ProofContext.theory_of ctxt)) elem
wenzelm@20965
  1291
  | prep_facts prep_name get intern ctxt (Ext elem) = elem |> Element.map_ctxt
wenzelm@15703
  1292
     {var = I, typ = I, term = I,
wenzelm@18678
  1293
      name = prep_name,
wenzelm@15703
  1294
      fact = get ctxt,
wenzelm@16458
  1295
      attrib = Args.assignable o intern (ProofContext.theory_of ctxt)};
wenzelm@12529
  1296
wenzelm@12529
  1297
in
wenzelm@12529
  1298
wenzelm@20965
  1299
fun read_facts x = prep_facts check_name ProofContext.get_thms Attrib.intern_src x;
wenzelm@20965
  1300
fun cert_facts x = prep_facts I (K I) (K I) x;
wenzelm@12529
  1301
wenzelm@12529
  1302
end;
wenzelm@12529
  1303
wenzelm@12529
  1304
ballarin@19931
  1305
(* Get the specification of a locale *)
ballarin@18795
  1306
wenzelm@19780
  1307
(*The global specification is made from the parameters and global
wenzelm@19780
  1308
  assumptions, the local specification from the parameters and the
wenzelm@19780
  1309
  local assumptions.*)
ballarin@18795
  1310
ballarin@18795
  1311
local
ballarin@18795
  1312
ballarin@18795
  1313
fun gen_asms_of get thy name =
ballarin@18795
  1314
  let
ballarin@18795
  1315
    val ctxt = ProofContext.init thy;
ballarin@18795
  1316
    val (_, raw_elemss) = flatten (ctxt, I) (([], Symtab.empty), Expr (Locale name));
ballarin@18795
  1317
    val ((_, elemss, _), _) = read_elemss false ctxt [] raw_elemss [];
ballarin@18795
  1318
  in
ballarin@18890
  1319
    elemss |> get
wenzelm@19780
  1320
      |> maps (fn (_, es) => map (fn Int e => e) es)
wenzelm@19780
  1321
      |> maps (fn Assumes asms => asms | _ => [])
ballarin@18795
  1322
      |> map (apsnd (map fst))
ballarin@18795
  1323
  end;
ballarin@18795
  1324
ballarin@18795
  1325
in
ballarin@18795
  1326
ballarin@18795
  1327
fun parameters_of thy name =
ballarin@19278
  1328
  the_locale thy name |> #params;
ballarin@18795
  1329
ballarin@19276
  1330
fun parameters_of_expr thy expr =
ballarin@19276
  1331
  let
ballarin@19276
  1332
    val ctxt = ProofContext.init thy;
ballarin@19783
  1333
    val pts = params_of_expr ctxt [] (intern_expr thy expr)
ballarin@19783
  1334
        ([], Symtab.empty, Symtab.empty);
ballarin@19783
  1335
    val raw_params_elemss = make_raw_params_elemss pts;
ballarin@19276
  1336
    val ((_, syn), raw_elemss) = flatten (ctxt, intern_expr thy)
ballarin@19276
  1337
        (([], Symtab.empty), Expr expr);
ballarin@19783
  1338
    val ((parms, _, _), _) =
ballarin@19783
  1339
        read_elemss false ctxt [] (raw_params_elemss @ raw_elemss) [];
ballarin@19276
  1340
  in map (fn p as (n, _) => (p, Symtab.lookup syn n |> the)) parms end;
ballarin@19276
  1341
ballarin@18795
  1342
fun local_asms_of thy name =
ballarin@18890
  1343
  gen_asms_of (single o Library.last_elem) thy name;
ballarin@18795
  1344
ballarin@18795
  1345
fun global_asms_of thy name =
ballarin@18890
  1346
  gen_asms_of I thy name;
ballarin@18795
  1347
wenzelm@19780
  1348
end;
ballarin@18795
  1349
ballarin@18795
  1350
wenzelm@12546
  1351
(* full context statements: import + elements + conclusion *)
wenzelm@12529
  1352
wenzelm@12529
  1353
local
wenzelm@12529
  1354
wenzelm@12529
  1355
fun prep_context_statement prep_expr prep_elemss prep_facts
ballarin@15206
  1356
    do_close fixed_params import elements raw_concl context =
wenzelm@12529
  1357
  let
wenzelm@16458
  1358
    val thy = ProofContext.theory_of context;
wenzelm@13375
  1359
ballarin@19783
  1360
    val (import_params, import_tenv, import_syn) =
ballarin@19783
  1361
      params_of_expr context fixed_params (prep_expr thy import)
ballarin@19783
  1362
        ([], Symtab.empty, Symtab.empty);
ballarin@19783
  1363
    val includes = map_filter (fn Expr e => SOME e | Elem _ => NONE) elements;
ballarin@19783
  1364
    val (incl_params, incl_tenv, incl_syn) = fold (params_of_expr context fixed_params)
ballarin@19783
  1365
      (map (prep_expr thy) includes) (import_params, import_tenv, import_syn);
ballarin@19783
  1366
ballarin@19783
  1367
    val ((import_ids, _), raw_import_elemss) =
wenzelm@16458
  1368
      flatten (context, prep_expr thy) (([], Symtab.empty), Expr import);
ballarin@14215
  1369
    (* CB: normalise "includes" among elements *)
wenzelm@16458
  1370
    val ((ids, syn), raw_elemsss) = foldl_map (flatten (context, prep_expr thy))
ballarin@19783
  1371
      ((import_ids, incl_syn), elements);
ballarin@15696
  1372
wenzelm@19482
  1373
    val raw_elemss = flat raw_elemsss;
ballarin@14508
  1374
    (* CB: raw_import_elemss @ raw_elemss is the normalised list of
ballarin@14508
  1375
       context elements obtained from import and elements. *)
ballarin@19783
  1376
    (* Now additional elements for parameters are inserted. *)
ballarin@19783
  1377
    val import_params_ids = make_params_ids import_params;
ballarin@19783
  1378
    val incl_params_ids =
ballarin@19783
  1379
        make_params_ids (incl_params \\ import_params);
ballarin@19783
  1380
    val raw_import_params_elemss =
ballarin@19783
  1381
        make_raw_params_elemss (import_params, incl_tenv, incl_syn);
ballarin@19783
  1382
    val raw_incl_params_elemss =
ballarin@19783
  1383
        make_raw_params_elemss (incl_params \\ import_params, incl_tenv, incl_syn);
wenzelm@13375
  1384
    val ((parms, all_elemss, concl), (spec, (_, _, defs))) = prep_elemss do_close
ballarin@19783
  1385
      context fixed_params
ballarin@19783
  1386
      (raw_import_params_elemss @ raw_import_elemss @ raw_incl_params_elemss @ raw_elemss) raw_concl;
ballarin@19783
  1387
ballarin@15696
  1388
    (* replace extended ids (for axioms) by ids *)
ballarin@19783
  1389
    val (import_ids', incl_ids) = chop (length import_ids) ids;
ballarin@20035
  1390
    val all_ids = import_params_ids @ import_ids' @ incl_params_ids @ incl_ids;
ballarin@17000
  1391
    val all_elemss' = map (fn (((_, ps), _), (((n, ps'), mode), elems)) =>
haftmann@17485
  1392
        (((n, map (fn p => (p, (the o AList.lookup (op =) ps') p)) ps), mode), elems))
ballarin@20035
  1393
      (all_ids ~~ all_elemss);
ballarin@19783
  1394
    (* CB: all_elemss and parms contain the correct parameter types *)
ballarin@15696
  1395
ballarin@19783
  1396
    val (ps, qs) = chop (length raw_import_params_elemss + length raw_import_elemss) all_elemss';
ballarin@15206
  1397
    val (import_ctxt, (import_elemss, _)) =
ballarin@19931
  1398
      activate_facts false prep_facts (context, ps);
ballarin@14215
  1399
ballarin@15206
  1400
    val (ctxt, (elemss, _)) =
wenzelm@21441
  1401
      activate_facts false prep_facts (ProofContext.set_stmt true import_ctxt, qs);
wenzelm@12834
  1402
  in
ballarin@19783
  1403
    ((((import_ctxt, import_elemss), (ctxt, elemss, syn)),
ballarin@19991
  1404
      (parms, spec, defs)), concl)
wenzelm@12834
  1405
  end;
wenzelm@12529
  1406
wenzelm@18806
  1407
fun prep_statement prep_locale prep_ctxt raw_locale elems concl ctxt =
wenzelm@12529
  1408
  let
wenzelm@12529
  1409
    val thy = ProofContext.theory_of ctxt;
wenzelm@16458
  1410
    val locale = Option.map (prep_locale thy) raw_locale;
ballarin@19931
  1411
    val (fixed_params, import) =
wenzelm@18806
  1412
      (case locale of
ballarin@19931
  1413
        NONE => ([], empty)
skalberg@15531
  1414
      | SOME name =>
ballarin@19931
  1415
          let val {params = ps, ...} = the_locale thy name
ballarin@19931
  1416
          in (map fst ps, Locale name) end);
ballarin@19991
  1417
    val ((((locale_ctxt, _), (elems_ctxt, _, _)), _), concl') =
ballarin@15206
  1418
      prep_ctxt false fixed_params import elems concl ctxt;
ballarin@19991
  1419
  in (locale, locale_ctxt, elems_ctxt, concl') end;
wenzelm@13399
  1420
wenzelm@19780
  1421
fun prep_expr prep import body ctxt =
wenzelm@19780
  1422
  let
wenzelm@19780
  1423
    val (((_, import_elemss), (ctxt', elemss, _)), _) = prep import body ctxt;
wenzelm@19780
  1424
    val all_elems = maps snd (import_elemss @ elemss);
wenzelm@19780
  1425
  in (all_elems, ctxt') end;
wenzelm@19780
  1426
wenzelm@12529
  1427
in
wenzelm@12529
  1428
wenzelm@18806
  1429
val read_ctxt = prep_context_statement intern_expr read_elemss read_facts;
wenzelm@18806
  1430
val cert_ctxt = prep_context_statement (K I) cert_elemss cert_facts;
ballarin@14215
  1431
wenzelm@18806
  1432
fun read_context import body ctxt = #1 (read_ctxt true [] import (map Elem body) [] ctxt);
wenzelm@18806
  1433
fun cert_context import body ctxt = #1 (cert_ctxt true [] import (map Elem body) [] ctxt);
wenzelm@12502
  1434
wenzelm@19780
  1435
val read_expr = prep_expr read_context;
wenzelm@19780
  1436
val cert_expr = prep_expr cert_context;
wenzelm@19780
  1437
wenzelm@21035
  1438
fun read_context_statement loc = prep_statement intern read_ctxt loc;
wenzelm@21035
  1439
fun read_context_statement_i loc = prep_statement (K I) read_ctxt loc;
wenzelm@21035
  1440
fun cert_context_statement loc = prep_statement (K I) cert_ctxt loc;
wenzelm@18806
  1441
wenzelm@12502
  1442
end;
wenzelm@11896
  1443
wenzelm@11896
  1444
wenzelm@13336
  1445
(* print locale *)
wenzelm@12070
  1446
ballarin@17228
  1447
fun print_locale thy show_facts import body =
wenzelm@20872
  1448
  let val (all_elems, ctxt) = read_expr import body (ProofContext.init thy) in
wenzelm@18137
  1449
    Pretty.big_list "locale elements:" (all_elems
ballarin@17316
  1450
      |> (if show_facts then I else filter (fn Notes _ => false | _ => true))
wenzelm@20872
  1451
      |> map (Pretty.chunks o Element.pretty_ctxt ctxt))
wenzelm@13336
  1452
    |> Pretty.writeln
wenzelm@12277
  1453
  end;
wenzelm@12070
  1454
wenzelm@12070
  1455
wenzelm@12706
  1456
wenzelm@16144
  1457
(** store results **)
wenzelm@12702
  1458
wenzelm@19018
  1459
(* naming of interpreted theorems *)
ballarin@15696
  1460
wenzelm@19018
  1461
fun global_note_prefix_i kind prfx args thy =
wenzelm@16144
  1462
  thy
wenzelm@19061
  1463
  |> Theory.qualified_names
wenzelm@19061
  1464
  |> Theory.sticky_prefix prfx
wenzelm@16144
  1465
  |> PureThy.note_thmss_i kind args
haftmann@18377
  1466
  ||> Theory.restore_naming thy;
ballarin@15696
  1467
wenzelm@21441
  1468
fun local_note_prefix_i kind prfx args ctxt =
wenzelm@16144
  1469
  ctxt
wenzelm@19061
  1470
  |> ProofContext.qualified_names
wenzelm@19061
  1471
  |> ProofContext.sticky_prefix prfx
wenzelm@21441
  1472
  |> ProofContext.note_thmss_i kind args
wenzelm@19780
  1473
  ||> ProofContext.restore_naming ctxt;
wenzelm@16144
  1474
ballarin@15696
  1475
wenzelm@19780
  1476
(* collect witnesses for global registration;
ballarin@17138
  1477
   requires parameters and flattened list of (assumed!) identifiers
ballarin@17138
  1478
   instead of recomputing it from the target *)
ballarin@17138
  1479
ballarin@17138
  1480
fun collect_global_witnesses thy parms ids vts = let
ballarin@17138
  1481
    val ts = map Logic.unvarify vts;
ballarin@17138
  1482
    val (parms, parmTs) = split_list parms;
wenzelm@19810
  1483
    val parmvTs = map Logic.varifyT parmTs;
ballarin@17138
  1484
    val vtinst = fold (Sign.typ_match thy) (parmvTs ~~ map Term.fastype_of ts) Vartab.empty;
ballarin@17138
  1485
    val tinst = Vartab.dest vtinst |> map (fn ((x, 0), (_, T)) => (x, T))
wenzelm@18137
  1486
        |> Symtab.make;
ballarin@17138
  1487
    (* replace parameter names in ids by instantiations *)
ballarin@17138
  1488
    val vinst = Symtab.make (parms ~~ vts);
wenzelm@17412
  1489
    fun vinst_names ps = map (the o Symtab.lookup vinst) ps;
ballarin@17138
  1490
    val inst = Symtab.make (parms ~~ ts);
ballarin@17138
  1491
    val ids' = map (apsnd vinst_names) ids;
wenzelm@19482
  1492
    val wits = maps (snd o the o get_global_registration thy) ids';
wenzelm@18137
  1493
  in ((tinst, inst), wits) end;
ballarin@17138
  1494
ballarin@17138
  1495
ballarin@15696
  1496
(* store instantiations of args for all registered interpretations
ballarin@15696
  1497
   of the theory *)
ballarin@15696
  1498
wenzelm@21441
  1499
fun note_thmss_registrations target (kind, args) thy =
ballarin@15596
  1500
  let
ballarin@19278
  1501
    val parms = the_locale thy target |> #params |> map fst;
wenzelm@16458
  1502
    val ids = flatten (ProofContext.init thy, intern_expr thy)
ballarin@17033
  1503
      (([], Symtab.empty), Expr (Locale target)) |> fst |> fst
wenzelm@19482
  1504
      |> map_filter (fn (id, (_, Assumed _)) => SOME id | _ => NONE)
ballarin@15696
  1505
ballarin@15696
  1506
    val regs = get_global_registrations thy target;
ballarin@15696
  1507
ballarin@15696
  1508
    (* add args to thy for all registrations *)
ballarin@15596
  1509
wenzelm@18190
  1510
    fun activate (vts, ((prfx, atts2), _)) thy =
ballarin@15696
  1511
      let
wenzelm@18137
  1512
        val (insts, prems) = collect_global_witnesses thy parms ids vts;
wenzelm@20911
  1513
        val attrib = Attrib.attribute_i thy;
wenzelm@21483
  1514
        val inst_atts = Args.morph_values (Element.inst_morphism thy insts);
wenzelm@20911
  1515
        val inst_thm =
wenzelm@20911
  1516
          Drule.standard o Element.satisfy_thm prems o Element.inst_thm thy insts;
wenzelm@20911
  1517
        val args' = args |> map (fn ((name, atts), bs) =>
wenzelm@20911
  1518
            ((name, map (attrib o inst_atts) atts),
wenzelm@20911
  1519
              bs |> map (fn (ths, more_atts) =>
wenzelm@20911
  1520
                (map inst_thm ths, map attrib (map inst_atts more_atts @ atts2)))));
wenzelm@19018
  1521
      in global_note_prefix_i kind prfx args' thy |> snd end;
wenzelm@18190
  1522
  in fold activate regs thy end;
ballarin@15596
  1523
ballarin@15596
  1524
wenzelm@19662
  1525
(* term syntax *)
wenzelm@19018
  1526
wenzelm@19662
  1527
fun add_term_syntax loc syn =
wenzelm@20366
  1528
  syn #> ProofContext.theory (change_locale loc
ballarin@19931
  1529
    (fn (axiom, import, elems, params, lparams, term_syntax, regs, intros) =>
ballarin@19931
  1530
      (axiom, import, elems, params, lparams, (syn, stamp ()) :: term_syntax, regs, intros)));
wenzelm@19018
  1531
wenzelm@19662
  1532
fun init_term_syntax loc ctxt =
wenzelm@19662
  1533
  fold_rev (fn (f, _) => fn ctxt' => f ctxt')
wenzelm@19662
  1534
    (#term_syntax (the_locale (ProofContext.theory_of ctxt) loc)) ctxt;
wenzelm@19018
  1535
wenzelm@19018
  1536
fun init loc =
wenzelm@19018
  1537
  ProofContext.init
wenzelm@19662
  1538
  #> init_term_syntax loc
wenzelm@19018
  1539
  #> (#2 o cert_context_statement (SOME loc) [] []);
wenzelm@19018
  1540
wenzelm@19018
  1541
wenzelm@20911
  1542
(* locale results *)
wenzelm@12958
  1543
wenzelm@21441
  1544
fun add_thmss loc kind args ctxt =
wenzelm@12706
  1545
  let
wenzelm@18806
  1546
    val (ctxt', ([(_, [Notes args'])], facts)) =
wenzelm@21441
  1547
      activate_facts true cert_facts
wenzelm@21441
  1548
        (ctxt, [((("", []), Assumed []), [Ext (Notes (kind, args))])]);
wenzelm@20911
  1549
    val ctxt'' = ctxt' |> ProofContext.theory
wenzelm@20911
  1550
      (change_locale loc
wenzelm@20911
  1551
        (fn (axiom, import, elems, params, lparams, term_syntax, regs, intros) =>
wenzelm@20911
  1552
          (axiom, import, elems @ [(Notes args', stamp ())],
wenzelm@20911
  1553
            params, lparams, term_syntax, regs, intros))
wenzelm@21441
  1554
      #> note_thmss_registrations loc args');
wenzelm@20911
  1555
  in (facts, ctxt'') end;
wenzelm@15703
  1556
wenzelm@11896
  1557
wenzelm@18137
  1558
wenzelm@18137
  1559
(** define locales **)
wenzelm@18137
  1560
wenzelm@13336
  1561
(* predicate text *)
ballarin@15596
  1562
(* CB: generate locale predicates and delta predicates *)
wenzelm@13336
  1563
wenzelm@13375
  1564
local
wenzelm@13375
  1565
ballarin@15206
  1566
(* introN: name of theorems for introduction rules of locale and
ballarin@15206
  1567
     delta predicates;
ballarin@15206
  1568
   axiomsN: name of theorem set with destruct rules for locale predicates,
ballarin@15206
  1569
     also name suffix of delta predicates. *)
ballarin@15206
  1570
wenzelm@13375
  1571
val introN = "intro";
ballarin@15206
  1572
val axiomsN = "axioms";
wenzelm@13375
  1573
wenzelm@16458
  1574
fun atomize_spec thy ts =
wenzelm@13375
  1575
  let
wenzelm@18502
  1576
    val t = Logic.mk_conjunction_list ts;
wenzelm@16458
  1577
    val body = ObjectLogic.atomize_term thy t;
wenzelm@13375
  1578
    val bodyT = Term.fastype_of body;
wenzelm@13375
  1579
  in
wenzelm@16458
  1580
    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
wenzelm@18782
  1581
    else (body, bodyT, ObjectLogic.atomize_cterm (Thm.cterm_of thy t))
wenzelm@13375
  1582
  end;
wenzelm@13375
  1583
wenzelm@13394
  1584
fun aprop_tr' n c = (c, fn args =>
wenzelm@13394
  1585
  if length args = n then Syntax.const "_aprop" $ Term.list_comb (Syntax.free c, args)
wenzelm@13394
  1586
  else raise Match);
wenzelm@13336
  1587
ballarin@15104
  1588
(* CB: define one predicate including its intro rule and axioms
ballarin@15104
  1589
   - bname: predicate name
ballarin@15104
  1590
   - parms: locale parameters
ballarin@15104
  1591
   - defs: thms representing substitutions from defines elements
ballarin@15104
  1592
   - ts: terms representing locale assumptions (not normalised wrt. defs)
ballarin@15104
  1593
   - norm_ts: terms representing locale assumptions (normalised wrt. defs)
ballarin@15104
  1594
   - thy: the theory
ballarin@15104
  1595
*)
ballarin@15104
  1596
wenzelm@13420
  1597
fun def_pred bname parms defs ts norm_ts thy =
wenzelm@13375
  1598
  let
wenzelm@16458
  1599
    val name = Sign.full_name thy bname;
wenzelm@13375
  1600
wenzelm@16458
  1601
    val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
wenzelm@13394
  1602
    val env = Term.add_term_free_names (body, []);
wenzelm@20664
  1603
    val xs = filter (member (op =) env o #1) parms;
wenzelm@13394
  1604
    val Ts = map #2 xs;
skalberg@15574
  1605
    val extraTs = (Term.term_tfrees body \\ foldr Term.add_typ_tfrees [] Ts)
wenzelm@13394
  1606
      |> Library.sort_wrt #1 |> map TFree;
wenzelm@13399
  1607
    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
wenzelm@13336
  1608
wenzelm@13394
  1609
    val args = map Logic.mk_type extraTs @ map Free xs;
wenzelm@13394
  1610
    val head = Term.list_comb (Const (name, predT), args);
wenzelm@18123
  1611
    val statement = ObjectLogic.ensure_propT thy head;
wenzelm@13375
  1612
haftmann@18358
  1613
    val ([pred_def], defs_thy) =
wenzelm@13375
  1614
      thy
wenzelm@13394
  1615
      |> (if bodyT <> propT then I else
wenzelm@13394
  1616
        Theory.add_trfuns ([], [], map (aprop_tr' (length args)) (NameSpace.accesses' name), []))
wenzelm@18671
  1617
      |> Theory.add_consts_i [(bname, predT, NoSyn)]
wenzelm@13375
  1618
      |> PureThy.add_defs_i false [((Thm.def_name bname, Logic.mk_equals (head, body)), [])];
wenzelm@20059
  1619
    val defs_ctxt = ProofContext.init defs_thy |> Variable.declare_term head;
wenzelm@13394
  1620
wenzelm@16458
  1621
    val cert = Thm.cterm_of defs_thy;
wenzelm@13375
  1622
wenzelm@20059
  1623
    val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
wenzelm@13375
  1624
      Tactic.rewrite_goals_tac [pred_def] THEN
wenzelm@13375
  1625
      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
wenzelm@20059
  1626
      Tactic.compose_tac (false, Conjunction.intr_list (map (Thm.assume o cert) norm_ts), 0) 1);
wenzelm@13375
  1627
wenzelm@13375
  1628
    val conjuncts =
wenzelm@19423
  1629
      (Drule.equal_elim_rule2 OF [body_eq,
haftmann@17257
  1630
        Tactic.rewrite_rule [pred_def] (Thm.assume (cert statement))])
wenzelm@19423
  1631
      |> Conjunction.elim_precise [length ts] |> hd;
haftmann@17257
  1632
    val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
wenzelm@20059
  1633
      Element.prove_witness defs_ctxt t
wenzelm@18123
  1634
       (Tactic.rewrite_goals_tac defs THEN
wenzelm@13375
  1635
        Tactic.compose_tac (false, ax, 0) 1));
haftmann@18550
  1636
  in ((statement, intro, axioms), defs_thy) end;
wenzelm@13375
  1637
haftmann@18550
  1638
fun assumes_to_notes (Assumes asms) axms =
wenzelm@21441
  1639
      fold_map (fn (a, spec) => fn axs =>
wenzelm@21441
  1640
          let val (ps, qs) = chop (length spec) axs
wenzelm@21441
  1641
          in ((a, [(ps, [])]), qs) end) asms axms
wenzelm@21441
  1642
      |> apfst (curry Notes Thm.assumptionK)
haftmann@18550
  1643
  | assumes_to_notes e axms = (e, axms);
wenzelm@13394
  1644
ballarin@19931
  1645
(* CB: the following two change only "new" elems, these have identifier ("", _). *)
ballarin@19931
  1646
ballarin@19931
  1647
(* turn Assumes into Notes elements *)
ballarin@15206
  1648
ballarin@19931
  1649
fun change_assumes_elemss axioms elemss =
haftmann@18550
  1650
  let
wenzelm@21483
  1651
    val satisfy = Element.morph_ctxt (Element.satisfy_morphism axioms);
ballarin@19931
  1652
    fun change (id as ("", _), es) =
wenzelm@21483
  1653
          fold_map assumes_to_notes (map satisfy es)
haftmann@18550
  1654
          #-> (fn es' => pair (id, es'))
haftmann@18550
  1655
      | change e = pair e;
haftmann@18550
  1656
  in
wenzelm@19780
  1657
    fst (fold_map change elemss (map Element.conclude_witness axioms))
haftmann@18550
  1658
  end;
wenzelm@13394
  1659
ballarin@19931
  1660
(* adjust hyps of Notes elements *)
ballarin@19931
  1661
ballarin@19931
  1662
fun change_elemss_hyps axioms elemss =
ballarin@19931
  1663
  let
wenzelm@21483
  1664
    val satisfy = Element.morph_ctxt (Element.satisfy_morphism axioms);
wenzelm@21483
  1665
    fun change (id as ("", _), es) = (id, map (fn e as Notes _ => satisfy e | e => e) es)
ballarin@19931
  1666
      | change e = e;
ballarin@19931
  1667
  in map change elemss end;
ballarin@19931
  1668
wenzelm@13394
  1669
in
wenzelm@13375
  1670
ballarin@15104
  1671
(* CB: main predicate definition function *)
ballarin@15104
  1672
wenzelm@13394
  1673
fun define_preds bname (parms, ((exts, exts'), (ints, ints')), defs) elemss thy =
wenzelm@13394
  1674
  let
ballarin@19931
  1675
    val ((elemss', more_ts), a_elem, a_intro, thy') =
ballarin@19931
  1676
      if null exts then ((elemss, []), [], [], thy)
wenzelm@13394
  1677
      else
wenzelm@13394
  1678
        let
skalberg@15531
  1679
          val aname = if null ints then bname else bname ^ "_" ^ axiomsN;
haftmann@18550
  1680
          val ((statement, intro, axioms), def_thy) =
wenzelm@13394
  1681
            thy |> def_pred aname parms defs exts exts';
ballarin@19931
  1682
          val elemss' = change_assumes_elemss axioms elemss;
ballarin@19931
  1683
          val def_thy' = def_thy
wenzelm@21441
  1684
            |> PureThy.note_thmss_qualified Thm.definitionK
wenzelm@21441
  1685
              aname [((introN, []), [([intro], [])])]
wenzelm@20366
  1686
            |> snd;
ballarin@19931
  1687
          val a_elem = [(("", []), [Assumes [((bname ^ "_" ^ axiomsN, []), [(statement, [])])]])];
ballarin@19931
  1688
        in ((elemss', [statement]), a_elem, [intro], def_thy') end;
ballarin@19931
  1689
    val (predicate, stmt', elemss'', b_intro, thy'') =
ballarin@19931
  1690
      if null ints then (([], []), more_ts, elemss' @ a_elem, [], thy')
wenzelm@13394
  1691
      else
wenzelm@13394
  1692
        let
haftmann@18550
  1693
          val ((statement, intro, axioms), def_thy) =
wenzelm@13394
  1694
            thy' |> def_pred bname parms defs (ints @ more_ts) (ints' @ more_ts);
wenzelm@16458
  1695
          val cstatement = Thm.cterm_of def_thy statement;
ballarin@19931
  1696
          val elemss'' = change_elemss_hyps axioms elemss';
ballarin@19931
  1697
          val def_thy' =
haftmann@18377
  1698
          def_thy
wenzelm@21441
  1699
          |> PureThy.note_thmss_qualified Thm.definitionK bname
wenzelm@21441
  1700
              [((introN, []), [([intro], [])]),
wenzelm@19780
  1701
                ((axiomsN, []), [(map (Drule.standard o Element.conclude_witness) axioms, [])])]
ballarin@19931
  1702
          |> snd;
ballarin@19931
  1703
          val b_elem = [(("", []),
ballarin@19931
  1704
               [Assumes [((bname ^ "_" ^ axiomsN, []), [(statement, [])])]])];
ballarin@19931
  1705
        in (([cstatement], axioms), [statement], elemss'' @ b_elem, [intro], def_thy') end;
ballarin@19931
  1706
  in (((elemss'', predicate, stmt'), (a_intro, b_intro)), thy'') end;
wenzelm@13375
  1707
wenzelm@13375
  1708
end;
wenzelm@13336
  1709
wenzelm@13336
  1710
wenzelm@13297
  1711
(* add_locale(_i) *)
wenzelm@13297
  1712
wenzelm@13297
  1713
local
wenzelm@13297
  1714
ballarin@19931
  1715
(* turn Defines into Notes elements, accumulate definition terms *)
ballarin@19931
  1716
ballarin@19942
  1717
fun defines_to_notes is_ext thy (Defines defs) defns =
ballarin@19942
  1718
    let
ballarin@19942
  1719
      val defs' = map (fn (_, (def, _)) => (("", []), (def, []))) defs
ballarin@19942
  1720
      val notes = map (fn (a, (def, _)) =>
ballarin@19942
  1721
        (a, [([assume (cterm_of thy def)], [])])) defs
wenzelm@21441
  1722
    in
wenzelm@21441
  1723
      (if is_ext then SOME (Notes (Thm.definitionK, notes)) else NONE, defns @ [Defines defs'])
wenzelm@21441
  1724
    end
ballarin@19942
  1725
  | defines_to_notes _ _ e defns = (SOME e, defns);
ballarin@19931
  1726
ballarin@19942
  1727
fun change_defines_elemss thy elemss defns =
ballarin@19931
  1728
  let
ballarin@19942
  1729
    fun change (id as (n, _), es) defns =
ballarin@19931
  1730
        let
ballarin@19942
  1731
          val (es', defns') = fold_map (defines_to_notes (n="") thy) es defns
ballarin@19942
  1732
        in ((id, map_filter I es'), defns') end
ballarin@19942
  1733
  in fold_map change elemss defns end;
ballarin@19931
  1734
wenzelm@18343
  1735
fun gen_add_locale prep_ctxt prep_expr
wenzelm@18343
  1736
    do_predicate bname raw_import raw_body thy =
wenzelm@13297
  1737
  let
wenzelm@16458
  1738
    val name = Sign.full_name thy bname;
wenzelm@18343
  1739
    val _ = conditional (is_some (get_locale thy name)) (fn () =>
wenzelm@13297
  1740
      error ("Duplicate definition of locale " ^ quote name));
wenzelm@13297
  1741
wenzelm@13297
  1742
    val thy_ctxt = ProofContext.init thy;
ballarin@17228
  1743
    val (((import_ctxt, import_elemss), (body_ctxt, body_elemss, syn)),
ballarin@19931
  1744
      text as (parms, ((_, exts'), _), defs)) =
wenzelm@13375
  1745
      prep_ctxt raw_import raw_body thy_ctxt;
ballarin@19931
  1746
    val elemss = import_elemss @ body_elemss |>
ballarin@19931
  1747
        map_filter (fn ((id, Assumed axs), elems) => SOME (id, elems) | _ => NONE);
wenzelm@16458
  1748
    val import = prep_expr thy raw_import;
wenzelm@13297
  1749
ballarin@17228
  1750
    val extraTs = foldr Term.add_term_tfrees [] exts' \\
wenzelm@17756
  1751
      foldr Term.add_typ_tfrees [] (map snd parms);
ballarin@17228
  1752
    val _ = if null extraTs then ()
ballarin@17437
  1753
      else warning ("Additional type variable(s) in locale specification " ^ quote bname);
ballarin@17228
  1754
ballarin@19931
  1755
    val ((((elemss', predicate as (predicate_statement, predicate_axioms), stmt'), intros),
ballarin@19931
  1756
          pred_thy), (import, regs)) =
ballarin@19931
  1757
      if do_predicate then
ballarin@19931
  1758
        let
ballarin@19942
  1759
          val (elemss', defns) = change_defines_elemss thy elemss [];
ballarin@20035
  1760
          val elemss'' = elemss' @ [(("", []), defns)];
ballarin@19931
  1761
          val (((elemss''', predicate as (_, axioms), stmt'), intros), thy') =
ballarin@19931
  1762
            define_preds bname text elemss'' thy;
ballarin@19931
  1763
          fun mk_regs elemss wits =
ballarin@19931
  1764
            fold_map (fn (id, elems) => fn wts => let
ballarin@19931
  1765
                val ts = List.concat (List.mapPartial (fn (Assumes asms) =>
ballarin@19931
  1766
                  SOME (List.concat (map (map #1 o #2) asms)) | _ => NONE) elems);
ballarin@19931
  1767
                val (wts1, wts2) = chop (length ts) wts
ballarin@19931
  1768
              in ((apsnd (map fst) id, wts1), wts2) end) elemss wits |> fst;
ballarin@19931
  1769
          val regs = mk_regs elemss''' axioms |>
ballarin@19931
  1770
                map_filter (fn (("", _), _) => NONE | e => SOME e);
ballarin@19931
  1771
        in ((((elemss''', predicate, stmt'), intros), thy'), (empty, regs)) end
ballarin@19931
  1772
      else ((((elemss, ([], []), []), ([], [])), thy), (import, []));
wenzelm@13420
  1773
wenzelm@18137
  1774
    fun axiomify axioms elemss =
ballarin@15206
  1775
      (axioms, elemss) |> foldl_map (fn (axs, (id, elems)) => let
wenzelm@19482
  1776
                   val ts = flat (map_filter (fn (Assumes asms) =>
wenzelm@19482
  1777
                     SOME (maps (map #1 o #2) asms) | _ => NONE) elems);
wenzelm@19018
  1778
                   val (axs1, axs2) = chop (length ts) axs;
ballarin@17000
  1779
                 in (axs2, ((id, Assumed axs1), elems)) end)
ballarin@15206
  1780
        |> snd;
ballarin@19931
  1781
    val (ctxt, (_, facts)) = activate_facts true (K I)
wenzelm@20965
  1782
      (ProofContext.init pred_thy, axiomify predicate_axioms elemss');
wenzelm@21393
  1783
    val view_ctxt = Assumption.add_view thy_ctxt predicate_statement ctxt;
wenzelm@21393
  1784
    val export = singleton (ProofContext.export_standard view_ctxt thy_ctxt);
wenzelm@13420
  1785
    val facts' = facts |> map (fn (a, ths) => ((a, []), [(map export ths, [])]));
wenzelm@19482
  1786
    val elems' = maps #2 (filter (equal "" o #1 o #1) elemss');
ballarin@19783
  1787
    val elems'' = map_filter (fn (Fixes _) => NONE | e => SOME e) elems';
ballarin@19931
  1788
    val axs' = map (Element.assume_witness pred_thy) stmt';
wenzelm@21393
  1789
    val loc_ctxt = pred_thy
wenzelm@21441
  1790
      |> PureThy.note_thmss_qualified Thm.assumptionK bname facts' |> snd
wenzelm@19061
  1791
      |> declare_locale name
wenzelm@19061
  1792
      |> put_locale name
ballarin@19931
  1793
       {axiom = axs',
wenzelm@19061
  1794
        import = import,
ballarin@19783
  1795
        elems = map (fn e => (e, stamp ())) elems'',
ballarin@19278
  1796
        params = params_of elemss' |> map (fn (x, SOME T) => ((x, T), the (Symtab.lookup syn x))),
ballarin@19931
  1797
        lparams = map #1 (params_of' body_elemss),
wenzelm@19662
  1798
        term_syntax = [],
ballarin@19931
  1799
        regs = regs,
wenzelm@21393
  1800
        intros = intros}
wenzelm@21393
  1801
      |> init name;
wenzelm@21393
  1802
  in (name, loc_ctxt) end;
wenzelm@13297
  1803
wenzelm@13297
  1804
in
wenzelm@13297
  1805
haftmann@18917
  1806
val add_locale = gen_add_locale read_context intern_expr;
haftmann@18917
  1807
val add_locale_i = gen_add_locale cert_context (K I);
wenzelm@13297
  1808
wenzelm@13297
  1809
end;
wenzelm@13297
  1810
wenzelm@19018
  1811
val _ = Context.add_setup
wenzelm@20965
  1812
 (add_locale_i true "var" empty [Fixes [(Name.internal "x", NONE, NoSyn)]] #>
wenzelm@20965
  1813
  snd #> ProofContext.theory_of #>
wenzelm@20965
  1814
  add_locale_i true "struct" empty [Fixes [(Name.internal "S", NONE, Structure)]] #>
wenzelm@20965
  1815
  snd #> ProofContext.theory_of);
wenzelm@15801
  1816
wenzelm@13297
  1817
wenzelm@12730
  1818
wenzelm@17355
  1819
ballarin@19931
  1820
(** Normalisation of locale statements ---
ballarin@19931
  1821
    discharges goals implied by interpretations **)
ballarin@19931
  1822
ballarin@19931
  1823
local
ballarin@19931
  1824
ballarin@19931
  1825
fun locale_assm_intros thy =
ballarin@19931
  1826
  Symtab.fold (fn (_, {intros = (a, _), ...}) => fn intros => (a @ intros))
ballarin@19931
  1827
    (#2 (GlobalLocalesData.get thy)) [];
ballarin@19931
  1828
fun locale_base_intros thy =
ballarin@19931
  1829
  Symtab.fold (fn (_, {intros = (_, b), ...}) => fn intros => (b @ intros))
ballarin@19931
  1830
    (#2 (GlobalLocalesData.get thy)) [];
ballarin@19931
  1831
ballarin@19931
  1832
fun all_witnesses ctxt =
ballarin@19931
  1833
  let
ballarin@19931
  1834
    val thy = ProofContext.theory_of ctxt;
ballarin@19931
  1835
    fun get registrations = Symtab.fold (fn (_, regs) => fn thms =>
ballarin@20069
  1836
        (Registrations.dest thy regs |> map (fn (_, (_, wits)) =>
ballarin@19931
  1837
          map Element.conclude_witness wits) |> flat) @ thms)
ballarin@19931
  1838
      registrations [];
ballarin@19931
  1839
    val globals = get (#3 (GlobalLocalesData.get thy));
ballarin@19931
  1840
    val locals = get (LocalLocalesData.get ctxt);
ballarin@19931
  1841
  in globals @ locals end;
ballarin@19931
  1842
(* FIXME: proper varification *)
ballarin@19931
  1843
ballarin@19931
  1844
in
ballarin@19931
  1845
ballarin@19984
  1846
fun intro_locales_tac eager ctxt facts st =
ballarin@19931
  1847
  let
ballarin@19931
  1848
    val wits = all_witnesses ctxt |> map Thm.varifyT;
ballarin@19931
  1849
    val thy = ProofContext.theory_of ctxt;
ballarin@19931
  1850
    val intros = locale_base_intros thy @ (if eager then locale_assm_intros thy else []);
ballarin@19931
  1851
  in
ballarin@19931
  1852
    (ALLGOALS (Method.insert_tac facts THEN'
ballarin@19931
  1853
        REPEAT_ALL_NEW (resolve_tac (wits @ intros)))
ballarin@19931
  1854
      THEN Tactic.distinct_subgoals_tac) st
ballarin@19931
  1855
  end;
ballarin@19931
  1856
ballarin@19931
  1857
val _ = Context.add_setup (Method.add_methods
ballarin@19931
  1858
  [("intro_locales",
ballarin@19984
  1859
    Method.ctxt_args (fn ctxt => Method.METHOD (intro_locales_tac false ctxt)),
ballarin@19984
  1860
    "back-chain introduction rules of locales without unfolding predicates"),
ballarin@19984
  1861
   ("unfold_locales",
ballarin@19984
  1862
    Method.ctxt_args (fn ctxt => Method.METHOD (intro_locales_tac true ctxt)),
ballarin@19984
  1863
    "back-chain all introduction rules of locales")]);
ballarin@19931
  1864
ballarin@19931
  1865
end;
ballarin@19931
  1866
wenzelm@19780
  1867
ballarin@15598
  1868
(** Interpretation commands **)
ballarin@15596
  1869
ballarin@15596
  1870
local
ballarin@15596
  1871
ballarin@15596
  1872
(* extract proof obligations (assms and defs) from elements *)
ballarin@15596
  1873
wenzelm@19780
  1874
fun extract_asms_elems ((id, Assumed _), elems) = (id, maps Element.prems_of elems)
ballarin@17138
  1875
  | extract_asms_elems ((id, Derived _), _) = (id, []);
ballarin@15596
  1876
ballarin@15596
  1877
ballarin@15624
  1878
(* activate instantiated facts in theory or context *)
ballarin@15596
  1879
ballarin@17138
  1880
fun gen_activate_facts_elemss get_reg note attrib std put_reg add_wit
wenzelm@18123
  1881
        attn all_elemss new_elemss propss thmss thy_ctxt =
ballarin@17033
  1882
    let
wenzelm@21441
  1883
      fun activate_elem disch (prfx, atts) (Notes (kind, facts)) thy_ctxt =
ballarin@17033
  1884
          let
wenzelm@21483
  1885
            val disch_morphism = Morphism.morphism
wenzelm@21483
  1886
              {name = I, var = I, typ = I, term = I, thm = disch};
ballarin@17033
  1887
            val facts' = facts
ballarin@17033
  1888
              (* discharge hyps in attributes *)
wenzelm@21483
  1889
              |> Attrib.map_facts (attrib thy_ctxt o Args.morph_values disch_morphism)
wenzelm@21441
  1890
              (* append interpretation attributes *)
ballarin@17033
  1891
              |> map (apfst (apsnd (fn a => a @ map (attrib thy_ctxt) atts)))
ballarin@17033
  1892
              (* discharge hyps *)
wenzelm@19061
  1893
              |> map (apsnd (map (apfst (map disch))));
wenzelm@21441
  1894
          in snd (note kind prfx facts' thy_ctxt) end
ballarin@17033
  1895
        | activate_elem _ _ _ thy_ctxt = thy_ctxt;
ballarin@17033
  1896
ballarin@17138
  1897
      fun activate_elems disch ((id, _), elems) thy_ctxt =
ballarin@17033
  1898
          let
wenzelm@18343
  1899
            val ((prfx, atts2), _) = the (get_reg thy_ctxt id)
ballarin@17033
  1900
                handle Option => sys_error ("Unknown registration of " ^
ballarin@17033
  1901
                  quote (fst id) ^ " while activating facts.");
ballarin@17033
  1902
          in
ballarin@17033
  1903
            fold (activate_elem disch (prfx, atts2)) elems thy_ctxt
ballarin@17033
  1904
          end;
ballarin@15596
  1905
ballarin@17033
  1906
      val thy_ctxt' = thy_ctxt
ballarin@17033
  1907
        (* add registrations *)
ballarin@17033
  1908
        |> fold (fn ((id, _), _) => put_reg id attn) new_elemss
ballarin@17033
  1909
        (* add witnesses of Assumed elements *)
wenzelm@19780
  1910
        |> fold (fn (id, thms) => fold (add_wit id) thms) (map fst propss ~~ thmss);
ballarin@15596
  1911
wenzelm@19482
  1912
      val prems = flat (map_filter
ballarin@17033
  1913
            (fn ((id, Assumed _), _) => Option.map snd (get_reg thy_ctxt' id)
ballarin@17033
  1914
              | ((_, Derived _), _) => NONE) all_elemss);
wenzelm@21483
  1915
      val satisfy = Element.satisfy_morphism prems;
ballarin@17033
  1916
      val thy_ctxt'' = thy_ctxt'
ballarin@17033
  1917
        (* add witnesses of Derived elements *)
wenzelm@21483
  1918
        |> fold (fn (id, thms) => fold (add_wit id o Element.morph_witness satisfy) thms)
wenzelm@19482
  1919
           (map_filter (fn ((_, Assumed _), _) => NONE
ballarin@19931
  1920
              | ((id, Derived thms), _) => SOME (id, thms)) new_elemss)
wenzelm@19780
  1921
wenzelm@21483
  1922
      val disch' = std o Morphism.thm satisfy;  (* FIXME *)
ballarin@17033
  1923
    in
ballarin@17033
  1924
      thy_ctxt''
ballarin@17033
  1925
        (* add facts to theory or context *)
ballarin@17033
  1926
        |> fold (activate_elems disch') new_elemss
ballarin@17033
  1927
    end;
ballarin@15596
  1928
wenzelm@17355
  1929
fun global_activate_facts_elemss x = gen_activate_facts_elemss
ballarin@15696
  1930
      (fn thy => fn (name, ps) =>
ballarin@15696
  1931
        get_global_registration thy (name, map Logic.varify ps))
wenzelm@21441
  1932
      global_note_prefix_i
wenzelm@18728
  1933
      Attrib.attribute_i Drule.standard
ballarin@17033
  1934
      (fn (name, ps) => put_global_registration (name, map Logic.varify ps))
wenzelm@19780
  1935
      (fn (n, ps) => add_global_witness (n, map Logic.varify ps) o
ballarin@19931
  1936
        Element.map_witness (fn (t, th) => (Logic.legacy_unvarify t, legacy_unvarify th))
wenzelm@19780
  1937
        (* FIXME *)) x;
wenzelm@17355
  1938
wenzelm@17355
  1939
fun local_activate_facts_elemss x = gen_activate_facts_elemss
ballarin@15696
  1940
      get_local_registration
wenzelm@19018
  1941
      local_note_prefix_i
wenzelm@18728
  1942
      (Attrib.attribute_i o ProofContext.theory_of) I
ballarin@17033
  1943
      put_local_registration
wenzelm@17355
  1944
      add_local_witness x;
ballarin@15624
  1945
ballarin@17033
  1946
fun gen_prep_registration mk_ctxt is_local read_terms test_reg activate
ballarin@15624
  1947
    attn expr insts thy_ctxt =
ballarin@15596
  1948
  let
ballarin@15624
  1949
    val ctxt = mk_ctxt thy_ctxt;
wenzelm@16458
  1950
    val thy = ProofContext.theory_of ctxt;
ballarin@15596
  1951
ballarin@15696
  1952
    val ctxt' = ctxt |> ProofContext.theory_of |> ProofContext.init;
ballarin@19783
  1953
    val pts = params_of_expr ctxt' [] (intern_expr thy expr)
ballarin@19783
  1954
          ([], Symtab.empty, Symtab.empty);
ballarin@19783
  1955
    val params_ids = make_params_ids (#1 pts);
ballarin@19783
  1956
    val raw_params_elemss = make_raw_params_elemss pts;
wenzelm@16458
  1957
    val ((ids, _), raw_elemss) = flatten (ctxt', intern_expr thy)
ballarin@16102
  1958
          (([], Symtab.empty), Expr expr);
ballarin@17000
  1959
    val ((parms, all_elemss, _), (_, (_, defs, _))) =
ballarin@19783
  1960
          read_elemss false ctxt' [] (raw_params_elemss @ raw_elemss) [];
ballarin@15596
  1961
ballarin@15596
  1962
    (** compute instantiation **)
ballarin@15596
  1963
ballarin@15696
  1964
    (* user input *)
ballarin@15596
  1965
    val insts = if length parms < length insts
ballarin@15596
  1966
         then error "More arguments than parameters in instantiation."
ballarin@15596
  1967
         else insts @ replicate (length parms - length insts) NONE;
ballarin@15596
  1968
    val (ps, pTs) = split_list parms;
wenzelm@19810
  1969
    val pvTs = map Logic.legacy_varifyT pTs;
ballarin@15598
  1970
ballarin@15598
  1971
    (* instantiations given by user *)
wenzelm@19482
  1972
    val given = map_filter (fn (_, (NONE, _)) => NONE
ballarin@15596
  1973
         | (x, (SOME inst, T)) => SOME (x, (inst, T))) (ps ~~ (insts ~~ pvTs));
ballarin@15596
  1974
    val (given_ps, given_insts) = split_list given;
ballarin@15596
  1975
    val tvars = foldr Term.add_typ_tvars [] pvTs;
ballarin@15596
  1976
    val used = foldr Term.add_typ_varnames [] pvTs;
haftmann@17485
  1977
    fun sorts (a, i) = AList.lookup (op =) tvars (a, i);
ballarin@15624
  1978
    val (vs, vinst) = read_terms thy_ctxt sorts used given_insts;
ballarin@15696
  1979
    val vars = foldl Term.add_term_tvar_ixns [] vs \\ map fst tvars;
wenzelm@20196
  1980
    val vars' = fold Term.add_varnames vs vars;
ballarin@15696
  1981
    val _ = if null vars' then ()
ballarin@15696
  1982
         else error ("Illegal schematic variable(s) in instantiation: " ^
ballarin@15696
  1983
           commas_quote (map Syntax.string_of_vname vars'));
ballarin@15598
  1984
    (* replace new types (which are TFrees) by ones with new names *)
ballarin@15598
  1985
    val new_Tnames = foldr Term.add_term_tfree_names [] vs;
wenzelm@20092
  1986
    val new_Tnames' = Name.invent_list used "'a" (length new_Tnames);
ballarin@15696
  1987
    val renameT =
ballarin@15696
  1988
          if is_local then I
wenzelm@19810
  1989
          else Logic.legacy_unvarifyT o Term.map_type_tfree (fn (a, s) =>
haftmann@17485
  1990
            TFree ((the o AList.lookup (op =) (new_Tnames ~~ new_Tnames')) a, s));
ballarin@15696
  1991
    val rename =
ballarin@15696
  1992
          if is_local then I
wenzelm@20548
  1993
          else Term.map_types renameT;
ballarin@15598
  1994
ballarin@15598
  1995
    val tinst = Symtab.make (map
ballarin@15696
  1996
                (fn ((x, 0), T) => (x, T |> renameT)
wenzelm@16850
  1997
                  | ((_, n), _) => sys_error "Internal error var in prep_registration") vinst);
ballarin@15696
  1998
    val inst = Symtab.make (given_ps ~~ map rename vs);
ballarin@15596
  1999
ballarin@15596
  2000
    (* defined params without user input *)
wenzelm@19482
  2001
    val not_given = map_filter (fn (x, (NONE, T)) => SOME (x, T)
ballarin@15596
  2002
         | (_, (SOME _, _)) => NONE) (ps ~~ (insts ~~ pTs));
wenzelm@18137
  2003
    fun add_def (p, pT) inst =
ballarin@15596
  2004
      let
ballarin@15596
  2005
        val (t, T) = case find_first (fn (Free (a, _), _) => a = p) defs of
ballarin@15596
  2006
               NONE => error ("Instance missing for parameter " ^ quote p)
ballarin@15596
  2007
             | SOME (Free (_, T), t) => (t, T);
wenzelm@18137
  2008
        val d = Element.inst_term (tinst, inst) t;
wenzelm@18137
  2009
      in Symtab.update_new (p, d) inst end;
wenzelm@18137
  2010
    val inst = fold add_def not_given inst;
wenzelm@18137
  2011
    val insts = (tinst, inst);
wenzelm@21483
  2012
    val inst_morphism = Element.inst_morphism thy insts;
wenzelm@18137
  2013
    (* Note: insts contain no vars. *)
ballarin@15596
  2014
ballarin@19783
  2015
ballarin@15596
  2016
    (** compute proof obligations **)
ballarin@15596
  2017
ballarin@15598
  2018
    (* restore "small" ids *)
ballarin@17000
  2019
    val ids' = map (fn ((n, ps), (_, mode)) =>
ballarin@19783
  2020
          ((n, map (fn p => Free (p, (the o AList.lookup (op =) parms) p)) ps), mode))
ballarin@19931
  2021
        ids;
ballarin@19931
  2022
    val (_, all_elemss') = chop (length raw_params_elemss) all_elemss
ballarin@15596
  2023
    (* instantiate ids and elements *)
ballarin@19931
  2024
    val inst_elemss = (ids' ~~ all_elemss') |> map (fn (((n, ps), _), ((_, mode), elems)) =>
wenzelm@21483
  2025
      ((n, map (Morphism.term inst_morphism) ps),
wenzelm@21483
  2026
        map (fn Int e => Element.morph_ctxt inst_morphism e) elems)
wenzelm@21483
  2027
      |> apfst (fn id => (id, map_mode (map (Element.morph_witness inst_morphism)) mode)));
ballarin@15596
  2028
ballarin@15624
  2029
    (* remove fragments already registered with theory or context *)
wenzelm@19482
  2030
    val new_inst_elemss = filter (fn ((id, _), _) =>
ballarin@15624
  2031
          not (test_reg thy_ctxt id)) inst_elemss;
wenzelm@15703
  2032
    val new_ids = map #1 new_inst_elemss;
ballarin@15596
  2033
wenzelm@19780
  2034
    val propss = map extract_asms_elems new_inst_elemss;
ballarin@15596
  2035
wenzelm@15703
  2036
    val bind_attrib = Attrib.crude_closure ctxt o Args.assignable;
wenzelm@16458
  2037
    val attn' = apsnd (map (bind_attrib o Attrib.intern_src thy)) attn;
ballarin@15596
  2038
ballarin@17033
  2039
  in (propss, activate attn' inst_elemss new_inst_elemss propss) end;
ballarin@15624
  2040
ballarin@15624
  2041
val prep_global_registration = gen_prep_registration
ballarin@15696
  2042
     ProofContext.init false
ballarin@15624
  2043
     (fn thy => fn sorts => fn used =>
wenzelm@16458
  2044
       Sign.read_def_terms (thy, K NONE, sorts) used true)
ballarin@15696
  2045
     (fn thy => fn (name, ps) =>
ballarin@15696
  2046
       test_global_registration thy (name, map Logic.varify ps))
ballarin@15624
  2047
     global_activate_facts_elemss;
ballarin@15624
  2048
ballarin@15624
  2049
val prep_local_registration = gen_prep_registration
ballarin@15696
  2050
     I true
ballarin@15624
  2051
     (fn ctxt => ProofContext.read_termTs ctxt (K false) (K NONE))
ballarin@15624
  2052
     smart_test_registration
ballarin@15624
  2053
     local_activate_facts_elemss;
ballarin@15596
  2054
ballarin@17000
  2055
fun prep_registration_in_locale target expr thy =
ballarin@17000
  2056
  (* target already in internal form *)
ballarin@17000
  2057
  let
ballarin@17000
  2058
    val ctxt = ProofContext.init thy;
ballarin@17138
  2059
    val ((raw_target_ids, target_syn), _) = flatten (ctxt, I)
ballarin@17000
  2060
        (([], Symtab.empty), Expr (Locale target));
ballarin@19278
  2061
    val fixed = the_locale thy target |> #params |> map #1;
ballarin@17000
  2062
    val ((all_ids, syn), raw_elemss) = flatten (ctxt, intern_expr thy)
ballarin@17138
  2063
        ((raw_target_ids, target_syn), Expr expr);
wenzelm@19018
  2064
    val (target_ids, ids) = chop (length raw_target_ids) all_ids;
ballarin@17138
  2065
    val ((parms, elemss, _), _) = read_elemss false ctxt fixed raw_elemss [];
ballarin@17000
  2066
ballarin@17000
  2067
    (** compute proof obligations **)
ballarin@17000
  2068
ballarin@17000
  2069
    (* restore "small" ids, with mode *)
ballarin@17000
  2070
    val ids' = map (apsnd snd) ids;
ballarin@17000
  2071
    (* remove Int markers *)
ballarin@17000
  2072
    val elemss' = map (fn (_, es) =>
ballarin@17000
  2073
        map (fn Int e => e) es) elemss
ballarin@17000
  2074
    (* extract assumptions and defs *)
ballarin@17138
  2075
    val ids_elemss = ids' ~~ elemss';
wenzelm@19780
  2076
    val propss = map extract_asms_elems ids_elemss;
ballarin@17000
  2077
ballarin@17138
  2078
    (** activation function:
ballarin@17138
  2079
        - add registrations to the target locale
ballarin@17138
  2080
        - add induced registrations for all global registrations of
ballarin@17138
  2081
          the target, unless already present
ballarin@17138
  2082
        - add facts of induced registrations to theory **)
ballarin@17138
  2083
wenzelm@19482
  2084
    val t_ids = map_filter
ballarin@17138
  2085
        (fn (id, (_, Assumed _)) => SOME id | _ => NONE) target_ids;
ballarin@17138
  2086
wenzelm@18123
  2087
    fun activate thmss thy = let
wenzelm@19780
  2088
        val satisfy = Element.satisfy_thm (flat thmss);
wenzelm@18123
  2089
        val ids_elemss_thmss = ids_elemss ~~ thmss;
ballarin@17138
  2090
        val regs = get_global_registrations thy target;
ballarin@17138
  2091
ballarin@17138
  2092
        fun activate_id (((id, Assumed _), _), thms) thy =
ballarin@17033
  2093
            thy |> put_registration_in_locale target id
ballarin@17138
  2094
                |> fold (add_witness_in_locale target id) thms
ballarin@17138
  2095
          | activate_id _ thy = thy;
ballarin@17138
  2096
wenzelm@21483
  2097
        fun activate_reg (vts, ((prfx, atts2), _)) thy =
wenzelm@21483
  2098
          let
wenzelm@18137
  2099
            val (insts, wits) = collect_global_witnesses thy fixed t_ids vts;
wenzelm@18137
  2100
            fun inst_parms ps = map
haftmann@17485
  2101
                  (the o AList.lookup (op =) (map #1 fixed ~~ vts)) ps;
wenzelm@19780
  2102
            val disch = Element.satisfy_thm wits;
wenzelm@19482
  2103
            val new_elemss = filter (fn (((name, ps), _), _) =>
ballarin@17138
  2104
                not (test_global_registration thy (name, inst_parms ps))) (ids_elemss);
ballarin@17138
  2105
            fun activate_assumed_id (((_, Derived _), _), _) thy = thy
ballarin@17138
  2106
              | activate_assumed_id ((((name, ps), Assumed _), _), thms) thy = let
ballarin@17138
  2107
                val ps' = inst_parms ps;
ballarin@17138
  2108
              in
ballarin@17138
  2109
                if test_global_registration thy (name, ps')
ballarin@17138
  2110
                then thy
ballarin@17138
  2111
                else thy
ballarin@17138
  2112
                  |> put_global_registration (name, ps') (prfx, atts2)
wenzelm@19780
  2113
                  |> fold (fn witn => fn thy => add_global_witness (name, ps')
wenzelm@21483
  2114
                     (Element.morph_witness (Element.inst_morphism thy insts) witn) thy) thms
ballarin@17138
  2115
              end;
ballarin@17138
  2116
ballarin@17138
  2117
            fun activate_derived_id ((_, Assumed _), _) thy = thy
ballarin@17138
  2118
              | activate_derived_id (((name, ps), Derived ths), _) thy = let
ballarin@17138
  2119
                val ps' = inst_parms ps;
ballarin@17138
  2120
              in
ballarin@17138
  2121
                if test_global_registration thy (name, ps')
ballarin@17138
  2122
                then thy
ballarin@17138
  2123
                else thy
ballarin@17138
  2124
                  |> put_global_registration (name, ps') (prfx, atts2)
wenzelm@19780
  2125
                  |> fold (fn witn => fn thy => add_global_witness (name, ps')
wenzelm@19780
  2126
                       (witn |> Element.map_witness (fn (t, th) =>  (* FIXME *)
wenzelm@18137
  2127
                       (Element.inst_term insts t,
wenzelm@19780
  2128
                        disch (Element.inst_thm thy insts (satisfy th))))) thy) ths
ballarin@17138
  2129
              end;
ballarin@17138
  2130
wenzelm@21441
  2131
            fun activate_elem (Notes (kind, facts)) thy =
ballarin@17138
  2132
                let
wenzelm@21483
  2133
                  val att_morphism = Morphism.morphism {var = I, name = I,
wenzelm@21483
  2134
                    typ = Element.instT_type (#1 insts), term = Element.inst_term insts,
wenzelm@21483
  2135
                    thm = disch o Element.inst_thm thy insts o satisfy};
ballarin@17138
  2136
                  val facts' = facts
wenzelm@21483
  2137
                      |> Attrib.map_facts (Attrib.attribute_i thy o Args.morph_values att_morphism)
wenzelm@18728
  2138
                      |> map (apfst (apsnd (fn a => a @ map (Attrib.attribute thy) atts2)))
wenzelm@18137
  2139
                      |> map (apsnd (map (apfst (map (disch o Element.inst_thm thy insts o satisfy)))))
ballarin@17138
  2140
                in
haftmann@18377
  2141
                  thy
wenzelm@21441
  2142
                  |> global_note_prefix_i kind prfx facts'
haftmann@18377
  2143
                  |> snd
ballarin@17138
  2144
                end
ballarin@17138
  2145
              | activate_elem _ thy = thy;
ballarin@17138
  2146
ballarin@17138
  2147
            fun activate_elems (_, elems) thy = fold activate_elem elems thy;
ballarin@17138
  2148
ballarin@17138
  2149
          in thy |> fold activate_assumed_id ids_elemss_thmss
ballarin@17138
  2150
                 |> fold activate_derived_id ids_elemss
ballarin@17138
  2151
                 |> fold activate_elems new_elemss end;
ballarin@17033
  2152
      in
ballarin@17138
  2153
        thy |> fold activate_id ids_elemss_thmss
ballarin@17138
  2154
            |> fold activate_reg regs
ballarin@17033
  2155
      end;
ballarin@17000
  2156
ballarin@17033
  2157
  in (propss, activate) end;
ballarin@17000
  2158
wenzelm@21005
  2159
fun prep_propp propss = propss |> map (fn (_, props) =>
wenzelm@21361
  2160
  map (rpair [] o Element.mark_witness) props);
wenzelm@18123
  2161
wenzelm@18123
  2162
fun prep_result propps thmss =
wenzelm@19780
  2163
  ListPair.map (fn ((_, props), thms) => map2 Element.make_witness props thms) (propps, thmss);
ballarin@17437
  2164
wenzelm@17355
  2165
in
wenzelm@17355
  2166
wenzelm@20366
  2167
fun interpretation after_qed (prfx, atts) expr insts thy =
wenzelm@17355
  2168
  let
wenzelm@17355
  2169
    val (propss, activate) = prep_global_registration (prfx, atts) expr insts thy;
wenzelm@20366
  2170
    fun after_qed' results =
wenzelm@20366
  2171
      ProofContext.theory (activate (prep_result propss results))
wenzelm@20366
  2172
      #> after_qed;
wenzelm@18123
  2173
  in
wenzelm@18137
  2174
    ProofContext.init thy
wenzelm@21441
  2175
    |> Proof.theorem_i NONE after_qed' (prep_propp propss)
wenzelm@19810
  2176
    |> Element.refine_witness |> Seq.hd
wenzelm@18123
  2177
  end;
wenzelm@17355
  2178
wenzelm@20366
  2179
fun interpretation_in_locale after_qed (raw_target, expr) thy =
wenzelm@17355
  2180
  let
wenzelm@17355
  2181
    val target = intern thy raw_target;
wenzelm@17355
  2182
    val (propss, activate) = prep_registration_in_locale target expr thy;
wenzelm@21361
  2183
    val raw_propp = prep_propp propss;
wenzelm@21005
  2184
wenzelm@21005
  2185
    val (_, _, goal_ctxt, propp) = thy
wenzelm@21005
  2186
      |> ProofContext.init |> init_term_syntax target
wenzelm@21361
  2187
      |> cert_context_statement (SOME target) [] raw_propp;
wenzelm@21005
  2188
wenzelm@21005
  2189
    fun after_qed' results =
wenzelm@20366
  2190
      ProofContext.theory (activate (prep_result propss results))
wenzelm@20366
  2191
      #> after_qed;
wenzelm@18123
  2192
  in
wenzelm@21005
  2193
    goal_ctxt
wenzelm@21441
  2194
    |> Proof.theorem_i NONE after_qed' propp
wenzelm@19810
  2195
    |> Element.refine_witness |> Seq.hd
wenzelm@18123
  2196
  end;
wenzelm@17449
  2197
wenzelm@20366
  2198
fun interpret after_qed (prfx, atts) expr insts int state =
wenzelm@17449
  2199
  let
wenzelm@19296
  2200
    val _ = Proof.assert_forward_or_chain state;
wenzelm@17449
  2201
    val ctxt = Proof.context_of state;
wenzelm@17449
  2202
    val (propss, activate) = prep_local_registration (prfx, atts) expr insts ctxt;
wenzelm@20366
  2203
    fun after_qed' results =
wenzelm@18123
  2204
      Proof.map_context (K (ctxt |> activate (prep_result propss results)))
wenzelm@17449
  2205
      #> Proof.put_facts NONE
wenzelm@20366
  2206
      #> after_qed;
wenzelm@17355
  2207
  in
wenzelm@18123
  2208
    state
wenzelm@18123
  2209
    |> Proof.local_goal (ProofDisplay.print_results int) (K I) ProofContext.bind_propp_i
wenzelm@21361
  2210
      "interpret" NONE after_qed' (map (pair ("", [])) (prep_propp propss))
wenzelm@19810
  2211
    |> Element.refine_witness |> Seq.hd
ballarin@17437
  2212
  end;
ballarin@15596
  2213
wenzelm@11896
  2214
end;
wenzelm@17355
  2215
wenzelm@17355
  2216
end;