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