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