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