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