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