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