src/Pure/Isar/locale.ML
author wenzelm
Wed Dec 05 03:18:03 2001 +0100 (2001-12-05 ago)
changeset 12385 389d11fb62c8
parent 12323 e151ee6e820f
child 12502 9e7f72e25022
permissions -rw-r--r--
removed unused functionality (weight etc.);
     1 (*  Title:      Pure/Isar/locale.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4     License:    GPL (GNU GENERAL PUBLIC LICENSE)
     5 
     6 Locales -- Isar proof contexts as meta-level predicates, with local
     7 syntax and implicit structures.  Draws some basic ideas from Florian
     8 Kammüller's original version of locales, but uses the richer
     9 infrastructure of Isar instead of the raw meta-logic.
    10 *)
    11 
    12 signature LOCALE =
    13 sig
    14   type context
    15   datatype ('typ, 'term, 'fact, 'att) elem =
    16     Fixes of (string * 'typ option * mixfix option) list |
    17     Assumes of ((string * 'att list) * ('term * ('term list * 'term list)) list) list |
    18     Defines of ((string * 'att list) * ('term * 'term list)) list |
    19     Notes of ((string * 'att list) * ('fact * 'att list) list) list
    20   datatype expr =
    21     Locale of string |
    22     Rename of expr * string option list |
    23     Merge of expr list
    24   val empty: expr
    25   datatype ('typ, 'term, 'fact, 'att) elem_expr =
    26     Elem of ('typ, 'term, 'fact, 'att) elem | Expr of expr
    27   type 'att element
    28   type 'att element_i
    29   type locale
    30   val intern: Sign.sg -> xstring -> string
    31   val cond_extern: Sign.sg -> string -> xstring
    32   val attribute: ('att -> context attribute) -> ('typ, 'term, 'thm, 'att) elem_expr
    33     -> ('typ, 'term, 'thm, context attribute) elem_expr
    34   val activate_elements: context attribute element list -> context -> context
    35   val activate_elements_i: context attribute element_i list -> context -> context
    36   val activate_locale: xstring -> context -> context
    37   val activate_locale_i: string -> context -> context
    38   val add_locale: bstring -> expr -> context attribute element list -> theory -> theory
    39   val add_locale_i: bstring -> expr -> context attribute element_i list -> theory -> theory
    40   val print_locales: theory -> unit
    41   val print_locale: theory -> expr -> unit
    42   val add_thmss: string -> ((string * thm list) * context attribute list) list -> theory -> theory
    43   val setup: (theory -> theory) list
    44 end;
    45 
    46 structure Locale: LOCALE =
    47 struct
    48 
    49 
    50 (** locale elements and expressions **)
    51 
    52 type context = ProofContext.context;
    53 
    54 datatype ('typ, 'term, 'fact, 'att) elem =
    55   Fixes of (string * 'typ option * mixfix option) list |
    56   Assumes of ((string * 'att list) * ('term * ('term list * 'term list)) list) list |
    57   Defines of ((string * 'att list) * ('term * 'term list)) list |
    58   Notes of ((string * 'att list) * ('fact * 'att list) list) list;
    59 
    60 datatype expr =
    61   Locale of string |
    62   Rename of expr * string option list |
    63   Merge of expr list;
    64 
    65 val empty = Merge [];
    66 
    67 datatype ('typ, 'term, 'fact, 'att) elem_expr =
    68   Elem of ('typ, 'term, 'fact, 'att) elem | Expr of expr;
    69 
    70 type 'att element = (string, string, string, 'att) elem_expr;
    71 type 'att element_i = (typ, term, thm list, 'att) elem_expr;
    72 
    73 type locale =
    74  {import: expr,                                                         (*dynamic import*)
    75   elems: ((typ, term, thm list, context attribute) elem * stamp) list,  (*static content*)
    76   params: (string * typ option) list * (string * typ option) list,      (*all vs. local params*)
    77   text: (string * typ) list * term list}                                (*logical representation*)
    78 
    79 fun make_locale import elems params text =
    80  {import = import, elems = elems, params = params, text = text}: locale;
    81 
    82 
    83 
    84 (** theory data **)
    85 
    86 structure LocalesArgs =
    87 struct
    88   val name = "Isar/locales";
    89   type T = NameSpace.T * locale Symtab.table;
    90 
    91   val empty = (NameSpace.empty, Symtab.empty);
    92   val copy = I;
    93   val prep_ext = I;
    94 
    95   (*joining of locale elements: only facts may be added later!*)
    96   fun join ({import, elems, params, text}: locale, {elems = elems', ...}: locale) =
    97     Some (make_locale import (gen_merge_lists eq_snd elems elems') params text);
    98   fun merge ((space1, locs1), (space2, locs2)) =
    99     (NameSpace.merge (space1, space2), Symtab.join join (locs1, locs2));
   100 
   101   fun print _ (space, locs) =
   102     Pretty.strs ("locales:" :: map (NameSpace.cond_extern space o #1) (Symtab.dest locs))
   103     |> Pretty.writeln;
   104 end;
   105 
   106 structure LocalesData = TheoryDataFun(LocalesArgs);
   107 val print_locales = LocalesData.print;
   108 
   109 val intern = NameSpace.intern o #1 o LocalesData.get_sg;
   110 val cond_extern = NameSpace.cond_extern o #1 o LocalesData.get_sg;
   111 
   112 
   113 (* access locales *)
   114 
   115 fun declare_locale name =
   116   LocalesData.map (apfst (fn space => (NameSpace.extend (space, [name]))));
   117 
   118 fun put_locale name loc = LocalesData.map (apsnd (fn locs => Symtab.update ((name, loc), locs)));
   119 fun get_locale thy name = Symtab.lookup (#2 (LocalesData.get thy), name);
   120 
   121 fun the_locale thy name =
   122   (case get_locale thy name of
   123     Some loc => loc
   124   | None => error ("Unknown locale " ^ quote name));
   125 
   126 
   127 (* diagnostics *)
   128 
   129 fun err_in_locale ctxt msg ids =
   130   let
   131     fun prt_id (name, parms) = [Pretty.block (Pretty.breaks (map Pretty.str (name :: parms)))];
   132     val prt_ids = flat (separate [Pretty.str " +", Pretty.brk 1] (map prt_id ids));
   133   in
   134     if null ids then raise ProofContext.CONTEXT (msg, ctxt)
   135     else raise ProofContext.CONTEXT (msg ^ "\n" ^ Pretty.string_of (Pretty.block
   136       (Pretty.str "The error(s) above occurred in locale:" :: Pretty.brk 1 :: prt_ids)), ctxt)
   137   end;
   138 
   139 
   140 
   141 (** operations on locale elements **)
   142 
   143 (* prepare elements *)
   144 
   145 local
   146 
   147 fun prep_name ctxt (name, atts) =
   148   if NameSpace.is_qualified name then
   149     raise ProofContext.CONTEXT ("Illegal qualified name: " ^ quote name, ctxt)
   150   else (name, atts);
   151 
   152 fun prep_elem prep_vars prep_propp prep_thms ctxt =
   153  fn Fixes fixes =>
   154       let val vars = snd (foldl_map prep_vars (ctxt, map (fn (x, T, _) => ([x], T)) fixes))
   155       in Fixes (map (fn (([x'], T'), (_, _, mx)) => (x', T', mx)) (vars ~~ fixes)) end
   156   | Assumes asms =>
   157       Assumes (map (prep_name ctxt o #1) asms ~~ snd (prep_propp (ctxt, map #2 asms)))
   158   | Defines defs =>
   159       let val propps = snd (prep_propp (ctxt, map (fn (_, (t, ps)) => [(t, (ps, []))]) defs)) in
   160         Defines (map (prep_name ctxt o #1) defs ~~ map (fn [(t', (ps', []))] => (t', ps')) propps)
   161       end
   162   | Notes facts =>
   163       Notes (map (fn (a, bs) => (prep_name ctxt a, map (apfst (prep_thms ctxt)) bs)) facts);
   164 
   165 fun read_elem x = prep_elem ProofContext.read_vars ProofContext.read_propp ProofContext.get_thms x;
   166 fun cert_elem x = prep_elem ProofContext.cert_vars ProofContext.cert_propp (K I) x;
   167 
   168 fun read_att attrib (x, srcs) = (x, map attrib srcs);
   169 
   170 in
   171 
   172 fun read_expr ctxt (Locale xname) = Locale (intern (ProofContext.sign_of ctxt) xname)
   173   | read_expr ctxt (Merge exprs) = Merge (map (read_expr ctxt) exprs)
   174   | read_expr ctxt (Rename (expr, xs)) = Rename (read_expr ctxt expr, xs);
   175 
   176 fun read_element ctxt (Elem e) = Elem (read_elem ctxt e)
   177   | read_element ctxt (Expr e) = Expr (read_expr ctxt e);
   178 
   179 fun cert_element ctxt (Elem e) = Elem (cert_elem ctxt e)
   180   | cert_element ctxt (Expr e) = Expr e;
   181 
   182 fun attribute _ (Elem (Fixes fixes)) = Elem (Fixes fixes)
   183   | attribute attrib (Elem (Assumes asms)) = Elem (Assumes (map (apfst (read_att attrib)) asms))
   184   | attribute attrib (Elem (Defines defs)) = Elem (Defines (map (apfst (read_att attrib)) defs))
   185   | attribute attrib (Elem (Notes facts)) =
   186       Elem (Notes (map (apfst (read_att attrib) o apsnd (map (read_att attrib))) facts))
   187   | attribute _ (Expr expr) = Expr expr;
   188 
   189 end;
   190 
   191 
   192 (* renaming *)
   193 
   194 fun rename ren x = if_none (assoc_string (ren, x)) x;
   195 
   196 fun rename_term ren (Free (x, T)) = Free (rename ren x, T)
   197   | rename_term ren (t $ u) = rename_term ren t $ rename_term ren u
   198   | rename_term ren (Abs (x, T, t)) = Abs (x, T, rename_term ren t)
   199   | rename_term _ a = a;
   200 
   201 fun rename_thm ren th =
   202   let
   203     val {sign, hyps, prop, maxidx, ...} = Thm.rep_thm th;
   204     val cert = Thm.cterm_of sign;
   205     val (xs, Ts) = Library.split_list (foldl Drule.add_frees ([], prop :: hyps));
   206     val xs' = map (rename ren) xs;
   207     fun cert_frees names = map (cert o Free) (names ~~ Ts);
   208     fun cert_vars names = map (cert o Var o apfst (rpair (maxidx + 1))) (names ~~ Ts);
   209   in
   210     if xs = xs' then th
   211     else
   212       th
   213       |> Drule.implies_intr_list (map cert hyps)
   214       |> Drule.forall_intr_list (cert_frees xs)
   215       |> Drule.forall_elim_list (cert_vars xs)
   216       |> Thm.instantiate ([], cert_vars xs ~~ cert_frees xs')
   217       |> (fn th' => Drule.implies_elim_list th' (map (Thm.assume o cert o rename_term ren) hyps))
   218   end;
   219 
   220 fun rename_elem ren (Fixes fixes) = Fixes (map (fn (x, T, mx) =>
   221       (rename ren x, T, if mx = None then mx else Some Syntax.NoSyn)) fixes)    (*drops syntax!*)
   222   | rename_elem ren (Assumes asms) = Assumes (map (apsnd (map (fn (t, (ps, qs)) =>
   223       (rename_term ren t, (map (rename_term ren) ps, map (rename_term ren) qs))))) asms)
   224   | rename_elem ren (Defines defs) = Defines (map (apsnd (fn (t, ps) =>
   225       (rename_term ren t, map (rename_term ren) ps))) defs)
   226   | rename_elem ren (Notes facts) = Notes (map (apsnd (map (apfst (map (rename_thm ren))))) facts);
   227 
   228 fun qualify_elem prfx elem =
   229   let
   230     fun qualify (arg as ((name, atts), x)) =
   231       if name = "" then arg
   232       else ((NameSpace.pack (filter_out (equal "") (prfx @ [name])), atts), x);
   233   in
   234     (case elem of
   235       Fixes fixes => Fixes fixes
   236     | Assumes asms => Assumes (map qualify asms)
   237     | Defines defs => Defines (map qualify defs)
   238     | Notes facts => Notes (map qualify facts))
   239   end;
   240 
   241 
   242 (* evaluation *)
   243 
   244 fun eval_expr ctxt expr =
   245   let
   246     val thy = ProofContext.theory_of ctxt;
   247 
   248     fun renaming (Some x :: xs) (y :: ys) = (y, x) :: renaming xs ys
   249       | renaming (None :: xs) (y :: ys) = renaming xs ys
   250       | renaming [] _ = []
   251       | renaming xs [] = raise ERROR_MESSAGE ("Too many arguments in renaming: " ^
   252           commas (map (fn None => "_" | Some x => quote x) xs));
   253 
   254     fun rename_parms ren (name, ps) =
   255       let val ps' = map (rename ren) ps in
   256         (case duplicates ps' of [] => (name, ps')
   257         | dups => err_in_locale ctxt ("Duplicate parameters: " ^ commas_quote dups) [(name, ps')])
   258       end;
   259 
   260     fun identify ((ids, parms), Locale name) =
   261           let
   262             val {import, params, ...} = the_locale thy name;
   263             val ps = map #1 (#1 params);
   264           in
   265             if (name, ps) mem ids then (ids, parms)
   266             else
   267               let val (ids', parms') = identify ((ids, parms), import);  (*acyclic dependencies!*)
   268               in (ids' @ [(name, ps)], merge_lists parms' ps) end
   269           end
   270       | identify ((ids, parms), Rename (e, xs)) =
   271           let
   272             val (ids', parms') = identify (([], []), e);
   273             val ren = renaming xs parms' handle ERROR_MESSAGE msg => err_in_locale ctxt msg ids';
   274             val ids'' = distinct (map (rename_parms ren) ids');
   275             val parms'' = distinct (flat (map #2 ids''));
   276           in (merge_lists ids ids'', merge_lists parms parms'') end
   277       | identify (arg, Merge es) = foldl identify (arg, es);
   278 
   279     fun eval (name, xs) =
   280       let
   281         val {params = (ps, _), elems, ...} = the_locale thy name;
   282         val ren = filter_out (op =) (map #1 ps ~~ xs);
   283         val (ps', elems') =
   284           if null ren then (ps, map #1 elems)
   285           else (map (apfst (rename ren)) ps, map (rename_elem ren o #1) elems);
   286       in ((name, ps'), map (qualify_elem [NameSpace.base name, space_implode "_" xs]) elems') end;
   287 
   288     (* FIXME unify types *)
   289 
   290     val (idents, parms) = identify (([], []), expr);
   291   in (map eval idents, parms) end;
   292 
   293 fun eval_element _ (Elem e) = [(("", []), [e])]
   294   | eval_element ctxt (Expr e) = #1 (eval_expr ctxt e);
   295 
   296 
   297 
   298 (** activation **)
   299 
   300 (* internal elems *)
   301 
   302 fun activate_elem (Fixes fixes) = ProofContext.add_syntax fixes o
   303       ProofContext.fix_direct (map (fn (x, T, mx) => ([x], T)) fixes)
   304   | activate_elem (Assumes asms) =
   305       #1 o ProofContext.assume_i ProofContext.export_assume asms o
   306       ProofContext.fix_frees (flat (map (map #1 o #2) asms))
   307   | activate_elem (Defines defs) = (fn ctxt => #1 (ProofContext.assume_i ProofContext.export_def
   308       (map (fn ((name, atts), (t, ps)) =>
   309         let val (c, t') = ProofContext.cert_def ctxt t
   310         in ((if name = "" then Thm.def_name c else name, atts), [(t', (ps, []))]) end) defs) ctxt))
   311   | activate_elem (Notes facts) = #1 o ProofContext.have_thmss facts;
   312 
   313 fun activate_elems es ctxt = foldl (fn (c, e) => activate_elem e c) (ctxt, es);
   314 
   315 fun activate_locale_elems named_elems = ProofContext.qualified (fn context =>
   316   foldl (fn (ctxt, ((name, ps), es)) =>    (* FIXME type inst *)
   317     activate_elems es ctxt handle ProofContext.CONTEXT (msg, ctxt) =>
   318       err_in_locale ctxt msg [(name, map fst ps)]) (context, named_elems));
   319 
   320 
   321 (* external elements and locales *)
   322 
   323 fun gen_activate_elements prep_element raw_elements context =
   324   foldl (fn (ctxt, e) => activate_locale_elems (eval_element ctxt (prep_element ctxt e)) ctxt)
   325     (context, raw_elements);
   326 
   327 val activate_elements = gen_activate_elements read_element;
   328 val activate_elements_i = gen_activate_elements cert_element;
   329 val activate_locale_i = activate_elements_i o single o Expr o Locale;
   330 val activate_locale = activate_elements o single o Expr o Locale;
   331 
   332 
   333 
   334 (** print locale **)
   335 
   336 fun print_locale thy raw_expr =
   337   let
   338     val sg = Theory.sign_of thy;
   339     val thy_ctxt = ProofContext.init thy;
   340 
   341     val expr = read_expr thy_ctxt raw_expr;
   342     val elems = #1 (eval_expr thy_ctxt expr);
   343     val ctxt = activate_locale_elems elems thy_ctxt;
   344 
   345     val prt_typ = Pretty.quote o ProofContext.pretty_typ ctxt;
   346     val prt_term = Pretty.quote o ProofContext.pretty_term ctxt;
   347     val prt_thm = Pretty.quote o ProofContext.pretty_thm ctxt;
   348 
   349     fun prt_syn syn =
   350       let val s = (case syn of None => "(structure)" | Some mx => Syntax.string_of_mixfix mx)
   351       in if s = "" then [] else [Pretty.brk 4, Pretty.str s] end;
   352     fun prt_fix (x, Some T, syn) = Pretty.block (Pretty.str (x ^ " ::") :: Pretty.brk 1 ::
   353           prt_typ T :: Pretty.brk 1 :: prt_syn syn)
   354       | prt_fix (x, None, syn) = Pretty.block (Pretty.str x :: Pretty.brk 1 :: prt_syn syn);
   355 
   356     fun prt_name "" = [Pretty.brk 1]
   357       | prt_name name = [Pretty.str (ProofContext.cond_extern ctxt name ^ ":"), Pretty.brk 1];
   358     fun prt_asm ((a, _), ts) = Pretty.block (prt_name a @ Pretty.breaks (map (prt_term o fst) ts));
   359     fun prt_def ((a, _), (t, _)) = Pretty.block (prt_name a @ [prt_term t]);
   360     fun prt_fact ((a, _), ths) = Pretty.block
   361       (prt_name a @ Pretty.breaks (map prt_thm (flat (map fst ths))));
   362 
   363     fun items _ [] = []
   364       | items prfx (x :: xs) = Pretty.block [Pretty.str prfx, Pretty.brk 1, x] :: items "  and" xs;
   365     fun prt_elem (Fixes fixes) = items "fixes" (map prt_fix fixes)
   366       | prt_elem (Assumes asms) = items "assumes" (map prt_asm asms)
   367       | prt_elem (Defines defs) = items "defines" (map prt_def defs)
   368       | prt_elem (Notes facts) = items "notes" (map prt_fact facts);
   369   in
   370     Pretty.big_list "locale elements:" (map (Pretty.chunks o prt_elem) (flat (map #2 elems)))
   371     |> Pretty.writeln
   372   end;
   373 
   374 
   375 
   376 (** define locales **)
   377 
   378 (* closeup -- quantify dangling frees *)
   379 
   380 fun close_frees_wrt ctxt t =
   381   let val frees = rev (filter_out (ProofContext.is_fixed ctxt o #1) (Drule.add_frees ([], t)))
   382   in curry Term.list_all_free frees end;
   383 
   384 fun closeup ctxt (Assumes asms) = Assumes (asms |> map (fn (a, propps) =>
   385       (a, propps |> map (fn (t, (ps1, ps2)) =>
   386         let val close = close_frees_wrt ctxt t in (close t, (map close ps1, map close ps2)) end))))
   387   | closeup ctxt (Defines defs) = Defines (defs |> map (fn (a, (t, ps)) =>
   388       let
   389         val (_, t') = ProofContext.cert_def ctxt t;
   390         val close = close_frees_wrt ctxt t';
   391       in (a, (close t', map close ps)) end))
   392   | closeup ctxt elem = elem;
   393 
   394 
   395 (* add_locale(_i) *)
   396 
   397 fun gen_add_locale prep_expr prep_element bname raw_import raw_elements thy =
   398   let
   399     val sign = Theory.sign_of thy;
   400     val name = Sign.full_name sign bname;
   401     val _ =
   402       if is_none (get_locale thy name) then () else
   403       error ("Duplicate definition of locale " ^ quote name);
   404 
   405     val thy_ctxt = ProofContext.init thy;
   406 
   407     val import = prep_expr thy_ctxt raw_import;
   408     val (import_elems, import_params) = eval_expr thy_ctxt import;
   409     val import_ctxt = activate_locale_elems import_elems thy_ctxt;
   410 
   411     fun prep (ctxt, raw_element) =
   412       let val elems = map (apsnd (map (closeup ctxt)))
   413         (eval_element ctxt (prep_element ctxt raw_element))
   414       in (activate_locale_elems elems ctxt, flat (map #2 elems)) end;
   415     val (locale_ctxt, elemss) = foldl_map prep (import_ctxt, raw_elements);
   416 
   417     val elems = flat elemss;
   418     val local_params =  (* FIXME lookup final types *)
   419       flat (map (fn Fixes fixes => map (fn (x, T, _) => (x, T)) fixes | _ => []) elems);
   420     val params = map (rpair None) import_params @ local_params;  (* FIXME *)
   421     val text = ([], []);  (* FIXME *)
   422   in
   423     thy
   424     |> declare_locale name
   425     |> put_locale name (make_locale import (map (fn e => (e, stamp ())) elems)
   426       (params, local_params) text)
   427   end;
   428 
   429 val add_locale = gen_add_locale read_expr read_element;
   430 val add_locale_i = gen_add_locale (K I) (K I);
   431 
   432 
   433 
   434 (** store results **)
   435 
   436 fun add_thmss name args thy =
   437   let
   438     val {import, params, elems, text} = the_locale thy name;
   439     val note = Notes (map (fn ((a, ths), atts) =>
   440       ((a, atts), [(map (curry Thm.name_thm a) ths, [])])) args);
   441   in
   442     thy |> ProofContext.init |> activate_locale_i name |> activate_elem note;  (*test attributes!*)
   443     thy |> put_locale name (make_locale import (elems @ [(note, stamp ())]) params text)
   444   end;
   445 
   446 
   447 
   448 (** locale theory setup **)
   449 
   450 val setup =
   451  [LocalesData.init];
   452 
   453 end;