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