src/Pure/Isar/locale.ML
author wenzelm
Fri Dec 14 22:28:52 2001 +0100 (2001-12-14)
changeset 12510 172d18ec3b54
parent 12502 9e7f72e25022
child 12514 4bdbc5a977f6
permissions -rw-r--r--
proper treatment of internal parameters;
wenzelm@12014
     1
(*  Title:      Pure/Isar/locale.ML
wenzelm@11896
     2
    ID:         $Id$
wenzelm@11896
     3
    Author:     Markus Wenzel, TU Muenchen
wenzelm@11896
     4
    License:    GPL (GNU GENERAL PUBLIC LICENSE)
wenzelm@11896
     5
wenzelm@12058
     6
Locales -- Isar proof contexts as meta-level predicates, with local
wenzelm@12289
     7
syntax and implicit structures.  Draws some basic ideas from Florian
wenzelm@12289
     8
Kammüller's original version of locales, but uses the richer
wenzelm@12063
     9
infrastructure of Isar instead of the raw meta-logic.
wenzelm@11896
    10
*)
wenzelm@11896
    11
wenzelm@11896
    12
signature LOCALE =
wenzelm@11896
    13
sig
wenzelm@12046
    14
  type context
wenzelm@12046
    15
  datatype ('typ, 'term, 'fact, 'att) elem =
