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