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