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