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