src/Pure/Isar/locale.ML
author skalberg
Fri Mar 04 15:07:34 2005 +0100 (2005-03-04)
changeset 15574 b1d1b5bfc464
parent 15570 8d8c70b41bab
child 15596 8665d08085df
permissions -rw-r--r--
Removed practically all references to Library.foldr.
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@14446
    14
See also:
ballarin@14446
    15
ballarin@14446
    16
[1] Clemens Ballarin. Locales and Locale Expressions in Isabelle/Isar.
ballarin@14446
    17
    In Stefano Berardi et al., Types for Proofs and Programs: International
ballarin@15099
    18
    Workshop, TYPES 2003, Torino, Italy, LNCS 3085, pages 34-50, 2004.
wenzelm@11896
    19
*)
wenzelm@11896
    20
wenzelm@11896
    21
signature LOCALE =
wenzelm@11896
    22
sig
wenzelm@12046
    23
  type context
ballarin@15206
    24
ballarin@15206
    25
  (* Constructors for elem, expr and elem_expr are
ballarin@15206
    26
     currently only used for inputting locales (outer_parse.ML). *)
wenzelm@12046
    27
  datatype ('typ, 'term, 'fact, 'att) elem =
wenzelm@12058
    28
    Fixes of (string * 'typ option * mixfix option) list |
wenzelm@12046
    29
    Assumes of ((string * 'att list) * ('term * ('term list * 'term list)) list) list |
wenzelm@12046
    30
    Defines of ((string * 'att list) * ('term * 'term list)) list |
wenzelm@12273
    31
    Notes of ((string * 'att list) * ('fact * 'att list) list) list
wenzelm@12273
    32
  datatype expr =
wenzelm@12273
    33
    Locale of string |
wenzelm@12273
    34
    Rename of expr * string option list |
wenzelm@12273
    35
    Merge of expr list
wenzelm@12273
    36
  val empty: expr
ballarin@15206
    37
  datatype 'a elem_expr = Elem of 'a | Expr of expr
ballarin@15206
    38
ballarin@15206
    39
  (* Abstract interface to locales *)
wenzelm@12046
    40
  type 'att element
wenzelm@12046
    41
  type 'att element_i
wenzelm@12046
    42
  type locale
wenzelm@12046
    43
  val intern: Sign.sg -> xstring -> string
wenzelm@12014
    44
  val cond_extern: Sign.sg -> string -> xstring
wenzelm@12502
    45
  val the_locale: theory -> string -> locale
ballarin@15206
    46
  val map_attrib_element: ('att -> context attribute) -> 'att element ->
ballarin@15206
    47
    context attribute element
ballarin@15206
    48
  val map_attrib_element_i: ('att -> context attribute) -> 'att element_i ->
ballarin@15206
    49
    context attribute element_i
ballarin@15206
    50
  val map_attrib_elem_or_expr: ('att -> context attribute) ->
ballarin@15206
    51
    'att element elem_expr -> context attribute element elem_expr
ballarin@15206
    52
  val map_attrib_elem_or_expr_i: ('att -> context attribute) ->
ballarin@15206
    53
    'att element_i elem_expr -> context attribute element_i elem_expr
ballarin@15206
    54
ballarin@15206
    55
  val read_context_statement: xstring option ->
ballarin@15206
    56
    context attribute element elem_expr list ->
wenzelm@12529
    57
    (string * (string list * string list)) list list -> context ->
ballarin@15206
    58
    string option * (cterm list * cterm list) * context * context * 
ballarin@15206
    59
      (term * (term list * term list)) list list
ballarin@15206
    60
  val cert_context_statement: string option ->
ballarin@15206
    61
    context attribute element_i elem_expr list ->
wenzelm@12529
    62
    (term * (term list * term list)) list list -> context ->
ballarin@15206
    63
    string option * (cterm list * cterm list) * context * context *
ballarin@15206
    64
      (term * (term list * term list)) list list
wenzelm@12758
    65
  val print_locales: theory -> unit
wenzelm@12758
    66
  val print_locale: theory -> expr -> context attribute element list -> unit
wenzelm@13394
    67
  val add_locale: bool -> bstring -> expr -> context attribute element list -> theory -> theory
wenzelm@13394
    68
  val add_locale_i: bool -> bstring -> expr -> context attribute element_i list
wenzelm@13394
    69
    -> theory -> theory
skalberg@15531
    70
  val smart_note_thmss: string -> (string * 'a) option ->
wenzelm@12958
    71
    ((bstring * theory attribute list) * (thm list * theory attribute list) list) list ->
wenzelm@12958
    72
    theory -> theory * (bstring * thm list) list
wenzelm@14564
    73
  val note_thmss: string -> xstring ->
berghofe@15456
    74
    ((bstring * context attribute list) * (thmref * context attribute list) list) list ->
wenzelm@12711
    75
    theory -> theory * (bstring * thm list) list
wenzelm@14564
    76
  val note_thmss_i: string -> string ->
wenzelm@12711
    77
    ((bstring * context attribute list) * (thm list * context attribute list) list) list ->
wenzelm@12711
    78
    theory -> theory * (bstring * thm list) list
wenzelm@12958
    79
  val add_thmss: string -> ((string * thm list) * context attribute list) list ->
wenzelm@13375
    80
    theory * context -> (theory * context) * (string * thm list) list
ballarin@14528
    81
  val instantiate: string -> string * context attribute list
ballarin@14528
    82
    -> thm list option -> context -> context
wenzelm@11896
    83
  val setup: (theory -> theory) list
wenzelm@11896
    84
end;
wenzelm@12839
    85
wenzelm@12289
    86
structure Locale: LOCALE =
wenzelm@11896
    87
struct
wenzelm@11896
    88
wenzelm@12273
    89
(** locale elements and expressions **)
wenzelm@11896
    90
wenzelm@12014
    91
type context = ProofContext.context;
wenzelm@11896
    92
wenzelm@12046
    93
datatype ('typ, 'term, 'fact, 'att) elem =
wenzelm@12058
    94
  Fixes of (string * 'typ option * mixfix option) list |
wenzelm@12046
    95
  Assumes of ((string * 'att list) * ('term * ('term list * 'term list)) list) list |
wenzelm@12046
    96
  Defines of ((string * 'att list) * ('term * 'term list)) list |
wenzelm@12273
    97
  Notes of ((string * 'att list) * ('fact * 'att list) list) list;
wenzelm@12273
    98
wenzelm@12273
    99
datatype expr =
wenzelm@12273
   100
  Locale of string |
wenzelm@12273
   101
  Rename of expr * string option list |
wenzelm@12273
   102
  Merge of expr list;
wenzelm@11896
   103
wenzelm@12273
   104
val empty = Merge [];
wenzelm@12273
   105
ballarin@15206
   106
datatype 'a elem_expr =
ballarin@15206
   107
  Elem of 'a | Expr of expr;
wenzelm@12273
   108
berghofe@15456
   109
type 'att element = (string, string, thmref, 'att) elem;
ballarin@15127
   110
type 'att element_i = (typ, term, thm list, 'att) elem;
wenzelm@12070
   111
wenzelm@12070
   112
type locale =
ballarin@15206
   113
 {predicate: cterm list * thm list,
ballarin@15206
   114
    (* CB: For old-style locales with "(open)" this entry is ([], []).
ballarin@15206
   115
       For new-style locales, which declare predicates, if the locale declares
ballarin@15206
   116
       no predicates, this is also ([], []).
ballarin@15206
   117
       If the locale declares predicates, the record field is
ballarin@15206
   118
       ([statement], axioms), where statement is the locale predicate applied
ballarin@15206
   119
       to the (assumed) locale parameters.  Axioms contains the projections
ballarin@15206
   120
       from the locale predicate to the normalised assumptions of the locale
ballarin@15206
   121
       (cf. [1], normalisation of locale expressions.)
ballarin@15206
   122
    *)
ballarin@15206
   123
  import: expr,                                       (*dynamic import*)
ballarin@15206
   124
  elems: (context attribute element_i * stamp) list,  (*static content*)
ballarin@15206
   125
  params: (string * typ option) list * string list}   (*all/local params*)
wenzelm@12063
   126
wenzelm@11896
   127
wenzelm@11896
   128
(** theory data **)
wenzelm@11896
   129
wenzelm@11896
   130
structure LocalesArgs =
wenzelm@11896
   131
struct
wenzelm@12014
   132
  val name = "Isar/locales";
wenzelm@12063
   133
  type T = NameSpace.T * locale Symtab.table;
wenzelm@11896
   134
wenzelm@12063
   135
  val empty = (NameSpace.empty, Symtab.empty);
wenzelm@12063
   136
  val copy = I;
wenzelm@12118
   137
  val prep_ext = I;
wenzelm@12289
   138
wenzelm@12289
   139
  (*joining of locale elements: only facts may be added later!*)
ballarin@15206
   140
  fun join ({predicate, import, elems, params}: locale, {elems = elems', ...}: locale) =
skalberg@15531
   141
    SOME {predicate = predicate, import = import, elems = gen_merge_lists eq_snd elems elems',
ballarin@15206
   142
      params = params};
wenzelm@12273
   143
  fun merge ((space1, locs1), (space2, locs2)) =
wenzelm@12289
   144
    (NameSpace.merge (space1, space2), Symtab.join join (locs1, locs2));
wenzelm@12289
   145
wenzelm@12273
   146
  fun print _ (space, locs) =
wenzelm@12273
   147
    Pretty.strs ("locales:" :: map (NameSpace.cond_extern space o #1) (Symtab.dest locs))
wenzelm@12014
   148
    |> Pretty.writeln;
wenzelm@11896
   149
end;
wenzelm@11896
   150
wenzelm@11896
   151
structure LocalesData = TheoryDataFun(LocalesArgs);
wenzelm@11896
   152
val print_locales = LocalesData.print;
wenzelm@11896
   153
wenzelm@12289
   154
val intern = NameSpace.intern o #1 o LocalesData.get_sg;
wenzelm@12289
   155
val cond_extern = NameSpace.cond_extern o #1 o LocalesData.get_sg;
wenzelm@12289
   156
wenzelm@12277
   157
wenzelm@12277
   158
(* access locales *)
wenzelm@12277
   159
wenzelm@12063
   160
fun declare_locale name =
wenzelm@12063
   161
  LocalesData.map (apfst (fn space => (NameSpace.extend (space, [name]))));
wenzelm@11896
   162
wenzelm@12273
   163
fun put_locale name loc = LocalesData.map (apsnd (fn locs => Symtab.update ((name, loc), locs)));
wenzelm@12063
   164
fun get_locale thy name = Symtab.lookup (#2 (LocalesData.get thy), name);
wenzelm@11896
   165
wenzelm@12014
   166
fun the_locale thy name =
wenzelm@12014
   167
  (case get_locale thy name of
skalberg@15531
   168
    SOME loc => loc
skalberg@15531
   169
  | NONE => error ("Unknown locale " ^ quote name));
wenzelm@11896
   170
wenzelm@12046
   171
ballarin@14215
   172
(* import hierarchy
ballarin@14215
   173
   implementation could be more efficient, eg. by maintaining a database
ballarin@14215
   174
   of dependencies *)
ballarin@14215
   175
ballarin@14215
   176
fun imports thy (upper, lower) =
ballarin@14215
   177
  let
ballarin@14215
   178
    val sign = sign_of thy;
ballarin@14215
   179
    fun imps (Locale name) low = (name = low) orelse
ballarin@14215
   180
      (case get_locale thy name of
skalberg@15531
   181
           NONE => false
skalberg@15531
   182
         | SOME {import, ...} => imps import low)
ballarin@14215
   183
      | imps (Rename (expr, _)) low = imps expr low
ballarin@14215
   184
      | imps (Merge es) low = exists (fn e => imps e low) es;
ballarin@14215
   185
  in
ballarin@14215
   186
    imps (Locale (intern sign upper)) (intern sign lower)
ballarin@14215
   187
  end;
ballarin@14215
   188
ballarin@14215
   189
wenzelm@12277
   190
(* diagnostics *)
wenzelm@12273
   191
wenzelm@12277
   192
fun err_in_locale ctxt msg ids =
wenzelm@12277
   193
  let
wenzelm@12529
   194
    val sign = ProofContext.sign_of ctxt;
wenzelm@12529
   195
    fun prt_id (name, parms) =
wenzelm@12529
   196
      [Pretty.block (Pretty.breaks (map Pretty.str (cond_extern sign name :: parms)))];
skalberg@15570
   197
    val prt_ids = List.concat (separate [Pretty.str " +", Pretty.brk 1] (map prt_id ids));
wenzelm@12502
   198
    val err_msg =
wenzelm@12529
   199
      if forall (equal "" o #1) ids then msg
wenzelm@12502
   200
      else msg ^ "\n" ^ Pretty.string_of (Pretty.block
wenzelm@12502
   201
        (Pretty.str "The error(s) above occurred in locale:" :: Pretty.brk 1 :: prt_ids));
wenzelm@12502
   202
  in raise ProofContext.CONTEXT (err_msg, ctxt) end;
wenzelm@12063
   203
ballarin@15206
   204
(* Version for identifiers with axioms *)
ballarin@15206
   205
ballarin@15206
   206
fun err_in_locale' ctxt msg ids' = err_in_locale ctxt msg (map fst ids');
wenzelm@12277
   207
wenzelm@12277
   208
wenzelm@12529
   209
(** primitives **)
wenzelm@12046
   210
wenzelm@12277
   211
(* renaming *)
wenzelm@12263
   212
skalberg@15570
   213
fun rename ren x = getOpt (assoc_string (ren, x), x);
wenzelm@12263
   214
wenzelm@12263
   215
fun rename_term ren (Free (x, T)) = Free (rename ren x, T)
wenzelm@12263
   216
  | rename_term ren (t $ u) = rename_term ren t $ rename_term ren u
wenzelm@12263
   217
  | rename_term ren (Abs (x, T, t)) = Abs (x, T, rename_term ren t)
wenzelm@12263
   218
  | rename_term _ a = a;
wenzelm@12263
   219
wenzelm@12263
   220
fun rename_thm ren th =
wenzelm@12263
   221
  let
wenzelm@12263
   222
    val {sign, hyps, prop, maxidx, ...} = Thm.rep_thm th;
wenzelm@12263
   223
    val cert = Thm.cterm_of sign;
skalberg@15570
   224
    val (xs, Ts) = Library.split_list (Library.foldl Term.add_frees ([], prop :: hyps));
wenzelm@12263
   225
    val xs' = map (rename ren) xs;
wenzelm@12263
   226
    fun cert_frees names = map (cert o Free) (names ~~ Ts);
wenzelm@12263
   227
    fun cert_vars names = map (cert o Var o apfst (rpair (maxidx + 1))) (names ~~ Ts);
wenzelm@12263
   228
  in
wenzelm@12263
   229
    if xs = xs' then th
wenzelm@12263
   230
    else
wenzelm@12263
   231
      th
wenzelm@12263
   232
      |> Drule.implies_intr_list (map cert hyps)
wenzelm@12263
   233
      |> Drule.forall_intr_list (cert_frees xs)
wenzelm@12263
   234
      |> Drule.forall_elim_list (cert_vars xs)
wenzelm@12263
   235
      |> Thm.instantiate ([], cert_vars xs ~~ cert_frees xs')
wenzelm@12263
   236
      |> (fn th' => Drule.implies_elim_list th' (map (Thm.assume o cert o rename_term ren) hyps))
wenzelm@12263
   237
  end;
wenzelm@12263
   238
wenzelm@12529
   239
fun rename_elem ren (Fixes fixes) = Fixes (fixes |> map (fn (x, T, mx) =>
wenzelm@12529
   240
      let val x' = rename ren x in
wenzelm@12529
   241
        if x = x' then (x, T, mx)
skalberg@15531
   242
        else (x', T, if mx = NONE then mx else SOME Syntax.NoSyn)    (*drop syntax*)
wenzelm@12529
   243
      end))
wenzelm@12263
   244
  | rename_elem ren (Assumes asms) = Assumes (map (apsnd (map (fn (t, (ps, qs)) =>
wenzelm@12263
   245
      (rename_term ren t, (map (rename_term ren) ps, map (rename_term ren) qs))))) asms)
wenzelm@12263
   246
  | rename_elem ren (Defines defs) = Defines (map (apsnd (fn (t, ps) =>
wenzelm@12263
   247
      (rename_term ren t, map (rename_term ren) ps))) defs)
wenzelm@12273
   248
  | rename_elem ren (Notes facts) = Notes (map (apsnd (map (apfst (map (rename_thm ren))))) facts);
wenzelm@12263
   249
wenzelm@12529
   250
fun rename_facts prfx elem =
wenzelm@12307
   251
  let
wenzelm@12323
   252
    fun qualify (arg as ((name, atts), x)) =
wenzelm@13394
   253
      if prfx = "" orelse name = "" then arg
wenzelm@13375
   254
      else ((NameSpace.pack [prfx, name], atts), x);
wenzelm@12307
   255
  in
wenzelm@12307
   256
    (case elem of
wenzelm@12307
   257
      Fixes fixes => Fixes fixes
wenzelm@12307
   258
    | Assumes asms => Assumes (map qualify asms)
wenzelm@12307
   259
    | Defines defs => Defines (map qualify defs)
wenzelm@12307
   260
    | Notes facts => Notes (map qualify facts))
wenzelm@12307
   261
  end;
wenzelm@12307
   262
wenzelm@12263
   263
wenzelm@12502
   264
(* type instantiation *)
wenzelm@12502
   265
wenzelm@12502
   266
fun inst_type [] T = T
skalberg@15570
   267
  | inst_type env T = Term.map_type_tfree (fn v => getOpt (assoc (env, v), TFree v)) T;
wenzelm@12502
   268
wenzelm@12502
   269
fun inst_term [] t = t
wenzelm@12502
   270
  | inst_term env t = Term.map_term_types (inst_type env) t;
wenzelm@12502
   271
wenzelm@13211
   272
fun inst_thm _ [] th = th
wenzelm@13211
   273
  | inst_thm ctxt env th =
wenzelm@12502
   274
      let
wenzelm@13211
   275
        val sign = ProofContext.sign_of ctxt;
wenzelm@12575
   276
        val cert = Thm.cterm_of sign;
wenzelm@12575
   277
        val certT = Thm.ctyp_of sign;
wenzelm@13211
   278
        val {hyps, prop, maxidx, ...} = Thm.rep_thm th;
skalberg@15574
   279
        val tfrees = foldr Term.add_term_tfree_names [] (prop :: hyps);
skalberg@15570
   280
        val env' = List.filter (fn ((a, _), _) => a mem_string tfrees) env;
wenzelm@12502
   281
      in
wenzelm@12502
   282
        if null env' then th
wenzelm@12502
   283
        else
wenzelm@12502
   284
          th
wenzelm@12502
   285
          |> Drule.implies_intr_list (map cert hyps)
wenzelm@12575
   286
          |> Drule.tvars_intr_list (map (#1 o #1) env')
wenzelm@12502
   287
          |> (fn (th', al) => th' |>
skalberg@15570
   288
            Thm.instantiate ((map (fn ((a, _), T) => (valOf (assoc (al, a)), certT T)) env'), []))
wenzelm@12502
   289
          |> (fn th'' => Drule.implies_elim_list th''
wenzelm@12502
   290
              (map (Thm.assume o cert o inst_term env') hyps))
wenzelm@12502
   291
      end;
wenzelm@12502
   292
wenzelm@13211
   293
fun inst_elem _ env (Fixes fixes) =
skalberg@15570
   294
      Fixes (map (fn (x, T, mx) => (x, Option.map (inst_type env) T, mx)) fixes)
wenzelm@13211
   295
  | inst_elem _ env (Assumes asms) = Assumes (map (apsnd (map (fn (t, (ps, qs)) =>
wenzelm@12502
   296
      (inst_term env t, (map (inst_term env) ps, map (inst_term env) qs))))) asms)
wenzelm@13211
   297
  | inst_elem _ env (Defines defs) = Defines (map (apsnd (fn (t, ps) =>
wenzelm@12502
   298
      (inst_term env t, map (inst_term env) ps))) defs)
wenzelm@13211
   299
  | inst_elem ctxt env (Notes facts) =
wenzelm@13211
   300
      Notes (map (apsnd (map (apfst (map (inst_thm ctxt env))))) facts);
wenzelm@12502
   301
wenzelm@12502
   302
wenzelm@12529
   303
wenzelm@12529
   304
(** structured contexts: rename + merge + implicit type instantiation **)
wenzelm@12529
   305
wenzelm@12529
   306
(* parameter types *)
wenzelm@12529
   307
ballarin@14508
   308
(* CB: frozen_tvars has the following type:
ballarin@14508
   309
  ProofContext.context -> Term.typ list -> (Term.indexname * Term.typ) list *)
ballarin@14508
   310
wenzelm@12529
   311
fun frozen_tvars ctxt Ts =
wenzelm@12529
   312
  let
skalberg@15570
   313
    val tvars = rev (Library.foldl Term.add_tvarsT ([], Ts));
wenzelm@12529
   314
    val tfrees = map TFree
wenzelm@14695
   315
      (Term.invent_names (ProofContext.used_types ctxt) "'a" (length tvars) ~~ map #2 tvars);
wenzelm@12529
   316
  in map #1 tvars ~~ tfrees end;
wenzelm@12529
   317
wenzelm@12529
   318
fun unify_frozen ctxt maxidx Ts Us =
wenzelm@12529
   319
  let
skalberg@15531
   320
    fun paramify (i, NONE) = (i, NONE)
skalberg@15531
   321
      | paramify (i, SOME T) = apsnd SOME (TypeInfer.paramify_dummies (i, T));
wenzelm@12529
   322
wenzelm@12529
   323
    val (maxidx', Ts') = foldl_map paramify (maxidx, Ts);
wenzelm@12727
   324
    val (maxidx'', Us') = foldl_map paramify (maxidx', Us);
ballarin@14215
   325
    val tsig = Sign.tsig_of (ProofContext.sign_of ctxt);
ballarin@14215
   326
skalberg@15531
   327
    fun unify (env, (SOME T, SOME U)) = (Type.unify tsig env (U, T)
ballarin@14215
   328
          handle Type.TUNIFY =>
ballarin@14215
   329
            raise TYPE ("unify_frozen: failed to unify types", [U, T], []))
ballarin@14215
   330
      | unify (env, _) = env;
skalberg@15570
   331
    val (unifier, _) = Library.foldl unify ((Vartab.empty, maxidx''), Ts' ~~ Us');
skalberg@15570
   332
    val Vs = map (Option.map (Envir.norm_type unifier)) Us';
skalberg@15570
   333
    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (List.mapPartial I Vs));
skalberg@15570
   334
  in map (Option.map (Envir.norm_type unifier')) Vs end;
wenzelm@12529
   335
skalberg@15570
   336
fun params_of elemss = gen_distinct eq_fst (List.concat (map (snd o fst) elemss));
skalberg@15570
   337
fun params_of' elemss = gen_distinct eq_fst (List.concat (map (snd o fst o fst) elemss));
ballarin@14508
   338
ballarin@14508
   339
(* CB: param_types has the following type:
skalberg@15531
   340
  ('a * 'b option) list -> ('a * 'b) list *)
skalberg@15570
   341
fun param_types ps = List.mapPartial (fn (_, NONE) => NONE | (x, SOME T) => SOME (x, T)) ps;
wenzelm@12529
   342
wenzelm@12529
   343
wenzelm@12529
   344
(* flatten expressions *)
wenzelm@11896
   345
wenzelm@12510
   346
local
wenzelm@12502
   347
ballarin@15206
   348
(* CB: OUTDATED unique_parms has the following type:
ballarin@14508
   349
     'a ->
ballarin@14508
   350
     (('b * (('c * 'd) list * Symtab.key list)) * 'e) list ->
ballarin@14508
   351
     (('b * ('c * 'd) list) * 'e) list  *)
ballarin@14508
   352
wenzelm@12529
   353
fun unique_parms ctxt elemss =
wenzelm@12529
   354
  let
wenzelm@12529
   355
    val param_decls =
skalberg@15570
   356
      List.concat (map (fn (((name, (ps, qs)), _), _) => map (rpair (name, ps)) qs) elemss)
wenzelm@12529
   357
      |> Symtab.make_multi |> Symtab.dest;
wenzelm@12529
   358
  in
wenzelm@12529
   359
    (case find_first (fn (_, ids) => length ids > 1) param_decls of
skalberg@15531
   360
      SOME (q, ids) => err_in_locale ctxt ("Multiple declaration of parameter " ^ quote q)
wenzelm@12529
   361
          (map (apsnd (map fst)) ids)
skalberg@15531
   362
    | NONE => map (apfst (apfst (apsnd #1))) elemss)
wenzelm@12529
   363
  end;
wenzelm@12529
   364
ballarin@14508
   365
(* CB: unify_parms has the following type:
ballarin@14508
   366
     ProofContext.context ->
ballarin@14508
   367
     (string * Term.typ) list ->
skalberg@15531
   368
     (string * Term.typ option) list list ->
ballarin@14508
   369
     ((string * Term.sort) * Term.typ) list list *)
ballarin@14508
   370
wenzelm@12529
   371
fun unify_parms ctxt fixed_parms raw_parmss =
wenzelm@12502
   372
  let
ballarin@15206
   373
    val sign = ProofContext.sign_of ctxt;
ballarin@15206
   374
    val tsig = Sign.tsig_of sign;
wenzelm@12502
   375
    val maxidx = length raw_parmss;
wenzelm@12502
   376
    val idx_parmss = (0 upto maxidx - 1) ~~ raw_parmss;
wenzelm@12502
   377
wenzelm@12502
   378
    fun varify i = Term.map_type_tfree (fn (a, S) => TVar ((a, i), S));
wenzelm@12529
   379
    fun varify_parms (i, ps) = map (apsnd (varify i)) (param_types ps);
skalberg@15570
   380
    val parms = fixed_parms @ List.concat (map varify_parms idx_parmss);
wenzelm@12502
   381
ballarin@15206
   382
    fun unify T ((env, maxidx), U) =
ballarin@15206
   383
      Type.unify tsig (env, maxidx) (U, T)
ballarin@15206
   384
      handle Type.TUNIFY =>
ballarin@15206
   385
        let val prt = Sign.string_of_typ sign
ballarin@15206
   386
        in raise TYPE ("unify_parms: failed to unify types " ^
ballarin@15206
   387
          prt U ^ " and " ^ prt T, [U, T], [])
ballarin@15206
   388
        end
skalberg@15570
   389
    fun unify_list (envir, T :: Us) = Library.foldl (unify T) (envir, Us)
wenzelm@12502
   390
      | unify_list (envir, []) = envir;
skalberg@15570
   391
    val (unifier, _) = Library.foldl unify_list
wenzelm@12502
   392
      ((Vartab.empty, maxidx), map #2 (Symtab.dest (Symtab.make_multi parms)));
wenzelm@12502
   393
wenzelm@12502
   394
    val parms' = map (apsnd (Envir.norm_type unifier)) (gen_distinct eq_fst parms);
wenzelm@12502
   395
    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (map #2 parms'));
wenzelm@12502
   396
wenzelm@12502
   397
    fun inst_parms (i, ps) =
skalberg@15574
   398
      foldr Term.add_typ_tfrees [] (List.mapPartial snd ps)
skalberg@15570
   399
      |> List.mapPartial (fn (a, S) =>
wenzelm@12502
   400
          let val T = Envir.norm_type unifier' (TVar ((a, i), S))
skalberg@15531
   401
          in if T = TFree (a, S) then NONE else SOME ((a, S), T) end)
wenzelm@12502
   402
  in map inst_parms idx_parmss end;
wenzelm@12502
   403
wenzelm@12529
   404
in
wenzelm@12502
   405
ballarin@15206
   406
(* like unify_elemss, but does not touch axioms *)
ballarin@15206
   407
ballarin@15206
   408
fun unify_elemss' _ _ [] = []
ballarin@15206
   409
  | unify_elemss' _ [] [elems] = [elems]
ballarin@15206
   410
  | unify_elemss' ctxt fixed_parms elemss =
ballarin@15206
   411
      let
ballarin@15206
   412
        val envs = unify_parms ctxt fixed_parms (map (#2 o #1 o #1) elemss);
ballarin@15206
   413
        fun inst ((((name, ps), axs), elems), env) =
skalberg@15570
   414
          (((name, map (apsnd (Option.map (inst_type env))) ps),  axs),
ballarin@15206
   415
           map (inst_elem ctxt env) elems);
ballarin@15206
   416
      in map inst (elemss ~~ envs) end;
ballarin@15206
   417
wenzelm@12529
   418
fun unify_elemss _ _ [] = []
wenzelm@12529
   419
  | unify_elemss _ [] [elems] = [elems]
wenzelm@12529
   420
  | unify_elemss ctxt fixed_parms elemss =
wenzelm@12502
   421
      let
ballarin@15206
   422
        val envs = unify_parms ctxt fixed_parms (map (#2 o #1 o #1) elemss);
ballarin@15206
   423
        fun inst ((((name, ps), axs), elems), env) =
skalberg@15570
   424
          (((name, map (apsnd (Option.map (inst_type env))) ps), 
ballarin@15206
   425
            map (inst_thm ctxt env) axs), map (inst_elem ctxt env) elems);
wenzelm@12839
   426
      in map inst (elemss ~~ envs) end;
wenzelm@12502
   427
wenzelm@12575
   428
fun flatten_expr ctxt (prev_idents, expr) =
wenzelm@12014
   429
  let
wenzelm@12014
   430
    val thy = ProofContext.theory_of ctxt;
wenzelm@12263
   431
skalberg@15531
   432
    fun renaming (SOME x :: xs) (y :: ys) = (y, x) :: renaming xs ys
skalberg@15531
   433
      | renaming (NONE :: xs) (y :: ys) = renaming xs ys
wenzelm@12273
   434
      | renaming [] _ = []
wenzelm@12289
   435
      | renaming xs [] = raise ERROR_MESSAGE ("Too many arguments in renaming: " ^
skalberg@15531
   436
          commas (map (fn NONE => "_" | SOME x => quote x) xs));
wenzelm@12289
   437
ballarin@15206
   438
    fun rename_parms top ren ((name, ps), (parms, axs)) =
wenzelm@12289
   439
      let val ps' = map (rename ren) ps in
ballarin@15206
   440
        (case duplicates ps' of [] => ((name, ps'),
ballarin@15206
   441
          if top then (map (rename ren) parms, map (rename_thm ren) axs)
ballarin@15206
   442
          else (parms, axs))
wenzelm@12289
   443
        | dups => err_in_locale ctxt ("Duplicate parameters: " ^ commas_quote dups) [(name, ps')])
wenzelm@12289
   444
      end;
wenzelm@12263
   445
ballarin@15206
   446
    fun identify top (Locale name) =
ballarin@15212
   447
    (* CB: ids is a list of tuples of the form ((name, ps)  axs),
ballarin@15206
   448
       where name is a locale name, ps a list of parameter names and axs
ballarin@15206
   449
       a list of axioms relating to the identifier, axs is empty unless
ballarin@15206
   450
       identify at top level (top = true);
ballarin@14215
   451
       parms is accumulated list of parameters *)
wenzelm@12289
   452
          let
ballarin@15206
   453
            val {predicate = (_, axioms), import, params, ...} =
ballarin@15206
   454
              the_locale thy name;
wenzelm@12289
   455
            val ps = map #1 (#1 params);
ballarin@15206
   456
            val (ids', parms') = identify false import;
ballarin@15206
   457
                (* acyclic import dependencies *)
ballarin@15206
   458
            val ids'' = ids' @ [((name, ps), ([], []))];
ballarin@15206
   459
            val ids_ax = if top then snd
ballarin@15206
   460
                 (foldl_map (fn (axs, ((name, parms), _)) => let
ballarin@15206
   461
                   val {elems, ...} = the_locale thy name;
skalberg@15570
   462
                   val ts = List.concat (List.mapPartial (fn (Assumes asms, _) =>
skalberg@15570
   463
                     SOME (List.concat (map (map #1 o #2) asms)) | _ => NONE) elems);
ballarin@15206
   464
                   val (axs1, axs2) = splitAt (length ts, axs);
ballarin@15206
   465
                 in (axs2, ((name, parms), (ps, axs1))) end) (axioms, ids''))
ballarin@15206
   466
               else ids'';
ballarin@15206
   467
          in (ids_ax, merge_lists parms' ps) end
ballarin@15206
   468
      | identify top (Rename (e, xs)) =
wenzelm@12273
   469
          let
ballarin@15206
   470
            val (ids', parms') = identify top e;
wenzelm@12839
   471
            val ren = renaming xs parms'
ballarin@15206
   472
              handle ERROR_MESSAGE msg => err_in_locale' ctxt msg ids';
ballarin@15206
   473
            val ids'' = gen_distinct eq_fst (map (rename_parms top ren) ids');
skalberg@15570
   474
            val parms'' = distinct (List.concat (map (#2 o #1) ids''));
ballarin@15206
   475
          in (ids'', parms'') end
ballarin@15206
   476
      | identify top (Merge es) =
skalberg@15570
   477
          Library.foldl (fn ((ids, parms), e) => let
ballarin@15206
   478
                     val (ids', parms') = identify top e
ballarin@15206
   479
                   in (gen_merge_lists eq_fst ids ids',
ballarin@15206
   480
                       merge_lists parms parms') end)
ballarin@15206
   481
            (([], []), es);
wenzelm@12014
   482
ballarin@15206
   483
    (* CB: enrich identifiers by parameter types and 
ballarin@15206
   484
       the corresponding elements (with renamed parameters) *)
ballarin@15206
   485
ballarin@15206
   486
    fun eval ((name, xs), axs) =
wenzelm@12273
   487
      let
wenzelm@13308
   488
        val {params = (ps, qs), elems, ...} = the_locale thy name;
wenzelm@12307
   489
        val ren = filter_out (op =) (map #1 ps ~~ xs);
wenzelm@13308
   490
        val (params', elems') =
wenzelm@13308
   491
          if null ren then ((ps, qs), map #1 elems)
wenzelm@12502
   492
          else ((map (apfst (rename ren)) ps, map (rename ren) qs),
wenzelm@13308
   493
            map (rename_elem ren o #1) elems);
wenzelm@13375
   494
        val elems'' = map (rename_facts (space_implode "_" xs)) elems';
ballarin@15206
   495
      in (((name, params'), axs), elems'') end;
wenzelm@12307
   496
ballarin@15206
   497
    (* compute identifiers, merge with previous ones *)
ballarin@15206
   498
    val idents = gen_rems eq_fst (#1 (identify true expr), prev_idents);
ballarin@15206
   499
    (* add types to params, check for unique params and unify them *)
wenzelm@12575
   500
    val raw_elemss = unique_parms ctxt (map eval idents);
ballarin@15206
   501
    val elemss = unify_elemss' ctxt [] raw_elemss;
ballarin@15206
   502
    (* replace params in ids by params from axioms,
ballarin@15206
   503
       adjust types in axioms *)
ballarin@15206
   504
    val all_params' = params_of' elemss;
ballarin@15206
   505
    val all_params = param_types all_params';
ballarin@15206
   506
    val elemss' = map (fn (((name, _), (ps, axs)), elems) =>
ballarin@15206
   507
         (((name, map (fn p => (p, assoc (all_params, p))) ps), axs), elems))
ballarin@15206
   508
         elemss;
ballarin@15206
   509
    fun inst_ax th = let
ballarin@15206
   510
         val {hyps, prop, ...} = Thm.rep_thm th;
skalberg@15570
   511
         val ps = map (apsnd SOME) (Library.foldl Term.add_frees ([], prop :: hyps));
ballarin@15206
   512
         val [env] = unify_parms ctxt all_params [ps];
ballarin@15206
   513
         val th' = inst_thm ctxt env th;
ballarin@15206
   514
       in th' end;
ballarin@15206
   515
    val final_elemss = map (fn ((id, axs), elems) =>
ballarin@15206
   516
         ((id, map inst_ax axs), elems)) elemss';
ballarin@15206
   517
  in (prev_idents @ idents, final_elemss) end;
wenzelm@12046
   518
wenzelm@12510
   519
end;
wenzelm@12510
   520
wenzelm@12070
   521
wenzelm@12529
   522
(* activate elements *)
wenzelm@12273
   523
wenzelm@12510
   524
local
wenzelm@12510
   525
wenzelm@13399
   526
fun export_axioms axs _ hyps th =
wenzelm@13399
   527
  th |> Drule.satisfy_hyps axs
ballarin@15206
   528
     (* CB: replace meta-hyps, using axs, by a single meta-hyp. *)
wenzelm@13399
   529
  |> Drule.implies_intr_list (Library.drop (length axs, hyps))
ballarin@15206
   530
     (* CB: turn remaining hyps into assumptions. *)
ballarin@15206
   531
  |> Seq.single
wenzelm@12263
   532
wenzelm@14643
   533
fun activate_elem _ ((ctxt, axs), Fixes fixes) =
wenzelm@14643
   534
      ((ctxt |> ProofContext.add_fixes fixes, axs), [])
wenzelm@13399
   535
  | activate_elem _ ((ctxt, axs), Assumes asms) =
wenzelm@13399
   536
      let
skalberg@15570
   537
        val ts = List.concat (map (map #1 o #2) asms);
ballarin@15206
   538
        val (ps,qs) = splitAt (length ts, axs);
wenzelm@13420
   539
        val (ctxt', _) =
wenzelm@13399
   540
          ctxt |> ProofContext.fix_frees ts
nipkow@13629
   541
          |> ProofContext.assume_i (export_axioms ps) asms;
nipkow@13629
   542
      in ((ctxt', qs), []) end
wenzelm@13399
   543
  | activate_elem _ ((ctxt, axs), Defines defs) =
wenzelm@13420
   544
      let val (ctxt', _) =
wenzelm@13399
   545
        ctxt |> ProofContext.assume_i ProofContext.export_def
wenzelm@13399
   546
          (defs |> map (fn ((name, atts), (t, ps)) =>
wenzelm@13399
   547
            let val (c, t') = ProofContext.cert_def ctxt t
wenzelm@13399
   548
            in ((if name = "" then Thm.def_name c else name, atts), [(t', (ps, []))]) end))
wenzelm@13420
   549
      in ((ctxt', axs), []) end
wenzelm@13399
   550
  | activate_elem is_ext ((ctxt, axs), Notes facts) =
wenzelm@14564
   551
      let val (ctxt', res) = ctxt |> ProofContext.note_thmss_i facts
wenzelm@13420
   552
      in ((ctxt', axs), if is_ext then res else []) end;
wenzelm@12502
   553
ballarin@15206
   554
fun activate_elems (((name, ps), axs), elems) ctxt =
ballarin@15206
   555
  let val ((ctxt', _), res) =
wenzelm@13399
   556
    foldl_map (activate_elem (name = "")) ((ProofContext.qualified true ctxt, axs), elems)
wenzelm@13399
   557
      handle ProofContext.CONTEXT (msg, ctxt) => err_in_locale ctxt msg [(name, map fst ps)]
ballarin@15206
   558
  in (ProofContext.restore_qualified ctxt ctxt', res) end;
wenzelm@13399
   559
ballarin@15206
   560
fun activate_elemss prep_facts = foldl_map (fn (ctxt, (((name, ps), axs), raw_elems)) =>
wenzelm@12834
   561
  let
wenzelm@12834
   562
    val elems = map (prep_facts ctxt) raw_elems;
skalberg@15570
   563
    val (ctxt', res) = apsnd List.concat (activate_elems (((name, ps), axs), elems) ctxt);
ballarin@15206
   564
  in (ctxt', (((name, ps), elems), res)) end);
wenzelm@12834
   565
wenzelm@12546
   566
in
wenzelm@12546
   567
ballarin@15206
   568
(* CB: activate_facts prep_facts (ctxt, elemss),
ballarin@15206
   569
   where elemss is a list of pairs consisting of identifiers and
ballarin@15206
   570
   context elements, extends ctxt by the context elements yielding
ballarin@15206
   571
   ctxt' and returns (ctxt', (elemss', facts)).
ballarin@15206
   572
   Identifiers in the argument are of the form ((name, ps), axs) and
ballarin@15206
   573
   assumptions use the axioms in the identifiers to set up exporters
ballarin@15206
   574
   in ctxt'.  elemss' does not contain identifiers and is obtained
ballarin@15206
   575
   from elemss and the intermediate context with prep_facts.
ballarin@14508
   576
   If get_facts or get_facts_i is used for prep_facts, these also remove
ballarin@14508
   577
   the internal/external markers from elemss. *)
ballarin@14508
   578
wenzelm@13399
   579
fun activate_facts prep_facts arg =
skalberg@15570
   580
  apsnd (apsnd List.concat o Library.split_list) (activate_elemss prep_facts arg);
wenzelm@12546
   581
wenzelm@12510
   582
end;
wenzelm@12510
   583
wenzelm@12307
   584
wenzelm@12529
   585
(** prepare context elements **)
wenzelm@12529
   586
wenzelm@12529
   587
(* expressions *)
wenzelm@12529
   588
wenzelm@12529
   589
fun intern_expr sg (Locale xname) = Locale (intern sg xname)
wenzelm@12529
   590
  | intern_expr sg (Merge exprs) = Merge (map (intern_expr sg) exprs)
wenzelm@12529
   591
  | intern_expr sg (Rename (expr, xs)) = Rename (intern_expr sg expr, xs);
wenzelm@12529
   592
wenzelm@12529
   593
wenzelm@12546
   594
(* attributes *)
wenzelm@12546
   595
ballarin@15206
   596
local
ballarin@15206
   597
ballarin@15206
   598
fun read_att attrib (x, srcs) = (x, map attrib srcs)
wenzelm@12546
   599
ballarin@14508
   600
(* CB: Map attrib over
ballarin@14446
   601
   * A context element: add attrib to attribute lists of assumptions,
ballarin@14446
   602
     definitions and facts (on both sides for facts).
ballarin@14446
   603
   * Locale expression: no effect. *)
ballarin@14446
   604
ballarin@15206
   605
fun gen_map_attrib_elem _ (Fixes fixes) = Fixes fixes
ballarin@15206
   606
  | gen_map_attrib_elem attrib (Assumes asms) = Assumes (map (apfst (read_att attrib)) asms)
ballarin@15206
   607
  | gen_map_attrib_elem attrib (Defines defs) = Defines (map (apfst (read_att attrib)) defs)
ballarin@15206
   608
  | gen_map_attrib_elem attrib (Notes facts) =
ballarin@15127
   609
      Notes (map (apfst (read_att attrib) o apsnd (map (read_att attrib))) facts)
ballarin@15127
   610
ballarin@15206
   611
fun gen_map_attrib_elem_expr attrib (Elem elem) = Elem (gen_map_attrib_elem attrib elem)
ballarin@15206
   612
  | gen_map_attrib_elem_expr _ (Expr expr) = Expr expr;
ballarin@15206
   613
ballarin@15206
   614
in
ballarin@15206
   615
ballarin@15206
   616
val map_attrib_element = gen_map_attrib_elem;
ballarin@15206
   617
val map_attrib_element_i = gen_map_attrib_elem;
ballarin@15206
   618
val map_attrib_elem_or_expr = gen_map_attrib_elem_expr;
ballarin@15206
   619
val map_attrib_elem_or_expr_i = gen_map_attrib_elem_expr;
wenzelm@12546
   620
wenzelm@12546
   621
end;
wenzelm@12546
   622
wenzelm@12546
   623
wenzelm@12529
   624
(* parameters *)
wenzelm@12502
   625
wenzelm@12502
   626
local
wenzelm@12502
   627
wenzelm@12529
   628
fun prep_fixes prep_vars ctxt fixes =
wenzelm@12529
   629
  let val vars = snd (foldl_map prep_vars (ctxt, map (fn (x, T, _) => ([x], T)) fixes))
wenzelm@12529
   630
  in map (fn (([x'], T'), (_, _, mx)) => (x', T', mx)) (vars ~~ fixes) end;
wenzelm@12529
   631
wenzelm@12529
   632
in
wenzelm@12529
   633
wenzelm@12529
   634
fun read_fixes x = prep_fixes ProofContext.read_vars x;
wenzelm@12529
   635
fun cert_fixes x = prep_fixes ProofContext.cert_vars x;
wenzelm@12529
   636
wenzelm@12529
   637
end;
wenzelm@12529
   638
wenzelm@12529
   639
wenzelm@12529
   640
(* propositions and bindings *)
wenzelm@12529
   641
ballarin@15206
   642
(* CB: an internal (Int) locale element was either imported or included,
ballarin@15104
   643
   an external (Ext) element appears directly in the locale. *)
ballarin@15104
   644
wenzelm@12529
   645
datatype ('a, 'b) int_ext = Int of 'a | Ext of 'b;
wenzelm@12529
   646
ballarin@14508
   647
(* CB: flatten (ids, expr) normalises expr (which is either a locale
ballarin@14508
   648
   expression or a single context element) wrt.
ballarin@14508
   649
   to the list ids of already accumulated identifiers.
ballarin@14508
   650
   It returns (ids', elemss) where ids' is an extension of ids
ballarin@14508
   651
   with identifiers generated for expr, and elemss is the list of
ballarin@14508
   652
   context elements generated from expr, decorated with additional
ballarin@15206
   653
   information (for expr it is the identifier, where parameters additionially
ballarin@15206
   654
   contain type information (extracted from the locale record), for a Fixes
ballarin@15206
   655
   element, it is an identifier with name = "" and parameters with type
skalberg@15531
   656
   information NONE, for other elements it is simply ("", [])).
ballarin@15206
   657
   The implementation of activate_facts relies on identifier names being
ballarin@15206
   658
   empty strings for external elements.
ballarin@15206
   659
TODO: correct this comment wrt axioms. *)
ballarin@14508
   660
ballarin@14508
   661
fun flatten _ (ids, Elem (Fixes fixes)) =
skalberg@15531
   662
      (ids, [((("", map (rpair NONE o #1) fixes), []), Ext (Fixes fixes))])
ballarin@15206
   663
  | flatten _ (ids, Elem elem) = (ids, [((("", []), []), Ext elem)])
ballarin@14508
   664
  | flatten (ctxt, prep_expr) (ids, Expr expr) =
ballarin@14508
   665
      apsnd (map (apsnd Int)) (flatten_expr ctxt (ids, prep_expr expr));
ballarin@14508
   666
wenzelm@12529
   667
local
wenzelm@12529
   668
wenzelm@12839
   669
local
wenzelm@12839
   670
wenzelm@12727
   671
fun declare_int_elem (ctxt, Fixes fixes) =
wenzelm@12575
   672
      (ctxt |> ProofContext.add_fixes (map (fn (x, T, mx) =>
skalberg@15570
   673
        (x, Option.map (Term.map_type_tfree (TypeInfer.param 0)) T, mx)) fixes), [])
wenzelm@12727
   674
  | declare_int_elem (ctxt, _) = (ctxt, []);
wenzelm@12529
   675
wenzelm@12529
   676
fun declare_ext_elem prep_fixes (ctxt, Fixes fixes) =
wenzelm@12575
   677
      (ctxt |> ProofContext.add_fixes (prep_fixes ctxt fixes), [])
wenzelm@12529
   678
  | declare_ext_elem _ (ctxt, Assumes asms) = (ctxt, map #2 asms)
wenzelm@12529
   679
  | declare_ext_elem _ (ctxt, Defines defs) = (ctxt, map (fn (_, (t, ps)) => [(t, (ps, []))]) defs)
wenzelm@12529
   680
  | declare_ext_elem _ (ctxt, Notes facts) = (ctxt, []);
wenzelm@12529
   681
ballarin@15206
   682
fun declare_elems prep_fixes (ctxt, (((name, ps), _), elems)) =
wenzelm@12529
   683
  let val (ctxt', propps) =
wenzelm@12529
   684
    (case elems of
wenzelm@13308
   685
      Int es => foldl_map declare_int_elem (ctxt, es)
wenzelm@12546
   686
    | Ext e => foldl_map (declare_ext_elem prep_fixes) (ctxt, [e]))
wenzelm@12529
   687
    handle ProofContext.CONTEXT (msg, ctxt) => err_in_locale ctxt msg [(name, map fst ps)]
wenzelm@12727
   688
  in (ctxt', propps) end;
wenzelm@12727
   689
wenzelm@12839
   690
in
wenzelm@12839
   691
ballarin@14215
   692
(* CB: only called by prep_elemss. *)
ballarin@14215
   693
wenzelm@12727
   694
fun declare_elemss prep_fixes fixed_params raw_elemss ctxt =
wenzelm@12727
   695
  let
ballarin@14215
   696
    (* CB: fix of type bug of goal in target with context elements.
ballarin@14215
   697
       Parameters new in context elements must receive types that are
ballarin@14215
   698
       distinct from types of parameters in target (fixed_params).  *)
ballarin@14215
   699
    val ctxt_with_fixed =
ballarin@14215
   700
      ProofContext.declare_terms (map Free fixed_params) ctxt;
wenzelm@12727
   701
    val int_elemss =
wenzelm@12727
   702
      raw_elemss
skalberg@15570
   703
      |> List.mapPartial (fn (id, Int es) => SOME (id, es) | _ => NONE)
ballarin@14215
   704
      |> unify_elemss ctxt_with_fixed fixed_params;
wenzelm@12727
   705
    val (_, raw_elemss') =
wenzelm@12727
   706
      foldl_map (fn ((_, es) :: elemss, (id, Int _)) => (elemss, (id, Int es)) | x => x)
wenzelm@12727
   707
        (int_elemss, raw_elemss);
wenzelm@12727
   708
  in foldl_map (declare_elems prep_fixes) (ctxt, raw_elemss') end;
wenzelm@12529
   709
wenzelm@12839
   710
end;
wenzelm@12529
   711
wenzelm@12839
   712
local
wenzelm@12839
   713
ballarin@14508
   714
(* CB: following code (norm_term, abstract_term, abstract_thm, bind_def)
ballarin@14508
   715
   used in eval_text for defines elements. *)
ballarin@14508
   716
wenzelm@12839
   717
val norm_term = Envir.beta_norm oo Term.subst_atomic;
wenzelm@12839
   718
wenzelm@13336
   719
fun abstract_term eq =    (*assumes well-formedness according to ProofContext.cert_def*)
wenzelm@12839
   720
  let
wenzelm@12839
   721
    val body = Term.strip_all_body eq;
wenzelm@12839
   722
    val vars = map Free (Term.rename_wrt_term body (Term.strip_all_vars eq));
wenzelm@12839
   723
    val (lhs, rhs) = Logic.dest_equals (Term.subst_bounds (vars, body));
wenzelm@12839
   724
    val (f, xs) = Term.strip_comb lhs;
wenzelm@13336
   725
    val eq' = Term.list_abs_free (map Term.dest_Free xs, rhs);
wenzelm@13336
   726
  in (Term.dest_Free f, eq') end;
wenzelm@13336
   727
wenzelm@13336
   728
fun abstract_thm sign eq =
wenzelm@13336
   729
  Thm.assume (Thm.cterm_of sign eq) |> Drule.gen_all |> Drule.abs_def;
wenzelm@12502
   730
wenzelm@13336
   731
fun bind_def ctxt (name, ps) ((xs, env, ths), eq) =
wenzelm@12839
   732
  let
wenzelm@13336
   733
    val ((y, T), b) = abstract_term eq;
wenzelm@13308
   734
    val b' = norm_term env b;
wenzelm@13336
   735
    val th = abstract_thm (ProofContext.sign_of ctxt) eq;
wenzelm@13308
   736
    fun err msg = err_in_locale ctxt (msg ^ ": " ^ quote y) [(name, map fst ps)];
wenzelm@12839
   737
  in
wenzelm@13308
   738
    conditional (exists (equal y o #1) xs) (fn () =>
wenzelm@13308
   739
      err "Attempt to define previously specified variable");
wenzelm@13308
   740
    conditional (exists (fn (Free (y', _), _) => y = y' | _ => false) env) (fn () =>
wenzelm@13308
   741
      err "Attempt to redefine variable");
wenzelm@13336
   742
    (Term.add_frees (xs, b'), (Free (y, T), b') :: env, th :: ths)
wenzelm@12839
   743
  end;
wenzelm@12575
   744
ballarin@15206
   745
(* CB: for finish_elems (Int and Ext) *)
ballarin@15206
   746
wenzelm@13308
   747
fun eval_text _ _ _ (text, Fixes _) = text
wenzelm@13394
   748
  | eval_text _ _ is_ext ((((exts, exts'), (ints, ints')), (xs, env, defs)), Assumes asms) =
wenzelm@13394
   749
      let
skalberg@15570
   750
        val ts = List.concat (map (map #1 o #2) asms);
wenzelm@13394
   751
        val ts' = map (norm_term env) ts;
wenzelm@13394
   752
        val spec' =
wenzelm@13394
   753
          if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
wenzelm@13394
   754
          else ((exts, exts'), (ints @ ts, ints' @ ts'));
skalberg@15570
   755
      in (spec', (Library.foldl Term.add_frees (xs, ts'), env, defs)) end
ballarin@15206
   756
  | eval_text ctxt (id, _) _ ((spec, binds), Defines defs) =
skalberg@15570
   757
      (spec, Library.foldl (bind_def ctxt id) (binds, map (#1 o #2) defs))
wenzelm@13308
   758
  | eval_text _ _ _ (text, Notes _) = text;
wenzelm@13308
   759
ballarin@15206
   760
(* CB: for finish_elems (Ext) *)
ballarin@15206
   761
wenzelm@13308
   762
fun closeup _ false elem = elem
wenzelm@13308
   763
  | closeup ctxt true elem =
wenzelm@12839
   764
      let
wenzelm@13308
   765
        fun close_frees t =
wenzelm@13308
   766
          let val frees = rev (filter_out (ProofContext.is_fixed ctxt o #1)
wenzelm@13308
   767
            (Term.add_frees ([], t)))
wenzelm@13308
   768
          in Term.list_all_free (frees, t) end;
wenzelm@13308
   769
wenzelm@13308
   770
        fun no_binds [] = []
wenzelm@13308
   771
          | no_binds _ =
wenzelm@13308
   772
              raise ProofContext.CONTEXT ("Illegal term bindings in locale element", ctxt);
wenzelm@13308
   773
      in
wenzelm@13308
   774
        (case elem of
wenzelm@13308
   775
          Assumes asms => Assumes (asms |> map (fn (a, propps) =>
wenzelm@13308
   776
            (a, map (fn (t, (ps, qs)) => (close_frees t, (no_binds ps, no_binds qs))) propps)))
wenzelm@13308
   777
        | Defines defs => Defines (defs |> map (fn (a, (t, ps)) =>
wenzelm@13308
   778
            (a, (close_frees (#2 (ProofContext.cert_def ctxt t)), no_binds ps))))
wenzelm@13308
   779
        | e => e)
wenzelm@13308
   780
      end;
wenzelm@12839
   781
wenzelm@12502
   782
wenzelm@12839
   783
fun finish_ext_elem parms _ (Fixes fixes, _) = Fixes (map (fn (x, _, mx) =>
wenzelm@12727
   784
      (x, assoc_string (parms, x), mx)) fixes)
wenzelm@12839
   785
  | finish_ext_elem _ close (Assumes asms, propp) =
wenzelm@12839
   786
      close (Assumes (map #1 asms ~~ propp))
wenzelm@12839
   787
  | finish_ext_elem _ close (Defines defs, propp) =
wenzelm@12727
   788
      close (Defines (map #1 defs ~~ map (fn [(t, (ps, []))] => (t, ps)) propp))
wenzelm@12839
   789
  | finish_ext_elem _ _ (Notes facts, _) = Notes facts;
wenzelm@12839
   790
ballarin@15206
   791
(* CB: finish_parms introduces type info from parms to identifiers *)
skalberg@15531
   792
(* CB: only needed for types that have been NONE so far???
ballarin@15206
   793
   If so, which are these??? *)
ballarin@15206
   794
ballarin@15206
   795
fun finish_parms parms (((name, ps), axs), elems) =
ballarin@15206
   796
  (((name, map (fn (x, _) => (x, assoc (parms, x))) ps), axs), elems);
wenzelm@12839
   797
wenzelm@13375
   798
fun finish_elems ctxt parms _ (text, ((id, Int e), _)) =
wenzelm@12839
   799
      let
ballarin@15206
   800
        val [(id', es)] = unify_elemss ctxt parms [(id, e)];
skalberg@15570
   801
        val text' = Library.foldl (eval_text ctxt id' false) (text, es);
ballarin@15206
   802
      in (text', (id', map Int es)) end
wenzelm@13375
   803
  | finish_elems ctxt parms do_close (text, ((id, Ext e), [propp])) =
wenzelm@13308
   804
      let
wenzelm@13308
   805
        val e' = finish_ext_elem parms (closeup ctxt do_close) (e, propp);
wenzelm@13375
   806
        val text' = eval_text ctxt id true (text, e');
wenzelm@13308
   807
      in (text', (id, [Ext e'])) end;
wenzelm@12839
   808
wenzelm@12839
   809
in
wenzelm@12510
   810
ballarin@15206
   811
(* CB: only called by prep_elemss *)
ballarin@15206
   812
wenzelm@13375
   813
fun finish_elemss ctxt parms do_close =
wenzelm@13375
   814
  foldl_map (apsnd (finish_parms parms) o finish_elems ctxt parms do_close);
wenzelm@12839
   815
wenzelm@12839
   816
end;
wenzelm@12839
   817
ballarin@15127
   818
(* CB: type inference and consistency checks for locales *)
ballarin@15127
   819
wenzelm@13375
   820
fun prep_elemss prep_fixes prepp do_close context fixed_params raw_elemss raw_concl =
wenzelm@12529
   821
  let
ballarin@15127
   822
    (* CB: contexts computed in the course of this function are discarded.
ballarin@15127
   823
       They are used for type inference and consistency checks only. *)
ballarin@15206
   824
    (* CB: fixed_params are the parameters (with types) of the target locale,
ballarin@15206
   825
       empty list if there is no target. *)
ballarin@14508
   826
    (* CB: raw_elemss are list of pairs consisting of identifiers and
ballarin@14508
   827
       context elements, the latter marked as internal or external. *)
wenzelm@12727
   828
    val (raw_ctxt, raw_proppss) = declare_elemss prep_fixes fixed_params raw_elemss context;
ballarin@14508
   829
    (* CB: raw_ctxt is context with additional fixed variables derived from
ballarin@14508
   830
       the fixes elements in raw_elemss,
ballarin@14508
   831
       raw_proppss contains assumptions and definitions from the
ballarin@15206
   832
       external elements in raw_elemss. *)
skalberg@15570
   833
    val raw_propps = map List.concat raw_proppss;
skalberg@15570
   834
    val raw_propp = List.concat raw_propps;
ballarin@15206
   835
ballarin@15206
   836
    (* CB: add type information from fixed_params to context (declare_terms) *)
ballarin@15206
   837
    (* CB: process patterns (conclusion and external elements only) *)
wenzelm@12529
   838
    val (ctxt, all_propp) =
wenzelm@12529
   839
      prepp (ProofContext.declare_terms (map Free fixed_params) raw_ctxt, raw_concl @ raw_propp);
ballarin@15206
   840
    
ballarin@15206
   841
    (* CB: add type information from conclusion and external elements
ballarin@15206
   842
       to context *)
skalberg@15570
   843
    val ctxt = ProofContext.declare_terms (List.concat (map (map fst) all_propp)) ctxt;
wenzelm@12502
   844
ballarin@15206
   845
    (* CB: resolve schematic variables (patterns) in conclusion and external
ballarin@15206
   846
       elements. *)
wenzelm@12529
   847
    val all_propp' = map2 (op ~~)
wenzelm@12529
   848
      (#1 (#2 (ProofContext.bind_propp_schematic_i (ctxt, all_propp))), map (map snd) all_propp);
nipkow@13629
   849
    val (concl, propp) = splitAt(length raw_concl, all_propp');
wenzelm@12529
   850
    val propps = unflat raw_propps propp;
wenzelm@12839
   851
    val proppss = map (uncurry unflat) (raw_proppss ~~ propps);
wenzelm@12502
   852
ballarin@15206
   853
    (* CB: obtain all parameters from identifier part of raw_elemss *)
ballarin@15206
   854
    val xs = map #1 (params_of' raw_elemss);
wenzelm@12727
   855
    val typing = unify_frozen ctxt 0
wenzelm@12529
   856
      (map (ProofContext.default_type raw_ctxt) xs)
wenzelm@12529
   857
      (map (ProofContext.default_type ctxt) xs);
wenzelm@12529
   858
    val parms = param_types (xs ~~ typing);
ballarin@14508
   859
    (* CB: parms are the parameters from raw_elemss, with correct typing. *)
wenzelm@12273
   860
ballarin@14508
   861
    (* CB: extract information from assumes and defines elements
ballarin@14508
   862
       (fixes and notes in raw_elemss don't have an effect on text and elemss),
ballarin@14508
   863
       compute final form of context elements. *)
wenzelm@13394
   864
    val (text, elemss) = finish_elemss ctxt parms do_close
wenzelm@13394
   865
      (((([], []), ([], [])), ([], [], [])), raw_elemss ~~ proppss);
ballarin@14508
   866
    (* CB: text has the following structure:
ballarin@14508
   867
           (((exts, exts'), (ints, ints')), (xs, env, defs))
ballarin@14508
   868
       where
ballarin@14508
   869
         exts: external assumptions (terms in external assumes elements)
ballarin@14508
   870
         exts': dito, normalised wrt. env
ballarin@14508
   871
         ints: internal assumptions (terms in internal assumes elements)
ballarin@14508
   872
         ints': dito, normalised wrt. env
ballarin@14508
   873
         xs: the free variables in exts' and ints' and rhss of definitions,
ballarin@14508
   874
           this includes parameters except defined parameters
ballarin@14508
   875
         env: list of term pairs encoding substitutions, where the first term
ballarin@14508
   876
           is a free variable; substitutions represent defines elements and
ballarin@14508
   877
           the rhs is normalised wrt. the previous env
ballarin@14508
   878
         defs: theorems representing the substitutions from defines elements
ballarin@14508
   879
           (thms are normalised wrt. env).
ballarin@14508
   880
       elemss is an updated version of raw_elemss:
ballarin@14508
   881
         - type info added to Fixes
ballarin@14508
   882
         - axiom and definition statement replaced by corresponding one
ballarin@14508
   883
           from proppss in Assumes and Defines
ballarin@14508
   884
         - Facts unchanged
ballarin@14508
   885
       *)
wenzelm@13308
   886
  in ((parms, elemss, concl), text) end;
wenzelm@12502
   887
wenzelm@12502
   888
in
wenzelm@12502
   889
wenzelm@12529
   890
fun read_elemss x = prep_elemss read_fixes ProofContext.read_propp_schematic x;
wenzelm@12529
   891
fun cert_elemss x = prep_elemss cert_fixes ProofContext.cert_propp_schematic x;
wenzelm@12529
   892
wenzelm@12529
   893
end;
wenzelm@12529
   894
wenzelm@12529
   895
wenzelm@12529
   896
(* facts *)
wenzelm@12529
   897
wenzelm@12529
   898
local
wenzelm@12529
   899
wenzelm@12529
   900
fun prep_name ctxt (name, atts) =
ballarin@15206
   901
  (* CB: reject qualified theorem names in locale declarations *)
wenzelm@12529
   902
  if NameSpace.is_qualified name then
wenzelm@12529
   903
    raise ProofContext.CONTEXT ("Illegal qualified name: " ^ quote name, ctxt)
wenzelm@12529
   904
  else (name, atts);
wenzelm@12529
   905
wenzelm@13375
   906
fun prep_facts _ _ (Int elem) = elem
wenzelm@13375
   907
  | prep_facts _ _ (Ext (Fixes fixes)) = Fixes fixes
wenzelm@13375
   908
  | prep_facts _ ctxt (Ext (Assumes asms)) = Assumes (map (apfst (prep_name ctxt)) asms)
wenzelm@13375
   909
  | prep_facts _ ctxt (Ext (Defines defs)) = Defines (map (apfst (prep_name ctxt)) defs)
wenzelm@13375
   910
  | prep_facts get ctxt (Ext (Notes facts)) = Notes (facts |> map (fn (a, bs) =>
wenzelm@13375
   911
      (prep_name ctxt a, map (apfst (get ctxt)) bs)));
wenzelm@12529
   912
wenzelm@12529
   913
in
wenzelm@12529
   914
wenzelm@12529
   915
fun get_facts x = prep_facts ProofContext.get_thms x;
wenzelm@12529
   916
fun get_facts_i x = prep_facts (K I) x;
wenzelm@12529
   917
wenzelm@12529
   918
end;
wenzelm@12529
   919
wenzelm@12529
   920
wenzelm@12546
   921
(* full context statements: import + elements + conclusion *)
wenzelm@12529
   922
wenzelm@12529
   923
local
wenzelm@12529
   924
wenzelm@12529
   925
fun prep_context_statement prep_expr prep_elemss prep_facts
ballarin@15206
   926
    do_close fixed_params import elements raw_concl context =
wenzelm@12529
   927
  let
wenzelm@12529
   928
    val sign = ProofContext.sign_of context;
wenzelm@13375
   929
ballarin@14508
   930
    val (import_ids, raw_import_elemss) = flatten (context, prep_expr sign) ([], Expr import);
ballarin@14215
   931
    (* CB: normalise "includes" among elements *)
skalberg@15570
   932
    val raw_elemss = List.concat (#2 ((foldl_map (flatten (context, prep_expr sign))
ballarin@14508
   933
      (import_ids, elements))));
ballarin@14508
   934
    (* CB: raw_import_elemss @ raw_elemss is the normalised list of
ballarin@14508
   935
       context elements obtained from import and elements. *)
wenzelm@13375
   936
    val ((parms, all_elemss, concl), (spec, (_, _, defs))) = prep_elemss do_close
wenzelm@13336
   937
      context fixed_params (raw_import_elemss @ raw_elemss) raw_concl;
ballarin@15206
   938
    (* CB: all_elemss and parms contain the correct parameter types *)
nipkow@13629
   939
    val (ps,qs) = splitAt(length raw_import_elemss, all_elemss)
ballarin@15206
   940
    val (import_ctxt, (import_elemss, _)) =
ballarin@15206
   941
      activate_facts prep_facts (context, ps);
ballarin@14215
   942
ballarin@15206
   943
    val (ctxt, (elemss, _)) =
ballarin@15206
   944
      activate_facts prep_facts (import_ctxt, qs);
ballarin@15212
   945
    val stmt = gen_distinct Term.aconv
skalberg@15570
   946
       (List.concat (map (fn ((_, axs), _) =>
skalberg@15570
   947
         List.concat (map (#hyps o Thm.rep_thm) axs)) qs));
ballarin@15206
   948
    val cstmt = map (cterm_of sign) stmt;
wenzelm@12834
   949
  in
ballarin@15206
   950
    ((((import_ctxt, import_elemss), (ctxt, elemss)), (parms, spec, defs)), (cstmt, concl))
wenzelm@12834
   951
  end;
wenzelm@12529
   952
wenzelm@12529
   953
val gen_context = prep_context_statement intern_expr read_elemss get_facts;
wenzelm@12529
   954
val gen_context_i = prep_context_statement (K I) cert_elemss get_facts_i;
wenzelm@12529
   955
wenzelm@12529
   956
fun gen_statement prep_locale prep_ctxt raw_locale elems concl ctxt =
wenzelm@12529
   957
  let
wenzelm@12529
   958
    val thy = ProofContext.theory_of ctxt;
skalberg@15570
   959
    val locale = Option.map (prep_locale (Theory.sign_of thy)) raw_locale;
ballarin@15206
   960
    val (target_stmt, fixed_params, import) =
skalberg@15531
   961
      (case locale of NONE => ([], [], empty)
skalberg@15531
   962
      | SOME name =>
ballarin@15206
   963
          let val {predicate = (stmt, _), params = (ps, _), ...} =
ballarin@15206
   964
            the_locale thy name
ballarin@15206
   965
          in (stmt, param_types ps, Locale name) end);
ballarin@15206
   966
    val ((((locale_ctxt, _), (elems_ctxt, _)), _), (elems_stmt, concl')) =
ballarin@15206
   967
      prep_ctxt false fixed_params import elems concl ctxt;
ballarin@15206
   968
  in (locale, (target_stmt, elems_stmt), locale_ctxt, elems_ctxt, concl') end;
wenzelm@13399
   969
wenzelm@12529
   970
in
wenzelm@12529
   971
ballarin@15127
   972
(* CB: processing of locales for add_locale(_i) and print_locale *)
ballarin@15127
   973
  (* CB: arguments are: x->import, y->body (elements), z->context *)
ballarin@15206
   974
fun read_context x y z = #1 (gen_context true [] x (map Elem y) [] z);
ballarin@15206
   975
fun cert_context x y z = #1 (gen_context_i true [] x (map Elem y) [] z);
ballarin@14215
   976
ballarin@15127
   977
(* CB: processing of locales for note_thmss(_i),
ballarin@15127
   978
   Proof.multi_theorem(_i) and antiquotations with option "locale" *)
wenzelm@12529
   979
val read_context_statement = gen_statement intern gen_context;
wenzelm@12529
   980
val cert_context_statement = gen_statement (K I) gen_context_i;
wenzelm@12502
   981
wenzelm@12502
   982
end;
wenzelm@11896
   983
wenzelm@11896
   984
ballarin@14508
   985
(** CB: experimental instantiation mechanism **)
ballarin@14508
   986
ballarin@14528
   987
fun instantiate loc_name (prfx, attribs) raw_inst ctxt =
ballarin@14508
   988
  let
ballarin@14508
   989
    val thy = ProofContext.theory_of ctxt;
ballarin@14508
   990
    val sign = Theory.sign_of thy;
ballarin@14508
   991
    val tsig = Sign.tsig_of sign;
ballarin@14508
   992
    val cert = cterm_of sign;
ballarin@14508
   993
ballarin@14508
   994
    (** process the locale **)
ballarin@14508
   995
ballarin@15206
   996
    val {predicate = (_, axioms), params = (ps, _), ...} =
ballarin@14508
   997
      the_locale thy (intern sign loc_name);
ballarin@14508
   998
    val fixed_params = param_types ps;
ballarin@14528
   999
    val init = ProofContext.init thy;
ballarin@14508
  1000
    val (ids, raw_elemss) =
ballarin@14528
  1001
          flatten (init, intern_expr sign) ([], Expr (Locale loc_name));
ballarin@14508
  1002
    val ((parms, all_elemss, concl),
ballarin@14508
  1003
         (spec as (_, (ints, _)), (xs, env, defs))) =
ballarin@14528
  1004
      read_elemss false (* do_close *) init
ballarin@14508
  1005
        fixed_params (* could also put [] here??? *) raw_elemss
ballarin@14508
  1006
        [] (* concl *);
ballarin@14508
  1007
ballarin@14508
  1008
    (** analyse the instantiation theorem inst **)
ballarin@14508
  1009
ballarin@14508
  1010
    val inst = case raw_inst of
skalberg@15531
  1011
        NONE => if null ints
skalberg@15531
  1012
	  then NONE
ballarin@14508
  1013
	  else error "Locale has assumptions but no chained fact was found"
skalberg@15531
  1014
      | SOME [] => if null ints
skalberg@15531
  1015
	  then NONE
ballarin@14508
  1016
	  else error "Locale has assumptions but no chained fact was found"
skalberg@15531
  1017
      | SOME [thm] => if null ints
skalberg@15531
  1018
	  then (warning "Locale has no assumptions: fact ignored"; NONE)
skalberg@15531
  1019
	  else SOME thm
skalberg@15531
  1020
      | SOME _ => error "Multiple facts are not allowed";
ballarin@14508
  1021
ballarin@14508
  1022
    val args = case inst of
skalberg@15531
  1023
            NONE => []
skalberg@15531
  1024
          | SOME thm => thm |> prop_of |> ObjectLogic.drop_judgment sign
ballarin@14528
  1025
              |> Term.strip_comb
ballarin@14528
  1026
              |>> (fn t as (Const (s, _)) => if (intern sign loc_name = s)
ballarin@14528
  1027
                        then t
ballarin@14528
  1028
                        else error ("Constant " ^ quote loc_name ^
ballarin@14528
  1029
                          " expected but constant " ^ quote s ^ " was found")
ballarin@14528
  1030
                    | t => error ("Constant " ^ quote loc_name ^ " expected \
ballarin@14528
  1031
                          \but term " ^ quote (Sign.string_of_term sign t) ^
ballarin@14528
  1032
                          " was found"))
ballarin@14528
  1033
              |> snd;
ballarin@14508
  1034
    val cargs = map cert args;
ballarin@14508
  1035
ballarin@14508
  1036
    (* process parameters: match their types with those of arguments *)
ballarin@14508
  1037
ballarin@14508
  1038
    val def_names = map (fn (Free (s, _), _) => s) env;
skalberg@15570
  1039
    val (defined, assumed) = List.partition
ballarin@14508
  1040
          (fn (s, _) => s mem def_names) fixed_params;
ballarin@14508
  1041
    val cassumed = map (cert o Free) assumed;
ballarin@14508
  1042
    val cdefined = map (cert o Free) defined;
ballarin@14508
  1043
ballarin@14508
  1044
    val param_types = map snd assumed;
ballarin@14508
  1045
    val v_param_types = map Type.varifyT param_types;
ballarin@14508
  1046
    val arg_types = map Term.fastype_of args;
skalberg@15570
  1047
    val Tenv = Library.foldl (Type.typ_match tsig)
ballarin@14508
  1048
          (Vartab.empty, v_param_types ~~ arg_types)
skalberg@15570
  1049
          handle UnequalLengths => error "Number of parameters does not \
ballarin@14528
  1050
            \match number of arguments of chained fact";
ballarin@14508
  1051
    (* get their sorts *)
skalberg@15574
  1052
    val tfrees = foldr Term.add_typ_tfrees [] param_types
ballarin@14508
  1053
    val Tenv' = map
skalberg@15570
  1054
          (fn ((a, i), T) => ((a, valOf (assoc_string (tfrees, a))), T))
ballarin@14508
  1055
          (Vartab.dest Tenv);
ballarin@14508
  1056
ballarin@14508
  1057
    (* process (internal) elements *)
ballarin@14508
  1058
ballarin@14508
  1059
    fun inst_type [] T = T
ballarin@14508
  1060
      | inst_type env T =
skalberg@15570
  1061
          Term.map_type_tfree (fn v => getOpt (assoc (env, v), TFree v)) T;
ballarin@14508
  1062
ballarin@14508
  1063
    fun inst_term [] t = t
ballarin@14508
  1064
      | inst_term env t = Term.map_term_types (inst_type env) t;
ballarin@14508
  1065
ballarin@14508
  1066
    (* parameters with argument types *)
ballarin@14508
  1067
ballarin@14508
  1068
    val cparams' = map (cterm_of sign o inst_term Tenv' o term_of) cassumed;
ballarin@14508
  1069
    val cdefined' = map (cert o inst_term Tenv' o term_of) cdefined;
ballarin@14508
  1070
    val cdefining = map (cert o inst_term Tenv' o snd) env;
ballarin@14508
  1071
ballarin@14508
  1072
    fun inst_thm _ [] th = th
ballarin@14508
  1073
      | inst_thm ctxt Tenv th =
ballarin@14508
  1074
	  let
ballarin@14508
  1075
	    val sign = ProofContext.sign_of ctxt;
ballarin@14508
  1076
	    val cert = Thm.cterm_of sign;
ballarin@14508
  1077
	    val certT = Thm.ctyp_of sign;
ballarin@14508
  1078
	    val {hyps, prop, maxidx, ...} = Thm.rep_thm th;
skalberg@15574
  1079
	    val tfrees = foldr Term.add_term_tfree_names [] (prop :: hyps);
skalberg@15570
  1080
	    val Tenv' = List.filter (fn ((a, _), _) => a mem_string tfrees) Tenv;
ballarin@14508
  1081
	  in
ballarin@14508
  1082
	    if null Tenv' then th
ballarin@14508
  1083
	    else
ballarin@14508
  1084
	      th
ballarin@14508
  1085
	      |> Drule.implies_intr_list (map cert hyps)
ballarin@14508
  1086
	      |> Drule.tvars_intr_list (map (#1 o #1) Tenv')
ballarin@14508
  1087
	      |> (fn (th', al) => th' |>
ballarin@14508
  1088
		Thm.instantiate ((map (fn ((a, _), T) =>
skalberg@15570
  1089
                  (valOf (assoc (al, a)), certT T)) Tenv'), []))
ballarin@14508
  1090
	      |> (fn th'' => Drule.implies_elim_list th''
ballarin@14508
  1091
		  (map (Thm.assume o cert o inst_term Tenv') hyps))
ballarin@14508
  1092
	  end;
ballarin@14508
  1093
ballarin@14508
  1094
    fun inst_thm' thm =
ballarin@14508
  1095
      let
ballarin@14508
  1096
        (* not all axs are normally applicable *)
ballarin@14508
  1097
        val hyps = #hyps (rep_thm thm);
ballarin@14508
  1098
        val ass = map (fn ax => (prop_of ax, ax)) axioms;
skalberg@15570
  1099
        val axs' = Library.foldl (fn (axs, hyp) => 
skalberg@15531
  1100
              (case gen_assoc (op aconv) (ass, hyp) of NONE => axs
skalberg@15531
  1101
                 | SOME ax => axs @ [ax])) ([], hyps);
ballarin@14508
  1102
        val thm' = Drule.satisfy_hyps axs' thm;
ballarin@14508
  1103
        (* instantiate types *)
ballarin@14508
  1104
        val thm'' = inst_thm ctxt Tenv' thm';
ballarin@14508
  1105
        (* substitute arguments and discharge hypotheses *)
ballarin@14508
  1106
        val thm''' = case inst of
skalberg@15531
  1107
                NONE => thm''
skalberg@15531
  1108
              | SOME inst_thm => let
ballarin@14508
  1109
		    val hyps = #hyps (rep_thm thm'');
ballarin@14508
  1110
		    val th = thm'' |> implies_intr_hyps
ballarin@14508
  1111
		      |> forall_intr_list (cparams' @ cdefined')
ballarin@14508
  1112
		      |> forall_elim_list (cargs @ cdefining)
ballarin@14508
  1113
		    (* th has premises of the form either inst_thm or x==x *)
ballarin@14508
  1114
		    fun mk hyp = if Logic.is_equals hyp
ballarin@14508
  1115
			  then hyp |> Logic.dest_equals |> snd |> cert
ballarin@14508
  1116
				 |> reflexive
ballarin@14508
  1117
			  else inst_thm
ballarin@14508
  1118
                  in implies_elim_list th (map mk hyps)
ballarin@14508
  1119
                  end;
ballarin@14508
  1120
      in thm''' end;
ballarin@14508
  1121
ballarin@14528
  1122
    val prefix_fact =
ballarin@14528
  1123
      if prfx = "" then I
ballarin@14528
  1124
      else (fn "" => ""
ballarin@14528
  1125
             | s => NameSpace.append prfx s);
ballarin@14528
  1126
ballarin@14508
  1127
    fun inst_elem (ctxt, (Ext _)) = ctxt
ballarin@14508
  1128
      | inst_elem (ctxt, (Int (Notes facts))) =
ballarin@14508
  1129
              (* instantiate fact *)
ballarin@14508
  1130
          let val facts' =
ballarin@14528
  1131
                map (apsnd (map (apfst (map inst_thm')))) facts
ballarin@14528
  1132
		handle THM (msg, n, thms) => error ("Exception THM " ^
ballarin@14528
  1133
		  string_of_int n ^ " raised\n" ^
ballarin@14528
  1134
		  "Note: instantiate does not support old-style locales \
ballarin@14528
  1135
                  \declared with (open)\n" ^ msg ^ "\n" ^
ballarin@14528
  1136
		  cat_lines (map string_of_thm thms))
ballarin@14508
  1137
              (* rename fact *)
ballarin@14528
  1138
              val facts'' = map (apfst (apfst prefix_fact)) facts'
ballarin@14528
  1139
              (* add attributes *)
ballarin@14528
  1140
              val facts''' = map (apfst (apsnd (fn atts => atts @ attribs))) facts''
wenzelm@14564
  1141
          in fst (ProofContext.note_thmss_i facts''' ctxt)
ballarin@14508
  1142
          end
ballarin@14508
  1143
      | inst_elem (ctxt, (Int _)) = ctxt;
ballarin@14508
  1144
skalberg@15570
  1145
    fun inst_elems (ctxt, (id, elems)) = Library.foldl inst_elem (ctxt, elems);
ballarin@14508
  1146
skalberg@15570
  1147
    fun inst_elemss ctxt elemss = Library.foldl inst_elems (ctxt, elemss);
ballarin@14508
  1148
ballarin@14508
  1149
    (* main part *)
ballarin@14508
  1150
ballarin@14508
  1151
    val ctxt' = ProofContext.qualified true ctxt;
ballarin@14508
  1152
  in ProofContext.restore_qualified ctxt (inst_elemss ctxt' all_elemss)
ballarin@14508
  1153
  end;
ballarin@14508
  1154
wenzelm@11896
  1155
wenzelm@13336
  1156
(** define locales **)
wenzelm@13336
  1157
wenzelm@13336
  1158
(* print locale *)
wenzelm@12070
  1159
wenzelm@12758
  1160
fun print_locale thy import body =
wenzelm@12070
  1161
  let
wenzelm@12289
  1162
    val thy_ctxt = ProofContext.init thy;
wenzelm@13420
  1163
    val (((_, import_elemss), (ctxt, elemss)), _) = read_context import body thy_ctxt;
skalberg@15570
  1164
    val all_elems = List.concat (map #2 (import_elemss @ elemss));
wenzelm@12070
  1165
wenzelm@12307
  1166
    val prt_typ = Pretty.quote o ProofContext.pretty_typ ctxt;
wenzelm@12307
  1167
    val prt_term = Pretty.quote o ProofContext.pretty_term ctxt;
wenzelm@12307
  1168
    val prt_thm = Pretty.quote o ProofContext.pretty_thm ctxt;
wenzelm@12070
  1169
wenzelm@12070
  1170
    fun prt_syn syn =
skalberg@15531
  1171
      let val s = (case syn of NONE => "(structure)" | SOME mx => Syntax.string_of_mixfix mx)
wenzelm@12575
  1172
      in if s = "" then [] else [Pretty.brk 2, Pretty.str s] end;
skalberg@15531
  1173
    fun prt_fix (x, SOME T, syn) = Pretty.block (Pretty.str (x ^ " ::") :: Pretty.brk 1 ::
wenzelm@12070
  1174
          prt_typ T :: Pretty.brk 1 :: prt_syn syn)
skalberg@15531
  1175
      | prt_fix (x, NONE, syn) = Pretty.block (Pretty.str x :: Pretty.brk 1 :: prt_syn syn);
wenzelm@12070
  1176
wenzelm@12307
  1177
    fun prt_name "" = [Pretty.brk 1]
wenzelm@12307
  1178
      | prt_name name = [Pretty.str (ProofContext.cond_extern ctxt name ^ ":"), Pretty.brk 1];
wenzelm@12307
  1179
    fun prt_asm ((a, _), ts) = Pretty.block (prt_name a @ Pretty.breaks (map (prt_term o fst) ts));
wenzelm@12307
  1180
    fun prt_def ((a, _), (t, _)) = Pretty.block (prt_name a @ [prt_term t]);
wenzelm@12307
  1181
    fun prt_fact ((a, _), ths) = Pretty.block
skalberg@15570
  1182
      (prt_name a @ Pretty.breaks (map prt_thm (List.concat (map fst ths))));
wenzelm@12070
  1183
wenzelm@12289
  1184
    fun items _ [] = []
wenzelm@12289
  1185
      | items prfx (x :: xs) = Pretty.block [Pretty.str prfx, Pretty.brk 1, x] :: items "  and" xs;
wenzelm@12289
  1186
    fun prt_elem (Fixes fixes) = items "fixes" (map prt_fix fixes)
wenzelm@12289
  1187
      | prt_elem (Assumes asms) = items "assumes" (map prt_asm asms)
wenzelm@12289
  1188
      | prt_elem (Defines defs) = items "defines" (map prt_def defs)
wenzelm@12289
  1189
      | prt_elem (Notes facts) = items "notes" (map prt_fact facts);
wenzelm@12277
  1190
  in
wenzelm@13336
  1191
    Pretty.big_list "context elements:" (map (Pretty.chunks o prt_elem) all_elems)
wenzelm@13336
  1192
    |> Pretty.writeln
wenzelm@12277
  1193
  end;
wenzelm@12070
  1194
wenzelm@12070
  1195
wenzelm@12730
  1196
(* store results *)
wenzelm@11896
  1197
wenzelm@12706
  1198
local
wenzelm@12706
  1199
wenzelm@12702
  1200
fun hide_bound_names names thy =
wenzelm@12702
  1201
  thy |> PureThy.hide_thms false
wenzelm@12702
  1202
    (map (Sign.full_name (Theory.sign_of thy)) (filter_out (equal "") names));
wenzelm@12702
  1203
wenzelm@12958
  1204
in
wenzelm@12958
  1205
wenzelm@14564
  1206
fun note_thmss_qualified kind name args thy =
wenzelm@12706
  1207
  thy
wenzelm@13375
  1208
  |> Theory.add_path (Sign.base_name name)
wenzelm@14564
  1209
  |> PureThy.note_thmss_i (Drule.kind kind) args
wenzelm@12706
  1210
  |>> hide_bound_names (map (#1 o #1) args)
wenzelm@12706
  1211
  |>> Theory.parent_path;
wenzelm@12706
  1212
skalberg@15531
  1213
fun smart_note_thmss kind NONE = PureThy.note_thmss_i (Drule.kind kind)
skalberg@15531
  1214
  | smart_note_thmss kind (SOME (loc, _)) = note_thmss_qualified kind loc;
ballarin@14508
  1215
  (* CB: only used in Proof.finish_global. *)
wenzelm@12958
  1216
wenzelm@12958
  1217
end;
wenzelm@12958
  1218
wenzelm@12958
  1219
local
wenzelm@12958
  1220
wenzelm@12958
  1221
fun put_facts loc args thy =
wenzelm@12958
  1222
  let
ballarin@15206
  1223
    val {predicate, import, elems, params} = the_locale thy loc;
wenzelm@12958
  1224
    val note = Notes (map (fn ((a, more_atts), th_atts) =>
wenzelm@12958
  1225
      ((a, more_atts), map (apfst (map (curry Thm.name_thm a))) th_atts)) args);
ballarin@15206
  1226
  in thy |> put_locale loc {predicate = predicate, import = import, elems = elems @ [(note, stamp ())],
ballarin@15206
  1227
    params = params} end;
wenzelm@12958
  1228
wenzelm@14564
  1229
fun gen_note_thmss prep_locale get_thms kind raw_loc raw_args thy =
wenzelm@12706
  1230
  let
wenzelm@12706
  1231
    val thy_ctxt = ProofContext.init thy;
wenzelm@12706
  1232
    val loc = prep_locale (Theory.sign_of thy) raw_loc;
ballarin@15206
  1233
    val (_, (stmt, _), loc_ctxt, _, _) =
skalberg@15531
  1234
      cert_context_statement (SOME loc) [] [] thy_ctxt;
wenzelm@12706
  1235
    val args = map (apsnd (map (apfst (get_thms loc_ctxt)))) raw_args;
ballarin@15206
  1236
    val export = ProofContext.export_standard stmt loc_ctxt thy_ctxt;
wenzelm@14564
  1237
    val results = map (map export o #2) (#2 (ProofContext.note_thmss_i args loc_ctxt));
wenzelm@12706
  1238
    val args' = map (rpair [] o #1 o #1) args ~~ map (single o Thm.no_attributes) results;
wenzelm@12706
  1239
  in
wenzelm@12706
  1240
    thy
wenzelm@12706
  1241
    |> put_facts loc args
wenzelm@14564
  1242
    |> note_thmss_qualified kind loc args'
wenzelm@12706
  1243
  end;
wenzelm@12706
  1244
wenzelm@12706
  1245
in
wenzelm@12706
  1246
ballarin@15206
  1247
(* CB: note_thmss(_i) is the base for the Isar commands
ballarin@15206
  1248
   "theorems (in loc)" and "declare (in loc)". *)
ballarin@15206
  1249
wenzelm@14564
  1250
val note_thmss = gen_note_thmss intern ProofContext.get_thms;
wenzelm@14564
  1251
val note_thmss_i = gen_note_thmss (K I) (K I);
ballarin@15206
  1252
ballarin@15206
  1253
(* CB: only used in Proof.finish_global. *)
wenzelm@12711
  1254
wenzelm@13336
  1255
fun add_thmss loc args (thy, ctxt) =
wenzelm@12958
  1256
  let
wenzelm@12958
  1257
    val args' = map (fn ((a, ths), atts) => ((a, atts), [(ths, [])])) args;
wenzelm@13336
  1258
    val thy' = put_facts loc args' thy;
ballarin@15206
  1259
    val (ctxt', (_, facts')) =
ballarin@15206
  1260
      activate_facts (K I) (ctxt, [((("", []), []), [Notes args'])]);
wenzelm@13420
  1261
  in ((thy', ctxt'), facts') end;
wenzelm@12702
  1262
wenzelm@12706
  1263
end;
wenzelm@12063
  1264
wenzelm@11896
  1265
wenzelm@13336
  1266
(* predicate text *)
ballarin@15104
  1267
(* CB: generate locale predicates (and delta predicates) *)
wenzelm@13336
  1268
wenzelm@13375
  1269
local
wenzelm@13375
  1270
ballarin@15206
  1271
(* introN: name of theorems for introduction rules of locale and
ballarin@15206
  1272
     delta predicates;
ballarin@15206
  1273
   axiomsN: name of theorem set with destruct rules for locale predicates,
ballarin@15206
  1274
     also name suffix of delta predicates. *)
ballarin@15206
  1275
wenzelm@13375
  1276
val introN = "intro";
ballarin@15206
  1277
val axiomsN = "axioms";
wenzelm@13375
  1278
wenzelm@13375
  1279
fun atomize_spec sign ts =
wenzelm@13375
  1280
  let
skalberg@15574
  1281
    val t = foldr1 Logic.mk_conjunction ts;
wenzelm@13375
  1282
    val body = ObjectLogic.atomize_term sign t;
wenzelm@13375
  1283
    val bodyT = Term.fastype_of body;
wenzelm@13375
  1284
  in
wenzelm@13375
  1285
    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of sign t))
wenzelm@13375
  1286
    else (body, bodyT, ObjectLogic.atomize_rule sign (Thm.cterm_of sign t))
wenzelm@13375
  1287
  end;
wenzelm@13375
  1288
wenzelm@13394
  1289
fun aprop_tr' n c = (c, fn args =>
wenzelm@13394
  1290
  if length args = n then Syntax.const "_aprop" $ Term.list_comb (Syntax.free c, args)
wenzelm@13394
  1291
  else raise Match);
wenzelm@13336
  1292
ballarin@15104
  1293
(* CB: define one predicate including its intro rule and axioms
ballarin@15104
  1294
   - bname: predicate name
ballarin@15104
  1295
   - parms: locale parameters
ballarin@15104
  1296
   - defs: thms representing substitutions from defines elements
ballarin@15104
  1297
   - ts: terms representing locale assumptions (not normalised wrt. defs)
ballarin@15104
  1298
   - norm_ts: terms representing locale assumptions (normalised wrt. defs)
ballarin@15104
  1299
   - thy: the theory
ballarin@15104
  1300
*)
ballarin@15104
  1301
wenzelm@13420
  1302
fun def_pred bname parms defs ts norm_ts thy =
wenzelm@13375
  1303
  let
wenzelm@13375
  1304
    val sign = Theory.sign_of thy;
wenzelm@13375
  1305
    val name = Sign.full_name sign bname;
wenzelm@13375
  1306
wenzelm@13420
  1307
    val (body, bodyT, body_eq) = atomize_spec sign norm_ts;
wenzelm@13394
  1308
    val env = Term.add_term_free_names (body, []);
skalberg@15570
  1309
    val xs = List.filter (fn (x, _) => x mem_string env) parms;
wenzelm@13394
  1310
    val Ts = map #2 xs;
skalberg@15574
  1311
    val extraTs = (Term.term_tfrees body \\ foldr Term.add_typ_tfrees [] Ts)
wenzelm@13394
  1312
      |> Library.sort_wrt #1 |> map TFree;
wenzelm@13399
  1313
    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
wenzelm@13336
  1314
wenzelm@13394
  1315
    val args = map Logic.mk_type extraTs @ map Free xs;
wenzelm@13394
  1316
    val head = Term.list_comb (Const (name, predT), args);
wenzelm@13375
  1317
    val statement = ObjectLogic.assert_propT sign head;
wenzelm@13375
  1318
wenzelm@13375
  1319
    val (defs_thy, [pred_def]) =
wenzelm@13375
  1320
      thy
wenzelm@13394
  1321
      |> (if bodyT <> propT then I else
wenzelm@13394
  1322
        Theory.add_trfuns ([], [], map (aprop_tr' (length args)) (NameSpace.accesses' name), []))
wenzelm@13375
  1323
      |> Theory.add_consts_i [(bname, predT, Syntax.NoSyn)]
wenzelm@13375
  1324
      |> PureThy.add_defs_i false [((Thm.def_name bname, Logic.mk_equals (head, body)), [])];
wenzelm@13394
  1325
wenzelm@13375
  1326
    val defs_sign = Theory.sign_of defs_thy;
wenzelm@13375
  1327
    val cert = Thm.cterm_of defs_sign;
wenzelm@13375
  1328
wenzelm@13420
  1329
    val intro = Tactic.prove_standard defs_sign [] norm_ts statement (fn _ =>
wenzelm@13375
  1330
      Tactic.rewrite_goals_tac [pred_def] THEN
wenzelm@13375
  1331
      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
wenzelm@13420
  1332
      Tactic.compose_tac (false, Drule.conj_intr_list (map (Thm.assume o cert) norm_ts), 0) 1);
wenzelm@13375
  1333
wenzelm@13375
  1334
    val conjuncts =
wenzelm@13399
  1335
      Drule.equal_elim_rule1 OF [Thm.symmetric body_eq,
wenzelm@13399
  1336
        Tactic.rewrite_rule [pred_def] (Thm.assume (cert statement))]
wenzelm@13375
  1337
      |> Drule.conj_elim_precise (length ts);
wenzelm@13394
  1338
    val axioms = (ts ~~ conjuncts) |> map (fn (t, ax) =>
wenzelm@13375
  1339
      Tactic.prove defs_sign [] [] t (fn _ =>
wenzelm@13375
  1340
        Tactic.rewrite_goals_tac defs THEN
wenzelm@13375
  1341
        Tactic.compose_tac (false, ax, 0) 1));
wenzelm@13394
  1342
  in (defs_thy, (statement, intro, axioms)) end;
wenzelm@13375
  1343
ballarin@15104
  1344
(* CB: modify the locale elements:
ballarin@15104
  1345
   - assume elements become notes elements,
ballarin@15104
  1346
   - notes elements are lifted
ballarin@15104
  1347
*)
ballarin@15104
  1348
wenzelm@13394
  1349
fun change_elem _ (axms, Assumes asms) =
wenzelm@13394
  1350
      apsnd Notes ((axms, asms) |> foldl_map (fn (axs, (a, spec)) =>
nipkow@13629
  1351
        let val (ps,qs) = splitAt(length spec, axs)
nipkow@13629
  1352
        in (qs, (a, [(ps, [])])) end))
wenzelm@13394
  1353
  | change_elem f (axms, Notes facts) = (axms, Notes (map (apsnd (map (apfst (map f)))) facts))
wenzelm@13394
  1354
  | change_elem _ e = e;
wenzelm@13394
  1355
ballarin@15206
  1356
(* CB: changes only "new" elems, these have identifier ("", _). *)
ballarin@15206
  1357
wenzelm@13394
  1358
fun change_elemss axioms elemss = (axioms, elemss) |> foldl_map
wenzelm@13394
  1359
  (fn (axms, (id as ("", _), es)) =>
wenzelm@13394
  1360
    foldl_map (change_elem (Drule.satisfy_hyps axioms)) (axms, es) |> apsnd (pair id)
wenzelm@13394
  1361
  | x => x) |> #2;
wenzelm@13394
  1362
wenzelm@13394
  1363
in
wenzelm@13375
  1364
ballarin@15104
  1365
(* CB: main predicate definition function *)
ballarin@15104
  1366
wenzelm@13394
  1367
fun define_preds bname (parms, ((exts, exts'), (ints, ints')), defs) elemss thy =
wenzelm@13394
  1368
  let
wenzelm@13394
  1369
    val (thy', (elemss', more_ts)) =
skalberg@15531
  1370
      if null exts then (thy, (elemss, []))
wenzelm@13394
  1371
      else
wenzelm@13394
  1372
        let
skalberg@15531
  1373
          val aname = if null ints then bname else bname ^ "_" ^ axiomsN;
wenzelm@13394
  1374
          val (def_thy, (statement, intro, axioms)) =
wenzelm@13394
  1375
            thy |> def_pred aname parms defs exts exts';
wenzelm@13394
  1376
          val elemss' = change_elemss axioms elemss @
wenzelm@13420
  1377
            [(("", []), [Assumes [((bname ^ "_" ^ axiomsN, []), [(statement, ([], []))])]])];
wenzelm@13394
  1378
        in
wenzelm@14564
  1379
          def_thy |> note_thmss_qualified "" aname
ballarin@14254
  1380
            [((introN, []), [([intro], [])])]
wenzelm@13394
  1381
          |> #1 |> rpair (elemss', [statement])
wenzelm@13394
  1382
        end;
ballarin@15206
  1383
    val (thy'', predicate) =
skalberg@15531
  1384
      if null ints then (thy', ([], []))
wenzelm@13394
  1385
      else
wenzelm@13394
  1386
        let
wenzelm@13394
  1387
          val (def_thy, (statement, intro, axioms)) =
wenzelm@13394
  1388
            thy' |> def_pred bname parms defs (ints @ more_ts) (ints' @ more_ts);
wenzelm@13399
  1389
          val cstatement = Thm.cterm_of (Theory.sign_of def_thy) statement;
wenzelm@13394
  1390
        in
wenzelm@14564
  1391
          def_thy |> note_thmss_qualified "" bname
ballarin@14254
  1392
            [((introN, []), [([intro], [])]),
ballarin@14254
  1393
             ((axiomsN, []), [(map Drule.standard axioms, [])])]
wenzelm@13415
  1394
          |> #1 |> rpair ([cstatement], axioms)
wenzelm@13394
  1395
        end;
ballarin@15206
  1396
  in (thy'', (elemss', predicate)) end;
wenzelm@13375
  1397
wenzelm@13375
  1398
end;
wenzelm@13336
  1399
wenzelm@13336
  1400
wenzelm@13297
  1401
(* add_locale(_i) *)
wenzelm@13297
  1402
wenzelm@13297
  1403
local
wenzelm@13297
  1404
wenzelm@13394
  1405
fun gen_add_locale prep_ctxt prep_expr do_pred bname raw_import raw_body thy =
ballarin@14528
  1406
  (* CB: do_pred = false means old-style locale, declared with (open).
ballarin@14528
  1407
     Old-style locales don't define predicates. *)
wenzelm@13297
  1408
  let
wenzelm@13297
  1409
    val sign = Theory.sign_of thy;
wenzelm@13297
  1410
    val name = Sign.full_name sign bname;
skalberg@15570
  1411
    val _ = conditional (isSome (get_locale thy name)) (fn () =>
wenzelm@13297
  1412
      error ("Duplicate definition of locale " ^ quote name));
wenzelm@13297
  1413
wenzelm@13297
  1414
    val thy_ctxt = ProofContext.init thy;
wenzelm@13420
  1415
    val (((import_ctxt, import_elemss), (body_ctxt, body_elemss)), text) =
wenzelm@13375
  1416
      prep_ctxt raw_import raw_body thy_ctxt;
wenzelm@13375
  1417
    val elemss = import_elemss @ body_elemss;
wenzelm@13297
  1418
ballarin@15206
  1419
    val (pred_thy, (elemss', predicate as (predicate_statement, predicate_axioms))) =
wenzelm@13394
  1420
      if do_pred then thy |> define_preds bname text elemss
wenzelm@13415
  1421
      else (thy, (elemss, ([], [])));
wenzelm@13375
  1422
    val pred_ctxt = ProofContext.init pred_thy;
wenzelm@13420
  1423
ballarin@15206
  1424
    fun axiomify axioms elemss = 
ballarin@15206
  1425
      (axioms, elemss) |> foldl_map (fn (axs, (id, elems)) => let
skalberg@15570
  1426
                   val ts = List.concat (List.mapPartial (fn (Assumes asms) =>
skalberg@15570
  1427
                     SOME (List.concat (map (map #1 o #2) asms)) | _ => NONE) elems);
ballarin@15206
  1428
                   val (axs1, axs2) = splitAt (length ts, axs);
ballarin@15206
  1429
                 in (axs2, ((id, axs1), elems)) end)
ballarin@15206
  1430
        |> snd;
ballarin@15206
  1431
    val (ctxt, (_, facts)) = activate_facts (K I)
ballarin@15206
  1432
      (pred_ctxt, axiomify predicate_axioms elemss');
ballarin@15206
  1433
    val export = ProofContext.export_standard predicate_statement ctxt pred_ctxt;
wenzelm@13420
  1434
    val facts' = facts |> map (fn (a, ths) => ((a, []), [(map export ths, [])]));
wenzelm@13297
  1435
  in
wenzelm@13375
  1436
    pred_thy
wenzelm@14564
  1437
    |> note_thmss_qualified "" name facts' |> #1
wenzelm@13297
  1438
    |> declare_locale name
ballarin@15206
  1439
    |> put_locale name {predicate = predicate, import = prep_expr sign raw_import,
skalberg@15570
  1440
        elems = map (fn e => (e, stamp ())) (List.concat (map #2 (List.filter (equal "" o #1 o #1) elemss'))),
ballarin@15206
  1441
        params = (params_of elemss', map #1 (params_of body_elemss))}
wenzelm@13297
  1442
  end;
wenzelm@13297
  1443
wenzelm@13297
  1444
in
wenzelm@13297
  1445
wenzelm@13297
  1446
val add_locale = gen_add_locale read_context intern_expr;
ballarin@14215
  1447
wenzelm@13297
  1448
val add_locale_i = gen_add_locale cert_context (K I);
wenzelm@13297
  1449
wenzelm@13297
  1450
end;
wenzelm@13297
  1451
wenzelm@13297
  1452
wenzelm@12730
  1453
wenzelm@11896
  1454
(** locale theory setup **)
wenzelm@12063
  1455
wenzelm@11896
  1456
val setup =
wenzelm@13460
  1457
 [LocalesData.init,
skalberg@15531
  1458
  add_locale_i true "var" empty [Fixes [(Syntax.internal "x", NONE, SOME Syntax.NoSyn)]],
skalberg@15531
  1459
  add_locale_i true "struct" empty [Fixes [(Syntax.internal "S", NONE, NONE)]]];
wenzelm@11896
  1460
wenzelm@11896
  1461
end;