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