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