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