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