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