src/Pure/sign.ML
author ballarin
Thu Mar 24 17:03:37 2005 +0100 (2005-03-24 ago)
changeset 15624 484178635bd8
parent 15574 b1d1b5bfc464
child 15703 727ef1b8b3ee
permissions -rw-r--r--
Further work on interpretation commands. New command `interpret' for
interpretation in proof contexts.
     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.tsig,
    26     consts: (typ * stamp) Symtab.table,
    27     path: string list option,
    28     spaces: (string * NameSpace.T) list,
    29     data: data}
    30   val name_of: sg -> string
    31   val stamp_names_of: sg -> string list
    32   val exists_stamp: string -> sg -> bool
    33   val tsig_of: sg -> Type.tsig
    34   val is_logtype: sg -> string -> bool
    35   val deref: sg_ref -> sg
    36   val self_ref: sg -> sg_ref
    37   val subsig: sg * sg -> bool
    38   val joinable: sg * sg -> bool
    39   val eq_sg: sg * sg -> bool
    40   val same_sg: sg * sg -> bool
    41   val is_draft: sg -> bool
    42   val is_stale: sg -> bool
    43   val syn_of: sg -> Syntax.syntax
    44   val const_type: sg -> string -> typ option
    45   val classes: sg -> class list
    46   val defaultS: sg -> sort
    47   val subsort: sg -> sort * sort -> bool
    48   val nodup_vars: term -> term
    49   val of_sort: sg -> typ * sort -> bool
    50   val witness_sorts: sg -> sort list -> sort list -> (typ * sort) list
    51   val universal_witness: sg -> (typ * sort) option
    52   val typ_instance: sg -> typ * typ -> bool
    53   val classK: string
    54   val typeK: string
    55   val constK: string
    56   val full_name: sg -> bstring -> string
    57   val full_name': sg -> bstring -> string
    58   val full_name_path: sg -> string -> bstring -> string
    59   val base_name: string -> bstring
    60   val intern: sg -> string -> xstring -> string
    61   val extern: sg -> string -> string -> xstring
    62   val cond_extern: sg -> string -> string -> xstring
    63   val cond_extern_table: sg -> string -> 'a Symtab.table -> (xstring * 'a) list
    64   val extern_typ: sg -> typ -> typ
    65   val intern_class: sg -> xclass -> class
    66   val intern_tycon: sg -> xstring -> string
    67   val intern_const: sg -> xstring -> string
    68   val intern_sort: sg -> xsort -> sort
    69   val intern_typ: sg -> xtyp -> typ
    70   val intern_term: sg -> xterm -> term
    71   val intern_tycons: sg -> xtyp -> typ
    72   val pretty_sg: sg -> Pretty.T
    73   val str_of_sg: sg -> string
    74   val pprint_sg: sg -> pprint_args -> unit
    75   val PureN: string
    76   val CPureN: string
    77   val pre_pure: sg
    78   val pretty_term: sg -> term -> Pretty.T
    79   val pretty_term': Syntax.syntax -> sg -> term -> Pretty.T
    80   val pretty_typ: sg -> typ -> Pretty.T
    81   val pretty_sort: sg -> sort -> Pretty.T
    82   val pretty_classrel: sg -> class list -> Pretty.T
    83   val pretty_arity: sg -> arity -> Pretty.T
    84   val string_of_term: sg -> term -> string
    85   val string_of_typ: sg -> typ -> string
    86   val string_of_sort: sg -> sort -> string
    87   val string_of_classrel: sg -> class list -> string
    88   val string_of_arity: sg -> arity -> string
    89   val pprint_term: sg -> term -> pprint_args -> unit
    90   val pprint_typ: sg -> typ -> pprint_args -> unit
    91   val pp: sg -> Pretty.pp
    92   val certify_class: sg -> class -> class
    93   val certify_sort: sg -> sort -> sort
    94   val certify_typ: sg -> typ -> typ
    95   val certify_typ_raw: sg -> typ -> typ
    96   val certify_tyname: sg -> string -> string
    97   val certify_const: sg -> string -> string
    98   val certify_term: Pretty.pp -> sg -> term -> term * typ * int
    99   val read_sort: sg -> string -> sort
   100   val read_raw_typ: sg * (indexname -> sort option) -> string -> typ
   101   val read_typ: sg * (indexname -> sort option) -> string -> typ
   102   val read_typ': Syntax.syntax -> sg * (indexname -> sort option) -> string -> typ
   103   val read_typ_raw': Syntax.syntax -> sg * (indexname -> sort option) -> string -> typ
   104   val inst_typ_tvars: sg -> (indexname * typ) list -> typ -> typ
   105   val inst_term_tvars: sg -> (indexname * typ) list -> term -> term
   106   val infer_types: Pretty.pp -> sg -> (indexname -> typ option) ->
   107     (indexname -> sort option) -> string list -> bool
   108     -> xterm list * typ -> term * (indexname * typ) list
   109   val infer_types_simult: Pretty.pp -> sg -> (indexname -> typ option) ->
   110     (indexname -> sort option) -> string list -> bool
   111     -> (xterm list * typ) list -> term list * (indexname * typ) list
   112   val read_def_terms': Pretty.pp -> (string -> bool) -> Syntax.syntax ->
   113     sg * (indexname -> typ option) * (indexname -> sort option) ->
   114     string list -> bool -> (string * typ) list -> term list * (indexname * typ) list
   115   val read_def_terms:
   116     sg * (indexname -> typ option) * (indexname -> sort option) ->
   117     string list -> bool -> (string * typ) list -> term list * (indexname * typ) list
   118   val simple_read_term: sg -> typ -> string -> term
   119   val const_of_class: class -> string
   120   val class_of_const: string -> class
   121   val add_classes: (bclass * xclass list) list -> sg -> sg
   122   val add_classes_i: (bclass * class list) list -> sg -> sg
   123   val add_classrel: (xclass * xclass) list -> sg -> sg
   124   val add_classrel_i: (class * class) list -> sg -> sg
   125   val add_defsort: string -> sg -> sg
   126   val add_defsort_i: sort -> sg -> sg
   127   val add_types: (bstring * int * mixfix) list -> sg -> sg
   128   val add_nonterminals: bstring list -> sg -> sg
   129   val add_tyabbrs: (bstring * string list * string * mixfix) list -> sg -> sg
   130   val add_tyabbrs_i: (bstring * string list * typ * mixfix) list -> sg -> sg
   131   val add_arities: (xstring * string list * string) list -> sg -> sg
   132   val add_arities_i: (string * sort list * sort) list -> sg -> sg
   133   val add_consts: (bstring * string * mixfix) list -> sg -> sg
   134   val add_consts_i: (bstring * typ * mixfix) list -> sg -> sg
   135   val add_syntax: (bstring * string * mixfix) list -> sg -> sg
   136   val add_syntax_i: (bstring * typ * mixfix) list -> sg -> sg
   137   val add_modesyntax: (string * bool) * (bstring * string * mixfix) list -> sg -> sg
   138   val add_modesyntax_i: (string * bool) * (bstring * typ * mixfix) list -> sg -> sg
   139   val add_trfuns:
   140     (string * (ast list -> ast)) list *
   141     (string * (term list -> term)) list *
   142     (string * (term list -> term)) list *
   143     (string * (ast list -> ast)) list -> sg -> sg
   144   val add_trfunsT:
   145     (string * (bool -> typ -> term list -> term)) list -> sg -> sg
   146   val add_advanced_trfuns:
   147     (string * (sg -> ast list -> ast)) list *
   148     (string * (sg -> term list -> term)) list *
   149     (string * (sg -> term list -> term)) list *
   150     (string * (sg -> ast list -> ast)) list -> sg -> sg
   151   val add_advanced_trfunsT:
   152     (string * (sg -> bool -> typ -> term list -> term)) list -> sg -> sg
   153   val add_tokentrfuns:
   154     (string * string * (string -> string * real)) list -> sg -> sg
   155   val add_trrules: (xstring * string) Syntax.trrule list -> sg -> sg
   156   val add_trrules_i: ast Syntax.trrule list -> sg -> sg
   157   val add_path: string -> sg -> sg
   158   val add_space: string * string list -> sg -> sg
   159   val hide_space: bool -> string * string list -> sg -> sg
   160   val hide_space_i: bool -> string * string list -> sg -> sg
   161   val add_name: string -> sg -> sg
   162   val data_kinds: data -> string list
   163   val merge_refs: sg_ref * sg_ref -> sg_ref
   164   val merge: sg * sg -> sg
   165   val copy: sg -> sg
   166   val prep_ext: sg -> sg
   167   val nontriv_merge: sg * sg -> sg
   168 end;
   169 
   170 signature PRIVATE_SIGN =
   171 sig
   172   include SIGN
   173   val init_data: Object.kind * (Object.T * (Object.T -> Object.T) * (Object.T -> Object.T) *
   174     (Object.T * Object.T -> Object.T) * (sg -> Object.T -> unit)) -> sg -> sg
   175   val get_data: Object.kind -> (Object.T -> 'a) -> sg -> 'a
   176   val put_data: Object.kind -> ('a -> Object.T) -> 'a -> sg -> sg
   177   val print_data: Object.kind -> sg -> unit
   178 end;
   179 
   180 structure Sign: PRIVATE_SIGN =
   181 struct
   182 
   183 (** datatype sg **)
   184 
   185 (* types sg, data, syn, sg_ref *)
   186 
   187 datatype sg =
   188   Sg of
   189    {id: string ref,                             (*id*)
   190     stamps: string ref list,                    (*unique theory indentifier*)
   191     syn: syn} *                                 (*syntax for parsing and printing*)
   192    {self: sg_ref,                               (*mutable self reference*)
   193     tsig: Type.tsig,                            (*order-sorted signature of types*)
   194     consts: (typ * stamp) Symtab.table,         (*type schemes of constants*)
   195     path: string list option,                   (*current name space entry prefix*)
   196     spaces: (string * NameSpace.T) list,        (*name spaces for consts, types etc.*)
   197     data: data}                                 (*anytype data*)
   198 and data =
   199   Data of
   200     (Object.kind *                              (*kind (for authorization)*)
   201       (Object.T *                               (*value*)
   202         ((Object.T -> Object.T) *               (*copy method*)
   203           (Object.T -> Object.T) *              (*prepare extend method*)
   204           (Object.T * Object.T -> Object.T) *   (*merge and prepare extend method*)
   205           (sg -> Object.T -> unit))))           (*print method*)
   206     Symtab.table
   207 and syn =
   208   Syn of
   209     Syntax.syntax *
   210      (((sg -> ast list -> ast) * stamp) Symtab.table *
   211       ((sg -> term list -> term) * stamp) Symtab.table *
   212       ((sg -> bool -> typ -> term list -> term) * stamp) list Symtab.table *
   213       ((sg -> ast list -> ast) * stamp) list Symtab.table)
   214 and sg_ref =
   215   SgRef of sg ref option;
   216 
   217 (*make signature*)
   218 fun make_sign (id, self, tsig, consts, syn, path, spaces, data, stamps) =
   219   Sg ({id = id, stamps = stamps, syn = syn}, {self = self, tsig = tsig,
   220     consts = consts, path = path, spaces = spaces, data = data});
   221 
   222 
   223 (* basic operations *)
   224 
   225 fun rep_sg (Sg (_, args)) = args;
   226 
   227 fun stamp_names_of (Sg ({stamps, ...}, _)) = rev (map ! stamps);
   228 fun exists_stamp name (Sg ({stamps, ...}, _)) = exists (equal name o !) stamps;
   229 fun pretty_sg sg = Pretty.str_list "{" "}" (stamp_names_of sg);
   230 val str_of_sg = Pretty.str_of o pretty_sg;
   231 val pprint_sg = Pretty.pprint o pretty_sg;
   232 
   233 val tsig_of = #tsig o rep_sg;
   234 fun is_logtype sg c = c mem_string Type.logical_types (tsig_of sg);
   235 fun const_type (Sg (_, {consts, ...})) c = Option.map #1 (Symtab.lookup (consts, c));
   236 
   237 
   238 (* id and self *)
   239 
   240 fun check_stale (sg as Sg ({id, ...},
   241         {self = SgRef (SOME (ref (Sg ({id = id', ...}, _)))), ...})) =
   242       if id = id' then sg
   243       else raise TERM ("Stale signature: " ^ str_of_sg sg, [])
   244   | check_stale _ = sys_error "Sign.check_stale";
   245 
   246 fun is_stale sg = (check_stale sg; false) handle TERM _ => true;
   247 
   248 fun self_ref (sg as Sg (_, {self, ...})) = (check_stale sg; self);
   249 
   250 fun deref (SgRef (SOME (ref sg))) = sg
   251   | deref (SgRef NONE) = sys_error "Sign.deref";
   252 
   253 fun name_of (sg as Sg ({id = ref name, ...}, _)) =
   254   if name = "" orelse ord name = ord "#" then
   255     raise TERM ("Nameless signature " ^ str_of_sg sg, [])
   256   else name;
   257 
   258 
   259 (* inclusion and equality *)
   260 
   261 local
   262   (*avoiding polymorphic equality: factor 10 speedup*)
   263   fun mem_stamp (_:string ref, []) = false
   264     | mem_stamp (x, y :: ys) = x = y orelse mem_stamp (x, ys);
   265 
   266   fun subset_stamp ([], ys) = true
   267     | subset_stamp (x :: xs, ys) =
   268         mem_stamp (x, ys) andalso subset_stamp (xs, ys);
   269 
   270   (*fast partial test*)
   271   fun fast_sub ([]: string ref list, _) = true
   272     | fast_sub (_, []) = false
   273     | fast_sub (x :: xs, y :: ys) =
   274         if x = y then fast_sub (xs, ys)
   275         else fast_sub (x :: xs, ys);
   276 in
   277   fun eq_sg (sg1 as Sg ({id = id1, ...}, _), sg2 as Sg ({id = id2, ...}, _)) =
   278     (check_stale sg1; check_stale sg2; id1 = id2);
   279 
   280   fun subsig (sg1 as Sg ({stamps = s1, ...}, _), sg2 as Sg ({stamps = s2, ...}, _)) =
   281     eq_sg (sg1, sg2) orelse subset_stamp (s1, s2);
   282 
   283   fun fast_subsig (sg1 as Sg ({stamps = s1, ...}, _), sg2 as Sg ({stamps = s2, ...}, _)) =
   284     eq_sg (sg1, sg2) orelse fast_sub (s1, s2);
   285 end;
   286 
   287 
   288 fun joinable (sg1, sg2) = subsig (sg1, sg2) orelse subsig (sg2, sg1);
   289 
   290 (*test if same theory names are contained in signatures' stamps,
   291   i.e. if signatures belong to same theory but not necessarily to the
   292   same version of it*)
   293 fun same_sg (sg1 as Sg ({stamps = s1, ...}, _), sg2 as Sg ({stamps = s2, ...}, _)) =
   294   eq_sg (sg1, sg2) orelse eq_set_string (pairself (map (op !)) (s1, s2));
   295 
   296 (*test for drafts*)
   297 fun is_draft (Sg ({stamps = ref name :: _, ...}, _)) =
   298   name = "" orelse ord name = ord "#";
   299 
   300 
   301 (* syntax *)
   302 
   303 fun map_syntax f (Syn (syntax, trfuns)) = Syn (f syntax, trfuns);
   304 
   305 fun make_syntax sg (Syn (syntax, (atrs, trs, tr's, atr's))) =
   306   let
   307     fun apply (s, (f, _: stamp)) = (s, f sg);
   308     fun prep tab = map apply (Symtab.dest tab);
   309     fun prep' tab = map apply (Symtab.dest_multi tab);
   310   in syntax |> Syntax.extend_trfuns (prep atrs, prep trs, prep' tr's, prep' atr's) end;
   311 
   312 fun syn_of (sg as Sg ({syn, ...}, _)) = make_syntax sg syn;
   313 
   314 
   315 (* advanced translation functions *)
   316 
   317 fun extend_trfuns (atrs, trs, tr's, atr's)
   318     (Syn (syn, (parse_ast_trtab, parse_trtab, print_trtab, print_ast_trtab))) =
   319   Syn (syn, (Syntax.extend_trtab parse_ast_trtab atrs "parse ast translation",
   320     Syntax.extend_trtab parse_trtab trs "parse translation",
   321     Syntax.extend_tr'tab print_trtab tr's,
   322     Syntax.extend_tr'tab print_ast_trtab atr's));
   323 
   324 fun merge_trfuns
   325     (parse_ast_trtab1, parse_trtab1, print_trtab1, print_ast_trtab1)
   326     (parse_ast_trtab2, parse_trtab2, print_trtab2, print_ast_trtab2) =
   327   (Syntax.merge_trtabs parse_ast_trtab1 parse_ast_trtab2 "parse ast translation",
   328     Syntax.merge_trtabs parse_trtab1 parse_trtab2 "parse translation",
   329     Syntax.merge_tr'tabs print_trtab1 print_trtab2,
   330     Syntax.merge_tr'tabs print_ast_trtab1 print_ast_trtab2);
   331 
   332 
   333 (* classes and sorts *)
   334 
   335 val classes = Type.classes o tsig_of;
   336 val defaultS = Type.defaultS o tsig_of;
   337 val subsort = Type.subsort o tsig_of;
   338 val of_sort = Type.of_sort o tsig_of;
   339 val witness_sorts = Type.witness_sorts o tsig_of;
   340 val universal_witness = Type.universal_witness o tsig_of;
   341 val typ_instance = Type.typ_instance o tsig_of;
   342 
   343 
   344 
   345 (** signature data **)
   346 
   347 (* errors *)
   348 
   349 fun of_theory sg = "\nof theory " ^ str_of_sg sg;
   350 
   351 fun err_inconsistent kinds =
   352   error ("Attempt to merge different versions of " ^ commas_quote kinds ^ " data");
   353 
   354 fun err_method name kind e =
   355   (writeln ("Error while invoking " ^ quote kind ^ " " ^ name ^ " method"); raise e);
   356 
   357 fun err_dup_init sg kind =
   358   error ("Duplicate initialization of " ^ quote kind ^ " data" ^ of_theory sg);
   359 
   360 fun err_uninit sg kind =
   361   error ("Tried to access uninitialized " ^ quote kind ^ " data" ^ of_theory sg);
   362 
   363 (*Trying to access theory data using get / put operations from a different
   364   instance of the TheoryDataFun result.  Typical cure: re-load all files*)
   365 fun err_access sg kind =
   366   error ("Unauthorized access to " ^ quote kind ^ " data" ^ of_theory sg);
   367 
   368 
   369 (* prepare data *)
   370 
   371 val empty_data = Data Symtab.empty;
   372 
   373 fun merge_data (Data tab1, Data tab2) =
   374   let
   375     val data1 = map snd (Symtab.dest tab1);
   376     val data2 = map snd (Symtab.dest tab2);
   377     val all_data = data1 @ data2;
   378     val kinds = gen_distinct Object.eq_kind (map fst all_data);
   379 
   380    fun entry data kind =
   381      (case gen_assoc Object.eq_kind (data, kind) of
   382        NONE => []
   383      | SOME x => [(kind, x)]);
   384 
   385     fun merge_entries [(kind, (e, mths as (_, ext, _, _)))] =
   386           (kind, (ext e handle exn => err_method "prep_ext" (Object.name_of_kind kind) exn, mths))
   387       | merge_entries [(kind, (e1, mths as (_, _, mrg, _))), (_, (e2, _))] =
   388           (kind, (mrg (e1, e2)
   389             handle exn => err_method "merge" (Object.name_of_kind kind) exn, mths))
   390       | merge_entries _ = sys_error "merge_entries";
   391 
   392     val data = map (fn k => merge_entries (entry data1 k @ entry data2 k)) kinds;
   393     val data_idx = map (fn (k, x) => (Object.name_of_kind k, (k, x))) data;
   394   in
   395     Data (Symtab.make data_idx)
   396       handle Symtab.DUPS dups => err_inconsistent dups
   397   end;
   398 
   399 fun prep_ext_data data = merge_data (data, empty_data);
   400 
   401 fun init_data_sg sg (Data tab) kind e cp ext mrg prt =
   402   let val name = Object.name_of_kind kind in
   403     Data (Symtab.update_new ((name, (kind, (e, (cp, ext, mrg, prt)))), tab))
   404       handle Symtab.DUP _ => err_dup_init sg name
   405   end;
   406 
   407 
   408 (* access data *)
   409 
   410 fun data_kinds (Data tab) = map fst (Symtab.dest tab);
   411 
   412 fun lookup_data sg tab kind =
   413   let val name = Object.name_of_kind kind in
   414     (case Symtab.lookup (tab, name) of
   415       SOME (k, x) =>
   416         if Object.eq_kind (kind, k) then x
   417         else err_access sg name
   418     | NONE => err_uninit sg name)
   419   end;
   420 
   421 fun get_data kind f (sg as Sg (_, {data = Data tab, ...})) =
   422   let val x = fst (lookup_data sg tab kind)
   423   in f x handle Match => Object.kind_error kind end;
   424 
   425 fun print_data kind (sg as Sg (_, {data = Data tab, ...})) =
   426   let val (e, (_, _, _, prt)) = lookup_data sg tab kind
   427   in prt sg e handle exn => err_method ("print" ^ of_theory sg) (Object.name_of_kind kind) exn end;
   428 
   429 fun put_data_sg sg (Data tab) kind f x =
   430   Data (Symtab.update ((Object.name_of_kind kind,
   431     (kind, (f x, snd (lookup_data sg tab kind)))), tab));
   432 
   433 
   434 
   435 (** build signatures **)
   436 
   437 fun ext_stamps stamps (id as ref name) =
   438   let val stmps = (case stamps of ref "#" :: ss => ss | ss => ss) in
   439     if exists (equal name o !) stmps then
   440       error ("Theory already contains a " ^ quote name ^ " component")
   441     else id :: stmps
   442   end;
   443 
   444 fun create_sign self stamps name (syn, tsig, ctab, (path, spaces), data) =
   445   let
   446     val id = ref name;
   447     val sign =
   448       make_sign (id, self, tsig, ctab, syn, path, spaces, data, ext_stamps stamps id);
   449   in
   450     (case self of
   451       SgRef (SOME r) => r := sign
   452     | _ => sys_error "Sign.create_sign");
   453     sign
   454   end;
   455 
   456 fun extend_sign keep extfun name decls
   457     (sg as Sg ({id = _, stamps, syn}, {self, tsig, consts, path, spaces, data})) =
   458   let
   459     val _ = check_stale sg;
   460     val (self', data') =
   461       if is_draft sg andalso keep then (self, data)
   462       else (SgRef (SOME (ref sg)), prep_ext_data data);
   463   in
   464     create_sign self' stamps name
   465       (extfun sg (syn, tsig, consts, (path, spaces), data') decls)
   466   end;
   467 
   468 
   469 
   470 (** name spaces **)
   471 
   472 (* kinds *)
   473 
   474 val classK = "class";
   475 val typeK = "type";
   476 val constK = "const";
   477 
   478 
   479 (* declare and retrieve names *)
   480 
   481 fun space_of spaces kind =
   482   getOpt (assoc (spaces, kind), NameSpace.empty);
   483 
   484 (*input and output of qualified names*)
   485 fun intrn spaces kind = NameSpace.intern (space_of spaces kind);
   486 fun extrn spaces kind = NameSpace.extern (space_of spaces kind);
   487 fun cond_extrn spaces kind = NameSpace.cond_extern (space_of spaces kind);
   488 fun cond_extrn_table spaces kind tab = NameSpace.cond_extern_table (space_of spaces kind) tab;
   489 
   490 (*add / hide names*)
   491 fun change_space f spaces kind x = overwrite (spaces, (kind, f (space_of spaces kind, x)));
   492 fun add_names x = change_space NameSpace.extend x;
   493 fun hide_names b x = change_space (NameSpace.hide b) x;
   494 
   495 (*make full names, standard version*)
   496 fun full _ "" = error "Attempt to declare empty name \"\""
   497   | full NONE bname = bname
   498   | full (SOME path) bname =
   499       if NameSpace.is_qualified bname then
   500         error ("Attempt to declare qualified name " ^ quote bname)
   501       else
   502         let val name = NameSpace.pack (path @ [bname]) in
   503           if Syntax.is_identifier bname then ()
   504           else warning ("Declared non-identifier " ^ quote name); name
   505         end;
   506 
   507 (*make full names, variant permitting qualified names*)
   508 fun full' _ "" = error "Attempt to declare empty name \"\""
   509   | full' NONE bname = bname
   510   | full' (SOME path) bname =
   511       let
   512         val bnames = NameSpace.unpack bname;
   513         val name = NameSpace.pack (path @ bnames)
   514       in
   515         if forall Syntax.is_identifier bnames then ()
   516         else warning ("Declared non-identifier " ^ quote name); name
   517       end;
   518 
   519 (*base name*)
   520 val base_name = NameSpace.base;
   521 
   522 
   523 (* intern / extern names *)
   524 
   525 local
   526   (*prepare mapping of names*)
   527   fun mapping f add_xs t =
   528     let
   529       fun f' x = let val y = f x in if x = y then NONE else SOME (x, y) end;
   530       val table = List.mapPartial f' (add_xs (t, []));
   531       fun lookup x = getOpt (assoc (table, x), x);
   532     in lookup end;
   533 
   534   (*intern / extern typ*)
   535   fun trn_typ trn T =
   536     T |> map_typ
   537       (mapping (trn classK) add_typ_classes T)
   538       (mapping (trn typeK) add_typ_tycons T);
   539 
   540   (*intern / extern term*)
   541   fun trn_term trn t =
   542     t |> map_term
   543       (mapping (trn classK) add_term_classes t)
   544       (mapping (trn typeK) add_term_tycons t)
   545       (mapping (trn constK) add_term_consts t);
   546 
   547   val spaces_of = #spaces o rep_sg;
   548 in
   549   fun intrn_class spaces = intrn spaces classK;
   550   fun extrn_class spaces = cond_extrn spaces classK;
   551 
   552   val intrn_sort = map o intrn_class;
   553   val intrn_typ = trn_typ o intrn;
   554   val intrn_term = trn_term o intrn;
   555 
   556   val extrn_sort = map o extrn_class;
   557   val extrn_typ = trn_typ o cond_extrn;
   558   val extrn_term = trn_term o cond_extrn;
   559 
   560   fun intrn_tycons spaces T =
   561     map_typ I (mapping (intrn spaces typeK) add_typ_tycons T) T;
   562 
   563   val intern = intrn o spaces_of;
   564   val extern = extrn o spaces_of;
   565   val cond_extern = cond_extrn o spaces_of;
   566   fun cond_extern_table sg = cond_extrn_table (spaces_of sg);
   567 
   568   fun extern_typ (sg as Sg (_, {spaces, ...})) T =
   569        if ! NameSpace.long_names then T else extrn_typ spaces T;
   570 
   571   val intern_class = intrn_class o spaces_of;
   572   val intern_sort = intrn_sort o spaces_of;
   573   val intern_typ = intrn_typ o spaces_of;
   574   val intern_term = intrn_term o spaces_of;
   575 
   576   fun intern_tycon sg = intrn (spaces_of sg) typeK;
   577   fun intern_const sg = intrn (spaces_of sg) constK;
   578 
   579   val intern_tycons = intrn_tycons o spaces_of;
   580 
   581   val full_name = full o #path o rep_sg;
   582   val full_name' = full' o #path o rep_sg;
   583 
   584   fun full_name_path sg elems =
   585     full (SOME (getOpt (#path (rep_sg sg), []) @ NameSpace.unpack elems));
   586 
   587 end;
   588 
   589 
   590 
   591 (** partial Pure signature **)
   592 
   593 val pure_syn =
   594   Syn (Syntax.pure_syn, (Symtab.empty, Symtab.empty, Symtab.empty, Symtab.empty));
   595 
   596 val dummy_sg = make_sign (ref "", SgRef NONE, Type.empty_tsig,
   597   Symtab.empty, pure_syn, SOME [], [], empty_data, []);
   598 
   599 val pre_pure =
   600   create_sign (SgRef (SOME (ref dummy_sg))) [] "#"
   601     (pure_syn, Type.empty_tsig, Symtab.empty, (SOME [], []), empty_data);
   602 
   603 val PureN = "Pure";
   604 val CPureN = "CPure";
   605 
   606 
   607 
   608 (** pretty printing of terms, types etc. **)
   609 
   610 fun pretty_term' syn (sg as Sg ({stamps, ...}, {spaces, ...})) t =
   611   Syntax.pretty_term syn
   612     (exists (equal CPureN o !) stamps)
   613     (if ! NameSpace.long_names then t else extrn_term spaces t);
   614 
   615 fun pretty_term sg t = pretty_term' (syn_of sg) sg t;
   616 
   617 fun pretty_typ sg T =
   618   Syntax.pretty_typ (syn_of sg) (extern_typ sg T);
   619 
   620 fun pretty_sort (sg as Sg (_, {spaces, ...})) S =
   621   Syntax.pretty_sort (syn_of sg)
   622     (if ! NameSpace.long_names then S else extrn_sort spaces S);
   623 
   624 fun pretty_classrel sg cs = Pretty.block (List.concat
   625   (separate [Pretty.str " <", Pretty.brk 1] (map (single o pretty_sort sg o single) cs)));
   626 
   627 fun pretty_arity sg (t, Ss, S) =
   628   let
   629     val t' = cond_extern sg typeK t;
   630     val dom =
   631       if null Ss then []
   632       else [Pretty.list "(" ")" (map (pretty_sort sg) Ss), Pretty.brk 1];
   633   in
   634     Pretty.block
   635       ([Pretty.str (t' ^ " ::"), Pretty.brk 1] @ dom @ [pretty_sort sg S])
   636   end;
   637 
   638 val string_of_term = Pretty.string_of oo pretty_term;
   639 val string_of_typ = Pretty.string_of oo pretty_typ;
   640 val string_of_sort = Pretty.string_of oo pretty_sort;
   641 val string_of_classrel = Pretty.string_of oo pretty_classrel;
   642 val string_of_arity = Pretty.string_of oo pretty_arity;
   643 
   644 fun pprint_term sg = Pretty.pprint o Pretty.quote o (pretty_term sg);
   645 fun pprint_typ sg = Pretty.pprint o Pretty.quote o (pretty_typ sg);
   646 
   647 fun pp sg = Pretty.pp (pretty_term sg, pretty_typ sg, pretty_sort sg,
   648   pretty_classrel sg, pretty_arity sg);
   649 
   650 
   651 
   652 (** read sorts **)  (*exception ERROR*)
   653 
   654 fun err_in_sort s =
   655   error ("The error(s) above occurred in sort " ^ quote s);
   656 
   657 fun rd_sort sg syn tsig spaces str =
   658   let val S = intrn_sort spaces (Syntax.read_sort (make_syntax sg syn) str
   659     handle ERROR => err_in_sort str)
   660   in Type.cert_sort tsig S handle TYPE (msg, _, _) => (error_msg msg; err_in_sort str) end;
   661 
   662 (*read and certify sort wrt a signature*)
   663 fun read_sort (sg as Sg ({syn, ...}, {tsig, spaces, ...})) str =
   664   (check_stale sg; rd_sort sg syn tsig spaces str);
   665 
   666 fun cert_sort _ _ tsig _ = Type.cert_sort tsig;
   667 
   668 
   669 
   670 (** read types **)  (*exception ERROR*)
   671 
   672 fun err_in_type s =
   673   error ("The error(s) above occurred in type " ^ quote s);
   674 
   675 fun rd_raw_typ syn tsig spaces def_sort str =
   676   intrn_tycons spaces (Syntax.read_typ syn
   677     (TypeInfer.get_sort tsig def_sort (intrn_sort spaces)) (intrn_sort spaces) str
   678       handle ERROR => err_in_type str);
   679 
   680 fun read_raw_typ' syn (sg as Sg (_, {tsig, spaces, ...}), def_sort) str =
   681   (check_stale sg; rd_raw_typ syn tsig spaces def_sort str);
   682 
   683 fun read_raw_typ (sg, def_sort) = read_raw_typ' (syn_of sg) (sg, def_sort);
   684 
   685 (*read and certify typ wrt a signature*)
   686 local
   687   fun read_typ_aux rd cert (sg, def_sort) str =
   688     cert (tsig_of sg) (rd (sg, def_sort) str)
   689       handle TYPE (msg, _, _) => (error_msg msg; err_in_type str);
   690 in
   691   val read_typ          = read_typ_aux read_raw_typ Type.cert_typ;
   692   val read_typ_raw      = read_typ_aux read_raw_typ Type.cert_typ_raw;
   693   fun read_typ' syn     = read_typ_aux (read_raw_typ' syn) Type.cert_typ;
   694   fun read_typ_raw' syn = read_typ_aux (read_raw_typ' syn) Type.cert_typ_raw;
   695 end;
   696 
   697 
   698 
   699 (** certify classes, sorts, types and terms **)   (*exception TYPE*)
   700 
   701 val certify_class = Type.cert_class o tsig_of;
   702 val certify_sort = Type.cert_sort o tsig_of;
   703 val certify_typ = Type.cert_typ o tsig_of;
   704 val certify_typ_raw = Type.cert_typ_raw o tsig_of;
   705 
   706 fun certify_tyname sg c =
   707   if isSome (Symtab.lookup (#types (Type.rep_tsig (tsig_of sg)), c)) then c
   708   else raise TYPE ("Undeclared type constructor: " ^ quote c, [], []);
   709 
   710 fun certify_const sg c =
   711   if isSome (const_type sg c) then c
   712   else raise TYPE ("Undeclared constant: " ^ quote c, [], []);
   713 
   714 
   715 (* certify_term *)
   716 
   717 local
   718 
   719 (*compute and check type of the term*)
   720 fun type_check pp sg tm =
   721   let
   722     fun err_appl why bs t T u U =
   723       let
   724         val xs = map Free bs;           (*we do not rename here*)
   725         val t' = subst_bounds (xs, t);
   726         val u' = subst_bounds (xs, u);
   727         val text = cat_lines
   728           (TypeInfer.appl_error (Syntax.pp_show_brackets pp) why t' T u' U);
   729       in raise TYPE (text, [T, U], [t', u']) end;
   730 
   731     fun typ_of (_, Const (_, T)) = T
   732       | typ_of (_, Free  (_, T)) = T
   733       | typ_of (_, Var (_, T)) = T
   734       | typ_of (bs, Bound i) = snd (List.nth (bs, i) handle Subscript =>
   735           raise TYPE ("Loose bound variable: B." ^ string_of_int i, [], [Bound i]))
   736       | typ_of (bs, Abs (x, T, body)) = T --> typ_of ((x, T) :: bs, body)
   737       | typ_of (bs, t $ u) =
   738           let val T = typ_of (bs, t) and U = typ_of (bs, u) in
   739             (case T of
   740               Type ("fun", [T1, T2]) =>
   741                 if T1 = U then T2 else err_appl "Incompatible operand type" bs t T u U
   742             | _ => err_appl "Operator not of function type" bs t T u U)
   743           end;
   744 
   745   in typ_of ([], tm) end;
   746 
   747 (*check for duplicate occurrences of TFree/TVar with distinct sorts*)
   748 fun nodup_tvars (env, Type (_, Ts)) = nodup_tvars_list (env, Ts)
   749   | nodup_tvars (env as (tfrees, tvars), T as TFree (v as (a, S))) =
   750       (case assoc_string (tfrees, a) of
   751         SOME S' =>
   752           if S = S' then env
   753           else raise TYPE ("Type variable " ^ quote a ^
   754             " has two distinct sorts", [TFree (a, S'), T], [])
   755       | NONE => (v :: tfrees, tvars))
   756   | nodup_tvars (env as (tfrees, tvars), T as TVar (v as (a, S))) =
   757       (case assoc_string_int (tvars, a) of
   758         SOME S' =>
   759           if S = S' then env
   760           else raise TYPE ("Type variable " ^ quote (Syntax.string_of_vname a) ^
   761             " has two distinct sorts", [TVar (a, S'), T], [])
   762       | NONE => (tfrees, v :: tvars))
   763 (*equivalent to foldl nodup_tvars_list, but 3X faster under Poly/ML*)
   764 and nodup_tvars_list (env, []) = env
   765   | nodup_tvars_list (env, T :: Ts) = nodup_tvars_list (nodup_tvars (env, T), Ts);
   766 
   767 in
   768 
   769 (*check for duplicate occurrences of Free/Var with distinct types*)
   770 fun nodup_vars tm =
   771   let
   772     fun nodups (envs as (env as (frees, vars), envT)) tm =
   773       (case tm of
   774         Const (c, T) => (env, nodup_tvars (envT, T))
   775       | Free (v as (a, T)) =>
   776           (case assoc_string (frees, a) of
   777             SOME T' =>
   778               if T = T' then (env, nodup_tvars (envT, T))
   779               else raise TYPE ("Variable " ^ quote a ^
   780                 " has two distinct types", [T', T], [])
   781           | NONE => ((v :: frees, vars), nodup_tvars (envT, T)))
   782       | Var (v as (ixn, T)) =>
   783           (case assoc_string_int (vars, ixn) of
   784             SOME T' =>
   785               if T = T' then (env, nodup_tvars (envT, T))
   786               else raise TYPE ("Variable " ^ quote (Syntax.string_of_vname ixn) ^
   787                 " has two distinct types", [T', T], [])
   788           | NONE => ((frees, v :: vars), nodup_tvars (envT, T)))
   789       | Bound _ => envs
   790       | Abs (_, T, t) => nodups (env, nodup_tvars (envT, T)) t
   791       | s $ t => nodups (nodups envs s) t)
   792   in nodups (([], []), ([], [])) tm; tm end;
   793 
   794 fun certify_term pp sg tm =
   795   let
   796     val _ = check_stale sg;
   797 
   798     val tm' = map_term_types (Type.cert_typ (tsig_of sg)) tm;
   799     val tm' = if tm = tm' then tm else tm';  (*avoid copying of already normal term*)
   800 
   801     fun err msg = raise TYPE (msg, [], [tm']);
   802 
   803     fun show_const a T = quote a ^ " :: " ^ Pretty.string_of_typ pp T;
   804 
   805     fun check_atoms (t $ u) = (check_atoms t; check_atoms u)
   806       | check_atoms (Abs (_, _, t)) = check_atoms t
   807       | check_atoms (Const (a, T)) =
   808           (case const_type sg a of
   809             NONE => err ("Undeclared constant " ^ show_const a T)
   810           | SOME U =>
   811               if typ_instance sg (T, U) then ()
   812               else err ("Illegal type for constant " ^ show_const a T))
   813       | check_atoms (Var ((x, i), _)) =
   814           if i < 0 then err ("Malformed variable: " ^ quote x) else ()
   815       | check_atoms _ = ();
   816   in
   817     check_atoms tm';
   818     nodup_vars tm';
   819     (tm', type_check pp sg tm', maxidx_of_term tm')
   820   end;
   821 
   822 end;
   823 
   824 
   825 
   826 (** instantiation **)
   827 
   828 fun inst_typ_tvars sg = Type.inst_typ_tvars (pp sg) (tsig_of sg);
   829 fun inst_term_tvars sg = Type.inst_term_tvars (pp sg) (tsig_of sg);
   830 
   831 
   832 
   833 (** infer_types **)         (*exception ERROR*)
   834 
   835 (*
   836   def_type: partial map from indexnames to types (constrains Frees, Vars)
   837   def_sort: partial map from indexnames to sorts (constrains TFrees, TVars)
   838   used: list of already used type variables
   839   freeze: if true then generated parameters are turned into TFrees, else TVars
   840 
   841   termss: lists of alternative parses (only one combination should be type-correct)
   842   typs: expected types
   843 *)
   844 
   845 fun infer_types_simult pp sg def_type def_sort used freeze args =
   846   let
   847     val tsig = tsig_of sg;
   848 
   849     val termss = foldr multiply [[]] (map fst args);
   850     val typs =
   851       map (fn (_, T) => certify_typ sg T handle TYPE (msg, _, _) => error msg) args;
   852 
   853     fun infer ts = OK (TypeInfer.infer_types (Syntax.pp_show_brackets pp) tsig
   854         (const_type sg) def_type def_sort (intern_const sg) (intern_tycons sg)
   855         (intern_sort sg) used freeze typs ts)
   856       handle TYPE (msg, _, _) => Error msg;
   857 
   858     val err_results = map infer termss;
   859     val errs = List.mapPartial get_error err_results;
   860     val results = List.mapPartial get_ok err_results;
   861 
   862     val ambiguity = length termss;
   863 
   864     fun ambig_msg () =
   865       if ambiguity > 1 andalso ambiguity <= ! Syntax.ambiguity_level
   866       then
   867         error_msg "Got more than one parse tree.\n\
   868           \Retry with smaller Syntax.ambiguity_level for more information."
   869       else ();
   870   in
   871     if null results then (ambig_msg (); error (cat_lines errs))
   872     else if length results = 1 then
   873       (if ambiguity > ! Syntax.ambiguity_level then
   874         warning "Fortunately, only one parse tree is type correct.\n\
   875           \You may still want to disambiguate your grammar or your input."
   876       else (); hd results)
   877     else (ambig_msg (); error ("More than one term is type correct:\n" ^
   878       cat_lines (map (Pretty.string_of_term pp) (List.concat (map fst results)))))
   879   end;
   880 
   881 
   882 fun infer_types pp sg def_type def_sort used freeze tsT =
   883   apfst hd (infer_types_simult pp sg def_type def_sort used freeze [tsT]);
   884 
   885 
   886 (** read_def_terms **)
   887 
   888 (*read terms, infer types*)
   889 fun read_def_terms' pp is_logtype syn (sign, types, sorts) used freeze sTs =
   890   let
   891     fun read (s, T) =
   892       let val T' = certify_typ sign T handle TYPE (msg, _, _) => error msg
   893       in (Syntax.read is_logtype syn T' s, T') end;
   894     val tsTs = map read sTs;
   895   in infer_types_simult pp sign types sorts used freeze tsTs end;
   896 
   897 fun read_def_terms (sign, types, sorts) =
   898   read_def_terms' (pp sign) (is_logtype sign) (syn_of sign) (sign, types, sorts);
   899 
   900 fun simple_read_term sign T s =
   901   (read_def_terms (sign, K NONE, K NONE) [] true [(s, T)]
   902     handle ERROR => error ("The error(s) above occurred for " ^ s)) |> #1 |> hd;
   903 
   904 
   905 
   906 (** extend signature **)    (*exception ERROR*)
   907 
   908 (** signature extension functions **)  (*exception ERROR*)
   909 
   910 fun decls_of path name_of mfixs =
   911   map (fn (x, y, mx) => (full path (name_of x mx), y)) mfixs;
   912 
   913 fun no_read _ _ _ _ decl = decl;
   914 
   915 
   916 (* add default sort *)
   917 
   918 fun ext_defS prep_sort sg (syn, tsig, ctab, (path, spaces), data) S =
   919   (syn, Type.set_defsort (prep_sort sg syn tsig spaces S) tsig,
   920     ctab, (path, spaces), data);
   921 
   922 fun ext_defsort arg = ext_defS rd_sort arg;
   923 fun ext_defsort_i arg = ext_defS cert_sort arg;
   924 
   925 
   926 (* add type constructors *)
   927 
   928 fun ext_types sg (syn, tsig, ctab, (path, spaces), data) types =
   929   let
   930     val decls = decls_of path Syntax.type_name types;
   931     val syn' = map_syntax (Syntax.extend_type_gram types) syn;
   932     val tsig' = Type.add_types decls tsig;
   933   in (syn', tsig', ctab, (path, add_names spaces typeK (map fst decls)), data) end;
   934 
   935 
   936 (* add type abbreviations *)
   937 
   938 fun read_abbr sg syn tsig spaces (t, vs, rhs_src) =
   939   (t, vs, rd_raw_typ (make_syntax sg syn) tsig spaces (K NONE) rhs_src)
   940     handle ERROR => error ("in type abbreviation " ^ t);
   941 
   942 fun ext_abbrs rd_abbr sg (syn, tsig, ctab, (path, spaces), data) abbrs =
   943   let
   944     fun mfix_of (t, vs, _, mx) = (t, length vs, mx);
   945     val syn' = syn |> map_syntax (Syntax.extend_type_gram (map mfix_of abbrs));
   946 
   947     val abbrs' =
   948       map (fn (t, vs, rhs, mx) =>
   949         (full path (Syntax.type_name t mx), vs, rhs)) abbrs;
   950     val spaces' = add_names spaces typeK (map #1 abbrs');
   951     val decls = map (rd_abbr sg syn' tsig spaces') abbrs';
   952   in (syn', Type.add_abbrs decls tsig, ctab, (path, spaces'), data) end;
   953 
   954 fun ext_tyabbrs abbrs = ext_abbrs read_abbr abbrs;
   955 fun ext_tyabbrs_i abbrs = ext_abbrs no_read abbrs;
   956 
   957 
   958 (* add nonterminals *)
   959 
   960 fun ext_nonterminals _ (syn, tsig, ctab, (path, spaces), data) bnames =
   961   let val names = map (full path) bnames in
   962     (map_syntax (Syntax.extend_consts names) syn,
   963       Type.add_nonterminals names tsig, ctab,
   964       (path, add_names spaces typeK names), data)
   965   end;
   966 
   967 
   968 (* add type arities *)
   969 
   970 fun ext_ars int prep_sort sg (syn, tsig, ctab, (path, spaces), data) arities =
   971   let
   972     val prepS = prep_sort sg syn tsig spaces;
   973     fun prep_arity (c, Ss, S) =
   974       (if int then intrn spaces typeK c else c, map prepS Ss, prepS S);
   975     val tsig' = Type.add_arities (pp sg) (map prep_arity arities) tsig;
   976   in (syn, tsig', ctab, (path, spaces), data) end;
   977 
   978 fun ext_arities arg = ext_ars true rd_sort arg;
   979 fun ext_arities_i arg = ext_ars false cert_sort arg;
   980 
   981 
   982 (* add term constants and syntax *)
   983 
   984 fun const_name path c mx =
   985   full path (Syntax.const_name c mx);
   986 
   987 fun err_in_const c =
   988   error ("in declaration of constant " ^ quote c);
   989 
   990 fun err_dup_consts cs =
   991   error ("Duplicate declaration of constant(s) " ^ commas_quote cs);
   992 
   993 
   994 fun read_const sg syn tsig (path, spaces) (c, ty_src, mx) =
   995   (c, rd_raw_typ (make_syntax sg syn) tsig spaces (K NONE) ty_src, mx)
   996     handle ERROR => err_in_const (const_name path c mx);
   997 
   998 fun ext_cnsts rd_const syn_only prmode sg (syn, tsig, ctab, (path, spaces), data)
   999     raw_consts =
  1000   let
  1001     val prep_typ = compress_type o Type.varifyT o Type.no_tvars o
  1002      (if syn_only then Type.cert_typ_syntax tsig else Term.no_dummyT o Type.cert_typ tsig);
  1003     fun prep_const (c, ty, mx) = (c, prep_typ ty, mx) handle TYPE (msg, _, _) =>
  1004       (error_msg msg; err_in_const (const_name path c mx));
  1005 
  1006     val consts = map (prep_const o rd_const sg syn tsig (path, spaces)) raw_consts;
  1007     val decls =
  1008       if syn_only then []
  1009       else decls_of path Syntax.const_name consts;
  1010   in
  1011     (map_syntax (Syntax.extend_const_gram (is_logtype sg) prmode consts) syn, tsig,
  1012       Symtab.extend (ctab, map (fn (c, T) => (c, (T, stamp ()))) decls)
  1013         handle Symtab.DUPS cs => err_dup_consts cs,
  1014       (path, add_names spaces constK (map fst decls)), data)
  1015   end;
  1016 
  1017 fun ext_consts_i x = ext_cnsts no_read false Syntax.default_mode x;
  1018 fun ext_consts x = ext_cnsts read_const false Syntax.default_mode x;
  1019 fun ext_syntax_i x = ext_cnsts no_read true Syntax.default_mode x;
  1020 fun ext_syntax x = ext_cnsts read_const true Syntax.default_mode x;
  1021 fun ext_modesyntax_i x y (prmode, consts) = ext_cnsts no_read true prmode x y consts;
  1022 fun ext_modesyntax x y (prmode, consts) = ext_cnsts read_const true prmode x y consts;
  1023 
  1024 
  1025 (* add type classes *)
  1026 
  1027 fun const_of_class c = c ^ "_class";
  1028 
  1029 fun class_of_const c_class =
  1030   let
  1031     val c = implode (Library.take (size c_class - size "_class", explode c_class));
  1032   in
  1033     if const_of_class c = c_class then c
  1034     else raise TERM ("class_of_const: bad name " ^ quote c_class, [])
  1035   end;
  1036 
  1037 
  1038 fun ext_classes int sg (syn, tsig, ctab, (path, spaces), data) classes =
  1039   let
  1040     val names = map fst classes;
  1041     val consts =
  1042       map (fn c => (const_of_class c, a_itselfT --> propT, NoSyn)) names;
  1043 
  1044     val full_names = map (full path) names;
  1045     val spaces' = add_names spaces classK full_names;
  1046     val intrn = if int then map (intrn_class spaces') else I;
  1047     val classes' =
  1048       ListPair.map (fn (c, (_, cs)) => (c, intrn cs)) (full_names, classes);
  1049   in
  1050     ext_consts_i sg
  1051       (map_syntax (Syntax.extend_consts names) syn,
  1052         Type.add_classes (pp sg) classes' tsig, ctab, (path, spaces'), data)
  1053     consts
  1054   end;
  1055 
  1056 
  1057 (* add to classrel *)
  1058 
  1059 fun ext_classrel int sg (syn, tsig, ctab, (path, spaces), data) pairs =
  1060   let val intrn = if int then map (pairself (intrn_class spaces)) else I in
  1061     (syn, Type.add_classrel (pp sg) (intrn pairs) tsig, ctab, (path, spaces), data)
  1062   end;
  1063 
  1064 
  1065 (* add translation functions *)
  1066 
  1067 fun ext_trfs ext non_typed sg (syn, tsig, ctab, names, data) (atrs, trs, tr's, atr's) =
  1068   let val syn' = syn |> ext (atrs, trs, map (apsnd non_typed) tr's, atr's)
  1069   in make_syntax sg syn'; (syn', tsig, ctab, names, data) end;
  1070 
  1071 fun ext_trfsT ext sg (syn, tsig, ctab, names, data) tr's =
  1072   let val syn' = syn |> ext ([], [], tr's, [])
  1073   in make_syntax sg syn'; (syn', tsig, ctab, names, data) end;
  1074 
  1075 fun ext_trfuns sg = ext_trfs (map_syntax o Syntax.extend_trfuns) Syntax.non_typed_tr' sg;
  1076 fun ext_trfunsT sg = ext_trfsT (map_syntax o Syntax.extend_trfuns) sg;
  1077 fun ext_advanced_trfuns sg = ext_trfs extend_trfuns Syntax.non_typed_tr'' sg;
  1078 fun ext_advanced_trfunsT sg = ext_trfsT extend_trfuns sg;
  1079 
  1080 
  1081 (* add token translation functions *)
  1082 
  1083 fun ext_tokentrfuns sg (syn, tsig, ctab, names, data) args =
  1084   (map_syntax (Syntax.extend_tokentrfuns args) syn, tsig, ctab, names, data);
  1085 
  1086 
  1087 (* add translation rules *)
  1088 
  1089 fun ext_trrules sg (syn, tsig, ctab, (path, spaces), data) args =
  1090   (syn |> map_syntax (Syntax.extend_trrules (is_logtype sg) (make_syntax sg syn)
  1091       (map (Syntax.map_trrule (fn (root, str) => (intrn spaces typeK root, str))) args)),
  1092     tsig, ctab, (path, spaces), data);
  1093 
  1094 fun ext_trrules_i _ (syn, tsig, ctab, names, data) args =
  1095   (syn |> map_syntax (Syntax.extend_trrules_i args), tsig, ctab, names, data);
  1096 
  1097 
  1098 (* add to path *)
  1099 
  1100 fun ext_path _ (syn, tsig, ctab, (path, spaces), data) elems =
  1101   let
  1102     val path' =
  1103       if elems = "//" then NONE
  1104       else if elems = "/" then SOME []
  1105       else if elems = ".." andalso isSome path andalso path <> SOME [] then
  1106         SOME (fst (split_last (valOf path)))
  1107       else SOME (getOpt (path,[]) @ NameSpace.unpack elems);
  1108   in
  1109     (syn, tsig, ctab, (path', spaces), data)
  1110   end;
  1111 
  1112 
  1113 (* change name space *)
  1114 
  1115 fun ext_add_space _ (syn, tsig, ctab, (path, spaces), data) (kind, names) =
  1116   (syn, tsig, ctab, (path, add_names spaces kind names), data);
  1117 
  1118 fun ext_hide_space _ (syn, tsig, ctab, (path, spaces), data) (b, (kind, xnames)) =
  1119   (syn, tsig, ctab, (path, hide_names b spaces kind (map (intrn spaces kind) xnames)), data);
  1120 
  1121 fun ext_hide_space_i _ (syn, tsig, ctab, (path, spaces), data) (b, (kind, names)) =
  1122   (syn, tsig, ctab, (path, hide_names b spaces kind names), data);
  1123 
  1124 
  1125 (* signature data *)
  1126 
  1127 fun ext_init_data sg (syn, tsig, ctab, names, data) (kind, (e, cp, ext, mrg, prt)) =
  1128   (syn, tsig, ctab, names, init_data_sg sg data kind e cp ext mrg prt);
  1129 
  1130 fun ext_put_data sg (syn, tsig, ctab, names, data) (kind, f, x) =
  1131   (syn, tsig, ctab, names, put_data_sg sg data kind f x);
  1132 
  1133 
  1134 fun copy_data (k, (e, mths as (cp, _, _, _))) =
  1135   (k, (cp e handle exn => err_method "copy" (Object.name_of_kind k) exn, mths));
  1136 
  1137 fun copy (sg as Sg ({id = _, stamps, syn}, {self, tsig, consts, path, spaces, data})) =
  1138   let
  1139     val _ = check_stale sg;
  1140     val self' = SgRef (SOME (ref sg));
  1141     val Data tab = data;
  1142     val data' = Data (Symtab.map copy_data tab);
  1143   in create_sign self' stamps "#" (syn, tsig, consts, (path, spaces), data') end;
  1144 
  1145 
  1146 (* the external interfaces *)
  1147 
  1148 val add_classes          = extend_sign true (ext_classes true) "#";
  1149 val add_classes_i        = extend_sign true (ext_classes false) "#";
  1150 val add_classrel         = extend_sign true (ext_classrel true) "#";
  1151 val add_classrel_i       = extend_sign true (ext_classrel false) "#";
  1152 val add_defsort          = extend_sign true ext_defsort "#";
  1153 val add_defsort_i        = extend_sign true ext_defsort_i "#";
  1154 val add_types            = extend_sign true ext_types "#";
  1155 val add_nonterminals     = extend_sign true ext_nonterminals "#";
  1156 val add_tyabbrs          = extend_sign true ext_tyabbrs "#";
  1157 val add_tyabbrs_i        = extend_sign true ext_tyabbrs_i "#";
  1158 val add_arities          = extend_sign true ext_arities "#";
  1159 val add_arities_i        = extend_sign true ext_arities_i "#";
  1160 val add_consts           = extend_sign true ext_consts "#";
  1161 val add_consts_i         = extend_sign true ext_consts_i "#";
  1162 val add_syntax           = extend_sign true ext_syntax "#";
  1163 val add_syntax_i         = extend_sign true ext_syntax_i "#";
  1164 val add_modesyntax       = extend_sign true ext_modesyntax "#";
  1165 val add_modesyntax_i     = extend_sign true ext_modesyntax_i "#";
  1166 val add_trfuns           = extend_sign true ext_trfuns "#";
  1167 val add_trfunsT          = extend_sign true ext_trfunsT "#";
  1168 val add_advanced_trfuns  = extend_sign true ext_advanced_trfuns "#";
  1169 val add_advanced_trfunsT = extend_sign true ext_advanced_trfunsT "#";
  1170 val add_tokentrfuns      = extend_sign true ext_tokentrfuns "#";
  1171 val add_trrules          = extend_sign true ext_trrules "#";
  1172 val add_trrules_i        = extend_sign true ext_trrules_i "#";
  1173 val add_path             = extend_sign true ext_path "#";
  1174 val add_space            = extend_sign true ext_add_space "#";
  1175 val hide_space           = curry (extend_sign true ext_hide_space "#");
  1176 val hide_space_i         = curry (extend_sign true ext_hide_space_i "#");
  1177 val init_data            = extend_sign true ext_init_data "#";
  1178 fun put_data k f x       = extend_sign true ext_put_data "#" (k, f, x);
  1179 fun add_name name        = extend_sign true (K K) name ();
  1180 val prep_ext             = extend_sign false (K K) "#" ();
  1181 
  1182 
  1183 
  1184 (** merge signatures **)        (*exception TERM*)
  1185 
  1186 (* merge_stamps *)
  1187 
  1188 fun merge_stamps stamps1 stamps2 =
  1189   let val stamps = merge_lists' stamps1 stamps2 in
  1190     (case duplicates (map ! stamps) of
  1191       [] => stamps
  1192     | dups => raise TERM ("Attempt to merge different versions of theories "
  1193         ^ commas_quote dups, []))
  1194   end;
  1195 
  1196 
  1197 (* trivial merge *)
  1198 
  1199 fun merge_refs (sgr1 as SgRef (SOME (ref (sg1 as Sg ({stamps = s1, ...}, _)))),
  1200         sgr2 as SgRef (SOME (ref (sg2 as Sg ({stamps = s2, ...}, _))))) =
  1201       if fast_subsig (sg2, sg1) then sgr1
  1202       else if fast_subsig (sg1, sg2) then sgr2
  1203       else if subsig (sg2, sg1) then sgr1
  1204       else if subsig (sg1, sg2) then sgr2
  1205       else (merge_stamps s1 s2; (*check for different versions*)
  1206         raise TERM ("Attempt to do non-trivial merge of signatures", []))
  1207   | merge_refs _ = sys_error "Sign.merge_refs";
  1208 
  1209 val merge = deref o merge_refs o pairself self_ref;
  1210 
  1211 
  1212 (* non-trivial merge *)              (*exception TERM/ERROR*)
  1213 
  1214 fun nontriv_merge (sg1, sg2) =
  1215   if subsig (sg2, sg1) then sg1
  1216   else if subsig (sg1, sg2) then sg2
  1217   else if is_draft sg1 orelse is_draft sg2 then
  1218     raise TERM ("Attempt to merge draft signatures", [])
  1219   else if exists_stamp PureN sg1 andalso exists_stamp CPureN sg2 orelse
  1220       exists_stamp CPureN sg1 andalso exists_stamp PureN sg2 then
  1221     raise TERM ("Cannot merge Pure and CPure signatures", [])
  1222   else
  1223     let
  1224       val Sg ({id = _, stamps = stamps1, syn = Syn (syntax1, trfuns1)},
  1225           {self = _, tsig = tsig1, consts = consts1,
  1226             path = _, spaces = spaces1, data = data1}) = sg1;
  1227       val Sg ({id = _, stamps = stamps2, syn = Syn (syntax2, trfuns2)},
  1228           {self = _, tsig = tsig2, consts = consts2,
  1229             path = _, spaces = spaces2, data = data2}) = sg2;
  1230 
  1231       val stamps = merge_stamps stamps1 stamps2;
  1232       val syntax = Syntax.merge_syntaxes syntax1 syntax2;
  1233       val trfuns = merge_trfuns trfuns1 trfuns2;
  1234       val consts = Symtab.merge eq_snd (consts1, consts2)
  1235         handle Symtab.DUPS cs => err_dup_consts cs;
  1236 
  1237       val path = SOME [];
  1238       val kinds = distinct (map fst (spaces1 @ spaces2));
  1239       val spaces =
  1240         kinds ~~
  1241           ListPair.map NameSpace.merge
  1242             (map (space_of spaces1) kinds, map (space_of spaces2) kinds);
  1243 
  1244       val data = merge_data (data1, data2);
  1245 
  1246       val pre_sign = make_sign (ref "", SgRef (SOME (ref dummy_sg)),
  1247         tsig1, consts, Syn (syntax, trfuns), path, spaces, data, ref "#" :: stamps1);
  1248       val tsig = Type.merge_tsigs (pp pre_sign) (tsig1, tsig2);
  1249 
  1250       val self_ref = ref dummy_sg;
  1251       val self = SgRef (SOME self_ref);
  1252       val sign = make_sign (ref "", self, tsig, consts, Syn (syntax, trfuns),
  1253         path, spaces, data, stamps);
  1254     in self_ref := sign; syn_of sign; sign end;
  1255 
  1256 end;