src/Pure/sign.ML
author wenzelm
Tue Oct 28 17:29:48 1997 +0100 (1997-10-28)
changeset 4017 63878e2587a7
parent 4007 1d6aed7ff375
child 4051 6b72919c9b4b
permissions -rw-r--r--
add_typ_classes, add_typ_tycons, add_term_classes, add_term_tycons,
add_term_consts, map_typ, map_term: moved from sign.ML to term.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   (*prepare mapping of names*)
   309   fun mapping f add_xs t =
   310     let
   311       fun f' x = let val y = f x in if x = y then None else Some (x, y) end;
   312       val table = mapfilter f' (add_xs (t, []));
   313       fun lookup x = if_none (assoc (table, x)) x;
   314     in lookup end;
   315 
   316   (*intern / extern typ*)
   317   fun trn_typ trn T =
   318     T |> map_typ
   319       (mapping (trn classK) add_typ_classes T)
   320       (mapping (trn typeK) add_typ_tycons T);
   321 
   322   (*intern / extern term*)
   323   fun trn_term trn t =
   324     t |> map_term
   325       (mapping (trn classK) add_term_classes t)
   326       (mapping (trn typeK) add_term_tycons t)
   327       (mapping (trn constK) add_term_consts t);
   328 
   329   val spaces_of = #spaces o rep_sg;
   330 in
   331   fun intrn_class spaces = intrn spaces classK;
   332   fun extrn_class spaces = extrn spaces classK;
   333 
   334   val intrn_sort = map o intrn_class;
   335   val intrn_typ = trn_typ o intrn;
   336   val intrn_term = trn_term o intrn;
   337 
   338   val extrn_sort = map o extrn_class;
   339   val extrn_typ = trn_typ o extrn;
   340   val extrn_term = trn_term o extrn;
   341 
   342   fun intrn_tycons spaces T =
   343     map_typ I (mapping (intrn spaces typeK) add_typ_tycons T) T;
   344 
   345   val intern = intrn o spaces_of;
   346   val extern = extrn o spaces_of;
   347   fun cond_extern sg kind = if ! long_names then I else extern sg kind;
   348 
   349   val intern_class = intrn_class o spaces_of;
   350   val intern_sort = intrn_sort o spaces_of;
   351   val intern_typ = intrn_typ o spaces_of;
   352   val intern_term = intrn_term o spaces_of;
   353 
   354   fun intern_tycon sg = intrn (spaces_of sg) typeK;
   355   fun intern_const sg = intrn (spaces_of sg) constK;
   356 
   357   val intern_tycons = intrn_tycons o spaces_of;
   358 
   359   val full_name = full o #path o rep_sg;
   360 end;
   361 
   362 
   363 
   364 (** pretty printing of terms and types **)
   365 
   366 fun pretty_term (sg as Sg (_, {syn, spaces, ...})) t =
   367   Syntax.pretty_term syn
   368     ("CPure" mem_string (stamp_names_of sg))
   369     (if ! long_names then t else extrn_term spaces t);
   370 
   371 fun pretty_typ (Sg (_, {syn, spaces, ...})) T =
   372   Syntax.pretty_typ syn
   373     (if ! long_names then T else extrn_typ spaces T);
   374 
   375 fun pretty_sort (Sg (_, {syn, spaces, ...})) S =
   376   Syntax.pretty_sort syn
   377     (if ! long_names then S else extrn_sort spaces S);
   378 
   379 fun pretty_classrel sg (c1, c2) = Pretty.block
   380   [pretty_sort sg [c1], Pretty.str " <", Pretty.brk 1, pretty_sort sg [c2]];
   381 
   382 fun pretty_arity sg (t, Ss, S) =
   383   let
   384     val t' = cond_extern sg typeK t;
   385     val dom =
   386       if null Ss then []
   387       else [Pretty.list "(" ")" (map (pretty_sort sg) Ss), Pretty.brk 1];
   388   in
   389     Pretty.block
   390       ([Pretty.str (t' ^ " ::"), Pretty.brk 1] @ dom @ [pretty_sort sg S])
   391   end;
   392 
   393 fun string_of_term sg t = Pretty.string_of (pretty_term sg t);
   394 fun string_of_typ sg T = Pretty.string_of (pretty_typ sg T);
   395 fun string_of_sort sg S = Pretty.string_of (pretty_sort sg S);
   396 
   397 fun str_of_sort sg S = Pretty.str_of (pretty_sort sg S);
   398 fun str_of_classrel sg c1_c2 = Pretty.str_of (pretty_classrel sg c1_c2);
   399 fun str_of_arity sg ar = Pretty.str_of (pretty_arity sg ar);
   400 
   401 fun pprint_term sg = Pretty.pprint o Pretty.quote o (pretty_term sg);
   402 fun pprint_typ sg = Pretty.pprint o Pretty.quote o (pretty_typ sg);
   403 
   404 
   405 
   406 (** print signature **)
   407 
   408 fun print_sg sg =
   409   let
   410     fun prt_cls c = pretty_sort sg [c];
   411     fun prt_sort S = pretty_sort sg S;
   412     fun prt_arity t (c, Ss) = pretty_arity sg (t, Ss, [c]);
   413     fun prt_typ ty = Pretty.quote (pretty_typ sg ty);
   414 
   415     val ext_class = cond_extern sg classK;
   416     val ext_tycon = cond_extern sg typeK;
   417     val ext_const = cond_extern sg constK;
   418 
   419 
   420     fun pretty_space (kind, space) = Pretty.block (Pretty.breaks
   421       (map Pretty.str (kind ^ ":" :: map quote (NameSpace.dest space))));
   422 
   423     fun pretty_classes cs = Pretty.block
   424       (Pretty.breaks (Pretty.str "classes:" :: map prt_cls cs));
   425 
   426     fun pretty_classrel (c, cs) = Pretty.block
   427       (prt_cls c :: Pretty.str " <" :: Pretty.brk 1 ::
   428         Pretty.commas (map prt_cls cs));
   429 
   430     fun pretty_default S = Pretty.block
   431       [Pretty.str "default:", Pretty.brk 1, pretty_sort sg S];
   432 
   433     fun pretty_ty (t, n) = Pretty.block
   434       [Pretty.str (ext_tycon t), Pretty.str (" " ^ string_of_int n)];
   435 
   436     fun pretty_abbr (t, (vs, rhs)) = Pretty.block
   437       [prt_typ (Type (t, map (fn v => TVar ((v, 0), [])) vs)),
   438         Pretty.str " =", Pretty.brk 1, prt_typ rhs];
   439 
   440     fun pretty_arities (t, ars) = map (prt_arity t) ars;
   441 
   442     fun pretty_const (c, ty) = Pretty.block
   443       [Pretty.str c, Pretty.str " ::", Pretty.brk 1, prt_typ ty];
   444 
   445     val Sg (_, {self = _, tsig, const_tab, syn = _, path, spaces, data}) = sg;
   446     val spaces' = sort (fn ((k1, _), (k2, _)) => k1 < k2) spaces;
   447     val {classes, classrel, default, tycons, abbrs, arities} =
   448       Type.rep_tsig tsig;
   449     val consts = sort_wrt fst (map (apfst ext_const) (Symtab.dest const_tab));
   450   in
   451     Pretty.writeln (Pretty.strs ("stamps:" :: stamp_names_of sg));
   452     Pretty.writeln (Pretty.strs ("data:" :: Data.kinds data));
   453     Pretty.writeln (Pretty.strs ["name entry path:", NameSpace.pack path]);
   454     Pretty.writeln (Pretty.big_list "name spaces:" (map pretty_space spaces'));
   455     Pretty.writeln (pretty_classes classes);
   456     Pretty.writeln (Pretty.big_list "class relation:" (map pretty_classrel classrel));
   457     Pretty.writeln (pretty_default default);
   458     Pretty.writeln (Pretty.big_list "type constructors:" (map pretty_ty tycons));
   459     Pretty.writeln (Pretty.big_list "type abbreviations:" (map pretty_abbr abbrs));
   460     Pretty.writeln (Pretty.big_list "type arities:" (flat (map pretty_arities arities)));
   461     Pretty.writeln (Pretty.big_list "consts:" (map pretty_const consts))
   462   end;
   463 
   464 
   465 
   466 (** read types **)  (*exception ERROR*)
   467 
   468 fun err_in_type s =
   469   error ("The error(s) above occurred in type " ^ quote s);
   470 
   471 fun read_raw_typ syn tsig spaces def_sort str =
   472   intrn_tycons spaces
   473     (Syntax.read_typ syn (Type.get_sort tsig def_sort (intrn_sort spaces)) str
   474       handle ERROR => err_in_type str);
   475   
   476 (*read and certify typ wrt a signature*)
   477 fun read_typ (sg as Sg (_, {tsig, syn, spaces, ...}), def_sort) str =
   478   (check_stale sg;
   479     Type.cert_typ tsig (read_raw_typ syn tsig spaces def_sort str)
   480       handle TYPE (msg, _, _) => (error_msg msg; err_in_type str));
   481 
   482 
   483 
   484 (** certify types and terms **)   (*exception TYPE*)
   485 
   486 val certify_typ = Type.cert_typ o tsig_of;
   487 
   488 (*check for duplicate TVars with distinct sorts*)
   489 fun nodup_TVars (tvars, T) =
   490   (case T of
   491     Type (_, Ts) => nodup_TVars_list (tvars, Ts)
   492   | TFree _ => tvars
   493   | TVar (v as (a, S)) =>
   494       (case assoc_string_int (tvars, a) of
   495         Some S' =>
   496           if S = S' then tvars
   497           else raise TYPE ("Type variable " ^ Syntax.string_of_vname a ^
   498             " has two distinct sorts", [TVar (a, S'), T], [])
   499       | None => v :: tvars))
   500 (*equivalent to foldl nodup_TVars_list, but 3X faster under Poly/ML*)
   501 and nodup_TVars_list (tvars, []) = tvars
   502   | nodup_TVars_list (tvars, T :: Ts) =
   503       nodup_TVars_list (nodup_TVars (tvars, T), Ts);
   504 
   505 (*check for duplicate Vars with distinct types*)
   506 fun nodup_Vars tm =
   507   let
   508     fun nodups vars tvars tm =
   509       (case tm of
   510         Const (c, T) => (vars, nodup_TVars (tvars, T))
   511       | Free (a, T) => (vars, nodup_TVars (tvars, T))
   512       | Var (v as (ixn, T)) =>
   513           (case assoc_string_int (vars, ixn) of
   514             Some T' =>
   515               if T = T' then (vars, nodup_TVars (tvars, T))
   516               else raise TYPE ("Variable " ^ Syntax.string_of_vname ixn ^
   517                 " has two distinct types", [T', T], [])
   518           | None => (v :: vars, tvars))
   519       | Bound _ => (vars, tvars)
   520       | Abs (_, T, t) => nodups vars (nodup_TVars (tvars, T)) t
   521       | s $ t =>
   522           let val (vars',tvars') = nodups vars tvars s in
   523             nodups vars' tvars' t
   524           end);
   525   in nodups [] [] tm; () end;
   526 
   527 
   528 fun mapfilt_atoms f (Abs (_, _, t)) = mapfilt_atoms f t
   529   | mapfilt_atoms f (t $ u) = mapfilt_atoms f t @ mapfilt_atoms f u
   530   | mapfilt_atoms f a = (case f a of Some y => [y] | None => []);
   531 
   532 
   533 fun certify_term sg tm =
   534   let
   535     val _ = check_stale sg;
   536     val tsig = tsig_of sg;
   537 
   538     fun show_const a T = quote a ^ " :: " ^ quote (string_of_typ sg T);
   539 
   540     fun atom_err (Const (a, T)) =
   541         (case const_type sg a of
   542           None => Some ("Undeclared constant " ^ show_const a T)
   543         | Some U =>
   544             if Type.typ_instance (tsig, T, U) then None
   545             else Some ("Illegal type for constant " ^ show_const a T))
   546       | atom_err (Var ((x, i), _)) =
   547           if i < 0 then Some ("Negative index for Var " ^ quote x) else None
   548       | atom_err _ = None;
   549 
   550     val norm_tm =
   551       (case it_term_types (Type.typ_errors tsig) (tm, []) of
   552         [] => map_term_types (Type.norm_typ tsig) tm
   553       | errs => raise TYPE (cat_lines errs, [], [tm]));
   554     val _ = nodup_Vars norm_tm;
   555   in
   556     (case mapfilt_atoms atom_err norm_tm of
   557       [] => (norm_tm, type_of norm_tm, maxidx_of_term norm_tm)
   558     | errs => raise TYPE (cat_lines errs, [], [norm_tm]))
   559   end;
   560 
   561 
   562 
   563 (** infer_types **)         (*exception ERROR*)
   564 
   565 (*
   566   ts: list of alternative parses (hopefully only one is type-correct)
   567   T: expected type
   568 
   569   def_type: partial map from indexnames to types (constrains Frees, Vars)
   570   def_sort: partial map from indexnames to sorts (constrains TFrees, TVars)
   571   used: list of already used type variables
   572   freeze: if true then generated parameters are turned into TFrees, else TVars
   573 *)
   574 
   575 fun infer_types sg def_type def_sort used freeze (ts, T) =
   576   let
   577     val tsig = tsig_of sg;
   578     val prt =
   579       setmp Syntax.show_brackets true
   580         (setmp long_names true (pretty_term sg));
   581     val prT = setmp long_names true (pretty_typ sg);
   582     val infer = Type.infer_types prt prT tsig (const_type sg) def_type def_sort
   583       (intern_const sg) (intern_tycons sg) (intern_sort sg) used freeze;
   584 
   585     val T' = certify_typ sg T handle TYPE (msg, _, _) => error msg;
   586 
   587     fun warn () =
   588       if length ts > 1 andalso length ts <= ! Syntax.ambiguity_level
   589       then (*no warning shown yet*)
   590         warning "Got more than one parse tree.\n\
   591           \Retry with smaller Syntax.ambiguity_level for more information."
   592       else ();
   593 
   594     datatype result =
   595       One of int * term * (indexname * typ) list |
   596       Errs of string list |
   597       Ambigs of term list;
   598 
   599     fun process_term (res, (t, i)) =
   600       let val ([u], tye) = infer [T'] [t] in
   601         (case res of
   602           One (_, t0, _) => Ambigs ([u, t0])
   603         | Errs _ => One (i, u, tye)
   604         | Ambigs us => Ambigs (u :: us))
   605       end handle TYPE (msg, _, _) =>
   606         (case res of
   607           Errs errs => Errs (msg :: errs)
   608         | _ => res);
   609   in
   610     (case foldl process_term (Errs [], ts ~~ (0 upto (length ts - 1))) of
   611       One res =>
   612        (if length ts > ! Syntax.ambiguity_level then
   613           warning "Fortunately, only one parse tree is type correct.\n\
   614             \You may still want to disambiguate your grammar or your input."
   615         else (); res)
   616     | Errs errs => (warn (); error (cat_lines errs))
   617     | Ambigs us =>
   618         (warn (); error ("More than one term is type correct:\n" ^
   619           (cat_lines (map (Pretty.string_of o prt) us)))))
   620   end;
   621 
   622 
   623 
   624 (** extend signature **)    (*exception ERROR*)
   625 
   626 (** signature extension functions **)  (*exception ERROR*)
   627 
   628 fun decls_of path name_of mfixs =
   629   map (fn (x, y, mx) => (full path (name_of x mx), y)) mfixs;
   630 
   631 fun no_read _ _ _ decl = decl;
   632 
   633 
   634 (* add default sort *)
   635 
   636 fun ext_defsort int (syn, tsig, ctab, (path, spaces), data) S =
   637   (syn, Type.ext_tsig_defsort tsig (if int then intrn_sort spaces S else S),
   638     ctab, (path, spaces), data);
   639 
   640 
   641 (* add type constructors *)
   642 
   643 fun ext_types (syn, tsig, ctab, (path, spaces), data) types =
   644   let val decls = decls_of path Syntax.type_name types in
   645     (Syntax.extend_type_gram syn types,
   646       Type.ext_tsig_types tsig decls, ctab,
   647       (path, add_names spaces typeK (map fst decls)), data)
   648   end;
   649 
   650 
   651 (* add type abbreviations *)
   652 
   653 fun read_abbr syn tsig spaces (t, vs, rhs_src) =
   654   (t, vs, read_raw_typ syn tsig spaces (K None) rhs_src)
   655     handle ERROR => error ("in type abbreviation " ^ t);
   656 
   657 fun ext_abbrs rd_abbr (syn, tsig, ctab, (path, spaces), data) abbrs =
   658   let
   659     fun mfix_of (t, vs, _, mx) = (t, length vs, mx);
   660     val syn' = Syntax.extend_type_gram syn (map mfix_of abbrs);
   661 
   662     val abbrs' =
   663       map (fn (t, vs, rhs, mx) =>
   664         (full path (Syntax.type_name t mx), vs, rhs)) abbrs;
   665     val spaces' = add_names spaces typeK (map #1 abbrs');
   666     val decls = map (rd_abbr syn' tsig spaces') abbrs';
   667   in
   668     (syn', Type.ext_tsig_abbrs tsig decls, ctab, (path, spaces'), data)
   669   end;
   670 
   671 fun ext_tyabbrs abbrs = ext_abbrs read_abbr abbrs;
   672 fun ext_tyabbrs_i abbrs = ext_abbrs no_read abbrs;
   673 
   674 
   675 (* add type arities *)
   676 
   677 fun ext_arities int (syn, tsig, ctab, (path, spaces), data) arities =
   678   let
   679     fun intrn_arity (c, Ss, S) =
   680       (intrn spaces typeK c, map (intrn_sort spaces) Ss, intrn_sort spaces S);
   681     val intrn = if int then map intrn_arity else I;
   682     val tsig' = Type.ext_tsig_arities tsig (intrn arities);
   683     val log_types = Type.logical_types tsig';
   684   in
   685     (Syntax.extend_log_types syn log_types, tsig', ctab, (path, spaces), data)
   686   end;
   687 
   688 
   689 (* add term constants and syntax *)
   690 
   691 fun const_name path c mx =
   692   full path (Syntax.const_name c mx);
   693 
   694 fun err_in_const c =
   695   error ("in declaration of constant " ^ quote c);
   696 
   697 fun err_dup_consts cs =
   698   error ("Duplicate declaration of constant(s) " ^ commas_quote cs);
   699 
   700 
   701 fun read_const syn tsig (path, spaces) (c, ty_src, mx) =
   702   (c, read_raw_typ syn tsig spaces (K None) ty_src, mx)
   703     handle ERROR => err_in_const (const_name path c mx);
   704 
   705 fun ext_cnsts rd_const syn_only prmode (syn, tsig, ctab, (path, spaces), data) raw_consts =
   706   let
   707     fun prep_const (c, ty, mx) =
   708       (c, compress_type (Type.varifyT (Type.cert_typ tsig (Type.no_tvars ty))), mx)
   709         handle TYPE (msg, _, _) =>
   710           (error_msg msg; err_in_const (const_name path c mx));
   711 
   712     val consts = map (prep_const o rd_const syn tsig (path, spaces)) raw_consts;
   713     val decls =
   714       if syn_only then []
   715       else decls_of path Syntax.const_name consts;
   716   in
   717     (Syntax.extend_const_gram syn prmode consts, tsig,
   718       Symtab.extend_new (ctab, decls)
   719         handle Symtab.DUPS cs => err_dup_consts cs,
   720       (path, add_names spaces constK (map fst decls)), data)
   721   end;
   722 
   723 fun ext_consts_i sg = ext_cnsts no_read false ("", true) sg;
   724 fun ext_consts sg = ext_cnsts read_const false ("", true) sg;
   725 fun ext_syntax_i sg = ext_cnsts no_read true ("", true) sg;
   726 fun ext_syntax sg = ext_cnsts read_const true ("", true) sg;
   727 fun ext_modesyntax_i sg (prmode, consts) = ext_cnsts no_read true prmode sg consts;
   728 fun ext_modesyntax sg (prmode, consts) = ext_cnsts read_const true prmode sg consts;
   729 
   730 
   731 (* add type classes *)
   732 
   733 fun const_of_class c = c ^ "_class";
   734 
   735 fun class_of_const c_class =
   736   let
   737     val c = implode (take (size c_class - size "_class", explode c_class));
   738   in
   739     if const_of_class c = c_class then c
   740     else raise TERM ("class_of_const: bad name " ^ quote c_class, [])
   741   end;
   742 
   743 
   744 fun ext_classes int (syn, tsig, ctab, (path, spaces), data) classes =
   745   let
   746     val names = map fst classes;
   747     val consts =
   748       map (fn c => (const_of_class c, a_itselfT --> propT, NoSyn)) names;
   749 
   750     val full_names = map (full path) names;
   751     val spaces' = add_names spaces classK full_names;
   752     val intrn = if int then map (intrn_class spaces') else I;
   753     val classes' =
   754       ListPair.map (fn (c, (_, cs)) => (c, intrn cs)) (full_names, classes);
   755   in
   756     ext_consts_i
   757       (Syntax.extend_consts syn names,
   758         Type.ext_tsig_classes tsig classes', ctab, (path, spaces'), data)
   759     consts
   760   end;
   761 
   762 
   763 (* add to classrel *)
   764 
   765 fun ext_classrel int (syn, tsig, ctab, (path, spaces), data) pairs =
   766   let val intrn = if int then map (pairself (intrn_class spaces)) else I in
   767     (syn, Type.ext_tsig_classrel tsig (intrn pairs), ctab, (path, spaces), data)
   768   end;
   769 
   770 
   771 (* add to syntax *)
   772 
   773 fun ext_syn extfun (syn, tsig, ctab, names, data) args =
   774   (extfun syn args, tsig, ctab, names, data);
   775 
   776 
   777 (* add to path *)
   778 
   779 fun ext_path (syn, tsig, ctab, (path, spaces), data) elem =
   780   let
   781     val path' =
   782       if elem = ".." andalso not (null path) then fst (split_last path)
   783       else if elem = "/" then []
   784       else path @ NameSpace.unpack elem;
   785   in
   786     (syn, tsig, ctab, (path', spaces), data)
   787   end;      
   788 
   789 
   790 (* add to name space *)
   791 
   792 fun ext_space (syn, tsig, ctab, (path, spaces), data) (kind, names) =
   793   (syn, tsig, ctab, (path, add_names spaces kind names), data);
   794 
   795 
   796 (* signature data *)
   797 
   798 fun ext_init_data (syn, tsig, ctab, names, data) (kind, (e, ext, mrg, prt)) =
   799   (syn, tsig, ctab, names, Data.init data kind e ext mrg prt);
   800 
   801 fun ext_put_data (syn, tsig, ctab, names, data) (kind, e) =
   802   (syn, tsig, ctab, names, Data.put data kind e);
   803 
   804 
   805 (* the external interfaces *)
   806 
   807 val add_classes      = extend_sign true (ext_classes true) "#";
   808 val add_classes_i    = extend_sign true (ext_classes false) "#";
   809 val add_classrel     = extend_sign true (ext_classrel true) "#";
   810 val add_classrel_i   = extend_sign true (ext_classrel false) "#";
   811 val add_defsort      = extend_sign true (ext_defsort true) "#";
   812 val add_defsort_i    = extend_sign true (ext_defsort false) "#";
   813 val add_types        = extend_sign true ext_types "#";
   814 val add_tyabbrs      = extend_sign true ext_tyabbrs "#";
   815 val add_tyabbrs_i    = extend_sign true ext_tyabbrs_i "#";
   816 val add_arities      = extend_sign true (ext_arities true) "#";
   817 val add_arities_i    = extend_sign true (ext_arities false) "#";
   818 val add_consts       = extend_sign true ext_consts "#";
   819 val add_consts_i     = extend_sign true ext_consts_i "#";
   820 val add_syntax       = extend_sign true ext_syntax "#";
   821 val add_syntax_i     = extend_sign true ext_syntax_i "#";
   822 val add_modesyntax   = extend_sign true ext_modesyntax "#";
   823 val add_modesyntax_i = extend_sign true ext_modesyntax_i "#";
   824 val add_trfuns       = extend_sign true (ext_syn Syntax.extend_trfuns) "#";
   825 val add_trfunsT      = extend_sign true (ext_syn Syntax.extend_trfunsT) "#";
   826 val add_tokentrfuns  = extend_sign true (ext_syn Syntax.extend_tokentrfuns) "#";
   827 val add_trrules      = extend_sign true (ext_syn Syntax.extend_trrules) "#";
   828 val add_trrules_i    = extend_sign true (ext_syn Syntax.extend_trrules_i) "#";
   829 val add_path         = extend_sign true ext_path "#";
   830 val add_space        = extend_sign true ext_space "#";
   831 val init_data        = extend_sign true ext_init_data "#";
   832 val put_data         = extend_sign true ext_put_data "#";
   833 fun add_name name sg = extend_sign true K name () sg;
   834 fun prep_ext sg      = extend_sign false K "#" () sg;
   835 
   836 
   837 
   838 (** merge signatures **)    	(*exception TERM*)
   839 
   840 (* merge of sg_refs -- trivial only *)
   841 
   842 fun merge_refs (sgr1 as SgRef (Some (ref sg1)),
   843         sgr2 as SgRef (Some (ref sg2))) =
   844       if fast_subsig (sg2, sg1) then sgr1
   845       else if fast_subsig (sg1, sg2) then sgr2
   846       else if subsig (sg2, sg1) then sgr1
   847       else if subsig (sg1, sg2) then sgr2
   848       else raise TERM ("Attempt to do non-trivial merge of signatures", [])
   849   | merge_refs _ = sys_error "Sign.merge_refs";
   850 
   851 
   852 
   853 (* proper merge *)
   854 
   855 fun merge_aux (sg1, sg2) =
   856   if subsig (sg2, sg1) then sg1
   857   else if subsig (sg1, sg2) then sg2
   858   else if is_draft sg1 orelse is_draft sg2 then
   859     raise TERM ("Attempt to merge draft signatures", [])
   860   else
   861     (*neither is union already; must form union*)
   862     let
   863       val Sg ({id = _, stamps = stamps1}, {self = _, tsig = tsig1, const_tab = const_tab1,
   864         syn = syn1, path = _, spaces = spaces1, data = data1}) = sg1;
   865       val Sg ({id = _, stamps = stamps2}, {self = _, tsig = tsig2, const_tab = const_tab2,
   866         syn = syn2, path = _, spaces = spaces2, data = data2}) = sg2;
   867 
   868       val id = ref "";
   869       val self_ref = ref sg1;                   (*dummy value*)
   870       val self = SgRef (Some self_ref);
   871       val stamps = merge_rev_lists stamps1 stamps2;
   872       val _ =
   873         (case duplicates (map ! stamps) of
   874           [] => ()
   875         | dups => raise TERM ("Attempt to merge different versions of theories "
   876             ^ commas_quote dups, []));
   877 
   878       val tsig = Type.merge_tsigs (tsig1, tsig2);
   879       val const_tab = Symtab.merge (op =) (const_tab1, const_tab2)
   880         handle Symtab.DUPS cs =>
   881           raise TERM ("Incompatible types for constant(s) " ^ commas_quote cs, []);
   882       val syn = Syntax.merge_syntaxes syn1 syn2;
   883 
   884       val path = [];
   885       val kinds = distinct (map fst (spaces1 @ spaces2));
   886       val spaces =
   887         kinds ~~
   888           ListPair.map NameSpace.merge
   889             (map (space_of spaces1) kinds, map (space_of spaces2) kinds);
   890 
   891       val data = Data.merge (data1, data2);
   892 
   893       val sign = make_sign (id, self, tsig, const_tab, syn, path, spaces, data, stamps);
   894     in
   895       self_ref := sign; sign
   896     end;
   897 
   898 fun merge sg1_sg2 =
   899   (case handle_error merge_aux sg1_sg2 of
   900     OK sg => sg
   901   | Error msg => raise TERM (msg, []));
   902 
   903 
   904 
   905 (** partial Pure signature **)
   906 
   907 val dummy_sg = make_sign (ref "", SgRef None, Type.tsig0,
   908   Symtab.null, Syntax.pure_syn, [], [], Data.empty, []);
   909 
   910 val pre_pure =
   911   create_sign (SgRef (Some (ref dummy_sg))) [] "#"
   912     (Syntax.pure_syn, Type.tsig0, Symtab.null, ([], []), Data.empty);
   913 
   914 
   915 end;
   916 
   917 
   918 val long_names = Sign.long_names;