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