wenzelm@12058
    16
    Fixes of (string * 'typ option * mixfix option) list |
wenzelm@12046
    17
    Assumes of ((string * 'att list) * ('term * ('term list * 'term list)) list) list |
wenzelm@12046
    18
    Defines of ((string * 'att list) * ('term * 'term list)) list |
wenzelm@12273
    19
    Notes of ((string * 'att list) * ('fact * 'att list) list) list
wenzelm@12273
    20
  datatype expr =
wenzelm@12273
    21
    Locale of string |
wenzelm@12273
    22
    Rename of expr * string option list |
wenzelm@12273
    23
    Merge of expr list
wenzelm@12273
    24
  val empty: expr
wenzelm@12273
    25
  datatype ('typ, 'term, 'fact, 'att) elem_expr =
wenzelm@12273
    26
    Elem of ('typ, 'term, 'fact, 'att) elem | Expr of expr
wenzelm@12046
    27
  type 'att element
wenzelm@12046
    28
  type 'att element_i
wenzelm@12046
    29
  type locale
wenzelm@12046
    30
  val intern: Sign.sg -> xstring -> string
wenzelm@12014
    31
  val cond_extern: Sign.sg -> string -> xstring
wenzelm@12502
    32
  val the_locale: theory -> string -> locale
wenzelm@12273
    33
  val attribute: ('att -> context attribute) -> ('typ, 'term, 'thm, 'att) elem_expr
wenzelm@12273
    34
    -> ('typ, 'term, 'thm, context attribute) elem_expr
wenzelm@12510
    35
  val activate_context: expr * context attribute element list -> context -> context * context
wenzelm@12510
    36
  val activate_context_i: expr * context attribute element_i list -> context -> context * context
wenzelm@12273
    37
  val add_locale: bstring -> expr -> context attribute element list -> theory -> theory
wenzelm@12273
    38
  val add_locale_i: bstring -> expr -> context attribute element_i list -> theory -> theory
wenzelm@12289
    39
  val print_locales: theory -> unit
wenzelm@12289
    40
  val print_locale: theory -> expr -> unit
wenzelm@12273
    41
  val add_thmss: string -> ((string * thm list) * context attribute list) list -> theory -> theory
wenzelm@11896
    42
  val setup: (theory -> theory) list
wenzelm@11896
    43
end;
wenzelm@11896
    44
wenzelm@12289
    45
structure Locale: LOCALE =
wenzelm@11896
    46
struct
wenzelm@11896
    47
wenzelm@12273
    48
(** locale elements and expressions **)
wenzelm@11896
    49
wenzelm@12014
    50
type context = ProofContext.context;
wenzelm@11896
    51
wenzelm@12046
    52
datatype ('typ, 'term, 'fact, 'att) elem =
wenzelm@12058
    53
  Fixes of (string * 'typ option * mixfix option) list |
wenzelm@12046
    54
  Assumes of ((string * 'att list) * ('term * ('term list * 'term list)) list) list |
wenzelm@12046
    55
  Defines of ((string * 'att list) * ('term * 'term list)) list |
wenzelm@12273
    56
  Notes of ((string * 'att list) * ('fact * 'att list) list) list;
wenzelm@12273
    57
wenzelm@12273
    58
datatype expr =
wenzelm@12273
    59
  Locale of string |
wenzelm@12273
    60
  Rename of expr * string option list |
wenzelm@12273
    61
  Merge of expr list;
wenzelm@11896
    62
wenzelm@12273
    63
val empty = Merge [];
wenzelm@12273
    64
wenzelm@12273
    65
datatype ('typ, 'term, 'fact, 'att) elem_expr =
wenzelm@12273
    66
  Elem of ('typ, 'term, 'fact, 'att) elem | Expr of expr;
wenzelm@12273
    67
wenzelm@12273
    68
type 'att element = (string, string, string, 'att) elem_expr;
wenzelm@12273
    69
type 'att element_i = (typ, term, thm list, 'att) elem_expr;
wenzelm@12070
    70
wenzelm@12070
    71
type locale =
wenzelm@12289
    72
 {import: expr,                                                         (*dynamic import*)
wenzelm@12289
    73
  elems: ((typ, term, thm list, context attribute) elem * stamp) list,  (*static content*)
wenzelm@12502
    74
  params: (string * typ option) list * string list,                     (*all vs. local params*)
wenzelm@12289
    75
  text: (string * typ) list * term list}                                (*logical representation*)
wenzelm@12063
    76
wenzelm@12289
    77
fun make_locale import elems params text =
wenzelm@12289
    78
 {import = import, elems = elems, params = params, text = text}: locale;
wenzelm@12063
    79
wenzelm@11896
    80
wenzelm@11896
    81
wenzelm@11896
    82
(** theory data **)
wenzelm@11896
    83
wenzelm@11896
    84
structure LocalesArgs =
wenzelm@11896
    85
struct
wenzelm@12014
    86
  val name = "Isar/locales";
wenzelm@12063
    87
  type T = NameSpace.T * locale Symtab.table;
wenzelm@11896
    88
wenzelm@12063
    89
  val empty = (NameSpace.empty, Symtab.empty);
wenzelm@12063
    90
  val copy = I;
wenzelm@12118
    91
  val prep_ext = I;
wenzelm@12289
    92
wenzelm@12289
    93
  (*joining of locale elements: only facts may be added later!*)
wenzelm@12289
    94
  fun join ({import, elems, params, text}: locale, {elems = elems', ...}: locale) =
wenzelm@12289
    95
    Some (make_locale import (gen_merge_lists eq_snd elems elems') params text);
wenzelm@12273
    96
  fun merge ((space1, locs1), (space2, locs2)) =
wenzelm@12289
    97
    (NameSpace.merge (space1, space2), Symtab.join join (locs1, locs2));
wenzelm@12289
    98
wenzelm@12273
    99
  fun print _ (space, locs) =
wenzelm@12273
   100
    Pretty.strs ("locales:" :: map (NameSpace.cond_extern space o #1) (Symtab.dest locs))
wenzelm@12014
   101
    |> Pretty.writeln;
wenzelm@11896
   102
end;
wenzelm@11896
   103
wenzelm@11896
   104
structure LocalesData = TheoryDataFun(LocalesArgs);
wenzelm@11896
   105
val print_locales = LocalesData.print;
wenzelm@11896
   106
wenzelm@12289
   107
val intern = NameSpace.intern o #1 o LocalesData.get_sg;
wenzelm@12289
   108
val cond_extern = NameSpace.cond_extern o #1 o LocalesData.get_sg;
wenzelm@12289
   109
wenzelm@12277
   110
wenzelm@12277
   111
(* access locales *)
wenzelm@12277
   112
wenzelm@12063
   113
fun declare_locale name =
wenzelm@12063
   114
  LocalesData.map (apfst (fn space => (NameSpace.extend (space, [name]))));
wenzelm@11896
   115
wenzelm@12273
   116
fun put_locale name loc = LocalesData.map (apsnd (fn locs => Symtab.update ((name, loc), locs)));
wenzelm@12063
   117
fun get_locale thy name = Symtab.lookup (#2 (LocalesData.get thy), name);
wenzelm@11896
   118
wenzelm@12014
   119
fun the_locale thy name =
wenzelm@12014
   120
  (case get_locale thy name of
wenzelm@12014
   121
    Some loc => loc
wenzelm@12014
   122
  | None => error ("Unknown locale " ^ quote name));
wenzelm@11896
   123
wenzelm@12046
   124
wenzelm@12277
   125
(* diagnostics *)
wenzelm@12273
   126
wenzelm@12277
   127
fun err_in_locale ctxt msg ids =
wenzelm@12277
   128
  let
wenzelm@12289
   129
    fun prt_id (name, parms) = [Pretty.block (Pretty.breaks (map Pretty.str (name :: parms)))];
wenzelm@12289
   130
    val prt_ids = flat (separate [Pretty.str " +", Pretty.brk 1] (map prt_id ids));
wenzelm@12502
   131
    val err_msg =
wenzelm@12502
   132
      if null ids then msg
wenzelm@12502
   133
      else msg ^ "\n" ^ Pretty.string_of (Pretty.block
wenzelm@12502
   134
        (Pretty.str "The error(s) above occurred in locale:" :: Pretty.brk 1 :: prt_ids));
wenzelm@12502
   135
  in raise ProofContext.CONTEXT (err_msg, ctxt) end;
wenzelm@12063
   136
wenzelm@12277
   137
wenzelm@12277
   138
wenzelm@12277
   139
(** operations on locale elements **)
wenzelm@12277
   140
wenzelm@12510
   141
(* misc utilities *)
wenzelm@12510
   142
wenzelm@12510
   143
fun frozen_tvars ctxt Ts =
wenzelm@12510
   144
  let
wenzelm@12510
   145
    val tvars = rev (foldl Term.add_tvarsT ([], Ts));
wenzelm@12510
   146
    val tfrees = map TFree
wenzelm@12510
   147
      (Term.invent_type_names (ProofContext.used_types ctxt) (length tvars) ~~ map #2 tvars);
wenzelm@12510
   148
  in map #1 tvars ~~ tfrees end;
wenzelm@12510
   149
wenzelm@12510
   150
fun fixes_of_elemss elemss = flat (map (snd o fst) elemss);
wenzelm@12510
   151
wenzelm@12510
   152
wenzelm@12289
   153
(* prepare elements *)
wenzelm@12263
   154
wenzelm@12510
   155
datatype fact = Int of thm list | Ext of string;
wenzelm@12510
   156
wenzelm@12307
   157
local
wenzelm@12307
   158
wenzelm@12307
   159
fun prep_name ctxt (name, atts) =
wenzelm@12307
   160
  if NameSpace.is_qualified name then
wenzelm@12307
   161
    raise ProofContext.CONTEXT ("Illegal qualified name: " ^ quote name, ctxt)
wenzelm@12307
   162
  else (name, atts);
wenzelm@12307
   163
wenzelm@12307
   164
fun prep_elem prep_vars prep_propp prep_thms ctxt =
wenzelm@12063
   165
 fn Fixes fixes =>
wenzelm@12307
   166
      let val vars = snd (foldl_map prep_vars (ctxt, map (fn (x, T, _) => ([x], T)) fixes))
wenzelm@12307
   167
      in Fixes (map (fn (([x'], T'), (_, _, mx)) => (x', T', mx)) (vars ~~ fixes)) end
wenzelm@12063
   168
  | Assumes asms =>
wenzelm@12307
   169
      Assumes (map (prep_name ctxt o #1) asms ~~ snd (prep_propp (ctxt, map #2 asms)))
wenzelm@12063
   170
  | Defines defs =>
wenzelm@12307
   171
      let val propps = snd (prep_propp (ctxt, map (fn (_, (t, ps)) => [(t, (ps, []))]) defs)) in
wenzelm@12307
   172
        Defines (map (prep_name ctxt o #1) defs ~~ map (fn [(t', (ps', []))] => (t', ps')) propps)
wenzelm@12307
   173
      end
wenzelm@12063
   174
  | Notes facts =>
wenzelm@12307
   175
      Notes (map (fn (a, bs) => (prep_name ctxt a, map (apfst (prep_thms ctxt)) bs)) facts);
wenzelm@12307
   176
wenzelm@12502
   177
in
wenzelm@12502
   178
wenzelm@12510
   179
fun read_elem x = prep_elem ProofContext.read_vars ProofContext.read_propp (K I) x;
wenzelm@12307
   180
fun cert_elem x = prep_elem ProofContext.cert_vars ProofContext.cert_propp (K I) x;
wenzelm@12510
   181
fun int_facts x = prep_elem I I (K Int) x;
wenzelm@12510
   182
fun ext_facts x = prep_elem I I (K Ext) x;
wenzelm@12510
   183
fun get_facts x = prep_elem I I
wenzelm@12510
   184
  (fn ctxt => (fn Int ths => ths | Ext name => ProofContext.get_thms ctxt name)) x;
wenzelm@12307
   185
wenzelm@12273
   186
fun read_expr ctxt (Locale xname) = Locale (intern (ProofContext.sign_of ctxt) xname)
wenzelm@12273
   187
  | read_expr ctxt (Merge exprs) = Merge (map (read_expr ctxt) exprs)
wenzelm@12289
   188
  | read_expr ctxt (Rename (expr, xs)) = Rename (read_expr ctxt expr, xs);
wenzelm@12273
   189
wenzelm@12502
   190
end;
wenzelm@12502
   191
wenzelm@12502
   192
wenzelm@12502
   193
(* internalize attributes *)
wenzelm@12502
   194
wenzelm@12502
   195
local fun read_att attrib (x, srcs) = (x, map attrib srcs) in
wenzelm@12502
   196
wenzelm@12273
   197
fun attribute _ (Elem (Fixes fixes)) = Elem (Fixes fixes)
wenzelm@12277
   198
  | attribute attrib (Elem (Assumes asms)) = Elem (Assumes (map (apfst (read_att attrib)) asms))
wenzelm@12277
   199
  | attribute attrib (Elem (Defines defs)) = Elem (Defines (map (apfst (read_att attrib)) defs))
wenzelm@12273
   200
  | attribute attrib (Elem (Notes facts)) =
wenzelm@12277
   201
      Elem (Notes (map (apfst (read_att attrib) o apsnd (map (read_att attrib))) facts))
wenzelm@12273
   202
  | attribute _ (Expr expr) = Expr expr;
wenzelm@12063
   203
wenzelm@12063
   204
end;
wenzelm@12046
   205
wenzelm@12046
   206
wenzelm@12277
   207
(* renaming *)
wenzelm@12263
   208
wenzelm@12263
   209
fun rename ren x = if_none (assoc_string (ren, x)) x;
wenzelm@12263
   210
wenzelm@12263
   211
fun rename_term ren (Free (x, T)) = Free (rename ren x, T)
wenzelm@12263
   212
  | rename_term ren (t $ u) = rename_term ren t $ rename_term ren u
wenzelm@12263
   213
  | rename_term ren (Abs (x, T, t)) = Abs (x, T, rename_term ren t)
wenzelm@12263
   214
  | rename_term _ a = a;
wenzelm@12263
   215
wenzelm@12263
   216
fun rename_thm ren th =
wenzelm@12263
   217
  let
wenzelm@12263
   218
    val {sign, hyps, prop, maxidx, ...} = Thm.rep_thm th;
wenzelm@12263
   219
    val cert = Thm.cterm_of sign;
wenzelm@12502
   220
    val (xs, Ts) = Library.split_list (foldl Term.add_frees ([], prop :: hyps));
wenzelm@12263
   221
    val xs' = map (rename ren) xs;
wenzelm@12263
   222
    fun cert_frees names = map (cert o Free) (names ~~ Ts);
wenzelm@12263
   223
    fun cert_vars names = map (cert o Var o apfst (rpair (maxidx + 1))) (names ~~ Ts);
wenzelm@12263
   224
  in
wenzelm@12263
   225
    if xs = xs' then th
wenzelm@12263
   226
    else
wenzelm@12263
   227
      th
wenzelm@12263
   228
      |> Drule.implies_intr_list (map cert hyps)
wenzelm@12263
   229
      |> Drule.forall_intr_list (cert_frees xs)
wenzelm@12263
   230
      |> Drule.forall_elim_list (cert_vars xs)
wenzelm@12263
   231
      |> Thm.instantiate ([], cert_vars xs ~~ cert_frees xs')
wenzelm@12263
   232
      |> (fn th' => Drule.implies_elim_list th' (map (Thm.assume o cert o rename_term ren) hyps))
wenzelm@12263
   233
  end;
wenzelm@12263
   234
wenzelm@12263
   235
fun rename_elem ren (Fixes fixes) = Fixes (map (fn (x, T, mx) =>
wenzelm@12273
   236
      (rename ren x, T, if mx = None then mx else Some Syntax.NoSyn)) fixes)    (*drops syntax!*)
wenzelm@12263
   237
  | rename_elem ren (Assumes asms) = Assumes (map (apsnd (map (fn (t, (ps, qs)) =>
wenzelm@12263
   238
      (rename_term ren t, (map (rename_term ren) ps, map (rename_term ren) qs))))) asms)
wenzelm@12263
   239
  | rename_elem ren (Defines defs) = Defines (map (apsnd (fn (t, ps) =>
wenzelm@12263
   240
      (rename_term ren t, map (rename_term ren) ps))) defs)
wenzelm@12273
   241
  | rename_elem ren (Notes facts) = Notes (map (apsnd (map (apfst (map (rename_thm ren))))) facts);
wenzelm@12263
   242
wenzelm@12307
   243
fun qualify_elem prfx elem =
wenzelm@12307
   244
  let
wenzelm@12323
   245
    fun qualify (arg as ((name, atts), x)) =
wenzelm@12323
   246
      if name = "" then arg
wenzelm@12323
   247
      else ((NameSpace.pack (filter_out (equal "") (prfx @ [name])), atts), x);
wenzelm@12307
   248
  in
wenzelm@12307
   249
    (case elem of
wenzelm@12307
   250
      Fixes fixes => Fixes fixes
wenzelm@12307
   251
    | Assumes asms => Assumes (map qualify asms)
wenzelm@12307
   252
    | Defines defs => Defines (map qualify defs)
wenzelm@12307
   253
    | Notes facts => Notes (map qualify facts))
wenzelm@12307
   254
  end;
wenzelm@12307
   255
wenzelm@12263
   256
wenzelm@12502
   257
(* type instantiation *)
wenzelm@12502
   258
wenzelm@12502
   259
fun inst_type [] T = T
wenzelm@12502
   260
  | inst_type env T = Term.map_type_tfree (fn v => if_none (assoc (env, v)) (TFree v)) T;
wenzelm@12502
   261
wenzelm@12502
   262
fun inst_term [] t = t
wenzelm@12502
   263
  | inst_term env t = Term.map_term_types (inst_type env) t;
wenzelm@12502
   264
wenzelm@12502
   265
fun inst_thm [] th = th
wenzelm@12502
   266
  | inst_thm env th =
wenzelm@12502
   267
      let
wenzelm@12502
   268
        val {sign, hyps, prop, maxidx, ...} = Thm.rep_thm th;
wenzelm@12502
   269
        val cert = Thm.cterm_of sign and certT = Thm.ctyp_of sign;
wenzelm@12502
   270
        val names = foldr Term.add_term_tfree_names (prop :: hyps, []);
wenzelm@12502
   271
        val env' = filter (fn ((a, _), _) => a mem_string names) env;
wenzelm@12502
   272
      in
wenzelm@12502
   273
        if null env' then th
wenzelm@12502
   274
        else
wenzelm@12502
   275
          th
wenzelm@12502
   276
          |> Drule.implies_intr_list (map cert hyps)
wenzelm@12502
   277
          |> Drule.tvars_intr_list names
wenzelm@12502
   278
          |> (fn (th', al) => th' |>
wenzelm@12502
   279
            Thm.instantiate ((map (fn ((a, _), T) => (the (assoc (al, a)), certT T)) env'), []))
wenzelm@12502
   280
          |> (fn th'' => Drule.implies_elim_list th''
wenzelm@12502
   281
              (map (Thm.assume o cert o inst_term env') hyps))
wenzelm@12502
   282
      end;
wenzelm@12502
   283
wenzelm@12502
   284
fun inst_elem env (Fixes fixes) =
wenzelm@12502
   285
      Fixes (map (fn (x, T, mx) => (x, apsome (inst_type env) T, mx)) fixes)
wenzelm@12502
   286
  | inst_elem env (Assumes asms) = Assumes (map (apsnd (map (fn (t, (ps, qs)) =>
wenzelm@12502
   287
      (inst_term env t, (map (inst_term env) ps, map (inst_term env) qs))))) asms)
wenzelm@12502
   288
  | inst_elem env (Defines defs) = Defines (map (apsnd (fn (t, ps) =>
wenzelm@12502
   289
      (inst_term env t, map (inst_term env) ps))) defs)
wenzelm@12502
   290
  | inst_elem env (Notes facts) = Notes (map (apsnd (map (apfst (map (inst_thm env))))) facts);
wenzelm@12502
   291
wenzelm@12502
   292
wenzelm@12277
   293
(* evaluation *)
wenzelm@11896
   294
wenzelm@12510
   295
local
wenzelm@12502
   296
wenzelm@12502
   297
fun unify_parms ctxt raw_parmss =
wenzelm@12502
   298
  let
wenzelm@12502
   299
    val tsig = Sign.tsig_of (ProofContext.sign_of ctxt);
wenzelm@12502
   300
    val maxidx = length raw_parmss;
wenzelm@12502
   301
    val idx_parmss = (0 upto maxidx - 1) ~~ raw_parmss;
wenzelm@12502
   302
wenzelm@12502
   303
    fun varify i = Term.map_type_tfree (fn (a, S) => TVar ((a, i), S));
wenzelm@12502
   304
    fun varify_parms (i, ps) =
wenzelm@12502
   305
      mapfilter (fn (_, None) => None | (x, Some T) => Some (x, varify i T)) ps;
wenzelm@12502
   306
    val parms = flat (map varify_parms idx_parmss);
wenzelm@12502
   307
wenzelm@12502
   308
    fun unify T ((env, maxidx), U) = Type.unify tsig maxidx env (U, T);  (*should never fail*)
wenzelm@12502
   309
    fun unify_list (envir, T :: Us) = foldl (unify T) (envir, Us)
wenzelm@12502
   310
      | unify_list (envir, []) = envir;
wenzelm@12502
   311
    val (unifier, _) = foldl unify_list
wenzelm@12502
   312
      ((Vartab.empty, maxidx), map #2 (Symtab.dest (Symtab.make_multi parms)));
wenzelm@12502
   313
wenzelm@12502
   314
    val parms' = map (apsnd (Envir.norm_type unifier)) (gen_distinct eq_fst parms);
wenzelm@12502
   315
    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (map #2 parms'));
wenzelm@12502
   316
wenzelm@12502
   317
    fun inst_parms (i, ps) =
wenzelm@12502
   318
      foldr Term.add_typ_tfrees (mapfilter snd ps, [])
wenzelm@12502
   319
      |> mapfilter (fn (a, S) =>
wenzelm@12502
   320
          let val T = Envir.norm_type unifier' (TVar ((a, i), S))
wenzelm@12502
   321
          in if T = TFree (a, S) then None else Some ((a, S), T) end);
wenzelm@12502
   322
  in map inst_parms idx_parmss end;
wenzelm@12502
   323
wenzelm@12502
   324
fun unique_parms ctxt elemss =
wenzelm@12502
   325
  let
wenzelm@12502
   326
    val param_decls =
wenzelm@12502
   327
      flat (map (fn ((name, (ps, qs)), _) => map (rpair (name, ps)) qs) elemss)
wenzelm@12502
   328
      |> Symtab.make_multi |> Symtab.dest;
wenzelm@12502
   329
  in
wenzelm@12502
   330
    (case find_first (fn (_, ids) => length ids > 1) param_decls of
wenzelm@12502
   331
      Some (q, ids) => err_in_locale ctxt ("Multiple declaration of parameter " ^ quote q)
wenzelm@12502
   332
          (map (apsnd (map fst)) ids)
wenzelm@12502
   333
    | None => map (apfst (apsnd #1)) elemss)
wenzelm@12502
   334
  end;
wenzelm@12502
   335
wenzelm@12502
   336
fun inst_types _ [elems] = [elems]
wenzelm@12502
   337
  | inst_types ctxt elemss =
wenzelm@12502
   338
      let
wenzelm@12502
   339
        val envs = unify_parms ctxt (map (#2 o #1) elemss);
wenzelm@12502
   340
        fun inst (((name, ps), elems), env) =
wenzelm@12502
   341
          ((name, map (apsnd (apsome (inst_type env))) ps), map (inst_elem env) elems);
wenzelm@12502
   342
      in map inst (elemss ~~ envs) end;
wenzelm@12502
   343
wenzelm@12510
   344
in
wenzelm@12502
   345
wenzelm@12273
   346
fun eval_expr ctxt expr =
wenzelm@12014
   347
  let
wenzelm@12014
   348
    val thy = ProofContext.theory_of ctxt;
wenzelm@12263
   349
wenzelm@12289
   350
    fun renaming (Some x :: xs) (y :: ys) = (y, x) :: renaming xs ys
wenzelm@12289
   351
      | renaming (None :: xs) (y :: ys) = renaming xs ys
wenzelm@12273
   352
      | renaming [] _ = []
wenzelm@12289
   353
      | renaming xs [] = raise ERROR_MESSAGE ("Too many arguments in renaming: " ^
wenzelm@12289
   354
          commas (map (fn None => "_" | Some x => quote x) xs));
wenzelm@12289
   355
wenzelm@12289
   356
    fun rename_parms ren (name, ps) =
wenzelm@12289
   357
      let val ps' = map (rename ren) ps in
wenzelm@12289
   358
        (case duplicates ps' of [] => (name, ps')
wenzelm@12289
   359
        | dups => err_in_locale ctxt ("Duplicate parameters: " ^ commas_quote dups) [(name, ps')])
wenzelm@12289
   360
      end;
wenzelm@12263
   361
wenzelm@12273
   362
    fun identify ((ids, parms), Locale name) =
wenzelm@12289
   363
          let
wenzelm@12289
   364
            val {import, params, ...} = the_locale thy name;
wenzelm@12289
   365
            val ps = map #1 (#1 params);
wenzelm@12289
   366
          in
wenzelm@12273
   367
            if (name, ps) mem ids then (ids, parms)
wenzelm@12277
   368
            else
wenzelm@12289
   369
              let val (ids', parms') = identify ((ids, parms), import);  (*acyclic dependencies!*)
wenzelm@12289
   370
              in (ids' @ [(name, ps)], merge_lists parms' ps) end
wenzelm@12273
   371
          end
wenzelm@12273
   372
      | identify ((ids, parms), Rename (e, xs)) =
wenzelm@12273
   373
          let
wenzelm@12273
   374
            val (ids', parms') = identify (([], []), e);
wenzelm@12289
   375
            val ren = renaming xs parms' handle ERROR_MESSAGE msg => err_in_locale ctxt msg ids';
wenzelm@12289
   376
            val ids'' = distinct (map (rename_parms ren) ids');
wenzelm@12289
   377
            val parms'' = distinct (flat (map #2 ids''));
wenzelm@12289
   378
          in (merge_lists ids ids'', merge_lists parms parms'') end
wenzelm@12273
   379
      | identify (arg, Merge es) = foldl identify (arg, es);
wenzelm@12014
   380
wenzelm@12307
   381
    fun eval (name, xs) =
wenzelm@12273
   382
      let
wenzelm@12502
   383
        val {params = (ps, qs), elems, ...} = the_locale thy name;
wenzelm@12307
   384
        val ren = filter_out (op =) (map #1 ps ~~ xs);
wenzelm@12502
   385
        val (params', elems') =
wenzelm@12502
   386
          if null ren then ((ps, qs), map #1 elems)
wenzelm@12502
   387
          else ((map (apfst (rename ren)) ps, map (rename ren) qs),
wenzelm@12502
   388
            map (rename_elem ren o #1) elems);
wenzelm@12502
   389
        val elems'' = map (qualify_elem [NameSpace.base name, space_implode "_" xs]) elems';
wenzelm@12502
   390
      in ((name, params'), elems'') end;
wenzelm@12307
   391
wenzelm@12502
   392
    val raw_elemss = unique_parms ctxt (map eval (#1 (identify (([], []), expr))));
wenzelm@12502
   393
    val elemss = inst_types ctxt raw_elemss;
wenzelm@12502
   394
  in elemss end;
wenzelm@12046
   395
wenzelm@12510
   396
end;
wenzelm@12510
   397
wenzelm@12070
   398
wenzelm@12273
   399
wenzelm@12273
   400
(** activation **)
wenzelm@12070
   401
wenzelm@12502
   402
(* internalize elems *)
wenzelm@12502
   403
wenzelm@12510
   404
local
wenzelm@12510
   405
wenzelm@12510
   406
fun perform_elems f named_elems = ProofContext.qualified (fn context =>
wenzelm@12510
   407
  foldl (fn (ctxt, ((name, ps), es)) =>
wenzelm@12510
   408
    foldl (fn (c, e) => f e c) (ctxt, es) handle ProofContext.CONTEXT (msg, ctxt) =>
wenzelm@12510
   409
      err_in_locale ctxt msg [(name, map fst ps)]) (context, named_elems));
wenzelm@12510
   410
wenzelm@12510
   411
in
wenzelm@12510
   412
wenzelm@12502
   413
fun declare_elem gen =
wenzelm@12502
   414
  let
wenzelm@12502
   415
    val gen_typ = if gen then Term.map_type_tfree (Type.param []) else I;
wenzelm@12502
   416
    val gen_term = if gen then Term.map_term_types gen_typ else I;
wenzelm@12502
   417
wenzelm@12502
   418
    fun declare (Fixes fixes) = ProofContext.add_syntax fixes o
wenzelm@12502
   419
          ProofContext.fix_direct (map (fn (x, T, _) => ([x], apsome gen_typ T)) fixes)
wenzelm@12502
   420
      | declare (Assumes asms) = (fn ctxt => #1 (ProofContext.bind_propp_i
wenzelm@12502
   421
          (ctxt, map (map (fn (t, (ps, ps')) =>
wenzelm@12502
   422
            (gen_term t, (map gen_term ps, map gen_term ps'))) o #2) asms)))
wenzelm@12502
   423
      | declare (Defines defs) = (fn ctxt => #1 (ProofContext.bind_propp_i
wenzelm@12502
   424
          (ctxt, map (fn (_, (t, ps)) => [(gen_term t, (map gen_term ps, []))]) defs)))
wenzelm@12502
   425
      | declare (Notes _) = I;
wenzelm@12502
   426
  in declare end;
wenzelm@12307
   427
wenzelm@12273
   428
fun activate_elem (Fixes fixes) = ProofContext.add_syntax fixes o
wenzelm@12502
   429
      ProofContext.fix_direct (map (fn (x, T, _) => ([x], T)) fixes)
wenzelm@12273
   430
  | activate_elem (Assumes asms) =
wenzelm@12273
   431
      #1 o ProofContext.assume_i ProofContext.export_assume asms o
wenzelm@12273
   432
      ProofContext.fix_frees (flat (map (map #1 o #2) asms))
wenzelm@12273
   433
  | activate_elem (Defines defs) = (fn ctxt => #1 (ProofContext.assume_i ProofContext.export_def
wenzelm@12273
   434
      (map (fn ((name, atts), (t, ps)) =>
wenzelm@12273
   435
        let val (c, t') = ProofContext.cert_def ctxt t
wenzelm@12273
   436
        in ((if name = "" then Thm.def_name c else name, atts), [(t', (ps, []))]) end) defs) ctxt))
wenzelm@12273
   437
  | activate_elem (Notes facts) = #1 o ProofContext.have_thmss facts;
wenzelm@12263
   438
wenzelm@12502
   439
fun declare_elemss gen = perform_elems (declare_elem gen);
wenzelm@12502
   440
fun activate_elemss x = perform_elems activate_elem x;
wenzelm@12502
   441
wenzelm@12510
   442
end;
wenzelm@12510
   443
wenzelm@12307
   444
wenzelm@12502
   445
(* context specifications: import expression + external elements *)
wenzelm@12502
   446
wenzelm@12502
   447
local
wenzelm@12502
   448
wenzelm@12502
   449
fun close_frees ctxt t =
wenzelm@12502
   450
  let val frees = rev (filter_out (ProofContext.is_fixed ctxt o #1) (Term.add_frees ([], t)))
wenzelm@12502
   451
  in Term.list_all_free (frees, t) end;
wenzelm@12502
   452
wenzelm@12502
   453
(*quantify dangling frees, strip term bindings*)
wenzelm@12502
   454
fun closeup ctxt (Assumes asms) = Assumes (asms |> map (fn (a, propps) =>
wenzelm@12502
   455
      (a, map (fn (t, _) => (close_frees ctxt t, ([], []))) propps)))
wenzelm@12502
   456
  | closeup ctxt (Defines defs) = Defines (defs |> map (fn (a, (t, _)) =>
wenzelm@12502
   457
      (a, (close_frees ctxt (#2 (ProofContext.cert_def ctxt t)), []))))
wenzelm@12502
   458
  | closeup ctxt elem = elem;
wenzelm@12502
   459
wenzelm@12510
   460
fun fixes_of_elem (Fixes fixes) = map (fn (x, T, _) => (x, T)) fixes
wenzelm@12510
   461
  | fixes_of_elem _ = [];
wenzelm@12510
   462
wenzelm@12510
   463
fun prepare_context prep_expr prep_elem1 prep_elem2 close (import, elements) context =
wenzelm@12502
   464
  let
wenzelm@12510
   465
    fun declare_expr (c, raw_expr) =
wenzelm@12510
   466
      let
wenzelm@12510
   467
        val expr = prep_expr c raw_expr;
wenzelm@12510
   468
        val named_elemss = eval_expr c expr;
wenzelm@12510
   469
      in (c |> declare_elemss true named_elemss, named_elemss) end;
wenzelm@12510
   470
wenzelm@12510
   471
    fun declare_element (c, Elem raw_elem) =
wenzelm@12502
   472
          let
wenzelm@12510
   473
            val elem = (if close then closeup c else I) (prep_elem2 c (prep_elem1 c raw_elem));
wenzelm@12510
   474
            val res = [(("", fixes_of_elem elem), [elem])];
wenzelm@12510
   475
          in (c |> declare_elemss false res, res) end
wenzelm@12510
   476
      | declare_element (c, Expr raw_expr) =
wenzelm@12510
   477
          apsnd (map (apsnd (map (int_facts c)))) (declare_expr (c, raw_expr));
wenzelm@12277
   478
wenzelm@12510
   479
    fun activate_elems (c, ((name, ps), raw_elems)) =
wenzelm@12510
   480
      let
wenzelm@12510
   481
        val elems = map (get_facts c) raw_elems;
wenzelm@12510
   482
        val res = ((name, ps), elems);
wenzelm@12510
   483
      in (c |> activate_elemss [res], res) end;
wenzelm@12502
   484
wenzelm@12510
   485
    val (import_ctxt, import_elemss) = declare_expr (context, import);
wenzelm@12510
   486
    val (ctxt, elemss) = apsnd flat (foldl_map declare_element (import_ctxt, elements));
wenzelm@12510
   487
    val type_env = frozen_tvars ctxt (mapfilter (ProofContext.default_type ctxt o #1)
wenzelm@12510
   488
      (fixes_of_elemss import_elemss @ fixes_of_elemss elemss));
wenzelm@12510
   489
    val FIXME = PolyML.print type_env;
wenzelm@12510
   490
wenzelm@12510
   491
    fun inst_elems ((name, ps), elems) = ((name, ps), elems);    (* FIXME *)
wenzelm@12502
   492
wenzelm@12510
   493
    val import_elemss' = map inst_elems import_elemss;
wenzelm@12510
   494
    val import_ctxt' = context |> activate_elemss import_elemss';
wenzelm@12510
   495
    val (ctxt', elemss') = foldl_map activate_elems (import_ctxt', map inst_elems elemss);
wenzelm@12510
   496
  in ((import_ctxt', import_elemss'), (ctxt', elemss')) end;
wenzelm@12273
   497
wenzelm@12510
   498
val prep_context = prepare_context read_expr read_elem ext_facts;
wenzelm@12510
   499
val prep_context_i = prepare_context (K I) cert_elem int_facts;
wenzelm@12502
   500
wenzelm@12502
   501
in
wenzelm@12502
   502
wenzelm@12510
   503
val read_context = prep_context true;
wenzelm@12510
   504
val cert_context = prep_context_i true;
wenzelm@12510
   505
val activate_context = pairself fst oo prep_context false;
wenzelm@12510
   506
val activate_context_i = pairself fst oo prep_context_i false;
wenzelm@12510
   507
fun activate_locale name = #1 o activate_context_i (Locale name, []);
wenzelm@12502
   508
wenzelm@12502
   509
end;
wenzelm@11896
   510
wenzelm@11896
   511
wenzelm@11896
   512
wenzelm@12070
   513
(** print locale **)
wenzelm@12070
   514
wenzelm@12307
   515
fun print_locale thy raw_expr =
wenzelm@12070
   516
  let
wenzelm@12070
   517
    val sg = Theory.sign_of thy;
wenzelm@12289
   518
    val thy_ctxt = ProofContext.init thy;
wenzelm@12510
   519
    val (ctxt, elemss) = #1 (read_context (raw_expr, []) thy_ctxt);
wenzelm@12070
   520
wenzelm@12307
   521
    val prt_typ = Pretty.quote o ProofContext.pretty_typ ctxt;
wenzelm@12307
   522
    val prt_term = Pretty.quote o ProofContext.pretty_term ctxt;
wenzelm@12307
   523
    val prt_thm = Pretty.quote o ProofContext.pretty_thm ctxt;
wenzelm@12070
   524
wenzelm@12070
   525
    fun prt_syn syn =
wenzelm@12070
   526
      let val s = (case syn of None => "(structure)" | Some mx => Syntax.string_of_mixfix mx)
wenzelm@12070
   527
      in if s = "" then [] else [Pretty.brk 4, Pretty.str s] end;
wenzelm@12070
   528
    fun prt_fix (x, Some T, syn) = Pretty.block (Pretty.str (x ^ " ::") :: Pretty.brk 1 ::
wenzelm@12070
   529
          prt_typ T :: Pretty.brk 1 :: prt_syn syn)
wenzelm@12070
   530
      | prt_fix (x, None, syn) = Pretty.block (Pretty.str x :: Pretty.brk 1 :: prt_syn syn);
wenzelm@12070
   531
wenzelm@12307
   532
    fun prt_name "" = [Pretty.brk 1]
wenzelm@12307
   533
      | prt_name name = [Pretty.str (ProofContext.cond_extern ctxt name ^ ":"), Pretty.brk 1];
wenzelm@12307
   534
    fun prt_asm ((a, _), ts) = Pretty.block (prt_name a @ Pretty.breaks (map (prt_term o fst) ts));
wenzelm@12307
   535
    fun prt_def ((a, _), (t, _)) = Pretty.block (prt_name a @ [prt_term t]);
wenzelm@12307
   536
    fun prt_fact ((a, _), ths) = Pretty.block
wenzelm@12307
   537
      (prt_name a @ Pretty.breaks (map prt_thm (flat (map fst ths))));
wenzelm@12070
   538
wenzelm@12289
   539
    fun items _ [] = []
wenzelm@12289
   540
      | items prfx (x :: xs) = Pretty.block [Pretty.str prfx, Pretty.brk 1, x] :: items "  and" xs;
wenzelm@12289
   541
    fun prt_elem (Fixes fixes) = items "fixes" (map prt_fix fixes)
wenzelm@12289
   542
      | prt_elem (Assumes asms) = items "assumes" (map prt_asm asms)
wenzelm@12289
   543
      | prt_elem (Defines defs) = items "defines" (map prt_def defs)
wenzelm@12289
   544
      | prt_elem (Notes facts) = items "notes" (map prt_fact facts);
wenzelm@12277
   545
  in
wenzelm@12502
   546
    Pretty.big_list "locale elements:" (map (Pretty.chunks o prt_elem) (flat (map #2 elemss)))
wenzelm@12307
   547
    |> Pretty.writeln
wenzelm@12277
   548
  end;
wenzelm@12070
   549
wenzelm@12070
   550
wenzelm@12070
   551
wenzelm@11896
   552
(** define locales **)
wenzelm@11896
   553
wenzelm@12063
   554
(* add_locale(_i) *)
wenzelm@11896
   555
wenzelm@12502
   556
local
wenzelm@12502
   557
wenzelm@12502
   558
fun gen_add_locale prep_context prep_expr bname raw_import raw_body thy =
wenzelm@12063
   559
  let
wenzelm@12063
   560
    val sign = Theory.sign_of thy;
wenzelm@11896
   561
    val name = Sign.full_name sign bname;
wenzelm@12502
   562
    val _ = conditional (is_some (get_locale thy name)) (fn () =>
wenzelm@12502
   563
      error ("Duplicate definition of locale " ^ quote name));
wenzelm@11896
   564
wenzelm@12273
   565
    val thy_ctxt = ProofContext.init thy;
wenzelm@12510
   566
    val ((import_ctxt, import_elemss), (body_ctxt, body_elemss)) =
wenzelm@12510
   567
      prep_context (raw_import, raw_body) thy_ctxt;
wenzelm@12510
   568
    val import_parms = fixes_of_elemss import_elemss;
wenzelm@12510
   569
    val import = (prep_expr thy_ctxt raw_import);
wenzelm@12273
   570
wenzelm@12510
   571
    val elems = flat (map snd body_elemss);
wenzelm@12510
   572
    val body_parms = fixes_of_elemss body_elemss;
wenzelm@12273
   573
    val text = ([], []);  (* FIXME *)
wenzelm@12063
   574
  in
wenzelm@12063
   575
    thy
wenzelm@12063
   576
    |> declare_locale name
wenzelm@12289
   577
    |> put_locale name (make_locale import (map (fn e => (e, stamp ())) elems)
wenzelm@12502
   578
      (import_parms @ body_parms, map #1 body_parms) text)
wenzelm@12063
   579
  end;
wenzelm@12063
   580
wenzelm@12502
   581
in
wenzelm@12502
   582
wenzelm@12502
   583
val add_locale = gen_add_locale read_context read_expr;
wenzelm@12502
   584
val add_locale_i = gen_add_locale cert_context (K I);
wenzelm@12502
   585
wenzelm@12502
   586
end;
wenzelm@12063
   587
wenzelm@11896
   588
wenzelm@12063
   589
wenzelm@12070
   590
(** store results **)
wenzelm@11896
   591
wenzelm@12143
   592
fun add_thmss name args thy =
wenzelm@12063
   593
  let
wenzelm@12289
   594
    val {import, params, elems, text} = the_locale thy name;
wenzelm@12143
   595
    val note = Notes (map (fn ((a, ths), atts) =>
wenzelm@12143
   596
      ((a, atts), [(map (curry Thm.name_thm a) ths, [])])) args);
wenzelm@12063
   597
  in
wenzelm@12502
   598
    thy |> ProofContext.init |> activate_locale name |> activate_elem note;  (*test attributes!*)
wenzelm@12289
   599
    thy |> put_locale name (make_locale import (elems @ [(note, stamp ())]) params text)
wenzelm@12063
   600
  end;
wenzelm@11896
   601
wenzelm@12063
   602
wenzelm@11896
   603
wenzelm@11896
   604
(** locale theory setup **)
wenzelm@12063
   605
wenzelm@11896
   606
val setup =
wenzelm@11896
   607
 [LocalesData.init];
wenzelm@11896
   608
wenzelm@11896
   609
end;