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