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