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