src/Pure/sign.ML
author nipkow
Thu Dec 30 10:18:23 1993 +0100 (1993-12-30)
changeset 206 0d624d1ba9cc
parent 200 39a931cc6558
child 211 7ab45715c0a6
permissions -rw-r--r--
added subsig: sg * sg -> bool to test if one signature is contained in another.
     1 (*  Title:      Pure/sign.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1992  University of Cambridge
     5 
     6 The abstract types "sg" (signatures) and "cterm" / "ctyp" (certified terms /
     7 typs under a signature).
     8 *)
     9 
    10 signature SIGN =
    11 sig
    12   structure Type: TYPE
    13   structure Symtab: SYMTAB
    14   structure Syntax: SYNTAX
    15   sharing Symtab = Type.Symtab
    16   type sg
    17   type cterm
    18   type ctyp
    19   val cfun: (term -> term) -> (cterm -> cterm)
    20   val cterm_of: sg -> term -> cterm
    21   val ctyp_of: sg -> typ -> ctyp
    22   val extend: sg -> string ->
    23         (class * class list) list * class list *
    24         (string list * int) list *
    25         (string * indexname list * string) list *
    26         (string list * (sort list * class)) list *
    27         (string list * string)list * Syntax.sext option -> sg
    28   val merge: sg * sg -> sg
    29   val pure: sg
    30   val read_cterm: sg -> string * typ -> cterm
    31   val read_ctyp: sg -> string -> ctyp
    32   val read_insts: sg -> (indexname -> typ option) * (indexname -> sort option)
    33                   -> (indexname -> typ option) * (indexname -> sort option)
    34                   -> (string*string)list
    35                   -> (indexname*ctyp)list * (cterm*cterm)list
    36   val read_typ: sg * (indexname -> sort option) -> string -> typ
    37   val rep_cterm: cterm -> {T: typ, t: term, sign: sg, maxidx: int}
    38   val rep_ctyp: ctyp -> {T: typ, sign: sg}
    39   val rep_sg: sg -> {tsig: Type.type_sig,
    40                      const_tab: typ Symtab.table,
    41                      syn: Syntax.syntax,
    42                      stamps: string ref list}
    43   val string_of_cterm: cterm -> string
    44   val string_of_ctyp: ctyp -> string
    45   val pprint_cterm: cterm -> pprint_args -> unit
    46   val pprint_ctyp: ctyp -> pprint_args -> unit
    47   val string_of_term: sg -> term -> string
    48   val string_of_typ: sg -> typ -> string
    49   val subsig: sg * sg -> bool
    50   val pprint_term: sg -> term -> pprint_args -> unit
    51   val pprint_typ: sg -> typ -> pprint_args -> unit
    52   val term_of: cterm -> term
    53   val typ_of: ctyp -> typ
    54   val pretty_term: sg -> term -> Syntax.Pretty.T
    55 end;
    56 
    57 functor SignFun(structure Type: TYPE and Syntax: SYNTAX) : SIGN =
    58 struct
    59 
    60 structure Type = Type;
    61 structure Symtab = Type.Symtab;
    62 structure Syntax = Syntax;
    63 structure Pretty = Syntax.Pretty
    64 
    65 
    66 (* Signatures of theories. *)
    67 
    68 datatype sg =
    69   Sg of {
    70     tsig: Type.type_sig,            (*order-sorted signature of types*)
    71     const_tab: typ Symtab.table,    (*types of constants*)
    72     syn: Syntax.syntax,             (*syntax for parsing and printing*)
    73     stamps: string ref list};       (*unique theory indentifier*)
    74 
    75 
    76 fun rep_sg (Sg args) = args;
    77 
    78 fun subsig(Sg{stamps=s1,...},Sg{stamps=s2,...}) = s1 subset s2;
    79 
    80 fun string_of_typ(Sg{tsig,syn,...}) = Syntax.string_of_typ syn;
    81 
    82 fun pprint_typ(Sg{syn,...}) = Pretty.pprint o Pretty.quote o (Syntax.pretty_typ syn);
    83 
    84 (*Is constant present in table with more generic type?*)
    85 fun valid_const tsig ctab (a,T) = case Symtab.lookup(ctab, a) of
    86         Some U => Type.typ_instance(tsig,T,U) | _ => false;
    87 
    88 
    89 (*Check a term for errors.  Are all constants and types valid in signature?
    90   Does not check that term is well-typed!*)
    91 fun term_errors (sign as Sg{tsig,const_tab,...}) =
    92 let val showtyp = string_of_typ sign
    93     fun terrs (Const (a,T), errs) =
    94         if valid_const tsig const_tab (a,T)
    95         then Type.type_errors tsig (T,errs)
    96         else ("Illegal type for constant: " ^ a ^ ": " ^ showtyp T) :: errs
    97       | terrs (Free (_,T), errs) = Type.type_errors tsig (T,errs)
    98       | terrs (Var  ((a,i),T), errs) =
    99         if  i>=0  then  Type.type_errors tsig (T,errs)
   100         else  ("Negative index for Var: " ^ a) :: errs
   101       | terrs (Bound _, errs) = errs (*loose bvars detected by type_of*)
   102       | terrs (Abs (_,T,t), errs) =
   103             Type.type_errors tsig (T,terrs(t,errs))
   104       | terrs (f$t, errs) = terrs(f, terrs (t,errs))
   105 in  terrs  end;
   106 
   107 
   108 
   109 (** The Extend operation **)
   110 
   111 (* Extend a signature: may add classes, types and constants. The "ref" in
   112    stamps ensures that no two signatures are identical -- it is impossible to
   113    forge a signature. *)
   114 
   115 fun extend (Sg {tsig, const_tab, syn, stamps}) name
   116   (classes, default, types, abbr, arities, const_decs, opt_sext) =
   117   let
   118     fun err_in_typ s = error ("The error(s) above occurred in type " ^ quote s);
   119 
   120     fun read_typ tsg sy s =
   121       Syntax.read_typ sy (K (Type.defaultS tsg)) s handle ERROR => err_in_typ s;
   122 
   123     fun check_typ tsg sy ty =
   124       (case Type.type_errors tsg (ty, []) of
   125         [] => ty
   126       | errs => (prs (cat_lines errs); err_in_typ (Syntax.string_of_typ sy ty)));
   127 
   128     (*reset TVar indices to zero, renaming to preserve distinctness*)
   129     fun zero_tvar_indices T =
   130       let
   131         val inxSs = typ_tvars T;
   132         val nms' = variantlist (map (#1 o #1) inxSs, []);
   133         val tye = map (fn ((v, S), a) => (v, TVar ((a, 0), S))) (inxSs ~~ nms');
   134       in typ_subst_TVars tye T end;
   135 
   136     (*read and check the type mentioned in a const declaration; zero type var
   137       indices because type inference requires it*)
   138 
   139     fun read_consts tsg sy (cs, s) =
   140       let val ty = zero_tvar_indices (Type.varifyT (read_typ tsg sy s));
   141       in
   142         (case Type.type_errors tsg (ty, []) of
   143           [] => (cs, ty)
   144         | errs => error (cat_lines (("Error in type of constants " ^
   145             space_implode " " (map quote cs)) :: errs)))
   146       end;
   147 
   148     val tsig' = Type.extend (tsig, classes, default, types, arities);
   149 
   150     fun read_typ_abbr(a,v,s)=
   151       let val T = Type.varifyT(read_typ tsig' syn s)
   152       in (a,(v,T)) end handle ERROR => error("This error occured in abbreviation "^ quote a);
   153 
   154     val abbr' = map read_typ_abbr abbr;
   155     val tsig'' = Type.add_abbrs(tsig',abbr');
   156 
   157     val read_ty =
   158       (Type.expand_typ tsig'') o (check_typ tsig'' syn) o (read_typ tsig'' syn);
   159     val log_types = Type.logical_types tsig'';
   160     val xconsts = map #1 classes @ flat (map #1 types) @ flat (map #1 const_decs);
   161     val sext = case opt_sext of Some sx => sx | None => Syntax.empty_sext;
   162 
   163     val syn' = Syntax.extend syn read_ty (log_types, xconsts, sext);
   164 
   165     val const_decs' =
   166       map (read_consts tsig'' syn') (Syntax.constants sext @ const_decs);
   167   in
   168     Sg {
   169       tsig = tsig'',
   170       const_tab = Symtab.st_of_declist (const_decs', const_tab)
   171         handle Symtab.DUPLICATE a => error ("Constant " ^ quote a ^ " declared twice"),
   172       syn = syn',
   173       stamps = ref name :: stamps}
   174   end;
   175 
   176 
   177 (* The empty signature *)
   178 
   179 val sg0 = Sg {tsig = Type.tsig0, const_tab = Symtab.null,
   180   syn = Syntax.type_syn, stamps = []};
   181 
   182 
   183 (* The pure signature *)
   184 
   185 val pure = extend sg0 "Pure"
   186 ([("logic", [])],
   187  ["logic"],
   188  [(["fun"], 2),
   189   (["prop"], 0),
   190   (Syntax.syntax_types, 0)],
   191  [],
   192  [(["fun"],  ([["logic"], ["logic"]], "logic")),
   193   (["prop"], ([], "logic"))],
   194  [([Syntax.constrainC], "'a::logic => 'a")],
   195  Some Syntax.pure_sext);
   196 
   197 
   198 
   199 (** The Merge operation **)
   200 
   201 (*Update table with (a,x) providing any existing asgt to "a" equals x. *)
   202 fun update_eq ((a,x),tab) =
   203     case Symtab.lookup(tab,a) of
   204         None => Symtab.update((a,x), tab)
   205       | Some y => if x=y then tab
   206             else  raise TERM ("Incompatible types for constant: "^a, []);
   207 
   208 (*Combine tables, updating tab2 by tab1 and checking.*)
   209 fun merge_tabs (tab1,tab2) =
   210     Symtab.balance (foldr update_eq (Symtab.alist_of tab1, tab2));
   211 
   212 (*Combine tables, overwriting tab2 with tab1.*)
   213 fun smash_tabs (tab1,tab2) =
   214     Symtab.balance (foldr Symtab.update (Symtab.alist_of tab1, tab2));
   215 
   216 (*Combine stamps, checking that theory names are disjoint. *)
   217 fun merge_stamps (stamps1,stamps2) =
   218   let val stamps = stamps1 union stamps2 in
   219   case findrep (map ! stamps) of
   220      a::_ => error ("Attempt to merge different versions of theory: " ^ a)
   221    | [] => stamps
   222   end;
   223 
   224 (*Merge two signatures.  Forms unions of tables.  Prefers sign1. *)
   225 fun merge
   226   (sign1 as Sg {tsig = tsig1, const_tab = ctab1, stamps = stamps1, syn = syn1},
   227    sign2 as Sg {tsig = tsig2, const_tab = ctab2, stamps = stamps2, syn = syn2}) =
   228     if stamps2 subset stamps1 then sign1
   229     else if stamps1 subset stamps2 then sign2
   230     else (*neither is union already; must form union*)
   231       let val tsig = Type.merge (tsig1, tsig2);
   232       in
   233         Sg {tsig = tsig, const_tab = merge_tabs (ctab1, ctab2),
   234           stamps = merge_stamps (stamps1, stamps2),
   235           syn = Syntax.merge (Type.logical_types tsig) syn1 syn2}
   236       end;
   237 
   238 
   239 
   240 (**** CERTIFIED TYPES ****)
   241 
   242 
   243 (*Certified typs under a signature*)
   244 datatype ctyp = Ctyp of {sign: sg,  T: typ};
   245 
   246 fun rep_ctyp(Ctyp ctyp) = ctyp;
   247 
   248 fun typ_of (Ctyp{sign,T}) = T;
   249 
   250 fun ctyp_of (sign as Sg{tsig,...}) T =
   251         case Type.type_errors tsig (T,[]) of
   252           [] => Ctyp{sign= sign,T= T}
   253         | errs =>  error (cat_lines ("Error in type:" :: errs));
   254 
   255 (*The only use is a horrible hack in the simplifier!*)
   256 fun read_typ(Sg{tsig,syn,...}, defS) s =
   257     let val term = Syntax.read syn Syntax.typeT s;
   258         val S0 = Type.defaultS tsig;
   259         fun defS0 s = case defS s of Some S => S | None => S0;
   260     in Syntax.typ_of_term defS0 term end;
   261 
   262 fun read_ctyp sign = ctyp_of sign o read_typ(sign, K None);
   263 
   264 fun string_of_ctyp (Ctyp{sign,T}) = string_of_typ sign T;
   265 
   266 fun pprint_ctyp (Ctyp{sign,T}) = pprint_typ sign T;
   267 
   268 
   269 (**** CERTIFIED TERMS ****)
   270 
   271 (*Certified terms under a signature, with checked typ and maxidx of Vars*)
   272 datatype cterm = Cterm of {sign: sg,  t: term,  T: typ,  maxidx: int};
   273 
   274 fun rep_cterm (Cterm args) = args;
   275 
   276 (*Return the underlying term*)
   277 fun term_of (Cterm{sign,t,T,maxidx}) = t;
   278 
   279 (** pretty printing of terms **)
   280 
   281 fun pretty_term (Sg{tsig,syn,...}) = Syntax.pretty_term syn;
   282 
   283 fun string_of_term sign t = Pretty.string_of (pretty_term sign t);
   284 
   285 fun pprint_term sign = Pretty.pprint o Pretty.quote o (pretty_term sign);
   286 
   287 fun string_of_cterm (Cterm{sign,t,...}) = string_of_term sign t;
   288 
   289 fun pprint_cterm (Cterm{sign,t,...}) = pprint_term sign t;
   290 
   291 (*Create a cterm by checking a "raw" term with respect to a signature*)
   292 fun cterm_of sign t =
   293   case  term_errors sign (t,[])  of
   294       [] => Cterm{sign=sign, t=t, T= type_of t, maxidx= maxidx_of_term t}
   295     | errs => raise TERM(cat_lines("Term not in signature"::errs), [t]);
   296 
   297 fun cfun f = fn Cterm{sign,t,...} => cterm_of sign (f t);
   298 
   299 (*Lexing, parsing, polymorphic typechecking of a term.*)
   300 fun read_def_cterm (sign as Sg{tsig, const_tab, syn,...}, types, sorts)
   301                    (a,T) =
   302   let val showtyp = string_of_typ sign
   303       and showterm = string_of_term sign
   304       fun termerr [] = ""
   305         | termerr [t] = "\nInvolving this term:\n" ^ showterm t ^ "\n"
   306         | termerr ts = "\nInvolving these terms:\n" ^
   307                        cat_lines (map showterm ts)
   308       val t = Syntax.read syn T a;
   309       val (t',tye) = Type.infer_types (tsig, const_tab, types,
   310                                        sorts, showtyp, T, t)
   311                   handle TYPE (msg, Ts, ts) =>
   312           error ("Type checking error: " ^ msg ^ "\n" ^
   313                   cat_lines (map showtyp Ts) ^ termerr ts)
   314   in (cterm_of sign t', tye)
   315   end
   316   handle TERM (msg, _) => error ("Error: " ^  msg);
   317 
   318 
   319 fun read_cterm sign = #1 o (read_def_cterm (sign, K None, K None));
   320 
   321 (** reading of instantiations **)
   322 
   323 fun indexname cs = case Syntax.scan_varname cs of (v,[]) => v
   324         | _ => error("Lexical error in variable name " ^ quote (implode cs));
   325 
   326 fun absent ixn =
   327   error("No such variable in term: " ^ Syntax.string_of_vname ixn);
   328 
   329 fun inst_failure ixn =
   330   error("Instantiation of " ^ Syntax.string_of_vname ixn ^ " fails");
   331 
   332 fun read_insts (sign as Sg{tsig,...}) (rtypes,rsorts) (types,sorts) insts =
   333 let fun split([],tvs,vs) = (tvs,vs)
   334       | split((sv,st)::l,tvs,vs) = (case explode sv of
   335                   "'"::cs => split(l,(indexname cs,st)::tvs,vs)
   336                 | cs => split(l,tvs,(indexname cs,st)::vs));
   337     val (tvs,vs) = split(insts,[],[]);
   338     fun readT((a,i),st) =
   339         let val ixn = ("'" ^ a,i);
   340             val S = case rsorts ixn of Some S => S | None => absent ixn;
   341             val T = read_typ (sign,sorts) st;
   342         in if Type.typ_instance(tsig,T,TVar(ixn,S)) then (ixn,T)
   343            else inst_failure ixn
   344         end
   345     val tye = map readT tvs;
   346     fun add_cterm ((cts,tye), (ixn,st)) =
   347         let val T = case rtypes ixn of
   348                       Some T => typ_subst_TVars tye T
   349                     | None => absent ixn;
   350             val (ct,tye2) = read_def_cterm (sign,types,sorts) (st,T);
   351             val cv = cterm_of sign (Var(ixn,typ_subst_TVars tye2 T))
   352         in ((cv,ct)::cts,tye2 @ tye) end
   353     val (cterms,tye') = foldl add_cterm (([],tye), vs);
   354 in (map (fn (ixn,T) => (ixn,ctyp_of sign T)) tye', cterms) end;
   355 
   356 end;
   357