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