2 /* --------------------------------------------------------------------------
3 * This is the Hugs type checker
5 * Hugs 98 is Copyright (c) Mark P Jones, Alastair Reid and the Yale
6 * Haskell Group 1994-99, and is distributed as Open Source software
7 * under the Artistic License; see the file "Artistic" that is included
8 * in the distribution for details.
10 * $RCSfile: type.c,v $
12 * $Date: 1999/06/07 17:22:31 $
13 * ------------------------------------------------------------------------*/
22 #include "Assembler.h" /* for AsmCTypes */
24 /*#define DEBUG_TYPES*/
25 /*#define DEBUG_KINDS*/
26 /*#define DEBUG_DEFAULTS*/
27 /*#define DEBUG_SELS*/
28 /*#define DEBUG_DEPENDS*/
29 /*#define DEBUG_DERIVING*/
30 /*#define DEBUG_CODE*/
32 Bool catchAmbigs = FALSE; /* TRUE => functions with ambig. */
33 /* types produce error */
36 /* --------------------------------------------------------------------------
37 * Local function prototypes:
38 * ------------------------------------------------------------------------*/
40 static Void local emptyAssumption Args((Void));
41 static Void local enterBindings Args((Void));
42 static Void local leaveBindings Args((Void));
43 static Int local defType Args((Cell));
44 static Type local useType Args((Cell));
45 static Void local markAssumList Args((List));
46 static Cell local findAssum Args((Text));
47 static Pair local findInAssumList Args((Text,List));
48 static List local intsIntersect Args((List,List));
49 static List local genvarAllAss Args((List));
50 static List local genvarAnyAss Args((List));
51 static Int local newVarsBind Args((Cell));
52 static Void local newDefnBind Args((Cell,Type));
54 static Void local enterPendingBtyvs Args((Void));
55 static Void local leavePendingBtyvs Args((Void));
56 static Cell local patBtyvs Args((Cell));
57 static Void local doneBtyvs Args((Int));
58 static Void local enterSkolVars Args((Void));
59 static Void local leaveSkolVars Args((Int,Type,Int,Int));
61 static Void local typeError Args((Int,Cell,Cell,String,Type,Int));
62 static Void local reportTypeError Args((Int,Cell,Cell,String,Type,Type));
63 static Void local cantEstablish Args((Int,String,Cell,Type,List));
64 static Void local tooGeneral Args((Int,Cell,Type,Type));
66 static Cell local typeExpr Args((Int,Cell));
68 static Cell local typeAp Args((Int,Cell));
69 static Type local typeExpected Args((Int,String,Cell,Type,Int,Int,Bool));
70 static Void local typeAlt Args((String,Cell,Cell,Type,Int,Int));
71 static Int local funcType Args((Int));
72 static Void local typeCase Args((Int,Int,Cell));
73 static Void local typeComp Args((Int,Type,Cell,List));
74 static Cell local typeMonadComp Args((Int,Cell));
75 static Void local typeDo Args((Int,Cell));
76 static Void local typeConFlds Args((Int,Cell));
77 static Void local typeUpdFlds Args((Int,Cell));
78 static Cell local typeFreshPat Args((Int,Cell));
80 static Void local typeBindings Args((List));
81 static Void local removeTypeSigs Args((Cell));
83 static Void local monorestrict Args((List));
84 static Void local restrictedBindAss Args((Cell));
85 static Void local restrictedAss Args((Int,Cell,Type));
87 static Void local unrestricted Args((List));
88 static List local itbscc Args((List));
89 static Void local addEvidParams Args((List,Cell));
91 static Void local typeClassDefn Args((Class));
92 static Void local typeInstDefn Args((Inst));
93 static Void local typeMember Args((String,Name,Cell,List,Cell,Int));
95 static Void local typeBind Args((Cell));
96 static Void local typeDefAlt Args((Int,Cell,Pair));
97 static Cell local typeRhs Args((Cell));
98 static Void local guardedType Args((Int,Cell));
100 static Void local genBind Args((List,Cell));
101 static Void local genAss Args((Int,List,Cell,Type));
102 static Type local genTest Args((Int,Cell,List,Type,Type,Int));
103 static Type local generalize Args((List,Type));
104 static Bool local equalTypes Args((Type,Type));
106 static Void local typeDefnGroup Args((List));
107 static Pair local typeSel Args((Name));
111 /* --------------------------------------------------------------------------
114 * A basic typing statement is a pair (Var,Type) and an assumption contains
115 * an ordered list of basic typing statements in which the type for a given
116 * variable is given by the most recently added assumption about that var.
118 * In practice, the assumption set is split between a pair of lists, one
119 * holding assumptions for vars defined in bindings, the other for vars
120 * defined in patterns/binding parameters etc. The reason for this
121 * separation is that vars defined in bindings may be overloaded (with the
122 * overloading being unknown until the whole binding is typed), whereas the
123 * vars defined in patterns have no overloading. A form of dependency
124 * analysis (at least as far as calculating dependents within the same group
125 * of value bindings) is required to implement this. Where it is known that
126 * no overloaded values are defined in a binding (i.e., when the `dreaded
127 * monomorphism restriction' strikes), the list used to record dependents
128 * is flagged with a NODEPENDS tag to avoid gathering dependents at that
131 * To interleave between vars for bindings and vars for patterns, we use
132 * a list of lists of typing statements for each. These lists are always
133 * the same length. The implementation here is very similar to that of the
134 * dependency analysis used in the static analysis component of this system.
136 * To deal with polymorphic recursion, variables defined in bindings can be
137 * assigned types of the form (POLYREC,(def,use)), where def is a type
138 * variable for the type of the defining occurence, and use is a type
139 * scheme for (recursive) calls/uses of the variable.
140 * ------------------------------------------------------------------------*/
142 static List defnBounds; /*::[[(Var,Type)]] possibly ovrlded*/
143 static List varsBounds; /*::[[(Var,Type)]] not overloaded */
144 static List depends; /*::[?[Var]] dependents/NODEPENDS */
145 static List skolVars; /*::[[Var]] skolem vars */
146 static List localEvs; /*::[[(Pred,offset,ev)]] */
147 static List savedPs; /*::[[(Pred,offset,ev)]] */
148 static Cell dummyVar; /* Used to put extra tvars into ass*/
150 #define saveVarsAss() List saveAssump = hd(varsBounds)
151 #define restoreVarsAss() hd(varsBounds) = saveAssump
152 #define addVarAssump(v,t) hd(varsBounds) = cons(pair(v,t),hd(varsBounds))
153 #define findTopBinding(v) findInAssumList(textOf(v),hd(defnBounds))
155 static Void local emptyAssumption() { /* set empty type assumption */
164 static Void local enterBindings() { /* Add new level to assumption sets */
165 defnBounds = cons(NIL,defnBounds);
166 varsBounds = cons(NIL,varsBounds);
167 depends = cons(NIL,depends);
170 static Void local leaveBindings() { /* Drop one level of assumptions */
171 defnBounds = tl(defnBounds);
172 varsBounds = tl(varsBounds);
173 depends = tl(depends);
176 static Int local defType(a) /* Return type for defining occ. */
177 Cell a; { /* of a var from assumption pair */
178 return (isPair(a) && fst(a)==POLYREC) ? fst(snd(a)) : a;
181 static Type local useType(a) /* Return type for use of a var */
182 Cell a; { /* defined in an assumption */
183 return (isPair(a) && fst(a)==POLYREC) ? snd(snd(a)) : a;
186 static Void local markAssumList(as) /* Mark all types in assumption set*/
187 List as; { /* :: [(Var, Type)] */
188 for (; nonNull(as); as=tl(as)) { /* No need to mark generic types; */
189 Type t = defType(snd(hd(as))); /* the only free variables in those*/
190 if (!isPolyType(t)) /* must have been free earlier too */
195 static Cell local findAssum(t) /* Find most recent assumption about*/
196 Text t; { /* variable named t, if any */
197 List defnBounds1 = defnBounds; /* return translated variable, with */
198 List varsBounds1 = varsBounds; /* type in typeIs */
199 List depends1 = depends;
201 while (nonNull(defnBounds1)) {
202 Pair ass = findInAssumList(t,hd(varsBounds1));/* search varsBounds */
208 ass = findInAssumList(t,hd(defnBounds1)); /* search defnBounds */
213 if (hd(depends1)!=NODEPENDS && /* save dependent? */
214 isNull(v=varIsMember(t,hd(depends1))))
215 /* N.B. make new copy of variable and store this on list of*/
216 /* dependents, and in the assumption so that all uses of */
217 /* the variable will be at the same node, if we need to */
218 /* overwrite the call of a function with a translation... */
219 hd(depends1) = cons(v=mkVar(t),hd(depends1));
224 defnBounds1 = tl(defnBounds1); /* look in next level*/
225 varsBounds1 = tl(varsBounds1); /* of assumption set */
226 depends1 = tl(depends1);
231 static Pair local findInAssumList(t,as)/* Search for assumption for var */
232 Text t; /* named t in list of assumptions as*/
234 for (; nonNull(as); as=tl(as))
235 if (textOf(fst(hd(as)))==t)
240 static List local intsIntersect(as,bs) /* calculate intersection of lists */
241 List as, bs; { /* of integers (as sets) */
242 List ts = NIL; /* destructively modifies as */
244 if (intIsMember(intOf(hd(as)),bs)) {
255 static List local genvarAllAss(as) /* calculate generic vars that are */
256 List as; { /* in every type in assumptions as */
257 List vs = genvarTyvar(intOf(defType(snd(hd(as)))),NIL);
258 for (as=tl(as); nonNull(as) && nonNull(vs); as=tl(as))
259 vs = intsIntersect(vs,genvarTyvar(intOf(defType(snd(hd(as)))),NIL));
263 static List local genvarAnyAss(as) /* calculate generic vars that are */
264 List as; { /* in any type in assumptions as */
265 List vs = genvarTyvar(intOf(defType(snd(hd(as)))),NIL);
266 for (as=tl(as); nonNull(as); as=tl(as))
267 vs = genvarTyvar(intOf(defType(snd(hd(as)))),vs);
271 static Int local newVarsBind(v) /* make new assump for pattern var */
273 Int beta = newTyvars(1);
274 addVarAssump(v,mkInt(beta));
276 Printf("variable, assume ");
278 Printf(" :: _%d\n",beta);
283 static Void local newDefnBind(v,type) /* make new assump for defn var */
284 Cell v; /* and set type if given (nonNull) */
286 Int beta = newTyvars(1);
287 Cell ta = mkInt(beta);
289 if (nonNull(type) && isPolyType(type))
290 ta = pair(POLYREC,pair(ta,type));
291 hd(defnBounds) = cons(pair(v,ta), hd(defnBounds));
293 Printf("definition, assume ");
295 Printf(" :: _%d\n",beta);
297 bindTv(beta,typeIs,typeOff); /* Bind beta to new type skeleton */
300 /* --------------------------------------------------------------------------
302 * ------------------------------------------------------------------------*/
306 /* --------------------------------------------------------------------------
307 * Bound and skolemized type variables:
308 * ------------------------------------------------------------------------*/
310 static List pendingBtyvs = NIL;
312 static Void local enterPendingBtyvs() {
314 pendingBtyvs = cons(NIL,pendingBtyvs);
317 static Void local leavePendingBtyvs() {
318 List pts = hd(pendingBtyvs);
319 pendingBtyvs = tl(pendingBtyvs);
320 for (; nonNull(pts); pts=tl(pts)) {
321 Int line = intOf(fst(hd(pts)));
322 List vs = snd(hd(pts));
325 for (; nonNull(vs); vs=tl(vs)) {
326 Cell v = fst(hd(vs));
327 Cell t = copyTyvar(intOf(snd(hd(vs))));
329 ERRMSG(line) "Type annotation uses variable " ETHEN ERREXPR(v);
330 ERRTEXT " where a more specific type " ETHEN ERRTYPE(t);
331 ERRTEXT " was inferred"
334 else if (offsetOf(t)!=i) {
335 List us = snd(hd(pts));
338 internal("leavePendingBtyvs");
341 ERRMSG(line) "Type annotation uses distinct variables " ETHEN
342 ERREXPR(v); ERRTEXT " and " ETHEN ERREXPR(fst(hd(us)));
343 ERRTEXT " where a single variable was inferred"
353 static Cell local patBtyvs(p) /* Strip bound type vars from pat */
355 if (whatIs(p)==BIGLAM) {
356 List bts = hd(btyvars) = fst(snd(p));
357 for (p=snd(snd(p)); nonNull(bts); bts=tl(bts)) {
358 Int beta = newTyvars(1);
359 tyvar(beta)->kind = snd(hd(bts));
360 snd(hd(bts)) = mkInt(beta);
366 static Void local doneBtyvs(l)
368 if (nonNull(hd(btyvars))) { /* Save bound tyvars */
369 hd(pendingBtyvs) = cons(pair(mkInt(l),hd(btyvars)),hd(pendingBtyvs));
374 static Void local enterSkolVars() {
375 skolVars = cons(NIL,skolVars);
376 localEvs = cons(NIL,localEvs);
377 savedPs = cons(preds,savedPs);
381 static Void local leaveSkolVars(l,t,o,m)
386 if (nonNull(hd(localEvs))) { /* Check for local predicates */
387 List sks = hd(skolVars);
390 internal("leaveSkolVars");
392 markAllVars(); /* Mark all variables in current */
393 do { /* substitution, then unmark sks. */
394 tyvar(intOf(fst(hd(sks))))->offs = UNUSED_GENERIC;
396 } while (nonNull(sks));
397 sps = elimPredsUsing(hd(localEvs),sps);
398 preds = revOnto(preds,sps);
401 if (nonNull(hd(skolVars))) { /* Check that Skolem vars do not */
402 List vs; /* escape their scope */
405 clearMarks(); /* Look for occurences in the */
406 for (; i<m; i++) /* inferred type */
410 for (vs=hd(skolVars); nonNull(vs); vs=tl(vs)) {
411 Int vn = intOf(fst(hd(vs)));
412 if (tyvar(vn)->offs == FIXED_TYVAR) {
413 Cell tv = copyTyvar(vn);
414 Type ty = liftRank2(t,o,m);
415 ERRMSG(l) "Existentially quantified variable in inferred type"
417 ERRTEXT "\n*** Variable : " ETHEN ERRTYPE(tv);
418 ERRTEXT "\n*** From pattern : " ETHEN ERREXPR(snd(hd(vs)));
419 ERRTEXT "\n*** Result type : " ETHEN ERRTYPE(ty);
425 markBtyvs(); /* Now check assumptions */
426 mapProc(markAssumList,defnBounds);
427 mapProc(markAssumList,varsBounds);
429 for (vs=hd(skolVars); nonNull(vs); vs=tl(vs)) {
430 Int vn = intOf(fst(hd(vs)));
431 if (tyvar(vn)->offs == FIXED_TYVAR) {
433 "Existentially quantified variable escapes from pattern "
434 ETHEN ERREXPR(snd(hd(vs)));
440 localEvs = tl(localEvs);
441 skolVars = tl(skolVars);
442 preds = revOnto(preds,hd(savedPs));
443 savedPs = tl(savedPs);
446 /* --------------------------------------------------------------------------
448 * ------------------------------------------------------------------------*/
450 static Void local typeError(l,e,in,wh,t,o)
451 Int l; /* line number near type error */
452 String wh; /* place in which error occurs */
453 Cell e; /* source of error */
454 Cell in; /* context if any (NIL if not) */
455 Type t; /* should be of type (t,o) */
456 Int o; { /* type inferred is (typeIs,typeOff) */
458 clearMarks(); /* types printed here are monotypes */
459 /* use marking to give sensible names*/
461 { List vs = genericVars;
462 for (; nonNull(vs); vs=tl(vs)) {
463 Int v = intOf(hd(vs));
464 Printf("%c :: ", ('a'+tyvar(v)->offs));
465 printKind(stdout,tyvar(v)->kind);
471 reportTypeError(l,e,in,wh,copyType(typeIs,typeOff),copyType(t,o));
474 static Void local reportTypeError(l,e,in,wh,inft,expt)
475 Int l; /* Error printing part of typeError*/
479 ERRMSG(l) "Type error in %s", wh ETHEN
481 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(in);
483 ERRTEXT "\n*** Term : " ETHEN ERREXPR(e);
484 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(inft);
485 ERRTEXT "\n*** Does not match : " ETHEN ERRTYPE(expt);
487 ERRTEXT "\n*** Because : %s", unifyFails ETHEN
493 #define shouldBe(l,e,in,where,t,o) if (!unify(typeIs,typeOff,t,o)) \
494 typeError(l,e,in,where,t,o);
495 #define check(l,e,in,where,t,o) e=typeExpr(l,e); shouldBe(l,e,in,where,t,o)
496 #define inferType(t,o) typeIs=t; typeOff=o
498 static Void local cantEstablish(line,wh,e,t,ps)
499 Int line; /* Complain when declared preds */
500 String wh; /* are not sufficient to discharge */
501 Cell e; /* or defer the inferred context. */
504 ERRMSG(line) "Cannot justify constraints in %s", wh ETHEN
505 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
506 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(t);
507 ERRTEXT "\n*** Given context : " ETHEN ERRCONTEXT(ps);
508 ERRTEXT "\n*** Constraints : " ETHEN ERRCONTEXT(copyPreds(preds));
513 static Void local tooGeneral(l,e,dt,it) /* explicit type sig. too general */
517 ERRMSG(l) "Inferred type is not general enough" ETHEN
518 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
519 ERRTEXT "\n*** Expected type : " ETHEN ERRTYPE(dt);
520 ERRTEXT "\n*** Inferred type : " ETHEN ERRTYPE(it);
525 /* --------------------------------------------------------------------------
526 * Typing of expressions:
527 * ------------------------------------------------------------------------*/
529 #define EXPRESSION 0 /* type checking expression */
530 #define NEW_PATTERN 1 /* pattern, introducing new vars */
531 #define OLD_PATTERN 2 /* pattern, involving bound vars */
532 static int tcMode = EXPRESSION;
535 static Cell local mytypeExpr Args((Int,Cell));
536 static Cell local typeExpr(l,e)
539 static int number = 0;
541 int mynumber = number++;
542 Printf("%d) to check: ",mynumber);
545 retv = mytypeExpr(l,e);
546 Printf("%d) result: ",mynumber);
547 printType(stdout,debugType(typeIs,typeOff));
551 static Cell local mytypeExpr(l,e) /* Determine type of expr/pattern */
553 static Cell local typeExpr(l,e) /* Determine type of expr/pattern */
557 static String cond = "conditional";
558 static String list = "list";
559 static String discr = "case discriminant";
560 static String aspat = "as (@) pattern";
561 static String typeSig = "type annotation";
562 static String lambda = "lambda expression";
566 /* The following cases can occur in either pattern or expr. mode */
571 case VARIDCELL : return typeAp(l,e);
573 case TUPLE : typeTuple(e);
576 case BIGCELL : { Int alpha = newTyvars(1);
577 inferType(aVar,alpha);
578 return ap(ap(nameFromInteger,
579 assumeEvid(predNum,alpha)),
583 case INTCELL : { Int alpha = newTyvars(1);
584 inferType(aVar,alpha);
585 return ap(ap(nameFromInt,
586 assumeEvid(predNum,alpha)),
590 case FLOATCELL : { Int alpha = newTyvars(1);
591 inferType(aVar,alpha);
592 return ap(ap(nameFromDouble,
593 assumeEvid(predFractional,alpha)),
597 case STRCELL : inferType(typeString,0);
600 case CHARCELL : inferType(typeChar,0);
603 case CONFLDS : typeConFlds(l,e);
606 case ESIGN : snd(snd(e)) = localizeBtyvs(snd(snd(e)));
607 return typeExpected(l,typeSig,
608 fst(snd(e)),snd(snd(e)),
612 case EXT : { Int beta = newTyvars(2);
613 Cell pi = ap(e,aVar);
616 ap(typeRec,ap(ap(e,aVar),bVar))));
617 tyvar(beta+1)->kind = ROW;
619 return ap(e,assumeEvid(pi,beta+1));
623 /* The following cases can only occur in expr mode */
625 case UPDFLDS : typeUpdFlds(l,e);
628 case COND : { Int beta = newTyvars(1);
629 check(l,fst3(snd(e)),e,cond,typeBool,0);
630 check(l,snd3(snd(e)),e,cond,aVar,beta);
631 check(l,thd3(snd(e)),e,cond,aVar,beta);
636 case LETREC : enterBindings();
638 mapProc(typeBindings,fst(snd(e)));
639 snd(snd(e)) = typeExpr(l,snd(snd(e)));
641 leaveSkolVars(l,typeIs,typeOff,0);
644 case FINLIST : { Int beta = newTyvars(1);
646 for (xs=snd(e); nonNull(xs); xs=tl(xs)) {
647 check(l,hd(xs),e,list,aVar,beta);
649 inferType(listof,beta);
653 case DOCOMP : typeDo(l,e);
656 case COMP : return typeMonadComp(l,e);
658 case CASE : { Int beta = newTyvars(2); /* discr result */
659 check(l,fst(snd(e)),NIL,discr,aVar,beta);
660 map2Proc(typeCase,l,beta,snd(snd(e)));
665 case LAMBDA : { Int beta = newTyvars(1);
667 typeAlt(lambda,e,snd(e),aVar,beta,1);
674 case RECSEL : { Int beta = newTyvars(2);
675 Cell pi = ap(snd(e),aVar);
676 Type t = fn(ap(typeRec,
679 tyvar(beta+1)->kind = ROW;
681 return ap(e,assumeEvid(pi,beta+1));
685 /* The remaining cases can only occur in pattern mode: */
687 case WILDCARD : inferType(aVar,newTyvars(1));
690 case ASPAT : { Int beta = newTyvars(1);
691 snd(snd(e)) = typeExpr(l,snd(snd(e)));
692 bindTv(beta,typeIs,typeOff);
693 check(l,fst(snd(e)),e,aspat,aVar,beta);
698 case LAZYPAT : snd(e) = typeExpr(l,snd(e));
702 case ADDPAT : { Int alpha = newTyvars(1);
703 inferType(typeVarToVar,alpha);
704 return ap(e,assumeEvid(predIntegral,alpha));
708 default : internal("typeExpr");
714 /* --------------------------------------------------------------------------
715 * Typing rules for particular special forms:
716 * ------------------------------------------------------------------------*/
718 static Cell local typeAp(l,e) /* Type check application, which */
719 Int l; /* may be headed with a variable */
720 Cell e; { /* requires polymorphism, qualified*/
721 static String app = "application"; /* types, and possible rank2 args. */
729 case NAME : typeIs = name(h).type;
733 case VARIDCELL : if (tcMode==NEW_PATTERN) {
734 inferType(aVar,newVarsBind(e));
737 Cell v = findAssum(textOf(h));
740 typeIs = (tcMode==OLD_PATTERN)
745 h = findName(textOf(h));
748 typeIs = name(h).type;
753 default : h = typeExpr(l,h);
757 if (isNull(typeIs)) {
761 instantiate(typeIs); /* Deal with polymorphism ... */
762 if (nonNull(predsAre)) { /* ... and with qualified types. */
764 for (; nonNull(predsAre); predsAre=tl(predsAre)) {
765 evs = cons(assumeEvid(hd(predsAre),typeOff),evs);
767 if (!isName(h) || !isCfun(h)) {
768 h = applyToArgs(h,rev(evs));
772 if (whatIs(typeIs)==CDICTS) { /* Deal with local dictionaries */
773 List evs = makePredAss(fst(snd(typeIs)),typeOff);
775 typeIs = snd(snd(typeIs));
776 for (; nonNull(ps); ps=tl(ps)) {
777 h = ap(h,thd3(hd(ps)));
779 if (tcMode==EXPRESSION) {
780 preds = revOnto(evs,preds);
782 hd(localEvs) = revOnto(evs,hd(localEvs));
786 if (whatIs(typeIs)==EXIST) { /* Deal with existential arguments */
787 Int n = intOf(fst(snd(typeIs)));
788 typeIs = snd(snd(typeIs));
789 if (!isCfun(getHead(h)) || n>typeFree) {
791 } else if (tcMode!=EXPRESSION) {
792 Int alpha = typeOff + typeFree;
794 bindTv(alpha-n,SKOLEM,0);
795 hd(skolVars) = cons(pair(mkInt(alpha-n),e),hd(skolVars));
800 if (whatIs(typeIs)==RANK2) { /* Deal with rank 2 arguments */
803 Int nr2 = intOf(fst(snd(typeIs)));
804 Type body = snd(snd(typeIs));
808 if (n<nr2) { /* Must have enough arguments */
809 ERRMSG(l) "Use of " ETHEN ERREXPR(h);
811 ERRTEXT " in " ETHEN ERREXPR(e);
813 ERRTEXT " requires at least %d argument%s\n",
814 nr2, (nr2==1 ? "" : "s")
818 for (i=nr2; i<n; ++i) /* Find rank two arguments */
821 for (as=getArgs(as); nonNull(as); as=tl(as), body=arg(body)) {
822 Type expect = dropRank1(arg(fun(body)),alpha,m);
823 if (isPolyType(expect)) {
824 if (tcMode==EXPRESSION) /* poly/qual type in expr */
825 hd(as) = typeExpected(l,app,hd(as),expect,alpha,m,TRUE);
826 else if (hd(as)!=WILDCARD) { /* Pattern binding/match */
827 if (!isVar(hd(as))) {
828 ERRMSG(l) "Argument " ETHEN ERREXPR(arg(as));
829 ERRTEXT " in pattern " ETHEN ERREXPR(e);
830 ERRTEXT " where a variable is required\n"
833 if (tcMode==NEW_PATTERN) { /* Pattern match */
836 addVarAssump(dummyVar,mkInt(alpha+i));
839 addVarAssump(hd(as),expect);
841 else { /* Pattern binding */
842 Text t = textOf(hd(as));
843 Cell a = findInAssumList(t,hd(defnBounds));
847 if (nonNull(predsAre)) {
848 ERRMSG(l) "Cannot use pattern binding for " ETHEN
850 ERRTEXT " as a component with a qualified type\n"
853 shouldBe(l,hd(as),e,app,aVar,intOf(defType(snd(a))));
857 else { /* Not a poly/qual type */
858 check(l,hd(as),e,app,expect,alpha);
860 h = ap(h,hd(as)); /* Save checked argument */
862 inferType(body,alpha);
866 if (n>0) { /* Deal with remaining args */
867 Int beta = funcType(n); /* check h::t1->t2->...->tn->rn+1 */
868 shouldBe(l,h,e,app,aVar,beta);
869 for (i=n; i>0; --i) { /* check e_i::t_i for each i */
870 check(l,arg(a),e,app,aVar,beta+2*i-1);
874 tyvarType(beta+2*n); /* Inferred type is r_n+1 */
877 if (isNull(p)) /* Replace head with translation */
885 static Cell local typeExpected(l,wh,e,reqd,alpha,n,addEvid)
886 Int l; /* Type check expression e in wh */
887 String wh; /* at line l, expecting type reqd, */
888 Cell e; /* and treating vars alpha through */
889 Type reqd; /* (alpha+n-1) as fixed. */
892 Bool addEvid; { /* TRUE => add \ev -> ... */
893 List savePreds = preds;
904 ps = makePredAss(predsAre,o);
907 check(l,e,NIL,wh,t,o);
910 mapProc(markAssumList,defnBounds);
911 mapProc(markAssumList,varsBounds);
912 mapProc(markPred,savePreds);
918 savePreds = elimPredsUsing(ps,savePreds);
919 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
920 savePreds = elimPredsUsing(ps,savePreds);
921 if (nonNull(preds)) {
922 Type ty = copyType(t,o);
923 List qs = copyPreds(ps);
924 cantEstablish(l,wh,e,ty,qs);
929 if (copyTyvar(o+i)!=mkOffset(i)) {
930 List qs = copyPreds(ps);
931 Type it = copyType(t,o);
932 tooGeneral(l,e,reqd,generalize(qs,it));
936 e = qualifyExpr(l,ps,e);
940 preds = revOnto(ps,savePreds);
946 static Void local typeAlt(wh,e,a,t,o,m) /* Type check abstraction (Alt) */
947 String wh; /* a = ( [p1, ..., pn], rhs ) */
954 List ps = fst(a) = patBtyvs(fst(a));
956 Int l = rhsLine(snd(a));
963 if (whatIs(t)==RANK2) {
964 if (n<(nr2=intOf(fst(snd(t))))) {
965 ERRMSG(l) "Definition requires at least %d parameters on lhs",
972 while (getHead(t)==typeArrow && argCount==2 && nonNull(ps)) {
973 Type ta = arg(fun(t));
974 if (isPolyType(ta)) {
975 if (hd(ps)!=WILDCARD) {
976 if (!isVar(hd(ps))) {
977 ERRMSG(l) "Argument " ETHEN ERREXPR(hd(ps));
978 ERRTEXT " used where a variable or wildcard is required\n"
984 addVarAssump(dummyVar,mkInt(o+i));
987 addVarAssump(hd(ps),ta);
991 hd(ps) = typeFreshPat(l,hd(ps));
992 shouldBe(l,hd(ps),NIL,wh,ta,o);
1001 snd(a) = typeRhs(snd(a));
1003 Int beta = funcType(n);
1006 hd(ps) = typeFreshPat(l,hd(ps));
1007 bindTv(beta+2*i+1,typeIs,typeOff);
1010 snd(a) = typeRhs(snd(a));
1011 bindTv(beta+2*n,typeIs,typeOff);
1015 if (!unify(typeIs,typeOff,t,o)) {
1018 req = liftRank2(origt,o,m);
1019 liftRank2Args(as,o,m);
1020 got = ap(RANK2,pair(mkInt(nr2),revOnto(as,copyType(typeIs,typeOff))));
1021 reportTypeError(l,e,NIL,wh,got,req);
1026 leaveSkolVars(l,origt,o,m);
1029 static Int local funcType(n) /*return skeleton for function type*/
1030 Int n; { /*with n arguments, taking the form*/
1031 Int beta = newTyvars(2*n+1); /* r1 t1 r2 t2 ... rn tn rn+1 */
1032 Int i; /* with r_i := t_i -> r_i+1 */
1034 bindTv(beta+2*i,arrow,beta+2*i+1);
1038 static Void local typeCase(l,beta,c) /* type check case: pat -> rhs */
1039 Int l; /* (case given by c == (pat,rhs)) */
1040 Int beta; /* need: pat :: (var,beta) */
1041 Cell c; { /* rhs :: (var,beta+1) */
1042 static String casePat = "case pattern";
1043 static String caseExpr = "case expression";
1047 fst(c) = typeFreshPat(l,patBtyvs(fst(c)));
1048 shouldBe(l,fst(c),NIL,casePat,aVar,beta);
1049 snd(c) = typeRhs(snd(c));
1050 shouldBe(l,rhsExpr(snd(c)),NIL,caseExpr,aVar,beta+1);
1054 leaveSkolVars(l,typeIs,typeOff,0);
1057 static Void local typeComp(l,m,e,qs) /* type check comprehension */
1059 Type m; /* monad (mkOffset(0)) */
1062 static String boolQual = "boolean qualifier";
1063 static String genQual = "generator";
1065 if (isNull(qs)) /* no qualifiers left */
1066 fst(e) = typeExpr(l,fst(e));
1070 switch (whatIs(q)) {
1071 case BOOLQUAL : check(l,snd(q),NIL,boolQual,typeBool,0);
1072 typeComp(l,m,e,qs1);
1075 case QWHERE : enterBindings();
1077 mapProc(typeBindings,snd(q));
1078 typeComp(l,m,e,qs1);
1080 leaveSkolVars(l,typeIs,typeOff,0);
1083 case FROMQUAL : { Int beta = newTyvars(1);
1085 check(l,snd(snd(q)),NIL,genQual,m,beta);
1088 = typeFreshPat(l,patBtyvs(fst(snd(q))));
1089 shouldBe(l,fst(snd(q)),NIL,genQual,aVar,beta);
1090 typeComp(l,m,e,qs1);
1093 leaveSkolVars(l,typeIs,typeOff,0);
1097 case DOQUAL : check(l,snd(q),NIL,genQual,m,newTyvars(1));
1098 typeComp(l,m,e,qs1);
1104 static Cell local typeMonadComp(l,e) /* type check monad comprehension */
1107 Int alpha = newTyvars(1);
1108 Int beta = newTyvars(1);
1109 Cell mon = ap(mkInt(beta),aVar);
1110 Cell m = assumeEvid(predMonad,beta);
1111 tyvar(beta)->kind = starToStar;
1113 bindTv(beta,typeList,0);
1116 typeComp(l,mon,snd(e),snd(snd(e)));
1117 bindTv(alpha,typeIs,typeOff);
1118 inferType(mon,alpha);
1119 return ap(MONADCOMP,pair(m,snd(e)));
1122 static Void local typeDo(l,e) /* type check do-notation */
1125 static String finGen = "final generator";
1126 Int alpha = newTyvars(1);
1127 Int beta = newTyvars(1);
1128 Cell mon = ap(mkInt(beta),aVar);
1129 Cell m = assumeEvid(predMonad,beta);
1130 tyvar(beta)->kind = starToStar;
1132 typeComp(l,mon,snd(e),snd(snd(e)));
1133 shouldBe(l,fst(snd(e)),NIL,finGen,mon,alpha);
1134 snd(e) = pair(m,snd(e));
1137 static Void local typeConFlds(l,e) /* Type check a construction */
1140 static String conExpr = "value construction";
1141 Name c = fst(snd(e));
1142 List fs = snd(snd(e));
1148 instantiate(name(c).type);
1149 for (; nonNull(predsAre); predsAre=tl(predsAre))
1150 assumeEvid(hd(predsAre),typeOff);
1151 if (whatIs(typeIs)==RANK2)
1152 typeIs = snd(snd(typeIs));
1157 for (; nonNull(fs); fs=tl(fs)) {
1159 for (i=sfunPos(fst(hd(fs)),c); --i>0; t=arg(t))
1161 t = dropRank1(arg(fun(t)),to,tf);
1163 snd(hd(fs)) = typeExpected(l,conExpr,snd(hd(fs)),t,to,tf,TRUE);
1165 check(l,snd(hd(fs)),e,conExpr,t,to);
1168 for (i=name(c).arity; i>0; i--)
1173 static Void local typeUpdFlds(line,e) /* Type check an update */
1174 Int line; /* (Written in what might seem a */
1175 Cell e; { /* bizarre manner for the benefit */
1176 static String update = "update"; /* of as yet unreleased extensions)*/
1177 List cs = snd3(snd(e)); /* List of constructors */
1178 List fs = thd3(snd(e)); /* List of field specifications */
1179 List ts = NIL; /* List of types for fields */
1181 Int alpha = newTyvars(2+n);
1185 /* Calculate type and translation for each expr in the field list */
1186 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1187 snd(hd(fs1)) = typeExpr(line,snd(hd(fs1)));
1188 bindTv(i,typeIs,typeOff);
1192 mapProc(markAssumList,defnBounds);
1193 mapProc(markAssumList,varsBounds);
1194 mapProc(markPred,preds);
1197 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1199 ts = cons(generalize(NIL,copyTyvar(i)),ts);
1203 /* Type check expression to be updated */
1204 fst3(snd(e)) = typeExpr(line,fst3(snd(e)));
1205 bindTv(alpha,typeIs,typeOff);
1207 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constrs */
1209 List ta = replicate(name(c).arity,NIL);
1213 tcMode = NEW_PATTERN; /* Domain type */
1214 instantiate(name(c).type);
1215 tcMode = EXPRESSION;
1218 for (; nonNull(predsAre); predsAre=tl(predsAre))
1219 assumeEvid(hd(predsAre),typeOff);
1221 if (whatIs(typeIs)==RANK2) {
1222 ERRMSG(line) "Sorry, record update syntax cannot currently be "
1223 "used for datatypes with polymorphic components"
1227 instantiate(name(c).type); /* Range type */
1230 for (; nonNull(predsAre); predsAre=tl(predsAre))
1231 assumeEvid(hd(predsAre),typeOff);
1233 for (fs1=fs, i=1; nonNull(fs1); fs1=tl(fs1), i++) {
1234 Int n = sfunPos(fst(hd(fs1)),c);
1241 for (; nonNull(ta); ta=tl(ta)) { /* For each cfun arg */
1242 if (nonNull(hd(ta))) { /* Field to updated? */
1243 Int n = intOf(hd(ta));
1246 for (; n-- > 1; f=tl(f), t=tl(t))
1251 shouldBe(line,snd(f),e,update,arg(fun(tr)),or);
1252 } /* Unmentioned component */
1253 else if (!unify(arg(fun(td)),od,arg(fun(tr)),or))
1254 internal("typeUpdFlds");
1260 inferType(td,od); /* Check domain type */
1261 shouldBe(line,fst3(snd(e)),e,update,aVar,alpha);
1262 inferType(tr,or); /* Check range type */
1263 shouldBe(line,e,NIL,update,aVar,alpha+1);
1265 /* (typeIs,typeOff) still carry the result type when we exit the loop */
1268 static Cell local typeFreshPat(l,p) /* find type of pattern, assigning */
1269 Int l; /* fresh type variables to each var */
1270 Cell p; { /* bound in the pattern */
1271 tcMode = NEW_PATTERN;
1273 tcMode = EXPRESSION;
1277 /* --------------------------------------------------------------------------
1278 * Type check group of bindings:
1279 * ------------------------------------------------------------------------*/
1281 static Void local typeBindings(bs) /* type check a binding group */
1283 Bool usesPatBindings = FALSE; /* TRUE => pattern binding in bs */
1284 Bool usesUntypedVar = FALSE; /* TRUE => var bind w/o type decl */
1287 /* The following loop is used to determine whether the monomorphism */
1288 /* restriction should be applied. It could be written marginally more */
1289 /* efficiently by using breaks, but clarity is more important here ... */
1291 for (bs1=bs; nonNull(bs1); bs1=tl(bs1)) { /* Analyse binding group */
1294 usesPatBindings = TRUE;
1295 else if (isNull(fst(hd(snd(snd(b))))) /* no arguments */
1296 && whatIs(fst(snd(b)))==IMPDEPS) /* implicitly typed*/
1297 usesUntypedVar = TRUE;
1300 if (usesPatBindings || usesUntypedVar)
1305 mapProc(removeTypeSigs,bs); /* Remove binding type info */
1306 hd(varsBounds) = revOnto(hd(defnBounds), /* transfer completed assmps*/
1307 hd(varsBounds)); /* out of defnBounds */
1308 hd(defnBounds) = NIL;
1312 static Void local removeTypeSigs(b) /* Remove type info from a binding */
1314 snd(b) = snd(snd(b));
1317 /* --------------------------------------------------------------------------
1318 * Type check a restricted binding group:
1319 * ------------------------------------------------------------------------*/
1321 static Void local monorestrict(bs) /* Type restricted binding group */
1323 List savePreds = preds;
1324 Int line = isVar(fst(hd(bs))) ? rhsLine(snd(hd(snd(snd(hd(bs))))))
1325 : rhsLine(snd(snd(snd(hd(bs)))));
1326 hd(defnBounds) = NIL;
1327 hd(depends) = NODEPENDS; /* No need for dependents here */
1329 preds = NIL; /* Type check the bindings */
1330 mapProc(restrictedBindAss,bs);
1331 mapProc(typeBind,bs);
1334 preds = revOnto(preds,savePreds);
1336 clearMarks(); /* Mark fixed variables */
1337 mapProc(markAssumList,tl(defnBounds));
1338 mapProc(markAssumList,tl(varsBounds));
1339 mapProc(markPred,preds);
1342 if (isNull(tl(defnBounds))) { /* Top-level may need defaulting */
1344 if (nonNull(preds) && resolveDefs(genvarAnyAss(hd(defnBounds))))
1349 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
1352 if (nonNull(preds)) { /* Look for unresolved overloading */
1353 Cell v = isVar(fst(hd(bs))) ? fst(hd(bs)) : hd(fst(hd(bs)));
1354 Cell ass = findInAssumList(textOf(v),hd(varsBounds));
1355 preds = scSimplify(preds);
1357 ERRMSG(line) "Unresolved top-level overloading" ETHEN
1358 ERRTEXT "\n*** Binding : %s", textToStr(textOf(v))
1361 ERRTEXT "\n*** Inferred type : " ETHEN ERRTYPE(snd(ass));
1363 ERRTEXT "\n*** Outstanding context : " ETHEN
1364 ERRCONTEXT(copyPreds(preds));
1370 map1Proc(genBind,NIL,bs); /* Generalize types of def'd vars */
1373 static Void local restrictedBindAss(b) /* Make assums for vars in binding */
1374 Cell b; { /* gp with restricted overloading */
1376 if (isVar(fst(b))) { /* function-binding? */
1377 Cell t = fst(snd(b));
1378 if (whatIs(t)==IMPDEPS) { /* Discard implicitly typed deps */
1379 fst(snd(b)) = t = NIL; /* in a restricted binding group. */
1381 fst(snd(b)) = localizeBtyvs(t);
1382 restrictedAss(rhsLine(snd(hd(snd(snd(b))))), fst(b), t);
1383 } else { /* pattern-binding? */
1385 List ts = fst(snd(b));
1386 Int line = rhsLine(snd(snd(snd(b))));
1388 for (; nonNull(vs); vs=tl(vs)) {
1390 restrictedAss(line,hd(vs),hd(ts)=localizeBtyvs(hd(ts)));
1393 restrictedAss(line,hd(vs),NIL);
1399 static Void local restrictedAss(l,v,t) /* Assume that type of binding var v*/
1400 Int l; /* is t (if nonNull) in restricted */
1401 Cell v; /* binding group */
1404 if (nonNull(predsAre)) {
1405 ERRMSG(l) "Explicit overloaded type for \"%s\"",textToStr(textOf(v))
1407 ERRTEXT " not permitted in restricted binding"
1412 /* --------------------------------------------------------------------------
1413 * Unrestricted binding group:
1414 * ------------------------------------------------------------------------*/
1416 static Void local unrestricted(bs) /* Type unrestricted binding group */
1418 List savePreds = preds;
1419 List imps = NIL; /* Implicitly typed bindings */
1420 List exps = NIL; /* Explicitly typed bindings */
1423 /* ----------------------------------------------------------------------
1424 * STEP 1: Separate implicitly typed bindings from explicitly typed
1425 * bindings and do a dependency analyis, where f depends on g iff f
1426 * is implicitly typed and involves a call to g.
1427 * --------------------------------------------------------------------*/
1429 for (; nonNull(bs); bs=tl(bs)) {
1431 if (whatIs(fst(snd(b)))==IMPDEPS)
1432 imps = cons(b,imps); /* N.B. New lists are built to */
1433 else /* avoid breaking the original */
1434 exps = cons(b,exps); /* list structure for bs. */
1437 for (bs=imps; nonNull(bs); bs=tl(bs)) {
1438 Cell b = hd(bs); /* Restrict implicitly typed dep */
1439 List ds = snd(fst(snd(b))); /* lists to bindings in imps */
1441 while (nonNull(ds)) {
1443 if (cellIsMember(hd(ds),imps)) {
1451 imps = itbscc(imps); /* Dependency analysis on imps */
1452 for (bs=imps; nonNull(bs); bs=tl(bs))
1453 for (bs1=hd(bs); nonNull(bs1); bs1=tl(bs1))
1454 fst(snd(hd(bs1))) = NIL; /* reset imps type fields */
1456 #ifdef DEBUG_DEPENDS
1457 Printf("Binding group:");
1458 for (bs1=imps; nonNull(bs1); bs1=tl(bs1)) {
1460 for (bs=hd(bs1); nonNull(bs); bs=tl(bs))
1461 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1464 if (nonNull(exps)) {
1466 for (bs=exps; nonNull(bs); bs=tl(bs))
1467 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1473 /* ----------------------------------------------------------------------
1474 * STEP 2: Add type assumptions about any explicitly typed variable.
1475 * --------------------------------------------------------------------*/
1477 for (bs=exps; nonNull(bs); bs=tl(bs)) {
1478 fst(snd(hd(bs))) = localizeBtyvs(fst(snd(hd(bs))));
1479 hd(varsBounds) = cons(pair(fst(hd(bs)),fst(snd(hd(bs)))),
1483 /* ----------------------------------------------------------------------
1484 * STEP 3: Calculate types for each group of implicitly typed bindings.
1485 * --------------------------------------------------------------------*/
1487 for (; nonNull(imps); imps=tl(imps)) {
1488 Cell b = hd(hd(imps));
1489 Int line = isVar(fst(b)) ? rhsLine(snd(hd(snd(snd(b)))))
1490 : rhsLine(snd(snd(snd(b))));
1491 hd(defnBounds) = NIL;
1493 for (bs1=hd(imps); nonNull(bs1); bs1=tl(bs1))
1494 newDefnBind(fst(hd(bs1)),NIL);
1497 mapProc(typeBind,hd(imps));
1500 mapProc(markAssumList,tl(defnBounds));
1501 mapProc(markAssumList,tl(varsBounds));
1502 mapProc(markPred,savePreds);
1506 savePreds = elimOuterPreds(savePreds);
1507 if (nonNull(preds) && resolveDefs(genvarAllAss(hd(defnBounds)))) {
1508 savePreds = elimOuterPreds(savePreds);
1511 map1Proc(genBind,preds,hd(imps));
1512 if (nonNull(preds)) {
1513 map1Proc(addEvidParams,preds,hd(depends));
1514 map1Proc(qualifyBinding,preds,hd(imps));
1517 h98CheckType(line,"inferred type",
1518 fst(hd(hd(defnBounds))),snd(hd(hd(defnBounds))));
1519 hd(varsBounds) = revOnto(hd(defnBounds),hd(varsBounds));
1522 /* ----------------------------------------------------------------------
1523 * STEP 4: Now infer a type for each explicitly typed variable and
1524 * check for compatibility with the declared type.
1525 * --------------------------------------------------------------------*/
1527 for (; nonNull(exps); exps=tl(exps)) {
1528 static String extbind = "explicitly typed binding";
1530 List alts = snd(snd(b));
1531 Int line = rhsLine(snd(hd(alts)));
1537 hd(defnBounds) = NIL;
1538 hd(depends) = NODEPENDS;
1541 instantiate(fst(snd(b)));
1544 t = dropRank2(typeIs,o,m);
1545 ps = makePredAss(predsAre,o);
1547 enterPendingBtyvs();
1548 for (; nonNull(alts); alts=tl(alts))
1549 typeAlt(extbind,fst(b),hd(alts),t,o,m);
1550 leavePendingBtyvs();
1552 if (nonNull(ps)) /* Add dict params, if necessary */
1553 qualifyBinding(ps,b);
1556 mapProc(markAssumList,tl(defnBounds));
1557 mapProc(markAssumList,tl(varsBounds));
1558 mapProc(markPred,savePreds);
1561 savePreds = elimPredsUsing(ps,savePreds);
1562 if (nonNull(preds)) {
1566 vs = cons(mkInt(o+i),vs);
1567 if (resolveDefs(vs))
1568 savePreds = elimPredsUsing(ps,savePreds);
1569 if (nonNull(preds)) {
1572 if (nonNull(preds) && resolveDefs(vs))
1573 savePreds = elimPredsUsing(ps,savePreds);
1577 resetGenerics(); /* Make sure we're general enough */
1579 t = generalize(ps,liftRank2(t,o,m));
1581 if (!sameSchemes(t,fst(snd(b))))
1582 tooGeneral(line,fst(b),fst(snd(b)),t);
1583 h98CheckType(line,"inferred type",fst(b),t);
1585 if (nonNull(preds)) /* Check context was strong enough */
1586 cantEstablish(line,extbind,fst(b),t,ps);
1589 preds = savePreds; /* Restore predicates */
1590 hd(defnBounds) = NIL;
1593 #define SCC itbscc /* scc for implicitly typed binds */
1594 #define LOWLINK itblowlink
1595 #define DEPENDS(t) fst(snd(t))
1596 #define SETDEPENDS(c,v) fst(snd(c))=v
1603 static Void local addEvidParams(qs,v) /* overwrite VARID/OPCELL v with */
1604 List qs; /* application of variable to evid. */
1605 Cell v; { /* parameters given by qs */
1610 internal("addEvidParams");
1612 for (nv=mkVar(textOf(v)); nonNull(tl(qs)); qs=tl(qs))
1613 nv = ap(nv,thd3(hd(qs)));
1615 snd(v) = thd3(hd(qs));
1619 /* --------------------------------------------------------------------------
1620 * Type check bodies of class and instance declarations:
1621 * ------------------------------------------------------------------------*/
1623 static Void local typeClassDefn(c) /* Type check implementations of */
1624 Class c; { /* defaults for class c */
1626 /* ----------------------------------------------------------------------
1627 * Generate code for default dictionary builder function:
1629 * class.C sc1 ... scn d = let v1 ... = ...
1631 * in Make.C sc1 ... scn v1 ... vm
1633 * where sci are superclass dictionary parameters, vj are implementations
1634 * for member functions, either taken from defaults, or using "error" to
1635 * produce a suitable error message. (Additional line number values must
1636 * be added at appropriate places but, for clarity, these are not shown
1638 * --------------------------------------------------------------------*/
1640 Int beta = newKindedVars(cclass(c).kinds);
1641 List params = makePredAss(cclass(c).supers,beta);
1642 Cell body = cclass(c).dcon;
1644 List mems = cclass(c).members;
1645 List defs = cclass(c).defaults;
1646 List dsels = cclass(c).dsels;
1647 Cell d = inventDictVar();
1650 Cell l = mkInt(cclass(c).line);
1653 for (ps=params; nonNull(ps); ps=tl(ps)) {
1654 Cell v = thd3(hd(ps));
1656 pat = ap(pat,inventVar());
1657 args = cons(v,args);
1659 args = revOnto(args,singleton(d));
1660 params = appendOnto(params,
1661 singleton(triple(cclass(c).head,mkInt(beta),d)));
1663 for (; nonNull(mems); mems=tl(mems)) {
1664 Cell v = inventVar(); /* Pick a name for component */
1667 if (nonNull(defs)) { /* Look for default implementation */
1672 if (isNull(imp)) { /* Generate undefined member msg */
1673 static String header = "Undefined member: ";
1674 String name = textToStr(name(hd(mems)).text);
1675 char msg[FILENAME_MAX+1];
1679 for (i=0; i<FILENAME_MAX && header[i]!='\0'; i++)
1681 for (j=0; (i+j)<FILENAME_MAX && name[j]!='\0'; j++)
1685 imp = pair(v,singleton(pair(NIL,ap(l,ap(nameError,
1686 mkStr(findText(msg)))))));
1688 else { /* Use default implementation */
1690 typeMember("default member binding",
1698 locs = cons(imp,locs);
1704 body = ap(LETREC,pair(singleton(locs),body));
1705 name(cclass(c).dbuild).defn
1706 = singleton(pair(args,body));
1708 name(cclass(c).dbuild).inlineMe = TRUE;
1709 genDefns = cons(cclass(c).dbuild,genDefns);
1710 cclass(c).defaults = NIL;
1712 /* ----------------------------------------------------------------------
1713 * Generate code for superclass and member function selectors:
1714 * --------------------------------------------------------------------*/
1716 args = getArgs(pat);
1717 pat = singleton(pat);
1718 for (; nonNull(dsels); dsels=tl(dsels)) {
1719 name(hd(dsels)).defn = singleton(pair(pat,ap(l,hd(args))));
1720 name(hd(dsels)).inlineMe = TRUE;
1722 genDefns = cons(hd(dsels),genDefns);
1724 for (mems=cclass(c).members; nonNull(mems); mems=tl(mems)) {
1725 name(hd(mems)).defn = singleton(pair(pat,ap(mkInt(name(hd(mems)).line),
1728 genDefns = cons(hd(mems),genDefns);
1732 static Void local typeInstDefn(in) /* Type check implementations of */
1733 Inst in; { /* member functions for instance in*/
1735 /* ----------------------------------------------------------------------
1736 * Generate code for instance specific dictionary builder function:
1738 * inst.maker d1 ... dn = let sc1 = ...
1743 * d = f (class.C sc1 ... scm d)
1744 * omit if the / f (Make.C sc1' ... scm' v1' ... vk')
1745 * instance decl { = let vj ... = ...
1746 * has no imps \ in Make.C sc1' ... scm' ... vj ...
1749 * where sci are superclass dictionaries, d and f are new names, vj
1750 * is a newly generated name corresponding to the implementation of a
1751 * member function. (Additional line number values must be added at
1752 * appropriate places but, for clarity, these are not shown above.)
1753 * --------------------------------------------------------------------*/
1755 Int alpha = newKindedVars(cclass(inst(in).c).kinds);
1756 List supers = makePredAss(cclass(inst(in).c).supers,alpha);
1757 Int beta = newKindedVars(inst(in).kinds);
1758 List params = makePredAss(inst(in).specifics,beta);
1759 Cell d = inventDictVar();
1760 List evids = cons(triple(inst(in).head,mkInt(beta),d),
1761 appendOnto(dupList(params),supers));
1763 List imps = inst(in).implements;
1764 Cell l = mkInt(inst(in).line);
1765 Cell dictDef = cclass(inst(in).c).dbuild;
1770 if (!unifyPred(cclass(inst(in).c).head,alpha,inst(in).head,beta))
1771 internal("typeInstDefn");
1773 for (ps=params; nonNull(ps); ps=tl(ps)) /* Build arglist */
1774 args = cons(thd3(hd(ps)),args);
1777 for (ps=supers; nonNull(ps); ps=tl(ps)) { /* Superclass dictionaries */
1779 Cell ev = scEntail(params,fst3(pi),intOf(snd3(pi)),0);
1781 ev = inEntail(evids,fst3(pi),intOf(snd3(pi)),0);
1784 ERRMSG(inst(in).line) "Cannot build superclass instance" ETHEN
1785 ERRTEXT "\n*** Instance : " ETHEN
1786 ERRPRED(copyPred(inst(in).head,beta));
1787 ERRTEXT "\n*** Context supplied : " ETHEN
1788 ERRCONTEXT(copyPreds(params));
1789 ERRTEXT "\n*** Required superclass : " ETHEN
1790 ERRPRED(copyPred(fst3(pi),intOf(snd3(pi))));
1794 locs = cons(pair(thd3(pi),singleton(pair(NIL,ap(l,ev)))),locs);
1795 dictDef = ap(dictDef,thd3(pi));
1797 dictDef = ap(dictDef,d);
1799 if (isNull(imps)) /* No implementations */
1800 locs = cons(pair(d,singleton(pair(NIL,ap(l,dictDef)))),locs);
1801 else { /* Implementations supplied*/
1802 List mems = cclass(inst(in).c).members;
1803 Cell f = inventVar();
1804 Cell pat = cclass(inst(in).c).dcon;
1808 locs = cons(pair(d,singleton(pair(NIL,ap(l,ap(f,dictDef))))),
1811 for (ps=supers; nonNull(ps); ps=tl(ps)){/* Add param for each sc */
1812 Cell v = inventVar();
1817 for (; nonNull(mems); mems=tl(mems)) { /* For each member: */
1818 Cell v = inventVar();
1821 if (nonNull(imps)) { /* Look for implementation */
1826 if (isNull(imp)) { /* If none, f will copy */
1827 pat = ap(pat,v); /* its argument unchanged */
1830 else { /* Otherwise, add the impl */
1831 pat = ap(pat,WILDCARD); /* to f as a local defn */
1833 typeMember("instance member binding",
1839 locs1 = cons(pair(v,snd(imp)),locs1);
1843 if (nonNull(locs1)) /* Build the body of f */
1844 res = ap(LETREC,pair(singleton(locs1),res));
1845 pat = singleton(pat); /* And the arglist for f */
1846 locs = cons(pair(f,singleton(pair(pat,res))),locs);
1850 name(inst(in).builder).defn /* Register builder imp */
1851 = singleton(pair(args,ap(LETREC,pair(singleton(locs),d))));
1853 name(inst(in).builder).inlineMe = TRUE;
1854 name(inst(in).builder).isDBuilder = TRUE;
1855 genDefns = cons(inst(in).builder,genDefns);
1858 static Void local typeMember(wh,mem,alts,evids,head,beta)
1859 String wh; /* Type check alternatives alts of */
1860 Name mem; /* member mem for inst type head */
1861 Cell alts; /* at offset beta using predicate */
1862 List evids; /* assignment evids */
1865 Int line = rhsLine(snd(hd(alts)));
1874 Printf("\nType check member: ");
1875 printExp(stdout,mem);
1877 printType(stdout,name(mem).type);
1878 Printf("\n for the instance: ");
1879 printPred(stdout,head);
1883 instantiate(name(mem).type); /* Find required type */
1886 t = dropRank2(typeIs,o,m);
1887 ps = makePredAss(predsAre,o);
1888 if (!unifyPred(hd(predsAre),typeOff,head,beta))
1889 internal("typeMember1");
1892 rt = generalize(qs,liftRank2(t,o,m));
1895 Printf("Required type is: ");
1896 printType(stdout,rt);
1900 hd(defnBounds) = NIL; /* Type check each alternative */
1901 hd(depends) = NODEPENDS;
1902 enterPendingBtyvs();
1903 for (preds=NIL; nonNull(alts); alts=tl(alts)) {
1904 typeAlt(wh,mem,hd(alts),t,o,m);
1905 qualify(tl(ps),hd(alts)); /* Add any extra dict params */
1907 leavePendingBtyvs();
1909 evids = appendOnto(dupList(tl(ps)), /* Build full complement of dicts */
1912 qs = elimPredsUsing(evids,NIL);
1913 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
1914 qs = elimPredsUsing(evids,qs);
1917 "Implementation of %s requires extra context",
1918 textToStr(name(mem).text) ETHEN
1919 ERRTEXT "\n*** Expected type : " ETHEN ERRTYPE(rt);
1920 ERRTEXT "\n*** Missing context : " ETHEN ERRCONTEXT(copyPreds(qs));
1925 resetGenerics(); /* Make sure we're general enough */
1927 t = generalize(ps,liftRank2(t,o,m));
1929 Printf(" Inferred type is: ");
1930 printType(stdout,t);
1933 if (!sameSchemes(t,rt))
1934 tooGeneral(line,mem,rt,t);
1936 cantEstablish(line,wh,mem,t,ps);
1939 /* --------------------------------------------------------------------------
1940 * Type check bodies of bindings:
1941 * ------------------------------------------------------------------------*/
1943 static Void local typeBind(b) /* Type check binding */
1945 if (isVar(fst(b))) { /* function binding */
1946 Cell ass = findTopBinding(fst(b));
1950 internal("typeBind");
1952 beta = intOf(defType(snd(ass)));
1953 enterPendingBtyvs();
1954 map2Proc(typeDefAlt,beta,fst(b),snd(snd(b)));
1955 leavePendingBtyvs();
1957 else { /* pattern binding */
1958 static String lhsPat = "lhs pattern";
1959 static String rhs = "right hand side";
1960 Int beta = newTyvars(1);
1961 Pair pb = snd(snd(b));
1962 Int l = rhsLine(snd(pb));
1964 tcMode = OLD_PATTERN;
1965 enterPendingBtyvs();
1966 fst(pb) = patBtyvs(fst(pb));
1967 check(l,fst(pb),NIL,lhsPat,aVar,beta);
1968 tcMode = EXPRESSION;
1969 snd(pb) = typeRhs(snd(pb));
1970 shouldBe(l,rhsExpr(snd(pb)),NIL,rhs,aVar,beta);
1972 leavePendingBtyvs();
1976 static Void local typeDefAlt(beta,v,a) /* type check alt in func. binding */
1980 static String valDef = "function binding";
1981 typeAlt(valDef,v,a,aVar,beta,0);
1984 static Cell local typeRhs(e) /* check type of rhs of definition */
1986 switch (whatIs(e)) {
1987 case GUARDED : { Int beta = newTyvars(1);
1988 map1Proc(guardedType,beta,snd(e));
1993 case LETREC : enterBindings();
1995 mapProc(typeBindings,fst(snd(e)));
1996 snd(snd(e)) = typeRhs(snd(snd(e)));
1998 leaveSkolVars(rhsLine(snd(snd(e))),typeIs,typeOff,0);
2001 case RSIGN : fst(snd(e)) = typeRhs(fst(snd(e)));
2002 shouldBe(rhsLine(fst(snd(e))),
2003 rhsExpr(fst(snd(e))),NIL,
2008 default : snd(e) = typeExpr(intOf(fst(e)),snd(e));
2014 static Void local guardedType(beta,gded)/* check type of guard (li,(gd,ex))*/
2015 Int beta; /* should have gd :: Bool, */
2016 Cell gded; { /* ex :: (var,beta) */
2017 static String guarded = "guarded expression";
2018 static String guard = "guard";
2019 Int line = intOf(fst(gded));
2022 check(line,fst(gded),NIL,guard,typeBool,0);
2023 check(line,snd(gded),NIL,guarded,aVar,beta);
2026 Cell rhsExpr(rhs) /* find first expression on a rhs */
2028 switch (whatIs(rhs)) {
2029 case GUARDED : return snd(snd(hd(snd(rhs))));
2030 case LETREC : return rhsExpr(snd(snd(rhs)));
2031 case RSIGN : return rhsExpr(fst(snd(rhs)));
2032 default : return snd(rhs);
2036 Int rhsLine(rhs) /* find line number associated with */
2037 Cell rhs; { /* a right hand side */
2038 switch (whatIs(rhs)) {
2039 case GUARDED : return intOf(fst(hd(snd(rhs))));
2040 case LETREC : return rhsLine(snd(snd(rhs)));
2041 case RSIGN : return rhsLine(fst(snd(rhs)));
2042 default : return intOf(fst(rhs));
2046 /* --------------------------------------------------------------------------
2047 * Calculate generalization of types and compare with declared type schemes:
2048 * ------------------------------------------------------------------------*/
2050 static Void local genBind(ps,b) /* Generalize the type of each var */
2051 List ps; /* defined in binding b, qualifying*/
2052 Cell b; { /* each with the predicates in ps. */
2054 Cell t = fst(snd(b));
2057 genAss(rhsLine(snd(hd(snd(snd(b))))),ps,v,t);
2059 Int line = rhsLine(snd(snd(snd(b))));
2060 for (; nonNull(v); v=tl(v)) {
2066 genAss(line,ps,hd(v),ty);
2071 static Void local genAss(l,ps,v,dt) /* Calculate inferred type of v and*/
2072 Int l; /* compare with declared type, dt, */
2073 List ps; /* if given & check for ambiguity. */
2076 Cell ass = findTopBinding(v);
2081 snd(ass) = genTest(l,v,ps,dt,aVar,intOf(defType(snd(ass))));
2086 printType(stdout,snd(ass));
2091 static Type local genTest(l,v,ps,dt,t,o)/* Generalize and test inferred */
2092 Int l; /* type (t,o) with context ps */
2093 Cell v; /* against declared type dt for v. */
2098 Type bt = NIL; /* Body of inferred type */
2099 Type it = NIL; /* Full inferred type */
2101 resetGenerics(); /* Calculate Haskell typing */
2104 it = generalize(ps,bt);
2106 if (nonNull(dt)) { /* If a declared type was given, */
2107 instantiate(dt); /* check body for match. */
2108 if (!equalTypes(typeIs,bt))
2109 tooGeneral(l,v,dt,it);
2111 else if (nonNull(ps)) /* Otherwise test for ambiguity in */
2112 if (isAmbiguous(it)) /* inferred type. */
2113 ambigError(l,"inferred type",v,it);
2118 static Type local generalize(qs,t) /* calculate generalization of t */
2119 List qs; /* having already marked fixed vars*/
2120 Type t; { /* with qualifying preds qs */
2122 t = ap(QUAL,pair(qs,t));
2123 if (nonNull(genericVars)) {
2125 List vs = genericVars;
2126 for (; nonNull(vs); vs=tl(vs)) {
2127 Tyvar *tyv = tyvar(intOf(hd(vs)));
2128 Kind ka = tyv->kind;
2131 t = mkPolyType(k,t);
2133 Printf("Generalized type: ");
2134 printType(stdout,t);
2136 printKind(stdout,k);
2143 static Bool local equalTypes(t1,t2) /* Compare simple types for equality*/
2146 et: if (whatIs(t1)!=whatIs(t2))
2149 switch (whatIs(t1)) {
2155 case TUPLE : return t1==t2;
2157 case INTCELL : return intOf(t1)!=intOf(t2);
2159 case AP : if (equalTypes(fun(t1),fun(t2))) {
2166 default : internal("equalTypes");
2169 return TRUE;/*NOTREACHED*/
2172 /* --------------------------------------------------------------------------
2173 * Entry points to type checker:
2174 * ------------------------------------------------------------------------*/
2176 Type typeCheckExp(useDefs) /* Type check top level expression */
2177 Bool useDefs; { /* using defaults if reqd */
2183 emptySubstitution();
2185 inputExpr = typeExpr(0,inputExpr);
2191 preds = scSimplify(preds);
2192 if (useDefs && nonNull(preds)) {
2195 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
2199 ctxt = copyPreds(preds);
2200 type = generalize(ctxt,copyType(type,beta));
2201 inputExpr = qualifyExpr(0,preds,inputExpr);
2202 h98CheckType(0,"inferred type",inputExpr,type);
2204 emptySubstitution();
2208 Void typeCheckDefns() { /* Type check top level bindings */
2209 Target t = length(selDefns) + length(valDefns) +
2210 length(instDefns) + length(classDefns);
2215 emptySubstitution();
2218 setGoal("Type checking",t);
2220 for (gs=selDefns; nonNull(gs); gs=tl(gs)) {
2221 mapOver(typeSel,hd(gs));
2224 for (gs=valDefns; nonNull(gs); gs=tl(gs)) {
2225 typeDefnGroup(hd(gs));
2229 for (gs=classDefns; nonNull(gs); gs=tl(gs)) {
2230 emptySubstitution();
2231 typeClassDefn(hd(gs));
2234 for (gs=instDefns; nonNull(gs); gs=tl(gs)) {
2235 emptySubstitution();
2236 typeInstDefn(hd(gs));
2241 emptySubstitution();
2245 static Void local typeDefnGroup(bs) /* type check group of value defns */
2246 List bs; { /* (one top level scc) */
2249 emptySubstitution();
2250 hd(defnBounds) = NIL;
2253 typeBindings(bs); /* find types for vars in bindings */
2255 if (nonNull(preds)) {
2256 Cell v = fst(hd(hd(varsBounds)));
2257 Name n = findName(textOf(v));
2258 Int l = nonNull(n) ? name(n).line : 0;
2259 preds = scSimplify(preds);
2260 ERRMSG(l) "Instance%s of ", (length(preds)==1 ? "" : "s") ETHEN
2261 ERRCONTEXT(copyPreds(preds));
2262 ERRTEXT " required for definition of " ETHEN
2263 ERREXPR(nonNull(n)?n:v);
2268 if (nonNull(hd(skolVars))) {
2270 Name n = findName(isVar(fst(b)) ? textOf(fst(b)) : textOf(hd(fst(b))));
2271 Int l = nonNull(n) ? name(n).line : 0;
2272 leaveSkolVars(l,typeUnit,0,0);
2276 for (as=hd(varsBounds); nonNull(as); as=tl(as)) {
2277 Cell a = hd(as); /* add infered types to environment*/
2278 Name n = findName(textOf(fst(a)));
2280 internal("typeDefnGroup");
2281 name(n).type = snd(a);
2283 hd(varsBounds) = NIL;
2286 static Pair local typeSel(s) /* Calculate a suitable type for a */
2287 Name s; { /* particular selector, s. */
2288 List cns = name(s).defn;
2289 Int line = name(s).line;
2290 Type dom = NIL; /* Inferred domain */
2291 Type rng = NIL; /* Inferred range */
2292 Cell nv = inventVar();
2298 Printf("Selector %s, cns=",textToStr(name(s).text));
2299 printExp(stdout,cns);
2303 emptySubstitution();
2306 for (; nonNull(cns); cns=tl(cns)) {
2307 Name c = fst(hd(cns));
2308 Int n = intOf(snd(hd(cns)));
2309 Int a = name(c).arity;
2316 instantiate(name(c).type); /* Instantiate constructor type */
2319 for (; nonNull(predsAre); predsAre=tl(predsAre))
2320 assumeEvid(hd(predsAre),o1);
2322 if (whatIs(typeIs)==RANK2) /* Skip rank2 annotation, if any */
2323 typeIs = snd(snd(typeIs));
2324 for (; --n>0; a--) { /* Get range */
2325 pat = ap(pat,WILDCARD);
2326 typeIs = arg(typeIs);
2328 rng1 = dropRank1(arg(fun(typeIs)),o1,m1);
2330 typeIs = arg(typeIs);
2331 while (--a>0) { /* And then look for domain */
2332 pat = ap(pat,WILDCARD);
2333 typeIs = arg(typeIs);
2337 if (isNull(dom)) { /* Save first domain type and then */
2338 dom = dom1; /* unify with subsequent domains to*/
2339 o = o1; /* match up preds and range types */
2342 else if (!unify(dom1,o1,dom,o))
2343 internal("typeSel1");
2345 if (isNull(rng)) /* Compare component types */
2347 else if (!sameSchemes(rng1,rng)) {
2349 rng = liftRank1(rng,o,m);
2350 rng1 = liftRank1(rng1,o1,m1);
2351 ERRMSG(name(s).line) "Mismatch in field types for selector \"%s\"",
2352 textToStr(name(s).text) ETHEN
2353 ERRTEXT "\n*** Field type : " ETHEN ERRTYPE(rng1);
2354 ERRTEXT "\n*** Does not match : " ETHEN ERRTYPE(rng);
2358 alts = cons(pair(singleton(pat),pair(mkInt(line),nv)),alts);
2362 if (isNull(dom) || isNull(rng)) /* Should have been initialized by */
2363 internal("typeSel2"); /* now, assuming length cns >= 1. */
2365 clearMarks(); /* No fixed variables here */
2366 preds = scSimplify(preds); /* Simplify context */
2367 dom = copyType(dom,o); /* Calculate domain type */
2369 rng = copyType(typeIs,typeOff);
2370 if (nonNull(predsAre)) {
2371 List ps = makePredAss(predsAre,typeOff);
2373 for (; nonNull(alts1); alts1=tl(alts1)) {
2376 for (; nonNull(qs); qs=tl(qs))
2377 body = ap(body,thd3(hd(qs)));
2378 snd(snd(hd(alts1))) = body;
2380 preds = appendOnto(preds,ps);
2382 name(s).type = generalize(copyPreds(preds),fn(dom,rng));
2383 name(s).arity = 1 + length(preds);
2384 map1Proc(qualify,preds,alts);
2387 Printf("Inferred arity = %d, type = ",name(s).arity);
2388 printType(stdout,name(s).type);
2392 return pair(s,alts);
2396 /* --------------------------------------------------------------------------
2397 * Local function prototypes:
2398 * ------------------------------------------------------------------------*/
2400 static Type local basicType Args((Char));
2403 static Type stateVar = NIL;
2404 static Type alphaVar = NIL;
2405 static Type betaVar = NIL;
2406 static Type gammaVar = NIL;
2407 static Int nextVar = 0;
2409 static Void clearTyVars( void )
2418 static Type mkStateVar( void )
2420 if (isNull(stateVar)) {
2421 stateVar = mkOffset(nextVar++);
2426 static Type mkAlphaVar( void )
2428 if (isNull(alphaVar)) {
2429 alphaVar = mkOffset(nextVar++);
2434 static Type mkBetaVar( void )
2436 if (isNull(betaVar)) {
2437 betaVar = mkOffset(nextVar++);
2442 static Type mkGammaVar( void )
2444 if (isNull(gammaVar)) {
2445 gammaVar = mkOffset(nextVar++);
2450 static Type local basicType(k)
2467 case ARR_REP: return ap(typePrimArray,mkAlphaVar());
2468 case BARR_REP: return typePrimByteArray;
2469 case REF_REP: return ap2(typeRef,mkStateVar(),mkAlphaVar());
2470 case MUTARR_REP: return ap2(typePrimMutableArray,mkStateVar(),mkAlphaVar());
2471 case MUTBARR_REP: return ap(typePrimMutableByteArray,mkStateVar());
2472 #ifdef PROVIDE_STABLE
2474 return ap(typeStable,mkAlphaVar());
2478 return ap(typeWeak,mkAlphaVar());
2480 return ap(typeIO,typeUnit);
2482 #ifdef PROVIDE_FOREIGN
2486 #ifdef PROVIDE_CONCURRENT
2488 return typeThreadId;
2490 return ap(typeMVar,mkAlphaVar());
2495 return fn(typeException,mkAlphaVar());
2497 return typeException;
2499 return mkAlphaVar(); /* polymorphic */
2501 return mkBetaVar(); /* polymorphic */
2503 return mkGammaVar(); /* polymorphic */
2505 printf("Kind: '%c'\n",k);
2506 internal("basicType");
2508 assert(0); return 0; /* NOTREACHED */
2511 /* Generate type of primop based on list of arg types and result types:
2513 * eg primType "II" "II" = Int -> Int -> (Int,Int)
2516 Type primType( Int /*AsmMonad*/ monad, String a_kinds, String r_kinds )
2520 List tvars = NIL; /* for polymorphic types */
2525 /* build result types */
2526 for(; *r_kinds; ++r_kinds) {
2527 rs = cons(basicType(*r_kinds),rs);
2529 /* Construct tuple of results */
2530 if (length(rs) == 0) {
2532 } else if (length(rs) == 1) {
2535 r = mkTuple(length(rs));
2536 for(rs = rev(rs); nonNull(rs); rs=tl(rs)) {
2540 /* Construct list of arguments */
2541 for(; *a_kinds; ++a_kinds) {
2542 as = cons(basicType(*a_kinds),as);
2544 /* Apply any monad magic */
2545 if (monad == MONAD_IO) {
2547 } else if (monad == MONAD_ST) {
2548 r = ap2(typeST,mkStateVar(),r);
2550 /* glue it all together */
2551 for(; nonNull(as); as=tl(as)) {
2554 tvars = offsetTyvarsIn(r,NIL);
2555 if (nonNull(tvars)) {
2556 assert(length(tvars) == nextVar);
2557 r = mkPolyType(simpleKind(length(tvars)),r);
2561 printType(stdout,r); printf("\n");
2567 /* forall a1 .. am. TC a1 ... am -> Int */
2568 Type conToTagType(t)
2573 for (i=0; i<tycon(t).arity; ++i) {
2574 Offset tv = mkOffset(i);
2576 tvars = cons(tv,tvars);
2578 ty = fn(ty,typeInt);
2579 if (nonNull(tvars)) {
2580 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2585 /* forall a1 .. am. Int -> TC a1 ... am */
2586 Type tagToConType(t)
2591 for (i=0; i<tycon(t).arity; ++i) {
2592 Offset tv = mkOffset(i);
2594 tvars = cons(tv,tvars);
2596 ty = fn(typeInt,ty);
2597 if (nonNull(tvars)) {
2598 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2603 /* --------------------------------------------------------------------------
2604 * Type checker control:
2605 * ------------------------------------------------------------------------*/
2607 Void typeChecker(what)
2610 case RESET : tcMode = EXPRESSION;
2617 case MARK : mark(daSccs);
2633 mark(predFractional);
2639 case INSTALL : typeChecker(RESET);
2640 dummyVar = inventVar();
2642 setCurrModule(modulePrelude);
2644 starToStar = simpleKind(1);
2646 typeUnit = addPrimTycon(findText("()"),
2647 STAR,0,DATATYPE,NIL);
2648 typeArrow = addPrimTycon(findText("(->)"),
2651 typeList = addPrimTycon(findText("[]"),
2655 arrow = fn(aVar,bVar);
2656 listof = ap(typeList,aVar);
2657 boundPair = ap(ap(mkTuple(2),aVar),aVar);
2659 nameUnit = addPrimCfun(findText("()"),0,0,typeUnit);
2660 tycon(typeUnit).defn
2661 = singleton(nameUnit);
2663 nameNil = addPrimCfun(findText("[]"),0,1,
2664 mkPolyType(starToStar,
2666 nameCons = addPrimCfun(findText(":"),2,2,
2667 mkPolyType(starToStar,
2671 name(nameNil).parent =
2672 name(nameCons).parent = typeList;
2674 name(nameCons).syntax
2675 = mkSyntax(RIGHT_ASS,5);
2677 tycon(typeList).defn
2678 = cons(nameNil,cons(nameCons,NIL));
2680 typeVarToVar = fn(aVar,aVar);
2682 typeNoRow = addPrimTycon(findText("EmptyRow"),
2683 ROW,0,DATATYPE,NIL);
2684 typeRec = addPrimTycon(findText("Rec"),
2687 nameNoRec = addPrimCfun(findText("EmptyRec"),0,0,
2688 ap(typeRec,typeNoRow));
2690 /* bogus definitions to avoid changing the prelude */
2691 addPrimCfun(findText("Rec"), 0,0,typeUnit);
2692 addPrimCfun(findText("EmptyRow"), 0,0,typeUnit);
2693 addPrimCfun(findText("EmptyRec"), 0,0,typeUnit);
2699 /*-------------------------------------------------------------------------*/