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