src/Pure/sign.ML
author wenzelm
Fri Oct 31 15:19:50 1997 +0100 (1997-10-31)
changeset 4052 026069ba0316
parent 4051 6b72919c9b4b
child 4124 1af16493c57f
permissions -rw-r--r--
*** empty log message ***
     1 (*  Title:      Pure/sign.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson and Markus Wenzel
     4 
     5 The abstract type "sg" of signatures.
     6 *)
     7 
     8 (*base names*)
     9 type bstring = string;
    10 type bclass = class;
    11 (*external forms -- partially qualified names*)
    12 type xstring = string;
    13 type xclass = class;
    14 type xsort = sort;
    15 type xtyp = typ;
    16 type xterm = term;
    17 
    18 signature SIGN =
    19 sig
    20   type sg
    21   type sg_ref
    22   val rep_sg: sg ->
    23    {self: sg_ref,
    24     tsig: Type.type_sig,
    25     const_tab: typ Symtab.table,
    26     syn: Syntax.syntax,
    27     path: string list,
    28     spaces: (string * NameSpace.T) list,
    29     data: Data.T}
    30   val name_of: sg -> string
    31   val stamp_names_of: sg -> string list
    32   val tsig_of: sg -> Type.type_sig
    33   val deref: sg_ref -> sg
    34   val self_ref: sg -> sg_ref
    35   val subsig: sg * sg -> bool
    36   val eq_sg: sg * sg -> bool
    37   val same_sg: sg * sg -> bool
    38   val is_draft: sg -> bool
    39   val const_type: sg -> string -> typ option
    40   val classes: sg -> class list
    41   val subsort: sg -> sort * sort -> bool
    42   val nodup_Vars: term -> unit
    43   val norm_sort: sg -> sort -> sort
    44   val nonempty_sort: sg -> sort list -> sort -> bool
    45   val long_names: bool ref
    46   val classK: string
    47   val typeK: string
    48   val constK: string
    49   val full_name: sg -> bstring -> string
    50   val base_name: string -> bstring
    51   val intern: sg -> string -> xstring -> string
    52   val extern: sg -> string -> string -> xstring
    53   val cond_extern: sg -> string -> string -> xstring
    54   val intern_class: sg -> xclass -> class
    55   val intern_tycon: sg -> xstring -> string
    56   val intern_const: sg -> xstring -> string
    57   val intern_sort: sg -> xsort -> sort
    58   val intern_typ: sg -> xtyp -> typ
    59   val intern_term: sg -> xterm -> term
    60   val intern_tycons: sg -> xtyp -> typ
    61   val print_sg: sg -> unit
    62   val pretty_sg: sg -> Pretty.T
    63   val str_of_sg: sg -> string
    64   val pprint_sg: sg -> pprint_args -> unit
    65   val pretty_term: sg -> term -> Pretty.T
    66   val pretty_typ: sg -> typ -> Pretty.T
    67   val pretty_sort: sg -> sort -> Pretty.T
    68   val string_of_term: sg -> term -> string
    69   val string_of_typ: sg -> typ -> string
    70   val string_of_sort: sg -> sort -> string
    71   val str_of_sort: sg -> sort -> string
    72   val str_of_classrel: sg -> class * class -> string
    73   val str_of_arity: sg -> string * sort list * sort -> string
    74   val pprint_term: sg -> term -> pprint_args -> unit
    75   val pprint_typ: sg -> typ -> pprint_args -> unit
    76   val certify_typ: sg -> typ -> typ
    77   val certify_term: sg -> term -> term * typ * int
    78   val read_typ: sg * (indexname -> sort option) -> string -> typ
    79   val infer_types: sg -> (indexname -> typ option) ->
    80     (indexname -> sort option) -> string list -> bool
    81     -> xterm list * typ -> int * term * (indexname * typ) list
    82   val add_classes: (bclass * xclass list) list -> sg -> sg
    83   val add_classes_i: (bclass * class list) list -> sg -> sg
    84   val add_classrel: (xclass * xclass) list -> sg -> sg
    85   val add_classrel_i: (class * class) list -> sg -> sg
    86   val add_defsort: xsort -> sg -> sg
    87   val add_defsort_i: sort -> sg -> sg
    88   val add_types: (bstring * int * mixfix) list -> sg -> sg
    89   val add_tyabbrs: (bstring * string list * string * mixfix) list -> sg -> sg
    90   val add_tyabbrs_i: (bstring * string list * typ * mixfix) list -> sg -> sg
    91   val add_arities: (xstring * xsort list * xsort) list -> sg -> sg
    92   val add_arities_i: (string * sort list * sort) list -> sg -> sg
    93   val add_consts: (bstring * string * mixfix) list -> sg -> sg
    94   val add_consts_i: (bstring * typ * mixfix) list -> sg -> sg
    95   val add_syntax: (bstring * string * mixfix) list -> sg -> sg
    96   val add_syntax_i: (bstring * typ * mixfix) list -> sg -> sg
    97   val add_modesyntax: (string * bool) * (bstring * string * mixfix) list -> sg -> sg
    98   val add_modesyntax_i: (string * bool) * (bstring * typ * mixfix) list -> sg -> sg
    99   val add_trfuns:
   100     (bstring * (ast list -> ast)) list *
   101     (bstring * (term list -> term)) list *
   102     (bstring * (term list -> term)) list *
   103     (bstring * (ast list -> ast)) list -> sg -> sg
   104   val add_trfunsT:
   105     (bstring * (typ -> term list -> term)) list -> sg -> sg
   106   val add_tokentrfuns:
   107     (string * string * (string -> string * int)) list -> sg -> sg
   108   val add_trrules: (string * string) Syntax.trrule list -> sg -> sg
   109   val add_trrules_i: ast Syntax.trrule list -> sg -> sg
   110   val add_path: string -> sg -> sg
   111   val add_space: string * string list -> sg -> sg
   112   val add_name: string -> sg -> sg
   113   val init_data: string * (exn * (exn -> exn) * (exn * exn -> exn) * (exn -> unit))
   114     -> sg -> sg
   115   val get_data: sg -> string -> exn
   116   val put_data: string * exn -> sg -> sg
   117   val print_data: sg -> string -> unit
   118   val merge_refs: sg_ref * sg_ref -> sg_ref
   119   val prep_ext: sg -> sg
   120   val merge: sg * sg -> sg
   121   val pre_pure: sg
   122   val const_of_class: class -> string
   123   val class_of_const: string -> class
   124 end;
   125 
   126 structure Sign : SIGN =
   127 struct
   128 
   129 
   130 (** datatype sg **)
   131 
   132 datatype sg =
   133   Sg of
   134    {id: string ref,                             (*id*)
   135     stamps: string ref list} *                  (*unique theory indentifier*)
   136    {self: sg_ref,                               (*mutable self reference*)
   137     tsig: Type.type_sig,                        (*order-sorted signature of types*)
   138     const_tab: typ Symtab.table,                (*type schemes of constants*)
   139     syn: Syntax.syntax,                         (*syntax for parsing and printing*)
   140     path: string list,                          (*current name space entry prefix*)
   141     spaces: (string * NameSpace.T) list,        (*name spaces for consts, types etc.*)
   142     data: Data.T}                               (*additional data*)
   143 and sg_ref =
   144   SgRef of sg ref option;
   145 
   146 (*make signature*)
   147 fun make_sign (id, self, tsig, const_tab, syn, path, spaces, data, stamps) =
   148   Sg ({id = id, stamps = stamps}, {self = self, tsig = tsig, const_tab = const_tab,
   149     syn = syn, path = path, spaces = spaces, data = data});
   150 
   151 
   152 (* basic components *)
   153 
   154 fun rep_sg (Sg (_, args)) = args;
   155 
   156 (*show stamps*)
   157 fun stamp_names_of (Sg ({stamps, ...}, _)) = rev (map ! stamps);
   158 fun pretty_sg sg = Pretty.str_list "{" "}" (stamp_names_of sg);
   159 val str_of_sg = Pretty.str_of o pretty_sg;
   160 val pprint_sg = Pretty.pprint o pretty_sg;
   161 
   162 val tsig_of = #tsig o rep_sg;
   163 
   164 fun const_type (Sg (_, {const_tab, ...})) c = Symtab.lookup (const_tab, c);
   165 val classes = #classes o Type.rep_tsig o tsig_of;
   166 
   167 val subsort = Type.subsort o tsig_of;
   168 val norm_sort = Type.norm_sort o tsig_of;
   169 val nonempty_sort = Type.nonempty_sort o tsig_of;
   170 
   171 
   172 (* data *)
   173 
   174 fun access_data f sg k = f (#data (rep_sg sg)) k
   175   handle ERROR => error ("of theory " ^ str_of_sg sg);
   176 
   177 val get_data = access_data Data.get;
   178 val print_data = access_data Data.print;
   179 
   180 
   181 (* id and self *)
   182 
   183 fun check_stale (sg as Sg ({id, ...},
   184         {self = SgRef (Some (ref (Sg ({id = id', ...}, _)))), ...})) =
   185       if id = id' then sg
   186       else raise TERM ("Stale signature: " ^ str_of_sg sg, [])
   187   | check_stale _ = sys_error "Sign.check_stale";
   188 
   189 fun self_ref (sg as Sg (_, {self, ...})) = (check_stale sg; self);
   190 
   191 fun deref (SgRef (Some (ref sg))) = sg
   192   | deref (SgRef None) = sys_error "Sign.deref";
   193 
   194 fun name_of (sg as Sg ({id = ref name, ...}, _)) =
   195   if name = "" orelse name = "#" then
   196     raise TERM ("Nameless signature " ^ str_of_sg sg, [])
   197   else name;
   198 
   199 
   200 (* inclusion and equality *)
   201 
   202 local
   203   (*avoiding polymorphic equality: factor 10 speedup*)
   204   fun mem_stamp (_:string ref, []) = false
   205     | mem_stamp (x, y :: ys) = x = y orelse mem_stamp (x, ys);
   206 
   207   fun subset_stamp ([], ys) = true
   208     | subset_stamp (x :: xs, ys) =
   209         mem_stamp (x, ys) andalso subset_stamp (xs, ys);
   210 
   211   (*fast partial test*)
   212   fun fast_sub ([]: string ref list, _) = true
   213     | fast_sub (_, []) = false
   214     | fast_sub (x :: xs, y :: ys) =
   215         if x = y then fast_sub (xs, ys)
   216         else fast_sub (x :: xs, ys);
   217 in
   218   fun eq_sg (sg1 as Sg ({id = id1, ...}, _), sg2 as Sg ({id = id2, ...}, _)) =
   219     (check_stale sg1; check_stale sg2; id1 = id2);
   220 
   221   fun subsig (sg1 as Sg ({stamps = s1, ...}, _), sg2 as Sg ({stamps = s2, ...}, _)) =
   222     eq_sg (sg1, sg2) orelse subset_stamp (s1, s2);
   223 
   224   fun fast_subsig (sg1 as Sg ({stamps = s1, ...}, _), sg2 as Sg ({stamps = s2, ...}, _)) =
   225     eq_sg (sg1, sg2) orelse fast_sub (s1, s2);
   226 end;
   227 
   228 
   229 (*test if same theory names are contained in signatures' stamps,
   230   i.e. if signatures belong to same theory but not necessarily to the
   231   same version of it*)
   232 fun same_sg (sg1 as Sg ({stamps = s1, ...}, _), sg2 as Sg ({stamps = s2, ...}, _)) =
   233   eq_sg (sg1, sg2) orelse eq_set_string (pairself (map (op !)) (s1, s2));
   234 
   235 (*test for drafts*)
   236 fun is_draft (Sg ({stamps = ref "#" :: _, ...}, _)) = true
   237   | is_draft _ = false;
   238 
   239 
   240 (* build signature *)
   241 
   242 fun ext_stamps stamps (id as ref name) =
   243   let val stmps = (case stamps of ref "#" :: ss => ss | ss => ss) in
   244     if exists (equal name o !) stmps then
   245       error ("Theory already contains a " ^ quote name ^ " component")
   246     else id :: stmps
   247   end;
   248 
   249 fun create_sign self stamps name (syn, tsig, ctab, (path, spaces), data) =
   250   let
   251     val id = ref name;
   252     val sign =
   253       make_sign (id, self, tsig, ctab, syn, path, spaces, data, ext_stamps stamps id);
   254   in
   255     (case self of
   256       SgRef (Some r) => r := sign
   257     | _ => sys_error "Sign.create_sign");
   258     sign
   259   end;
   260 
   261 fun extend_sign keep extfun name decls
   262     (sg as Sg ({id = _, stamps}, {self, tsig, const_tab, syn, path, spaces, data})) =
   263   let
   264     val _ = check_stale sg;
   265     val (self', data') =
   266       if is_draft sg andalso keep then (self, data)
   267       else (SgRef (Some (ref sg)), Data.prep_ext data);
   268   in
   269     create_sign self' stamps name
   270       (extfun (syn, tsig, const_tab, (path, spaces), data') decls)
   271   end;
   272 
   273 
   274 
   275 (** name spaces **)
   276 
   277 (*prune names on output by default*)
   278 val long_names = ref false;
   279 
   280 
   281 (* kinds *)
   282 
   283 val classK = "class";
   284 val typeK = "type";
   285 val constK = "const";
   286 
   287 
   288 (* add and retrieve names *)
   289 
   290 fun space_of spaces kind =
   291   if_none (assoc (spaces, kind)) NameSpace.empty;
   292 
   293 (*input and output of qualified names*)
   294 fun intrn spaces kind = NameSpace.intern (space_of spaces kind);
   295 fun extrn spaces kind = NameSpace.extern (space_of spaces kind);
   296 
   297 (*add names*)
   298 fun add_names spaces kind names =
   299   let val space' = NameSpace.extend (names, space_of spaces kind) in
   300     overwrite (spaces, (kind, space'))
   301   end;
   302 
   303 (*make full names*)
   304 fun full path name =
   305   if NameSpace.qualified name then
   306     error ("Attempt to declare qualified name " ^ quote name)
   307   else NameSpace.pack (path @ [name]);
   308 
   309 (*base name*)
   310 val base_name = NameSpace.base;
   311 
   312 
   313 (* intern / extern names *)
   314 
   315 local
   316   (*prepare mapping of names*)
   317   fun mapping f add_xs t =
   318     let
   319       fun f' x = let val y = f x in if x = y then None else Some (x, y) end;
   320       val table = mapfilter f' (add_xs (t, []));
   321       fun lookup x = if_none (assoc (table, x)) x;
   322     in lookup end;
   323 
   324   (*intern / extern typ*)
   325   fun trn_typ trn T =
   326     T |> map_typ
   327       (mapping (trn classK) add_typ_classes T)
   328       (mapping (trn typeK) add_typ_tycons T);
   329 
   330   (*intern / extern term*)
   331   fun trn_term trn t =
   332     t |> map_term
   333       (mapping (trn classK) add_term_classes t)
   334       (mapping (trn typeK) add_term_tycons t)
   335       (mapping (trn constK) add_term_consts t);
   336 
   337   val spaces_of = #spaces o rep_sg;
   338 in
   339   fun intrn_class spaces = intrn spaces classK;
   340   fun extrn_class spaces = extrn spaces classK;
   341 
   342   val intrn_sort = map o intrn_class;
   343   val intrn_typ = trn_typ o intrn;
   344   val intrn_term = trn_term o intrn;
   345 
   346   val extrn_sort = map o extrn_class;
   347   val extrn_typ = trn_typ o extrn;
   348   val extrn_term = trn_term o extrn;
   349 
   350   fun intrn_tycons spaces T =
   351     map_typ I (mapping (intrn spaces typeK) add_typ_tycons T) T;
   352 
   353   val intern = intrn o spaces_of;
   354   val extern = extrn o spaces_of;
   355   fun cond_extern sg kind = if ! long_names then I else extern sg kind;
   356 
   357   val intern_class = intrn_class o spaces_of;
   358   val intern_sort = intrn_sort o spaces_of;
   359   val intern_typ = intrn_typ o spaces_of;
   360   val intern_term = intrn_term o spaces_of;
   361 
   362   fun intern_tycon sg = intrn (spaces_of sg) typeK;
   363   fun intern_const sg = intrn (spaces_of sg) constK;
   364 
   365   val intern_tycons = intrn_tycons o spaces_of;
   366 
   367   val full_name = full o #path o rep_sg;
   368 end;
   369 
   370 
   371 
   372 (** pretty printing of terms and types **)
   373 
   374 fun pretty_term (sg as Sg (_, {syn, spaces, ...})) t =
   375   Syntax.pretty_term syn
   376     ("CPure" mem_string (stamp_names_of sg))
   377     (if ! long_names then t else extrn_term spaces t);
   378 
   379 fun pretty_typ (Sg (_, {syn, spaces, ...})) T =
   380   Syntax.pretty_typ syn
   381     (if ! long_names then T else extrn_typ spaces T);
   382 
   383 fun pretty_sort (Sg (_, {syn, spaces, ...})) S =
   384   Syntax.pretty_sort syn
   385     (if ! long_names then S else extrn_sort spaces S);
   386 
   387 fun pretty_classrel sg (c1, c2) = Pretty.block
   388   [pretty_sort sg [c1], Pretty.str " <", Pretty.brk 1, pretty_sort sg [c2]];
   389 
   390 fun pretty_arity sg (t, Ss, S) =
   391   let
   392     val t' = cond_extern sg typeK t;
   393     val dom =
   394       if null Ss then []
   395       else [Pretty.list "(" ")" (map (pretty_sort sg) Ss), Pretty.brk 1];
   396   in
   397     Pretty.block
   398       ([Pretty.str (t' ^ " ::"), Pretty.brk 1] @ dom @ [pretty_sort sg S])
   399   end;
   400 
   401 fun string_of_term sg t = Pretty.string_of (pretty_term sg t);
   402 fun string_of_typ sg T = Pretty.string_of (pretty_typ sg T);
   403 fun string_of_sort sg S = Pretty.string_of (pretty_sort sg S);
   404 
   405 fun str_of_sort sg S = Pretty.str_of (pretty_sort sg S);
   406 fun str_of_classrel sg c1_c2 = Pretty.str_of (pretty_classrel sg c1_c2);
   407 fun str_of_arity sg ar = Pretty.str_of (pretty_arity sg ar);
   408 
   409 fun pprint_term sg = Pretty.pprint o Pretty.quote o (pretty_term sg);
   410 fun pprint_typ sg = Pretty.pprint o Pretty.quote o (pretty_typ sg);
   411 
   412 
   413 
   414 (** print signature **)
   415 
   416 fun print_sg sg =
   417   let
   418     fun prt_cls c = pretty_sort sg [c];
   419     fun prt_sort S = pretty_sort sg S;
   420     fun prt_arity t (c, Ss) = pretty_arity sg (t, Ss, [c]);
   421     fun prt_typ ty = Pretty.quote (pretty_typ sg ty);
   422 
   423     val ext_class = cond_extern sg classK;
   424     val ext_tycon = cond_extern sg typeK;
   425     val ext_const = cond_extern sg constK;
   426 
   427 
   428     fun pretty_space (kind, space) = Pretty.block (Pretty.breaks
   429       (map Pretty.str (kind ^ ":" :: map quote (NameSpace.dest space))));
   430 
   431     fun pretty_classes cs = Pretty.block
   432       (Pretty.breaks (Pretty.str "classes:" :: map prt_cls cs));
   433 
   434     fun pretty_classrel (c, cs) = Pretty.block
   435       (prt_cls c :: Pretty.str " <" :: Pretty.brk 1 ::
   436         Pretty.commas (map prt_cls cs));
   437 
   438     fun pretty_default S = Pretty.block
   439       [Pretty.str "default:", Pretty.brk 1, pretty_sort sg S];
   440 
   441     fun pretty_ty (t, n) = Pretty.block
   442       [Pretty.str (ext_tycon t), Pretty.str (" " ^ string_of_int n)];
   443 
   444     fun pretty_abbr (t, (vs, rhs)) = Pretty.block
   445       [prt_typ (Type (t, map (fn v => TVar ((v, 0), [])) vs)),
   446         Pretty.str " =", Pretty.brk 1, prt_typ rhs];
   447 
   448     fun pretty_arities (t, ars) = map (prt_arity t) ars;
   449 
   450     fun pretty_const (c, ty) = Pretty.block
   451       [Pretty.str c, Pretty.str " ::", Pretty.brk 1, prt_typ ty];
   452 
   453     val Sg (_, {self = _, tsig, const_tab, syn = _, path, spaces, data}) = sg;
   454     val spaces' = sort (fn ((k1, _), (k2, _)) => k1 < k2) spaces;
   455     val {classes, classrel, default, tycons, abbrs, arities} =
   456       Type.rep_tsig tsig;
   457     val consts = sort_wrt fst (map (apfst ext_const) (Symtab.dest const_tab));
   458   in
   459     Pretty.writeln (Pretty.strs ("stamps:" :: stamp_names_of sg));
   460     Pretty.writeln (Pretty.strs ("data:" :: Data.kinds data));
   461     Pretty.writeln (Pretty.strs ["name entry path:", NameSpace.pack path]);
   462     Pretty.writeln (Pretty.big_list "name spaces:" (map pretty_space spaces'));
   463     Pretty.writeln (pretty_classes classes);
   464     Pretty.writeln (Pretty.big_list "class relation:" (map pretty_classrel classrel));
   465     Pretty.writeln (pretty_default default);
   466     Pretty.writeln (Pretty.big_list "type constructors:" (map pretty_ty tycons));
   467     Pretty.writeln (Pretty.big_list "type abbreviations:" (map pretty_abbr abbrs));
   468     Pretty.writeln (Pretty.big_list "type arities:" (flat (map pretty_arities arities)));
   469     Pretty.writeln (Pretty.big_list "consts:" (map pretty_const consts))
   470   end;
   471 
   472 
   473 
   474 (** read types **)  (*exception ERROR*)
   475 
   476 fun err_in_type s =
   477   error ("The error(s) above occurred in type " ^ quote s);
   478 
   479 fun read_raw_typ syn tsig spaces def_sort str =
   480   intrn_tycons spaces
   481     (Syntax.read_typ syn (Type.get_sort tsig def_sort (intrn_sort spaces)) str
   482       handle ERROR => err_in_type str);
   483   
   484 (*read and certify typ wrt a signature*)
   485 fun read_typ (sg as Sg (_, {tsig, syn, spaces, ...}), def_sort) str =
   486   (check_stale sg;
   487     Type.cert_typ tsig (read_raw_typ syn tsig spaces def_sort str)
   488       handle TYPE (msg, _, _) => (error_msg msg; err_in_type str));
   489 
   490 
   491 
   492 (** certify types and terms **)   (*exception TYPE*)
   493 
   494 val certify_typ = Type.cert_typ o tsig_of;
   495 
   496 (*check for duplicate TVars with distinct sorts*)
   497 fun nodup_TVars (tvars, T) =
   498   (case T of
   499     Type (_, Ts) => nodup_TVars_list (tvars, Ts)
   500   | TFree _ => tvars
   501   | TVar (v as (a, S)) =>
   502       (case assoc_string_int (tvars, a) of
   503         Some S' =>
   504           if S = S' then tvars
   505           else raise TYPE ("Type variable " ^ Syntax.string_of_vname a ^
   506             " has two distinct sorts", [TVar (a, S'), T], [])
   507       | None => v :: tvars))
   508 (*equivalent to foldl nodup_TVars_list, but 3X faster under Poly/ML*)
   509 and nodup_TVars_list (tvars, []) = tvars
   510   | nodup_TVars_list (tvars, T :: Ts) =
   511       nodup_TVars_list (nodup_TVars (tvars, T), Ts);
   512 
   513 (*check for duplicate Vars with distinct types*)
   514 fun nodup_Vars tm =
   515   let
   516     fun nodups vars tvars tm =
   517       (case tm of
   518         Const (c, T) => (vars, nodup_TVars (tvars, T))
   519       | Free (a, T) => (vars, nodup_TVars (tvars, T))
   520       | Var (v as (ixn, T)) =>
   521           (case assoc_string_int (vars, ixn) of
   522             Some T' =>
   523               if T = T' then (vars, nodup_TVars (tvars, T))
   524               else raise TYPE ("Variable " ^ Syntax.string_of_vname ixn ^
   525                 " has two distinct types", [T', T], [])
   526           | None => (v :: vars, tvars))
   527       | Bound _ => (vars, tvars)
   528       | Abs (_, T, t) => nodups vars (nodup_TVars (tvars, T)) t
   529       | s $ t =>
   530           let val (vars',tvars') = nodups vars tvars s in
   531             nodups vars' tvars' t
   532           end);
   533   in nodups [] [] tm; () end;
   534 
   535 
   536 fun mapfilt_atoms f (Abs (_, _, t)) = mapfilt_atoms f t
   537   | mapfilt_atoms f (t $ u) = mapfilt_atoms f t @ mapfilt_atoms f u
   538   | mapfilt_atoms f a = (case f a of Some y => [y] | None => []);
   539 
   540 
   541 fun certify_term sg tm =
   542   let
   543     val _ = check_stale sg;
   544     val tsig = tsig_of sg;
   545 
   546     fun show_const a T = quote a ^ " :: " ^ quote (string_of_typ sg T);
   547 
   548     fun atom_err (Const (a, T)) =
   549         (case const_type sg a of
   550           None => Some ("Undeclared constant " ^ show_const a T)
   551         | Some U =>
   552             if Type.typ_instance (tsig, T, U) then None
   553             else Some ("Illegal type for constant " ^ show_const a T))
   554       | atom_err (Var ((x, i), _)) =
   555           if i < 0 then Some ("Negative index for Var " ^ quote x) else None
   556       | atom_err _ = None;
   557 
   558     val norm_tm =
   559       (case it_term_types (Type.typ_errors tsig) (tm, []) of
   560         [] => map_term_types (Type.norm_typ tsig) tm
   561       | errs => raise TYPE (cat_lines errs, [], [tm]));
   562     val _ = nodup_Vars norm_tm;
   563   in
   564     (case mapfilt_atoms atom_err norm_tm of
   565       [] => (norm_tm, type_of norm_tm, maxidx_of_term norm_tm)
   566     | errs => raise TYPE (cat_lines errs, [], [norm_tm]))
   567   end;
   568 
   569 
   570 
   571 (** infer_types **)         (*exception ERROR*)
   572 
   573 (*
   574   ts: list of alternative parses (hopefully only one is type-correct)
   575   T: expected type
   576 
   577   def_type: partial map from indexnames to types (constrains Frees, Vars)
   578   def_sort: partial map from indexnames to sorts (constrains TFrees, TVars)
   579   used: list of already used type variables
   580   freeze: if true then generated parameters are turned into TFrees, else TVars
   581 *)
   582 
   583 fun infer_types sg def_type def_sort used freeze (ts, T) =
   584   let
   585     val tsig = tsig_of sg;
   586     val prt =
   587       setmp Syntax.show_brackets true
   588         (setmp long_names true (pretty_term sg));
   589     val prT = setmp long_names true (pretty_typ sg);
   590     val infer = Type.infer_types prt prT tsig (const_type sg) def_type def_sort
   591       (intern_const sg) (intern_tycons sg) (intern_sort sg) used freeze;
   592 
   593     val T' = certify_typ sg T handle TYPE (msg, _, _) => error msg;
   594 
   595     fun warn () =
   596       if length ts > 1 andalso length ts <= ! Syntax.ambiguity_level
   597       then (*no warning shown yet*)
   598         warning "Got more than one parse tree.\n\
   599           \Retry with smaller Syntax.ambiguity_level for more information."
   600       else ();
   601 
   602     datatype result =
   603       One of int * term * (indexname * typ) list |
   604       Errs of string list |
   605       Ambigs of term list;
   606 
   607     fun process_term (res, (t, i)) =
   608       let val ([u], tye) = infer [T'] [t] in
   609         (case res of
   610           One (_, t0, _) => Ambigs ([u, t0])
   611         | Errs _ => One (i, u, tye)
   612         | Ambigs us => Ambigs (u :: us))
   613       end handle TYPE (msg, _, _) =>
   614         (case res of
   615           Errs errs => Errs (msg :: errs)
   616         | _ => res);
   617   in
   618     (case foldl process_term (Errs [], ts ~~ (0 upto (length ts - 1))) of
   619       One res =>
   620        (if length ts > ! Syntax.ambiguity_level then
   621           warning "Fortunately, only one parse tree is type correct.\n\
   622             \You may still want to disambiguate your grammar or your input."
   623         else (); res)
   624     | Errs errs => (warn (); error (cat_lines errs))
   625     | Ambigs us =>
   626         (warn (); error ("More than one term is type correct:\n" ^
   627           (cat_lines (map (Pretty.string_of o prt) us)))))
   628   end;
   629 
   630 
   631 
   632 (** extend signature **)    (*exception ERROR*)
   633 
   634 (** signature extension functions **)  (*exception ERROR*)
   635 
   636 fun decls_of path name_of mfixs =
   637   map (fn (x, y, mx) => (full path (name_of x mx), y)) mfixs;
   638 
   639 fun no_read _ _ _ decl = decl;
   640 
   641 
   642 (* add default sort *)
   643 
   644 fun ext_defsort int (syn, tsig, ctab, (path, spaces), data) S =
   645   (syn, Type.ext_tsig_defsort tsig (if int then intrn_sort spaces S else S),
   646     ctab, (path, spaces), data);
   647 
   648 
   649 (* add type constructors *)
   650 
   651 fun ext_types (syn, tsig, ctab, (path, spaces), data) types =
   652   let val decls = decls_of path Syntax.type_name types in
   653     (Syntax.extend_type_gram syn types,
   654       Type.ext_tsig_types tsig decls, ctab,
   655       (path, add_names spaces typeK (map fst decls)), data)
   656   end;
   657 
   658 
   659 (* add type abbreviations *)
   660 
   661 fun read_abbr syn tsig spaces (t, vs, rhs_src) =
   662   (t, vs, read_raw_typ syn tsig spaces (K None) rhs_src)
   663     handle ERROR => error ("in type abbreviation " ^ t);
   664 
   665 fun ext_abbrs rd_abbr (syn, tsig, ctab, (path, spaces), data) abbrs =
   666   let
   667     fun mfix_of (t, vs, _, mx) = (t, length vs, mx);
   668     val syn' = Syntax.extend_type_gram syn (map mfix_of abbrs);
   669 
   670     val abbrs' =
   671       map (fn (t, vs, rhs, mx) =>
   672         (full path (Syntax.type_name t mx), vs, rhs)) abbrs;
   673     val spaces' = add_names spaces typeK (map #1 abbrs');
   674     val decls = map (rd_abbr syn' tsig spaces') abbrs';
   675   in
   676     (syn', Type.ext_tsig_abbrs tsig decls, ctab, (path, spaces'), data)
   677   end;
   678 
   679 fun ext_tyabbrs abbrs = ext_abbrs read_abbr abbrs;
   680 fun ext_tyabbrs_i abbrs = ext_abbrs no_read abbrs;
   681 
   682 
   683 (* add type arities *)
   684 
   685 fun ext_arities int (syn, tsig, ctab, (path, spaces), data) arities =
   686   let
   687     fun intrn_arity (c, Ss, S) =
   688       (intrn spaces typeK c, map (intrn_sort spaces) Ss, intrn_sort spaces S);
   689     val intrn = if int then map intrn_arity else I;
   690     val tsig' = Type.ext_tsig_arities tsig (intrn arities);
   691     val log_types = Type.logical_types tsig';
   692   in
   693     (Syntax.extend_log_types syn log_types, tsig', ctab, (path, spaces), data)
   694   end;
   695 
   696 
   697 (* add term constants and syntax *)
   698 
   699 fun const_name path c mx =
   700   full path (Syntax.const_name c mx);
   701 
   702 fun err_in_const c =
   703   error ("in declaration of constant " ^ quote c);
   704 
   705 fun err_dup_consts cs =
   706   error ("Duplicate declaration of constant(s) " ^ commas_quote cs);
   707 
   708 
   709 fun read_const syn tsig (path, spaces) (c, ty_src, mx) =
   710   (c, read_raw_typ syn tsig spaces (K None) ty_src, mx)
   711     handle ERROR => err_in_const (const_name path c mx);
   712 
   713 fun ext_cnsts rd_const syn_only prmode (syn, tsig, ctab, (path, spaces), data) raw_consts =
   714   let
   715     fun prep_const (c, ty, mx) =
   716       (c, compress_type (Type.varifyT (Type.cert_typ tsig (Type.no_tvars ty))), mx)
   717         handle TYPE (msg, _, _) =>
   718           (error_msg msg; err_in_const (const_name path c mx));
   719 
   720     val consts = map (prep_const o rd_const syn tsig (path, spaces)) raw_consts;
   721     val decls =
   722       if syn_only then []
   723       else decls_of path Syntax.const_name consts;
   724   in
   725     (Syntax.extend_const_gram syn prmode consts, tsig,
   726       Symtab.extend_new (ctab, decls)
   727         handle Symtab.DUPS cs => err_dup_consts cs,
   728       (path, add_names spaces constK (map fst decls)), data)
   729   end;
   730 
   731 fun ext_consts_i sg = ext_cnsts no_read false ("", true) sg;
   732 fun ext_consts sg = ext_cnsts read_const false ("", true) sg;
   733 fun ext_syntax_i sg = ext_cnsts no_read true ("", true) sg;
   734 fun ext_syntax sg = ext_cnsts read_const true ("", true) sg;
   735 fun ext_modesyntax_i sg (prmode, consts) = ext_cnsts no_read true prmode sg consts;
   736 fun ext_modesyntax sg (prmode, consts) = ext_cnsts read_const true prmode sg consts;
   737 
   738 
   739 (* add type classes *)
   740 
   741 fun const_of_class c = c ^ "_class";
   742 
   743 fun class_of_const c_class =
   744   let
   745     val c = implode (take (size c_class - size "_class", explode c_class));
   746   in
   747     if const_of_class c = c_class then c
   748     else raise TERM ("class_of_const: bad name " ^ quote c_class, [])
   749   end;
   750 
   751 
   752 fun ext_classes int (syn, tsig, ctab, (path, spaces), data) classes =
   753   let
   754     val names = map fst classes;
   755     val consts =
   756       map (fn c => (const_of_class c, a_itselfT --> propT, NoSyn)) names;
   757 
   758     val full_names = map (full path) names;
   759     val spaces' = add_names spaces classK full_names;
   760     val intrn = if int then map (intrn_class spaces') else I;
   761     val classes' =
   762       ListPair.map (fn (c, (_, cs)) => (c, intrn cs)) (full_names, classes);
   763   in
   764     ext_consts_i
   765       (Syntax.extend_consts syn names,
   766         Type.ext_tsig_classes tsig classes', ctab, (path, spaces'), data)
   767     consts
   768   end;
   769 
   770 
   771 (* add to classrel *)
   772 
   773 fun ext_classrel int (syn, tsig, ctab, (path, spaces), data) pairs =
   774   let val intrn = if int then map (pairself (intrn_class spaces)) else I in
   775     (syn, Type.ext_tsig_classrel tsig (intrn pairs), ctab, (path, spaces), data)
   776   end;
   777 
   778 
   779 (* add to syntax *)
   780 
   781 fun ext_syn extfun (syn, tsig, ctab, names, data) args =
   782   (extfun syn args, tsig, ctab, names, data);
   783 
   784 
   785 (* add to path *)
   786 
   787 fun ext_path (syn, tsig, ctab, (path, spaces), data) elem =
   788   let
   789     val path' =
   790       if elem = ".." andalso not (null path) then fst (split_last path)
   791       else if elem = "/" then []
   792       else path @ NameSpace.unpack elem;
   793   in
   794     (syn, tsig, ctab, (path', spaces), data)
   795   end;      
   796 
   797 
   798 (* add to name space *)
   799 
   800 fun ext_space (syn, tsig, ctab, (path, spaces), data) (kind, names) =
   801   (syn, tsig, ctab, (path, add_names spaces kind names), data);
   802 
   803 
   804 (* signature data *)
   805 
   806 fun ext_init_data (syn, tsig, ctab, names, data) (kind, (e, ext, mrg, prt)) =
   807   (syn, tsig, ctab, names, Data.init data kind e ext mrg prt);
   808 
   809 fun ext_put_data (syn, tsig, ctab, names, data) (kind, e) =
   810   (syn, tsig, ctab, names, Data.put data kind e);
   811 
   812 
   813 (* the external interfaces *)
   814 
   815 val add_classes      = extend_sign true (ext_classes true) "#";
   816 val add_classes_i    = extend_sign true (ext_classes false) "#";
   817 val add_classrel     = extend_sign true (ext_classrel true) "#";
   818 val add_classrel_i   = extend_sign true (ext_classrel false) "#";
   819 val add_defsort      = extend_sign true (ext_defsort true) "#";
   820 val add_defsort_i    = extend_sign true (ext_defsort false) "#";
   821 val add_types        = extend_sign true ext_types "#";
   822 val add_tyabbrs      = extend_sign true ext_tyabbrs "#";
   823 val add_tyabbrs_i    = extend_sign true ext_tyabbrs_i "#";
   824 val add_arities      = extend_sign true (ext_arities true) "#";
   825 val add_arities_i    = extend_sign true (ext_arities false) "#";
   826 val add_consts       = extend_sign true ext_consts "#";
   827 val add_consts_i     = extend_sign true ext_consts_i "#";
   828 val add_syntax       = extend_sign true ext_syntax "#";
   829 val add_syntax_i     = extend_sign true ext_syntax_i "#";
   830 val add_modesyntax   = extend_sign true ext_modesyntax "#";
   831 val add_modesyntax_i = extend_sign true ext_modesyntax_i "#";
   832 val add_trfuns       = extend_sign true (ext_syn Syntax.extend_trfuns) "#";
   833 val add_trfunsT      = extend_sign true (ext_syn Syntax.extend_trfunsT) "#";
   834 val add_tokentrfuns  = extend_sign true (ext_syn Syntax.extend_tokentrfuns) "#";
   835 val add_trrules      = extend_sign true (ext_syn Syntax.extend_trrules) "#";
   836 val add_trrules_i    = extend_sign true (ext_syn Syntax.extend_trrules_i) "#";
   837 val add_path         = extend_sign true ext_path "#";
   838 val add_space        = extend_sign true ext_space "#";
   839 val init_data        = extend_sign true ext_init_data "#";
   840 val put_data         = extend_sign true ext_put_data "#";
   841 fun add_name name sg = extend_sign true K name () sg;
   842 fun prep_ext sg      = extend_sign false K "#" () sg;
   843 
   844 
   845 
   846 (** merge signatures **)    	(*exception TERM*)
   847 
   848 (* merge of sg_refs -- trivial only *)
   849 
   850 fun merge_refs (sgr1 as SgRef (Some (ref sg1)),
   851         sgr2 as SgRef (Some (ref sg2))) =
   852       if fast_subsig (sg2, sg1) then sgr1
   853       else if fast_subsig (sg1, sg2) then sgr2
   854       else if subsig (sg2, sg1) then sgr1
   855       else if subsig (sg1, sg2) then sgr2
   856       else raise TERM ("Attempt to do non-trivial merge of signatures", [])
   857   | merge_refs _ = sys_error "Sign.merge_refs";
   858 
   859 
   860 (* proper merge *)
   861 
   862 fun merge_aux (sg1, sg2) =
   863   if subsig (sg2, sg1) then sg1
   864   else if subsig (sg1, sg2) then sg2
   865   else if is_draft sg1 orelse is_draft sg2 then
   866     raise TERM ("Attempt to merge draft signatures", [])
   867   else
   868     (*neither is union already; must form union*)
   869     let
   870       val Sg ({id = _, stamps = stamps1}, {self = _, tsig = tsig1, const_tab = const_tab1,
   871         syn = syn1, path = _, spaces = spaces1, data = data1}) = sg1;
   872       val Sg ({id = _, stamps = stamps2}, {self = _, tsig = tsig2, const_tab = const_tab2,
   873         syn = syn2, path = _, spaces = spaces2, data = data2}) = sg2;
   874 
   875       val id = ref "";
   876       val self_ref = ref sg1;                   (*dummy value*)
   877       val self = SgRef (Some self_ref);
   878       val stamps = merge_rev_lists stamps1 stamps2;
   879       val _ =
   880         (case duplicates (map ! stamps) of
   881           [] => ()
   882         | dups => raise TERM ("Attempt to merge different versions of theories "
   883             ^ commas_quote dups, []));
   884 
   885       val tsig = Type.merge_tsigs (tsig1, tsig2);
   886       val const_tab = Symtab.merge (op =) (const_tab1, const_tab2)
   887         handle Symtab.DUPS cs =>
   888           raise TERM ("Incompatible types for constant(s) " ^ commas_quote cs, []);
   889       val syn = Syntax.merge_syntaxes syn1 syn2;
   890 
   891       val path = [];
   892       val kinds = distinct (map fst (spaces1 @ spaces2));
   893       val spaces =
   894         kinds ~~
   895           ListPair.map NameSpace.merge
   896             (map (space_of spaces1) kinds, map (space_of spaces2) kinds);
   897 
   898       val data = Data.merge (data1, data2);
   899 
   900       val sign = make_sign (id, self, tsig, const_tab, syn, path, spaces, data, stamps);
   901     in
   902       self_ref := sign; sign
   903     end;
   904 
   905 fun merge sg1_sg2 =
   906   (case handle_error merge_aux sg1_sg2 of
   907     OK sg => sg
   908   | Error msg => raise TERM (msg, []));
   909 
   910 
   911 
   912 (** partial Pure signature **)
   913 
   914 val dummy_sg = make_sign (ref "", SgRef None, Type.tsig0,
   915   Symtab.null, Syntax.pure_syn, [], [], Data.empty, []);
   916 
   917 val pre_pure =
   918   create_sign (SgRef (Some (ref dummy_sg))) [] "#"
   919     (Syntax.pure_syn, Type.tsig0, Symtab.null, ([], []), Data.empty);
   920 
   921 
   922 end;
   923 
   924 
   925 val long_names = Sign.long_names;