src/Pure/sign.ML
author wenzelm
Wed Oct 15 15:17:32 1997 +0200 (1997-10-15)
changeset 3877 83c5310aaaab
parent 3867 3b2587c809f4
child 3886 eb0681305d3f
permissions -rw-r--r--
make_draft replaced by prep_ext;
improved print_data;
merge now does trivial (absorptive) merges only;
added nontriv_merge;
     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, [], S) = Pretty.block
   406       [Pretty.str (t ^ " ::"), Pretty.brk 1, pretty_sort sg S]
   407   | pretty_arity sg (t, Ss, S) = Pretty.block
   408       [Pretty.str (t ^ " ::"), Pretty.brk 1,
   409         Pretty.list "(" ")" (map (pretty_sort sg) Ss),
   410         Pretty.brk 1, pretty_sort sg S];
   411 
   412 fun string_of_term sg t = Pretty.string_of (pretty_term sg t);
   413 fun string_of_typ sg T = Pretty.string_of (pretty_typ sg T);
   414 fun string_of_sort sg S = Pretty.string_of (pretty_sort sg S);
   415 
   416 fun str_of_sort sg S = Pretty.str_of (pretty_sort sg S);
   417 fun str_of_classrel sg c1_c2 = Pretty.str_of (pretty_classrel sg c1_c2);
   418 fun str_of_arity sg ar = Pretty.str_of (pretty_arity sg ar);
   419 
   420 fun pprint_term sg = Pretty.pprint o Pretty.quote o (pretty_term sg);
   421 fun pprint_typ sg = Pretty.pprint o Pretty.quote o (pretty_typ sg);
   422 
   423 
   424 
   425 (** read types **)  (*exception ERROR*)
   426 
   427 fun err_in_type s =
   428   error ("The error(s) above occurred in type " ^ quote s);
   429 
   430 fun read_raw_typ syn tsig spaces def_sort str =
   431   intrn_tycons spaces
   432     (Syntax.read_typ syn (Type.get_sort tsig def_sort (intrn_sort spaces)) str
   433       handle ERROR => err_in_type str);
   434   
   435 (*read and certify typ wrt a signature*)
   436 fun read_typ (Sg {tsig, syn, spaces, ...}, def_sort) str =
   437   Type.cert_typ tsig (read_raw_typ syn tsig spaces def_sort str)
   438     handle TYPE (msg, _, _) => (error_msg msg; err_in_type str);
   439 
   440 
   441 
   442 (** certify types and terms **)   (*exception TYPE*)
   443 
   444 fun certify_typ (Sg {tsig, ...}) ty = Type.cert_typ tsig ty;
   445 
   446 (*check for duplicate TVars with distinct sorts*)
   447 fun nodup_TVars (tvars, T) =
   448   (case T of
   449     Type (_, Ts) => nodup_TVars_list (tvars, Ts)
   450   | TFree _ => tvars
   451   | TVar (v as (a, S)) =>
   452       (case assoc_string_int (tvars, a) of
   453         Some S' =>
   454           if S = S' then tvars
   455           else raise TYPE ("Type variable " ^ Syntax.string_of_vname a ^
   456             " has two distinct sorts", [TVar (a, S'), T], [])
   457       | None => v :: tvars))
   458 (*equivalent to foldl nodup_TVars_list, but 3X faster under Poly/ML*)
   459 and nodup_TVars_list (tvars, []) = tvars
   460   | nodup_TVars_list (tvars, T :: Ts) =
   461       nodup_TVars_list (nodup_TVars (tvars, T), Ts);
   462 
   463 (*check for duplicate Vars with distinct types*)
   464 fun nodup_Vars tm =
   465   let
   466     fun nodups vars tvars tm =
   467       (case tm of
   468         Const (c, T) => (vars, nodup_TVars (tvars, T))
   469       | Free (a, T) => (vars, nodup_TVars (tvars, T))
   470       | Var (v as (ixn, T)) =>
   471           (case assoc_string_int (vars, ixn) of
   472             Some T' =>
   473               if T = T' then (vars, nodup_TVars (tvars, T))
   474               else raise TYPE ("Variable " ^ Syntax.string_of_vname ixn ^
   475                 " has two distinct types", [T', T], [])
   476           | None => (v :: vars, tvars))
   477       | Bound _ => (vars, tvars)
   478       | Abs (_, T, t) => nodups vars (nodup_TVars (tvars, T)) t
   479       | s $ t =>
   480           let val (vars',tvars') = nodups vars tvars s in
   481             nodups vars' tvars' t
   482           end);
   483   in nodups [] [] tm; () end;
   484 
   485 
   486 fun mapfilt_atoms f (Abs (_, _, t)) = mapfilt_atoms f t
   487   | mapfilt_atoms f (t $ u) = mapfilt_atoms f t @ mapfilt_atoms f u
   488   | mapfilt_atoms f a = (case f a of Some y => [y] | None => []);
   489 
   490 
   491 fun certify_term (sg as Sg {tsig, ...}) tm =
   492   let
   493     fun valid_const a T =
   494       (case const_type sg a of
   495         Some U => Type.typ_instance (tsig, T, U)
   496       | _ => false);
   497 
   498     fun atom_err (Const (a, T)) =
   499           if valid_const a T then None
   500           else Some ("Illegal type for constant " ^ quote a ^ " :: " ^
   501             quote (string_of_typ sg T))
   502       | atom_err (Var ((x, i), _)) =
   503           if i < 0 then Some ("Negative index for Var " ^ quote x) else None
   504       | atom_err _ = None;
   505 
   506     val norm_tm =
   507       (case it_term_types (Type.typ_errors tsig) (tm, []) of
   508         [] => map_term_types (Type.norm_typ tsig) tm
   509       | errs => raise TYPE (cat_lines errs, [], [tm]));
   510     val _ = nodup_Vars norm_tm;
   511   in
   512     (case mapfilt_atoms atom_err norm_tm of
   513       [] => (norm_tm, type_of norm_tm, maxidx_of_term norm_tm)
   514     | errs => raise TYPE (cat_lines errs, [], [norm_tm]))
   515   end;
   516 
   517 
   518 
   519 (** infer_types **)         (*exception ERROR*)
   520 
   521 (*
   522   ts: list of alternative parses (hopefully only one is type-correct)
   523   T: expected type
   524 
   525   def_type: partial map from indexnames to types (constrains Frees, Vars)
   526   def_sort: partial map from indexnames to sorts (constrains TFrees, TVars)
   527   used: list of already used type variables
   528   freeze: if true then generated parameters are turned into TFrees, else TVars
   529 *)
   530 
   531 fun infer_types sg def_type def_sort used freeze (ts, T) =
   532   let
   533     val Sg {tsig, ...} = sg;
   534     val prt =
   535       setmp Syntax.show_brackets true
   536         (setmp long_names true (pretty_term sg));
   537     val prT = setmp long_names true (pretty_typ sg);
   538     val infer = Type.infer_types prt prT tsig (const_type sg) def_type def_sort
   539       (intern_const sg) (intern_tycons sg) (intern_sort sg) used freeze;
   540 
   541     val T' = certify_typ sg T handle TYPE (msg, _, _) => error msg;
   542 
   543     fun warn () =
   544       if length ts > 1 andalso length ts <= ! Syntax.ambiguity_level
   545       then (*no warning shown yet*)
   546         warning "Got more than one parse tree.\n\
   547           \Retry with smaller Syntax.ambiguity_level for more information."
   548       else ();
   549 
   550     datatype result =
   551       One of int * term * (indexname * typ) list |
   552       Errs of string list |
   553       Ambigs of term list;
   554 
   555     fun process_term (res, (t, i)) =
   556       let val ([u], tye) = infer [T'] [t] in
   557         (case res of
   558           One (_, t0, _) => Ambigs ([u, t0])
   559         | Errs _ => One (i, u, tye)
   560         | Ambigs us => Ambigs (u :: us))
   561       end handle TYPE (msg, _, _) =>
   562         (case res of
   563           Errs errs => Errs (msg :: errs)
   564         | _ => res);
   565   in
   566     (case foldl process_term (Errs [], ts ~~ (0 upto (length ts - 1))) of
   567       One res =>
   568        (if length ts > ! Syntax.ambiguity_level then
   569           warning "Fortunately, only one parse tree is type correct.\n\
   570             \You may still want to disambiguate your grammar or your input."
   571         else (); res)
   572     | Errs errs => (warn (); error (cat_lines errs))
   573     | Ambigs us =>
   574         (warn (); error ("More than one term is type correct:\n" ^
   575           (cat_lines (map (Pretty.string_of o prt) us)))))
   576   end;
   577 
   578 
   579 
   580 (** extend signature **)    (*exception ERROR*)
   581 
   582 (** signature extension functions **)  (*exception ERROR*)
   583 
   584 fun decls_of path name_of mfixs =
   585   map (fn (x, y, mx) => (full path (name_of x mx), y)) mfixs;
   586 
   587 fun no_read _ _ _ decl = decl;
   588 
   589 
   590 (* add default sort *)
   591 
   592 fun ext_defsort int (syn, tsig, ctab, (path, spaces)) S =
   593   (syn, Type.ext_tsig_defsort tsig (if int then intrn_sort spaces S else S),
   594     ctab, (path, spaces));
   595 
   596 
   597 (* add type constructors *)
   598 
   599 fun ext_types (syn, tsig, ctab, (path, spaces)) types =
   600   let val decls = decls_of path Syntax.type_name types in
   601     (Syntax.extend_type_gram syn types,
   602       Type.ext_tsig_types tsig decls, ctab,
   603       (path, add_names spaces typeK (map fst decls)))
   604   end;
   605 
   606 
   607 (* add type abbreviations *)
   608 
   609 fun read_abbr syn tsig spaces (t, vs, rhs_src) =
   610   (t, vs, read_raw_typ syn tsig spaces (K None) rhs_src)
   611     handle ERROR => error ("in type abbreviation " ^ t);
   612 
   613 fun ext_abbrs rd_abbr (syn, tsig, ctab, (path, spaces)) abbrs =
   614   let
   615     fun mfix_of (t, vs, _, mx) = (t, length vs, mx);
   616     val syn' = Syntax.extend_type_gram syn (map mfix_of abbrs);
   617 
   618     val abbrs' =
   619       map (fn (t, vs, rhs, mx) =>
   620         (full path (Syntax.type_name t mx), vs, rhs)) abbrs;
   621     val spaces' = add_names spaces typeK (map #1 abbrs');
   622     val decls = map (rd_abbr syn' tsig spaces') abbrs';
   623   in
   624     (syn', Type.ext_tsig_abbrs tsig decls, ctab, (path, spaces'))
   625   end;
   626 
   627 fun ext_tyabbrs abbrs = ext_abbrs read_abbr abbrs;
   628 fun ext_tyabbrs_i abbrs = ext_abbrs no_read abbrs;
   629 
   630 
   631 (* add type arities *)
   632 
   633 fun ext_arities int (syn, tsig, ctab, (path, spaces)) arities =
   634   let
   635     fun intrn_arity (c, Ss, S) =
   636       (intrn spaces typeK c, map (intrn_sort spaces) Ss, intrn_sort spaces S);
   637     val intrn = if int then map intrn_arity else I;
   638     val tsig' = Type.ext_tsig_arities tsig (intrn arities);
   639     val log_types = Type.logical_types tsig';
   640   in
   641     (Syntax.extend_log_types syn log_types, tsig', ctab, (path, spaces))
   642   end;
   643 
   644 
   645 (* add term constants and syntax *)
   646 
   647 fun const_name path c mx =
   648   full path (Syntax.const_name c mx);
   649 
   650 fun err_in_const c =
   651   error ("in declaration of constant " ^ quote c);
   652 
   653 fun err_dup_consts cs =
   654   error ("Duplicate declaration of constant(s) " ^ commas_quote cs);
   655 
   656 
   657 fun read_const syn tsig (path, spaces) (c, ty_src, mx) =
   658   (c, read_raw_typ syn tsig spaces (K None) ty_src, mx)
   659     handle ERROR => err_in_const (const_name path c mx);
   660 
   661 fun ext_cnsts rd_const syn_only prmode (syn, tsig, ctab, (path, spaces)) raw_consts =
   662   let
   663     fun prep_const (c, ty, mx) =
   664       (c, compress_type (Type.varifyT (Type.cert_typ tsig (Type.no_tvars ty))), mx)
   665         handle TYPE (msg, _, _) =>
   666           (error_msg msg; err_in_const (const_name path c mx));
   667 
   668     val consts = map (prep_const o rd_const syn tsig (path, spaces)) raw_consts;
   669     val decls =
   670       if syn_only then []
   671       else decls_of path Syntax.const_name consts;
   672   in
   673     (Syntax.extend_const_gram syn prmode consts, tsig,
   674       Symtab.extend_new (ctab, decls)
   675         handle Symtab.DUPS cs => err_dup_consts cs,
   676       (path, add_names spaces constK (map fst decls)))
   677   end;
   678 
   679 val ext_consts_i = ext_cnsts no_read false ("", true);
   680 val ext_consts = ext_cnsts read_const false ("", true);
   681 val ext_syntax_i = ext_cnsts no_read true ("", true);
   682 val ext_syntax = ext_cnsts read_const true ("", true);
   683 fun ext_modesyntax_i sg (prmode, consts) = ext_cnsts no_read true prmode sg consts;
   684 fun ext_modesyntax sg (prmode, consts) = ext_cnsts read_const true prmode sg consts;
   685 
   686 
   687 (* add type classes *)
   688 
   689 fun const_of_class c = c ^ "_class";
   690 
   691 fun class_of_const c_class =
   692   let
   693     val c = implode (take (size c_class - size "_class", explode c_class));
   694   in
   695     if const_of_class c = c_class then c
   696     else raise TERM ("class_of_const: bad name " ^ quote c_class, [])
   697   end;
   698 
   699 
   700 fun ext_classes int (syn, tsig, ctab, (path, spaces)) classes =
   701   let
   702     val names = map fst classes;
   703     val consts =
   704       map (fn c => (const_of_class c, a_itselfT --> propT, NoSyn)) names;
   705 
   706     val full_names = map (full path) names;
   707     val spaces' = add_names spaces classK full_names;
   708     val intrn = if int then map (intrn_class spaces') else I;
   709     val classes' =
   710       ListPair.map (fn (c, (_, cs)) => (c, intrn cs)) (full_names, classes);
   711   in
   712     ext_consts_i
   713       (Syntax.extend_consts syn names,
   714         Type.ext_tsig_classes tsig classes', ctab, (path, spaces'))
   715     consts
   716   end;
   717 
   718 
   719 (* add to classrel *)
   720 
   721 fun ext_classrel int (syn, tsig, ctab, (path, spaces)) pairs =
   722   let val intrn = if int then map (pairself (intrn_class spaces)) else I in
   723     (syn, Type.ext_tsig_classrel tsig (intrn pairs), ctab, (path, spaces))
   724   end;
   725 
   726 
   727 (* add to syntax *)
   728 
   729 fun ext_syn extfun (syn, tsig, ctab, names) args =
   730   (extfun syn args, tsig, ctab, names);
   731 
   732 
   733 (* add to path *)
   734 
   735 fun ext_path (syn, tsig, ctab, (path, spaces)) elem =
   736   let
   737     val path' =
   738       if elem = ".." andalso not (null path) then fst (split_last path)
   739       else if elem = "/" then []
   740       else path @ NameSpace.unpack elem;
   741   in
   742     (syn, tsig, ctab, (path', spaces))
   743   end;      
   744 
   745 
   746 (* add to name space *)
   747 
   748 fun ext_space (syn, tsig, ctab, (path, spaces)) (kind, names) =
   749   (syn, tsig, ctab, (path, add_names spaces kind names));
   750 
   751 
   752 (* build signature *)
   753 
   754 fun ext_stamps stamps name =
   755   let
   756     val stmps = (case stamps of ref "#" :: ss => ss | ss => ss);
   757   in
   758     if exists (equal name o !) stmps then
   759       error ("Theory already contains a " ^ quote name ^ " component")
   760     else ref name :: stmps
   761   end;
   762 
   763 fun make_sign (syn, tsig, ctab, (path, spaces)) data stamps name =
   764   Sg {tsig = tsig, const_tab = ctab, syn = syn, path = path, spaces = spaces,
   765     data = data, stamps = ext_stamps stamps name};
   766 
   767 fun extend_sign extfun name decls
   768     (Sg {tsig, const_tab, syn, path, spaces, data, stamps}) =
   769   make_sign (extfun (syn, tsig, const_tab, (path, spaces)) decls) data stamps name;
   770 
   771 
   772 (* the external interfaces *)
   773 
   774 val add_classes      = extend_sign (ext_classes true) "#";
   775 val add_classes_i    = extend_sign (ext_classes false) "#";
   776 val add_classrel     = extend_sign (ext_classrel true) "#";
   777 val add_classrel_i   = extend_sign (ext_classrel false) "#";
   778 val add_defsort      = extend_sign (ext_defsort true) "#";
   779 val add_defsort_i    = extend_sign (ext_defsort false) "#";
   780 val add_types        = extend_sign ext_types "#";
   781 val add_tyabbrs      = extend_sign ext_tyabbrs "#";
   782 val add_tyabbrs_i    = extend_sign ext_tyabbrs_i "#";
   783 val add_arities      = extend_sign (ext_arities true) "#";
   784 val add_arities_i    = extend_sign (ext_arities false) "#";
   785 val add_consts       = extend_sign ext_consts "#";
   786 val add_consts_i     = extend_sign ext_consts_i "#";
   787 val add_syntax       = extend_sign ext_syntax "#";
   788 val add_syntax_i     = extend_sign ext_syntax_i "#";
   789 val add_modesyntax   = extend_sign ext_modesyntax "#";
   790 val add_modesyntax_i = extend_sign ext_modesyntax_i "#";
   791 val add_trfuns       = extend_sign (ext_syn Syntax.extend_trfuns) "#";
   792 val add_trfunsT      = extend_sign (ext_syn Syntax.extend_trfunsT) "#";
   793 val add_tokentrfuns  = extend_sign (ext_syn Syntax.extend_tokentrfuns) "#";
   794 val add_trrules      = extend_sign (ext_syn Syntax.extend_trrules) "#";
   795 val add_trrules_i    = extend_sign (ext_syn Syntax.extend_trrules_i) "#";
   796 val add_path         = extend_sign ext_path "#";
   797 val add_space        = extend_sign ext_space "#";
   798 fun add_name name sg = extend_sign K name () sg;
   799 
   800 val make_draft = add_name "#";
   801 
   802 
   803 (* additional signature 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, ext, mrg, prt) =
   809   map_data (fn d => Data.init d kind e ext mrg prt);
   810 
   811 fun get_data (Sg {data, ...}) = Data.get data;
   812 fun put_data (kind, e) = map_data (fn d => Data.put d kind e);
   813 fun print_data (Sg {data, ...}) kind = Data.print data kind;
   814 
   815 (*prepare extension*)
   816 val prep_ext = map_data Data.prep_ext;
   817 
   818 
   819 
   820 (** merge signatures **)    (*exception TERM*)
   821 
   822 fun merge_aux triv_only (sg1, sg2) =
   823   if fast_subsig (sg2, sg1) then sg1
   824   else if fast_subsig (sg1, sg2) then sg2
   825   else if subsig (sg2, sg1) then sg1
   826   else if subsig (sg1, sg2) then sg2
   827   else if is_draft sg1 orelse is_draft sg2 then
   828     raise TERM ("Illegal merge of draft signatures", [])
   829   else if triv_only then
   830     raise TERM ("Illegal non-trivial merge of signatures", [])
   831   else
   832     (*neither is union already; must form union*)
   833     let
   834       val Sg {tsig = tsig1, const_tab = const_tab1, syn = syn1,
   835         path = _, spaces = spaces1, data = data1, stamps = stamps1} = sg1;
   836       val Sg {tsig = tsig2, const_tab = const_tab2, syn = syn2,
   837         path = _, spaces = spaces2, data = data2, stamps = stamps2} = sg2;
   838 
   839 
   840       val stamps = merge_rev_lists stamps1 stamps2;
   841       val _ =
   842         (case duplicates (stamp_names stamps) of
   843           [] => ()
   844         | dups => raise TERM ("Attempt to merge different versions of theories "
   845             ^ commas_quote dups, []));
   846 
   847       val tsig = Type.merge_tsigs (tsig1, tsig2);
   848 
   849       val const_tab = Symtab.merge (op =) (const_tab1, const_tab2)
   850         handle Symtab.DUPS cs =>
   851           raise TERM ("Incompatible types for constant(s) " ^ commas_quote cs, []);
   852 
   853       val syn = Syntax.merge_syntaxes syn1 syn2;
   854 
   855       val kinds = distinct (map fst (spaces1 @ spaces2));
   856       val spaces =
   857         kinds ~~
   858           ListPair.map NameSpace.merge
   859             (map (space_of spaces1) kinds, map (space_of spaces2) kinds);
   860 
   861       val data = Data.merge (data1, data2);
   862     in
   863       Sg {tsig = tsig, const_tab = const_tab, syn = syn,
   864         path = [], spaces = spaces, data = data, stamps = stamps}
   865     end;
   866 
   867 fun gen_merge triv sgs =
   868   (case handle_error (merge_aux triv) sgs of
   869     OK sg => sg
   870   | Error msg => raise TERM (msg, []));
   871 
   872 val merge = gen_merge true;
   873 val nontriv_merge = gen_merge false;
   874 
   875 
   876 
   877 (** the Pure signature **)
   878 
   879 val proto_pure =
   880   make_sign (Syntax.pure_syn, Type.tsig0, Symtab.null, ([], [])) Data.empty [] "#"
   881   |> add_types
   882    (("fun", 2, NoSyn) ::
   883     ("prop", 0, NoSyn) ::
   884     ("itself", 1, NoSyn) ::
   885     Syntax.pure_types)
   886   |> add_classes_i [(NameSpace.base logicC, [])]
   887   |> add_defsort_i logicS
   888   |> add_arities_i
   889    [("fun", [logicS, logicS], logicS),
   890     ("prop", [], logicS),
   891     ("itself", [logicS], logicS)]
   892   |> add_syntax Syntax.pure_syntax
   893   |> add_modesyntax (("symbols", true), Syntax.pure_sym_syntax)
   894   |> add_trfuns Syntax.pure_trfuns
   895   |> add_trfunsT Syntax.pure_trfunsT
   896   |> add_syntax
   897    [("==>", "[prop, prop] => prop", Delimfix "op ==>")]
   898   |> add_consts
   899    [("==", "['a::{}, 'a] => prop", InfixrName ("==", 2)),
   900     ("=?=", "['a::{}, 'a] => prop", InfixrName ("=?=", 2)),
   901     ("==>", "[prop, prop] => prop", Mixfix ("(_/ ==> _)", [2, 1], 1)),
   902     ("all", "('a => prop) => prop", Binder ("!!", 0, 0)),
   903     ("TYPE", "'a itself", NoSyn)]
   904   |> add_name "ProtoPure";
   905 
   906 val pure = proto_pure
   907   |> add_syntax Syntax.pure_appl_syntax
   908   |> add_name "Pure";
   909 
   910 val cpure = proto_pure
   911   |> add_syntax Syntax.pure_applC_syntax
   912   |> add_name "CPure";
   913 
   914 
   915 end;
   916 
   917 
   918 val long_names = Sign.long_names;