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