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