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