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