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