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