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