1 /* -*- mode: hugs-c; -*- */
2 /* --------------------------------------------------------------------------
3 * subst.c: Copyright (c) Mark P Jones 1991-1998. All rights reserved.
4 * See NOTICE for details and conditions of use etc...
5 * Hugs version 1.3c, March 1998
7 * Provides an implementation for the `current substitution' used during
8 * type and kind inference in both static analysis and type checking.
9 * ------------------------------------------------------------------------*/
18 /*#define DEBUG_TYPES*/
20 static Int numTyvars; /* no. type vars currently in use */
21 static Int maxTyvars = 0;
22 static Int nextGeneric; /* number of generics found so far */
25 Tyvar tyvars[NUM_TYVARS]; /* storage for type variables */
27 Tyvar *tyvars = 0; /* storage for type variables */
29 Int typeOff; /* offset of result type */
30 Type typeIs; /* skeleton of result type */
31 Int typeFree; /* freedom in instantiated type */
32 List predsAre; /* list of predicates in type */
33 List genericVars; /* list of generic vars */
34 List btyvars = NIL; /* explicitly scoped type vars */
36 /* --------------------------------------------------------------------------
37 * local function prototypes:
38 * ------------------------------------------------------------------------*/
40 static Void local expandSubst Args((Int));
41 static Int local findBtyvsInt Args((Text));
42 static Type local makeTupleType Args((Int));
43 static Kind local makeSimpleKind Args((Int));
44 static Kind local makeVarKind Args((Int));
45 static Void local expandSyn1 Args((Tycon, Type *, Int *));
46 static Type local dropRank1Body Args((Type,Int,Int));
47 static Type local liftRank1Body Args((Type,Int));
49 static Bool local varToVarBind Args((Tyvar *,Tyvar *));
50 static Bool local varToTypeBind Args((Tyvar *,Type,Int));
52 static Bool local inserter Args((Type,Int,Type,Int));
53 static Int local remover Args((Text,Type,Int));
55 static Bool local kvarToVarBind Args((Tyvar *,Tyvar *));
56 static Bool local kvarToTypeBind Args((Tyvar *,Type,Int));
58 /* --------------------------------------------------------------------------
59 * The substitution, types, and kinds:
61 * In early versions of Gofer, the `substitution' data structure was only
62 * used by the type checker, so it made sense to include support for it in
63 * type.c. This changed when kinds and kind inference where introduced,
64 * which required access to the substitution during static analysis. The
65 * links between type.c and static.c that were intially used to accomplish
66 * this have now been avoided by making the substitution visible as an
67 * independent data structure in storage.c.
69 * In the same way that values have types, type constructors (and more
70 * generally, expressions built from such constructors) have kinds.
71 * The syntax of kinds in the current implementation is very simple:
73 * kind ::= STAR -- the kind of types
74 * | kind => kind -- constructors
75 * | variables -- either INTCELL or OFFSET
77 * For various reasons, this implementation uses structure sharing, instead
78 * of a copying approach. In principal, this is fast and avoids the need to
79 * build new type expressions. Unfortunately, this implementation will not
80 * be able to handle *very* large expressions.
82 * The substitution is represented by an array of type variables each of
84 * bound a (skeletal) type expression, or NIL if the variable
85 * is not bound, or SKOLEM for a Skolem constant (i.e., an
86 * uninstantiable variable).
87 * offs offset of skeleton in bound. If isNull(bound), then offs is
88 * used to indicate whether that variable is generic (i.e. free
89 * in the current assumption set) or fixed (i.e. bound in the
90 * current assumption set). Generic variables are assigned
91 * offset numbers whilst copying type expressions (t,o) to
92 * obtain their most general form.
93 * kind kind of value bound to type variable (`type variable' is
94 * rather inaccurate -- `constructor variable' would be better).
95 * ------------------------------------------------------------------------*/
97 Void emptySubstitution() { /* clear current substitution */
100 if (maxTyvars!=NUM_TYVARS) {
115 static Void local expandSubst(n) /* add further n type variables to */
116 Int n; { /* current substituion */
118 if (numTyvars+n>NUM_TYVARS) {
119 ERRMSG(0) "Too many type variables in type checker"
123 if (numTyvars+n>maxTyvars) { /* need to expand substitution */
124 Int newMax = maxTyvars+NUM_TYVARS;
128 if (numTyvars+n>newMax) { /* safety precaution */
129 ERRMSG(0) "Substitution expanding too quickly"
133 /* It would be better to realloc() here, but that isn't portable
134 * enough for calloc()ed arrays. The following code could cause
135 * a space leak if an interrupt occurs while we're copying the
136 * array ... we won't worry about this for the time being because
137 * we don't expect to have to go through this process much (if at
138 * all) in normal use of the type checker.
141 newTvs = (Tyvar *)calloc(newMax,sizeof(Tyvar));
143 ERRMSG(0) "Too many variables (%d) in type checker", newMax
146 for (i=0; i<numTyvars;++i) { /* copy substitution */
147 newTvs[i].offs = tyvars[i].offs;
148 newTvs[i].bound = tyvars[i].bound;
149 newTvs[i].kind = tyvars[i].kind;
151 maxTyvars = 0; /* protection from SIGINT? */
152 if (tyvars) free(tyvars);
159 Int newTyvars(n) /* allocate new type variables */
160 Int n; { /* all of kind STAR */
161 Int beta = numTyvars;
164 for (numTyvars+=n; n>0; n--) {
165 tyvars[numTyvars-n].offs = UNUSED_GENERIC;
166 tyvars[numTyvars-n].bound = NIL;
167 tyvars[numTyvars-n].kind = STAR;
169 printf("new type variable: _%d ::: ",numTyvars-n);
170 printKind(stdout,tyvars[numTyvars-n].kind);
177 Int newKindedVars(k) /* allocate new variables with */
178 Kind k; { /* specified kinds */
179 Int beta = numTyvars; /* if k = k0 -> k1 -> ... -> kn */
180 for (; isPair(k); k=snd(k)) { /* then allocate n vars with kinds */
181 expandSubst(1); /* k0, k1, ..., k(n-1) */
182 tyvars[numTyvars].offs = UNUSED_GENERIC;
183 tyvars[numTyvars].bound = NIL;
184 tyvars[numTyvars].kind = fst(k);
186 printf("new type variable: _%d ::: ",numTyvars);
187 printKind(stdout,tyvars[numTyvars].kind);
195 Void instantiate(type) /* instantiate type, if nonNull */
201 if (nonNull(typeIs)) { /* instantiate type expression ? */
203 if (isPolyType(typeIs)) { /* Polymorphic type scheme ? */
204 Kinds ks = polySigOf(typeIs);
205 typeOff = newKindedVars(ks);
206 typeIs = monotypeOf(typeIs);
207 for (; isAp(ks); ks=arg(ks))
211 if (whatIs(typeIs)==QUAL) { /* Qualified type? */
212 predsAre = fst(snd(typeIs));
213 typeIs = snd(snd(typeIs));
218 /* --------------------------------------------------------------------------
219 * Bound type variables:
220 * ------------------------------------------------------------------------*/
222 Pair findBtyvs(t) /* Look for bound tyvar */
225 for (; nonNull(bts); bts=tl(bts)) {
227 for (; nonNull(bts1); bts1=tl(bts1))
228 if (t==textOf(fst(hd(bts1))))
234 static Int local findBtyvsInt(t) /* Look for bound type variable */
235 Text t; { /* expecting to find an integer */
236 Pair p = findBtyvs(t);
238 internal("findBtyvsInt");
239 return intOf(snd(p));
242 Void markBtyvs() { /* Mark explicitly scoped vars */
244 for (; nonNull(bts); bts=tl(bts)) {
246 for (; nonNull(bts1); bts1=tl(bts1))
247 markTyvar(intOf(snd(hd(bts1))));
251 Type localizeBtyvs(t) /* Localize type to eliminate refs */
252 Type t; { /* to explicitly scoped vars */
255 case POLYTYPE : snd(snd(t)) = localizeBtyvs(snd(snd(t)));
258 case QUAL : fst(snd(t)) = localizeBtyvs(fst(snd(t)));
259 snd(snd(t)) = localizeBtyvs(snd(snd(t)));
262 case AP : fst(t) = localizeBtyvs(fst(t));
263 snd(t) = localizeBtyvs(snd(t));
267 case VAROPCELL: return mkInt(findBtyvsInt(textOf(t)));
272 /* --------------------------------------------------------------------------
273 * Dereference or bind types in subsitution:
274 * ------------------------------------------------------------------------*/
276 Tyvar *getTypeVar(t,o) /* get number of type variable */
277 Type t; /* represented by (t,o) [if any]. */
280 case INTCELL : return tyvar(intOf(t));
281 case OFFSET : return tyvar(o+offsetOf(t));
283 case VAROPCELL : return tyvar(findBtyvsInt(textOf(t)));
288 Void tyvarType(vn) /* load type held in type variable */
289 Int vn; { /* vn into (typeIs,typeOff) */
292 while ((tyv=tyvar(vn)), isBound(tyv))
293 switch(whatIs(tyv->bound)) {
294 case INTCELL : vn = intOf(tyv->bound);
297 case OFFSET : vn = offsetOf(tyv->bound)+(tyv->offs);
301 case VAROPCELL : vn = findBtyvsInt(textOf(tyv->bound));
304 default : typeIs = tyv->bound;
312 Void bindTv(vn,t,o) /* set type variable vn to (t,o) */
316 Tyvar *tyv = tyvar(vn);
320 printf("binding type variable: _%d to ",vn);
321 printType(stdout,debugType(t,o));
326 Cell getDerefHead(t,o) /* get value at head of type exp. */
336 if ((tyv=getTypeVar(t,o)) && isBound(tyv)) {
346 /* --------------------------------------------------------------------------
347 * Expand type synonyms:
348 * ------------------------------------------------------------------------*/
350 Void expandSyn(h,ar,at,ao) /* Expand type synonym with: */
351 Tycon h; /* head h */
352 Int ar; /* ar args (NB. ar>=tycon(h).arity)*/
353 Type *at; /* original expression (*at,*ao) */
354 Int *ao; { /* expansion returned in (*at,*ao) */
355 ar -= tycon(h).arity; /* calculate surplus arguments */
358 else { /* if there are more args than the */
359 Type t = *at; /* arity, we have to do a little */
360 Int o = *ao; /* bit of work to isolate args that*/
361 Type args = NIL; /* will not be changed by expansion*/
363 while (ar-- > 0) { /* find part to expand, and the */
364 Tyvar *tyv; /* unused arguments */
365 args = cons(arg(t),args);
369 expandSyn1(h,&t,&o); /* do the expansion */
370 bindTv((i=newTyvars(1)),t,o); /* and embed the results back in */
371 tyvar(i)->kind = getKind(t,o); /* (*at, *ao) as required */
372 *at = applyToArgs(mkInt(i),args);
376 static Void local expandSyn1(h,at,ao) /* Expand type synonym with: */
377 Tycon h; /* head h, tycon(h).arity args, */
378 Type *at; /* original expression (*at,*ao) */
379 Int *ao; { /* expansion returned in (*at,*ao) */
380 Int n = tycon(h).arity;
386 *ao = newKindedVars(tycon(h).kind);
387 for (; 0<n--; t=fun(t)) {
390 internal("expandSyn1");
391 bindTv(*ao+n,arg(t),o);
395 /* --------------------------------------------------------------------------
396 * Marking fixed variables in type expressions:
397 * ------------------------------------------------------------------------*/
399 Void clearMarks() { /* set all unbound type vars to */
400 Int i; /* unused generic variables */
401 for (i=0; i<numTyvars; ++i)
402 if (!isBound(tyvar(i)))
403 tyvar(i)->offs = UNUSED_GENERIC;
408 Void resetGenerics() { /* Reset all generic vars to unused*/
410 for (i=0; i<numTyvars; ++i)
411 if (!isBound(tyvar(i)) && tyvar(i)->offs>=GENERIC)
412 tyvar(i)->offs = UNUSED_GENERIC;
417 Void markTyvar(vn) /* mark fixed vars in type bound to*/
418 Int vn; { /* given type variable */
419 Tyvar *tyv = tyvar(vn);
422 markType(tyv->bound, tyv->offs);
424 (tyv->offs) = FIXED_TYVAR;
427 Void markType(t,o) /* mark fixed vars in type (t,o) */
437 case AP : markType(fst(t),o);
441 case OFFSET : markTyvar(o+offsetOf(t));
444 case INTCELL : markTyvar(intOf(t));
448 case VAROPCELL : markTyvar(findBtyvsInt(textOf(t)));
451 case RANK2 : markType(snd(snd(t)),o);
453 case POLYTYPE : /* No need to mark generic types */
456 default : internal("markType");
460 Void markPred(pi) /* Marked fixed type vars in pi */
463 Int o = intOf(snd3(pi));
465 for (; isAp(cl); cl=fun(cl))
469 /* --------------------------------------------------------------------------
470 * Copy type expression from substitution to make a single type expression:
471 * ------------------------------------------------------------------------*/
473 Type copyTyvar(vn) /* calculate most general form of */
474 Int vn; { /* type bound to given type var */
475 Tyvar *tyv = tyvar(vn);
478 return copyType(tyv->bound,tyv->offs);
481 case FIXED_TYVAR : return mkInt(vn);
483 case UNUSED_GENERIC : (tyv->offs) = GENERIC + nextGeneric++;
484 if (nextGeneric>=NUM_OFFSETS) {
486 "Too many quantified type variables"
489 genericVars = cons(mkInt(vn),genericVars);
491 default : return mkOffset(tyv->offs - GENERIC);
495 Type copyType(t,o) /* calculate most general form of */
496 Type t; /* type expression (t,o) */
499 case AP : { Type l = copyType(fst(t),o);/* ensure correct */
500 Type r = copyType(snd(t),o);/* eval. order */
503 case OFFSET : return copyTyvar(o+offsetOf(t));
504 case INTCELL : return copyTyvar(intOf(t));
506 case VAROPCELL : return copyTyvar(findBtyvsInt(textOf(t)));
512 Cell copyPred(pi,o) /* Copy single predicate (or part */
513 Cell pi; /* thereof) ... */
516 Cell temp = copyPred(fun(pi),o);/* to ensure correct order of eval.*/
517 return ap(temp,copyType(arg(pi),o));
524 Type debugTyvar(vn) /* expand type structure in full */
525 Int vn; { /* detail */
526 Tyvar *tyv = tyvar(vn);
529 return debugType(tyv->bound,tyv->offs);
537 case AP : { Type l = debugType(fst(t),o);
538 Type r = debugType(snd(t),o);
541 case OFFSET : return debugTyvar(o+offsetOf(t));
542 case INTCELL : return debugTyvar(intOf(t));
544 case VAROPCELL : return debugTyvar(findBtyvsInt(textOf(t)));
549 #endif /*DEBUG_TYPES*/
551 Kind copyKindvar(vn) /* build kind attatched to variable*/
553 Tyvar *tyv = tyvar(vn);
555 return copyKind(tyv->bound,tyv->offs);
556 return STAR; /* any unbound variable defaults to*/
557 } /* the kind of all types */
559 Kind copyKind(k,o) /* build kind expression from */
560 Kind k; /* given skeleton */
563 case AP : { Kind l = copyKind(fst(k),o); /* ensure correct */
564 Kind r = copyKind(snd(k),o); /* eval. order */
567 case OFFSET : return copyKindvar(o+offsetOf(k));
568 case INTCELL : return copyKindvar(intOf(k));
573 /* --------------------------------------------------------------------------
574 * Droping and lifting of type schemes that appear in rank 2 position:
575 * ------------------------------------------------------------------------*/
577 Type dropRank2(t,alpha,n) /* Drop a (potentially) rank2 type */
581 if (whatIs(t)==RANK2) {
582 Cell r = fst(snd(t));
585 for (t=snd(snd(t)); i>0; i--) {
586 Type a = arg(fun(t));
588 a = dropRank1(a,alpha,n);
589 as = ap2(typeArrow,a,as);
592 t = ap(RANK2,pair(r,revOnto(as,t)));
597 Type dropRank1(t,alpha,n) /* Copy rank1 argument type t to */
598 Type t; /* make a rank1 type scheme */
601 if (n>0 && isPolyType(t))
602 t = mkPolyType(polySigOf(t),dropRank1Body(monotypeOf(t),alpha,n));
606 static Type local dropRank1Body(t,alpha,n)
611 case OFFSET : { Int m = offsetOf(t);
612 return (m>=n) ? mkOffset(m-n) : mkInt(alpha+m);
615 case POLYTYPE : return mkPolyType(polySigOf(t),
616 dropRank1Body(monotypeOf(t),alpha,n));
618 case QUAL : return ap(QUAL,dropRank1Body(snd(t),alpha,n));
620 case RANK2 : return ap(RANK2,pair(fst(snd(t)),
621 dropRank1Body(snd(snd(t)),
625 case AP : return ap(dropRank1Body(fun(t),alpha,n),
626 dropRank1Body(arg(t),alpha,n));
632 Void liftRank2Args(as,alpha,m)
639 for (m=nextGeneric; nonNull(as); as=tl(as)) {
640 Type ta = arg(fun(as));
641 ta = isPolyType(ta) ? liftRank1Body(ta,m) : copyType(ta,alpha);
647 Type liftRank2(t,alpha,m)
651 if (whatIs(t)==RANK2) {
652 Cell r = fst(snd(t));
659 for (i=intOf(r); i>0; i--) {
660 Type a = arg(fun(t));
661 a = isPolyType(a) ? liftRank1Body(a,m) : copyType(a,alpha);
662 as = ap2(typeArrow,a,as);
665 t = ap(RANK2,pair(r,revOnto(as,copyType(t,alpha))));
668 t = copyType(t,alpha);
672 Type liftRank1(t,alpha,m)
676 if (m>0 && isPolyType(t)) {
681 t = liftRank1Body(t,nextGeneric);
686 static Type local liftRank1Body(t,n)
690 case OFFSET : return mkOffset(n+offsetOf(t));
692 case INTCELL : return copyTyvar(intOf(t));
695 case VAROPCELL : return copyTyvar(findBtyvsInt(textOf(t)));
697 case POLYTYPE : return mkPolyType(polySigOf(t),
698 liftRank1Body(monotypeOf(t),n));
700 case QUAL : return ap(QUAL,liftRank1Body(snd(t),n));
702 case RANK2 : return ap(RANK2,pair(fst(snd(t)),
703 liftRank1Body(snd(snd(t)),n)));
705 case AP : return ap(liftRank1Body(fun(t),n),
706 liftRank1Body(arg(t),n));
712 /* --------------------------------------------------------------------------
713 * Support for `kind preserving substitutions' from unification:
714 * ------------------------------------------------------------------------*/
716 Bool eqKind(k1,k2) /* check that two (mono)kinds are */
717 Kind k1, k2; { /* equal */
719 || (isPair(k1) && isPair(k2)
720 && eqKind(fst(k1),fst(k2))
721 && eqKind(snd(k1),snd(k2)));
724 Kind getKind(c,o) /* Find kind of constr during type */
725 Cell c; /* checking process */
727 if (isAp(c)) /* application */
728 return snd(getKind(fst(c),o));
730 case TUPLE : return simpleKind(tupleOf(c)); /*(,)::* -> * -> * */
731 case OFFSET : return tyvar(o+offsetOf(c))->kind;
732 case INTCELL : return tyvar(intOf(c))->kind;
734 case VAROPCELL : return tyvar(findBtyvsInt(textOf(c)))->kind;
735 case TYCON : return tycon(c).kind;
737 case EXT : return extKind;
741 printf("getKind c = %d, whatIs=%d\n",c,whatIs(c));
744 return STAR;/* not reached */
747 /* --------------------------------------------------------------------------
748 * Find generic variables in a type:
749 * ------------------------------------------------------------------------*/
751 Type genvarTyvar(vn,vs) /* calculate list of generic vars */
752 Int vn; /* thru variable vn, prepended to */
753 List vs; { /* list vs */
754 Tyvar *tyv = tyvar(vn);
757 return genvarType(tyv->bound,tyv->offs,vs);
758 else if (tyv->offs == UNUSED_GENERIC) {
759 tyv->offs += GENERIC + nextGeneric++;
760 return cons(mkInt(vn),vs);
762 else if (tyv->offs>=GENERIC && !intIsMember(vn,vs))
763 return cons(mkInt(vn),vs);
768 List genvarType(t,o,vs) /* calculate list of generic vars */
769 Type t; /* in type expression (t,o) */
770 Int o; /* results are prepended to vs */
773 case AP : return genvarType(snd(t),o,genvarType(fst(t),o,vs));
774 case OFFSET : return genvarTyvar(o+offsetOf(t),vs);
775 case INTCELL : return genvarTyvar(intOf(t),vs);
777 case VAROPCELL : return genvarTyvar(findBtyvsInt(textOf(t)),vs);
782 /* --------------------------------------------------------------------------
784 * ------------------------------------------------------------------------*/
786 Bool doesntOccurIn(lookFor,t,o) /* Return TRUE if var lookFor */
787 Tyvar *lookFor; /* isn't referenced in (t,o) */
794 if (tyv) /* type variable */
796 else if (isAp(t)) { /* application */
797 if (doesntOccurIn(lookFor,snd(t),o))
802 else /* no variable found */
808 /* --------------------------------------------------------------------------
809 * Unification algorithm:
810 * ------------------------------------------------------------------------*/
812 char *unifyFails = 0; /* Unification error message */
813 static Int bindAbove = 0; /* Used to restrict var binding */
815 #define bindOnlyAbove(beta) bindAbove=beta
816 #define noBind() bindAbove=MAXPOSINT
817 #define unrestrictBind() bindAbove=0
819 static Bool local varToVarBind(tyv1,tyv2)/* Make binding tyv1 := tyv2 */
820 Tyvar *tyv1, *tyv2; {
821 if (tyv1!=tyv2) { /* If vars are same, nothing to do!*/
823 /* Check that either tyv1 or tyv2 is in allowed range for binding */
824 /* and is not a Skolem constant, and swap vars if nec. so we can */
827 if (tyvNum(tyv1)<bindAbove || tyv1->bound==SKOLEM) {
828 if (tyvNum(tyv2)<bindAbove || tyv2->bound==SKOLEM) {
829 unifyFails = "types do not match";
838 if (!eqKind(tyv1->kind,tyv2->kind)) {
839 unifyFails = "constructor variable kinds do not match";
843 tyv1->offs = tyvNum(tyv2);
845 printf("vv binding tyvar: _%d to _%d\n",tyvNum(tyv1),tyvNum(tyv2));
851 static Bool local varToTypeBind(tyv,t,o)/* Make binding tyv := (t,o) */
853 Type t; /* guaranteed not to be a v'ble or */
854 Int o; { /* have synonym as outermost constr*/
855 if (tyvNum(tyv)<bindAbove) { /* Check that tyv is in range */
856 unifyFails = "types do not match";
859 else if (tyv->bound == SKOLEM) { /* Check that it is not Skolemized */
860 unifyFails = "cannot instantiate Skolem constant";
863 else if (!doesntOccurIn(tyv,t,o)) /* Carry out occurs check */
864 unifyFails = "unification would give infinite type";
865 else if (!eqKind(tyv->kind,getKind(t,o)))
866 unifyFails = "kinds do not match";
871 printf("vt binding type variable: _%d to ",tyvNum(tyv));
872 printType(stdout,debugType(t,o));
880 Bool unify(t1,o1,t2,o2) /* Main unification routine */
881 Type t1,t2; /* unify (t1,o1) with (t2,o2) */
890 return varToVarBind(tyv1,tyv2); /* t1, t2 variables */
892 Cell h2 = getDerefHead(t2,o2); /* t1 variable, t2 not */
893 if (isSynonym(h2) && argCount>=tycon(h2).arity) {
894 expandSyn(h2,argCount,&t2,&o2);
898 return varToTypeBind(tyv1,t2,o2);
902 Cell h1 = getDerefHead(t1,o1); /* t2 variable, t1 not */
903 if (isSynonym(h1) && argCount>=tycon(h1).arity) {
904 expandSyn(h1,argCount,&t1,&o1);
908 return varToTypeBind(tyv2,t1,o1);
910 else { /* t1, t2 not vars */
911 Type h1 = getDerefHead(t1,o1);
913 Type h2 = getDerefHead(t2,o2);
917 printf("tt unifying types: ");
918 printType(stdout,debugType(t1,o1));
920 printType(stdout,debugType(t2,o2));
924 if (isOffset(h1) || isInt(h1)) h1=NIL; /* represent var by NIL*/
925 if (isOffset(h2) || isInt(h2)) h2=NIL;
928 if (isExt(h1) || isExt(h2)) {
929 if (a1==2 && isExt(h1) && a2==2 && isExt(h2))
930 return inserter(fun(t1),o1,t2,o2) &&
931 unify(arg(t1),o1,aVar,
932 remover(extText(h1),t2,o2));
934 unifyFails = "rows are not compatible";
939 if (nonNull(h1) && h1==h2) {/* Assuming well-formed types, both*/
940 if (a1!=a2) { /* t1, t2 must have same no of args*/
941 unifyFails = "incompatible constructors";
945 if (!unify(arg(t1),o1,arg(t2),o2))
956 /* Types do not match -- look for type synonyms to expand */
958 if (isSynonym(h1) && a1>=tycon(h1).arity) {
959 expandSyn(h1,a1,&t1,&o1);
963 if (isSynonym(h2) && a2>=tycon(h2).arity) {
964 expandSyn(h2,a2,&t2,&o2);
969 if ((isNull(h1) && a1<=a2) || /* last attempt -- maybe */
970 (isNull(h2) && a2<=a1)) { /* one head is a variable? */
975 if (tyv1) /* unify heads! */
977 return varToVarBind(tyv1,tyv2);
979 return varToTypeBind(tyv1,t2,o2);
981 return varToTypeBind(tyv2,t1,o1);
983 /* at this point, neither t1 nor t2 is a variable. In */
984 /* addition, they must both be APs unless one of the */
985 /* head variables has been bound during unification of */
988 if (!isAp(t1) || !isAp(t2)) { /* might not be APs*/
992 if (!unify(arg(t1),o1,arg(t2),o2)) /* o/w must be APs */
1004 static Bool local inserter(ins,o,r,or) /* Insert field into row (r,or) */
1005 Type ins; /* inserter (ins,o), where ins is */
1006 Int o; /* an applic of an EXT to a type. */
1009 Text labt = extText(fun(ins)); /* Find the text of the label */
1014 Int beta = newTyvars(1); /* Extend row with new field */
1015 tyvar(beta)->kind = ROW;
1016 return varToTypeBind(tyv,ap(ins,mkInt(beta)),o);
1018 else if (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r)))) {
1019 if (labt==extText(fun(fun(r))))/* Compare existing fields */
1020 return unify(arg(ins),o,extField(r),or);
1021 r = extRow(r); /* Or skip to next field */
1023 else { /* Nothing else will match */
1024 unifyFails = "field mismatch";
1030 static Int local remover(l,r,o) /* Make a new row by copying (r,o) */
1031 Text l; /* but removing the l field (which */
1032 Type r; /* MUST exist) */
1035 Int beta = newTyvars(1);
1036 tyvar(beta)->kind = ROW;
1038 if (tyv || !isAp(r) || !isAp(fun(r)) || !isExt(fun(fun(r))))
1039 internal("remover");
1040 if (l==extText(fun(fun(r))))
1043 r = ap(fun(r),mkInt(remover(l,extRow(r),o)));
1049 Bool typeMatches(type,mt) /* test if type matches monotype mt*/
1052 if (isPolyType(type) || whatIs(type)==QUAL)
1054 emptySubstitution();
1056 result = unify(mt,0,type,0);
1058 emptySubstitution();
1062 /* --------------------------------------------------------------------------
1063 * Matching predicates:
1065 * There are (at least) four situations where we need to match up pairs
1068 * 1) Testing to see if two predicates are the same (ignoring differences
1069 * caused by the use of type synonyms, for example).
1071 * 2) Matching a predicate with the head of its class so that we can
1072 * find the corresponding superclass predicates. If the predicates
1073 * have already been kind-checked, and the classes are known to be
1074 * the same, then this should never fail.
1076 * 3) Matching a predicate against the head of an instance to see if
1077 * that instance is applicable.
1079 * 4) Matching two instance heads to see if there is an overlap.
1081 * For (1), we need a matching process that does not bind any variables.
1082 * For (2) and (3), we need to use one-way matching, only allowing
1083 * variables in the class or instance head to be instantiated. For
1084 * (4), we need two-way unification.
1086 * Another situation in which both one-way and two-way unification might
1087 * be used is in an implementation of improvement. Here, a one-way match
1088 * would be used to determine applicability of a rule for improvement
1089 * that would then be followed by unification with another predicate.
1090 * One possible syntax for this might be:
1092 * instance P => pi [improves pi'] where ...
1094 * The intention here is that any predicate matching pi' can be unified
1095 * with pi to get more accurate types. A simple example of this is:
1097 * instance Collection [a] a improves Collection [a] b where ...
1099 * As soon as we know what the collection type is (in this case, a list),
1100 * we will also know what the element type is. To ensure that the rule
1101 * for improvement is valid, the compilation system will also need to use
1102 * a one-way matching process to ensure that pi is a (substitution) instance
1103 * of pi'. Another extension would be to allow more than one predicate pi'
1104 * in an improving rule. Read the paper on simplification and improvement
1105 * for technical background. Watch this space for implementation news!
1106 * ------------------------------------------------------------------------*/
1108 Bool samePred(pi1,o1,pi,o) /* Test to see if predicates are */
1109 Cell pi1; /* the same, with no binding of */
1110 Int o1; /* the variables in either one. */
1111 Cell pi; /* Assumes preds are kind correct */
1112 Int o; { /* with the same class. */
1115 result = unifyPred(pi1,o1,pi,o);
1120 Bool matchPred(pi1,o1,pi,o) /* One way match predicate (pi1,o1)*/
1121 Cell pi1; /* against (pi,o), allowing only */
1122 Int o1; /* vars in 2nd pred to be bound. */
1123 Cell pi; /* Assumes preds are kind correct */
1124 Int o; { /* with the same class and that no */
1125 Bool result; /* vars have been alloc'd since o. */
1127 result = unifyPred(pi1,o1,pi,o);
1132 Bool unifyPred(pi1,o1,pi,o) /* Unify two predicates */
1133 Cell pi1; /* Assumes preds are kind correct */
1134 Int o1; /* with the same class. */
1137 for (; isAp(pi1); pi1=fun(pi1), pi=fun(pi))
1138 if (!unify(arg(pi1),o1,arg(pi),o))
1143 Inst findInstFor(pi,o) /* Find matching instance for pred */
1144 Cell pi; /* (pi,o), or otherwise NIL. If a */
1145 Int o; { /* match is found, then tyvars from*/
1146 Class c = getHead(pi); /* typeOff have been initialized to*/
1147 List ins; /* allow direct use of specifics. */
1152 for (ins=cclass(c).instances; nonNull(ins); ins=tl(ins)) {
1154 Int beta = newKindedVars(inst(in).kinds);
1155 if (matchPred(pi,o,inst(in).head,beta)) {
1165 { Int showRow = strcmp(textToStr(cclass(c).text),"ShowRecRow");
1166 Int eqRow = strcmp(textToStr(cclass(c).text),"EqRecRow");
1168 if (showRow==0 || eqRow==0) { /* Generate instances of */
1169 Type t = arg(pi); /* ShowRecRow and EqRecRow */
1170 Tyvar *tyv; /* on the fly */
1176 for (ins=cclass(c).instances; nonNull(ins); ins=tl(ins))
1177 if (getHead(arg(inst(hd(ins)).head))==e) {
1182 in = (showRow==0) ? addRecShowInst(c,e)
1183 : addRecEqInst(c,e);
1184 typeOff = newKindedVars(extKind);
1185 bindTv(typeOff,arg(fun(t)),o);
1186 bindTv(typeOff+1,arg(t),o);
1196 /* --------------------------------------------------------------------------
1197 * Compare type schemes:
1198 * ------------------------------------------------------------------------*/
1200 Bool sameSchemes(s,s1) /* Test to see whether two type */
1201 Type s; /* schemes are the same */
1206 Bool b = isPolyType(s); /* Check quantifiers are the same */
1207 Bool b1 = isPolyType(s1);
1209 if (b && b1 && eqKind(polySigOf(s),polySigOf(s1))) {
1210 Kind k = polySigOf(s);
1212 s1 = monotypeOf(s1);
1213 o = newKindedVars(k);
1214 for (; isAp(k); k=arg(k))
1221 b = (whatIs(s)==QUAL); /* Check that contexts are the same*/
1222 b1 = (whatIs(s1)==QUAL);
1225 List ps = fst(snd(s));
1226 List ps1 = fst(snd(s1));
1228 while (nonNull(ps) && nonNull(ps1)) {
1231 if (getHead(pi)!=getHead(pi1)
1232 || !unifyPred(pi,o,pi1,o))
1238 if (nonNull(ps) || nonNull(ps1))
1247 b = (whatIs(s)==RANK2); /* Check any rank 2 annotations */
1248 b1 = (whatIs(s1)==RANK2);
1250 if (b && b1 && intOf(fst(snd(s)))==intOf(fst(snd(s1)))) {
1251 nr2 = intOf(fst(snd(s)));
1259 for (; nr2>0; nr2--) { /* Deal with rank 2 arguments */
1260 Type t = arg(fun(s));
1261 Type t1 = arg(fun(s1));
1263 b1 = isPolyType(t1);
1266 t = dropRank1(t,o,m);
1267 t1 = dropRank1(t1,o,m);
1268 if (!sameSchemes(t,t1))
1276 b = unify(t,o,t1,o);
1285 noBind(); /* Ensure body types are the same */
1286 b = unify(s,o,s1,o);
1291 /* --------------------------------------------------------------------------
1292 * Unify kind expressions:
1293 * ------------------------------------------------------------------------*/
1295 static Bool local kvarToVarBind(tyv1,tyv2)/* Make binding tyv1 := tyv2 */
1296 Tyvar *tyv1, *tyv2; { /* for kind variable bindings */
1299 tyv1->offs = tyvNum(tyv2);
1301 printf("vv binding kvar: _%d to _%d\n",tyvNum(tyv1),tyvNum(tyv2));
1307 static Bool local kvarToTypeBind(tyv,t,o)/* Make binding tyv := (t,o) */
1308 Tyvar *tyv; /* for kind variable bindings */
1309 Type t; /* guaranteed not to be a v'ble or */
1310 Int o; { /* have synonym as outermost constr*/
1311 if (doesntOccurIn(tyv,t,o)) {
1315 printf("vt binding kind variable: _%d to ",tyvNum(tyv));
1316 printType(stdout,debugType(t,o));
1321 unifyFails = "unification would give infinite kind";
1325 Bool kunify(k1,o1,k2,o2) /* Unify kind expr (k1,o1) with */
1326 Kind k1,k2; /* (k2,o2) */
1335 return kvarToVarBind(kyv1,kyv2); /* k1, k2 variables */
1337 return kvarToTypeBind(kyv1,k2,o2); /* k1 variable, k2 not */
1340 return kvarToTypeBind(kyv2,k1,o1); /* k2 variable, k1 not */
1343 printf("unifying kinds: ");
1344 printType(stdout,debugType(k1,o1));
1346 printType(stdout,debugType(k2,o2));
1349 if (k1==STAR && k2==STAR) /* k1, k2 not vars */
1352 else if (k1==ROW && k2==ROW)
1355 else if (isAp(k1) && isAp(k2))
1356 return kunify(fst(k1),o1,fst(k2),o2) &&
1357 kunify(snd(k1),o1,snd(k2),o2);
1363 /* --------------------------------------------------------------------------
1364 * Tuple type constructors: are generated as necessary. The most common
1365 * n-tuple constructors (n<MAXTUPCON) are held in a cache to avoid
1366 * repeated generation of the constructor types.
1367 * ------------------------------------------------------------------------*/
1369 #define MAXTUPCON 10
1370 static Type tupleConTypes[MAXTUPCON];
1372 Void typeTuple(e) /* find type for tuple constr, using*/
1373 Cell e; { /* tupleConTypes to cache previously*/
1374 Int n = tupleOf(e); /* calculated tuple constr. types. */
1375 typeOff = newTyvars(n);
1377 typeIs = makeTupleType(n);
1378 else if (tupleConTypes[n])
1379 typeIs = tupleConTypes[n];
1381 typeIs = tupleConTypes[n] = makeTupleType(n);
1384 static Type local makeTupleType(n) /* construct type for tuple constr. */
1385 Int n; { /* t1 -> ... -> tn -> (t1,...,tn) */
1386 Type h = mkTuple(n);
1390 h = ap(h,mkOffset(i));
1392 h = fn(mkOffset(n),h);
1396 /* --------------------------------------------------------------------------
1397 * Two forms of kind expression are used quite frequently:
1398 * * -> * -> ... -> * -> * for kinds of ->, [], ->, (,) etc...
1399 * v1 -> v2 -> ... -> vn -> vn+1 skeletons for constructor kinds
1400 * Expressions of these forms are produced by the following functions which
1401 * use a cache to avoid repeated construction of commonly used values.
1402 * A similar approach is used to store the types of tuple constructors in the
1403 * main type checker.
1404 * ------------------------------------------------------------------------*/
1406 #define MAXKINDFUN 10
1407 static Kind simpleKindCache[MAXKINDFUN];
1408 static Kind varKindCache[MAXKINDFUN];
1410 static Kind local makeSimpleKind(n) /* construct * -> ... -> * (n args)*/
1418 Kind simpleKind(n) /* return (possibly cached) simple */
1419 Int n; { /* function kind */
1421 return makeSimpleKind(n);
1422 else if (nonNull(simpleKindCache[n]))
1423 return simpleKindCache[n];
1425 return simpleKindCache[0] = STAR;
1427 return simpleKindCache[n] = ap(STAR,simpleKind(n-1));
1430 static Kind local makeVarKind(n) /* construct v0 -> .. -> vn */
1432 Kind k = mkOffset(n);
1434 k = ap(mkOffset(n),k);
1438 Void varKind(n) /* return (possibly cached) var */
1439 Int n; { /* function kind */
1440 typeOff = newKindvars(n+1);
1442 typeIs = makeVarKind(n);
1443 else if (nonNull(varKindCache[n]))
1444 typeIs = varKindCache[n];
1446 typeIs = varKindCache[n] = makeVarKind(n);
1449 /* --------------------------------------------------------------------------
1450 * Substitutution control:
1451 * ------------------------------------------------------------------------*/
1453 Void substitution(what)
1458 case RESET : emptySubstitution();
1463 case MARK : for (i=0; i<MAXTUPCON; ++i)
1464 mark(tupleConTypes[i]);
1465 for (i=0; i<MAXKINDFUN; ++i) {
1466 mark(simpleKindCache[i]);
1467 mark(varKindCache[i]);
1469 for (i=0; i<numTyvars; ++i)
1470 mark(tyvars[i].bound);
1477 case INSTALL : substitution(RESET);
1478 for (i=0; i<MAXTUPCON; ++i)
1479 tupleConTypes[i] = NIL;
1480 for (i=0; i<MAXKINDFUN; ++i) {
1481 simpleKindCache[i] = NIL;
1482 varKindCache[i] = NIL;
1488 /*-------------------------------------------------------------------------*/