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