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