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