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