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