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