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