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