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/04/27 10:07:09 $
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. */
731 case NAME : typeIs = name(h).type;
735 case VARIDCELL : if (tcMode==NEW_PATTERN) {
736 inferType(aVar,newVarsBind(e));
739 Cell v = findAssum(textOf(h));
742 typeIs = (tcMode==OLD_PATTERN)
747 h = findName(textOf(h));
750 typeIs = name(h).type;
755 default : h = typeExpr(l,h);
759 if (isNull(typeIs)) {
760 //printf("\n NAME " );
762 //printf(" TYPE " ); print(typeIs,1000);
766 instantiate(typeIs); /* Deal with polymorphism ... */
767 if (nonNull(predsAre)) { /* ... and with qualified types. */
769 for (; nonNull(predsAre); predsAre=tl(predsAre)) {
770 evs = cons(assumeEvid(hd(predsAre),typeOff),evs);
772 if (!isName(h) || !isCfun(h)) {
773 h = applyToArgs(h,rev(evs));
777 if (whatIs(typeIs)==CDICTS) { /* Deal with local dictionaries */
778 List evs = makePredAss(fst(snd(typeIs)),typeOff);
780 typeIs = snd(snd(typeIs));
781 for (; nonNull(ps); ps=tl(ps)) {
782 h = ap(h,thd3(hd(ps)));
784 if (tcMode==EXPRESSION) {
785 preds = revOnto(evs,preds);
787 hd(localEvs) = revOnto(evs,hd(localEvs));
791 if (whatIs(typeIs)==EXIST) { /* Deal with existential arguments */
792 Int n = intOf(fst(snd(typeIs)));
793 typeIs = snd(snd(typeIs));
794 if (!isCfun(getHead(h)) || n>typeFree) {
796 } else if (tcMode!=EXPRESSION) {
797 Int alpha = typeOff + typeFree;
799 bindTv(alpha-n,SKOLEM,0);
800 hd(skolVars) = cons(pair(mkInt(alpha-n),e),hd(skolVars));
805 if (whatIs(typeIs)==RANK2) { /* Deal with rank 2 arguments */
808 Int nr2 = intOf(fst(snd(typeIs)));
809 Type body = snd(snd(typeIs));
813 if (n<nr2) { /* Must have enough arguments */
814 ERRMSG(l) "Use of " ETHEN ERREXPR(h);
816 ERRTEXT " in " ETHEN ERREXPR(e);
818 ERRTEXT " requires at least %d argument%s\n",
819 nr2, (nr2==1 ? "" : "s")
823 for (i=nr2; i<n; ++i) /* Find rank two arguments */
826 for (as=getArgs(as); nonNull(as); as=tl(as), body=arg(body)) {
827 Type expect = dropRank1(arg(fun(body)),alpha,m);
828 if (isPolyType(expect)) {
829 if (tcMode==EXPRESSION) /* poly/qual type in expr */
830 hd(as) = typeExpected(l,app,hd(as),expect,alpha,m,TRUE);
831 else if (hd(as)!=WILDCARD) { /* Pattern binding/match */
832 if (!isVar(hd(as))) {
833 ERRMSG(l) "Argument " ETHEN ERREXPR(arg(as));
834 ERRTEXT " in pattern " ETHEN ERREXPR(e);
835 ERRTEXT " where a variable is required\n"
838 if (tcMode==NEW_PATTERN) { /* Pattern match */
841 addVarAssump(dummyVar,mkInt(alpha+i));
844 addVarAssump(hd(as),expect);
846 else { /* Pattern binding */
847 Text t = textOf(hd(as));
848 Cell a = findInAssumList(t,hd(defnBounds));
852 if (nonNull(predsAre)) {
853 ERRMSG(l) "Cannot use pattern binding for " ETHEN
855 ERRTEXT " as a component with a qualified type\n"
858 shouldBe(l,hd(as),e,app,aVar,intOf(defType(snd(a))));
862 else { /* Not a poly/qual type */
863 check(l,hd(as),e,app,expect,alpha);
865 h = ap(h,hd(as)); /* Save checked argument */
867 inferType(body,alpha);
871 if (n>0) { /* Deal with remaining args */
872 Int beta = funcType(n); /* check h::t1->t2->...->tn->rn+1 */
873 shouldBe(l,h,e,app,aVar,beta);
874 for (i=n; i>0; --i) { /* check e_i::t_i for each i */
875 check(l,arg(a),e,app,aVar,beta+2*i-1);
879 tyvarType(beta+2*n); /* Inferred type is r_n+1 */
882 if (isNull(p)) /* Replace head with translation */
890 static Cell local typeExpected(l,wh,e,reqd,alpha,n,addEvid)
891 Int l; /* Type check expression e in wh */
892 String wh; /* at line l, expecting type reqd, */
893 Cell e; /* and treating vars alpha through */
894 Type reqd; /* (alpha+n-1) as fixed. */
897 Bool addEvid; { /* TRUE => add \ev -> ... */
898 List savePreds = preds;
909 ps = makePredAss(predsAre,o);
912 check(l,e,NIL,wh,t,o);
915 mapProc(markAssumList,defnBounds);
916 mapProc(markAssumList,varsBounds);
917 mapProc(markPred,savePreds);
923 savePreds = elimPredsUsing(ps,savePreds);
924 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
925 savePreds = elimPredsUsing(ps,savePreds);
926 if (nonNull(preds)) {
927 Type ty = copyType(t,o);
928 List qs = copyPreds(ps);
929 cantEstablish(l,wh,e,ty,qs);
934 if (copyTyvar(o+i)!=mkOffset(i)) {
935 List qs = copyPreds(ps);
936 Type it = copyType(t,o);
937 tooGeneral(l,e,reqd,generalize(qs,it));
941 e = qualifyExpr(l,ps,e);
945 preds = revOnto(ps,savePreds);
951 static Void local typeAlt(wh,e,a,t,o,m) /* Type check abstraction (Alt) */
952 String wh; /* a = ( [p1, ..., pn], rhs ) */
959 List ps = fst(a) = patBtyvs(fst(a));
961 Int l = rhsLine(snd(a));
968 if (whatIs(t)==RANK2) {
969 if (n<(nr2=intOf(fst(snd(t))))) {
970 ERRMSG(l) "Definition requires at least %d parameters on lhs",
977 while (getHead(t)==typeArrow && argCount==2 && nonNull(ps)) {
978 Type ta = arg(fun(t));
979 if (isPolyType(ta)) {
980 if (hd(ps)!=WILDCARD) {
981 if (!isVar(hd(ps))) {
982 ERRMSG(l) "Argument " ETHEN ERREXPR(hd(ps));
983 ERRTEXT " used where a variable or wildcard is required\n"
989 addVarAssump(dummyVar,mkInt(o+i));
992 addVarAssump(hd(ps),ta);
996 hd(ps) = typeFreshPat(l,hd(ps));
997 shouldBe(l,hd(ps),NIL,wh,ta,o);
1006 snd(a) = typeRhs(snd(a));
1008 Int beta = funcType(n);
1011 hd(ps) = typeFreshPat(l,hd(ps));
1012 bindTv(beta+2*i+1,typeIs,typeOff);
1015 snd(a) = typeRhs(snd(a));
1016 bindTv(beta+2*n,typeIs,typeOff);
1020 if (!unify(typeIs,typeOff,t,o)) {
1023 req = liftRank2(origt,o,m);
1024 liftRank2Args(as,o,m);
1025 got = ap(RANK2,pair(mkInt(nr2),revOnto(as,copyType(typeIs,typeOff))));
1026 reportTypeError(l,e,NIL,wh,got,req);
1031 leaveSkolVars(l,origt,o,m);
1034 static Int local funcType(n) /*return skeleton for function type*/
1035 Int n; { /*with n arguments, taking the form*/
1036 Int beta = newTyvars(2*n+1); /* r1 t1 r2 t2 ... rn tn rn+1 */
1037 Int i; /* with r_i := t_i -> r_i+1 */
1039 bindTv(beta+2*i,arrow,beta+2*i+1);
1043 static Void local typeCase(l,beta,c) /* type check case: pat -> rhs */
1044 Int l; /* (case given by c == (pat,rhs)) */
1045 Int beta; /* need: pat :: (var,beta) */
1046 Cell c; { /* rhs :: (var,beta+1) */
1047 static String casePat = "case pattern";
1048 static String caseExpr = "case expression";
1052 fst(c) = typeFreshPat(l,patBtyvs(fst(c)));
1053 shouldBe(l,fst(c),NIL,casePat,aVar,beta);
1054 snd(c) = typeRhs(snd(c));
1055 shouldBe(l,rhsExpr(snd(c)),NIL,caseExpr,aVar,beta+1);
1059 leaveSkolVars(l,typeIs,typeOff,0);
1062 static Void local typeComp(l,m,e,qs) /* type check comprehension */
1064 Type m; /* monad (mkOffset(0)) */
1067 static String boolQual = "boolean qualifier";
1068 static String genQual = "generator";
1070 if (isNull(qs)) /* no qualifiers left */
1071 fst(e) = typeExpr(l,fst(e));
1075 switch (whatIs(q)) {
1076 case BOOLQUAL : check(l,snd(q),NIL,boolQual,typeBool,0);
1077 typeComp(l,m,e,qs1);
1080 case QWHERE : enterBindings();
1082 mapProc(typeBindings,snd(q));
1083 typeComp(l,m,e,qs1);
1085 leaveSkolVars(l,typeIs,typeOff,0);
1088 case FROMQUAL : { Int beta = newTyvars(1);
1090 check(l,snd(snd(q)),NIL,genQual,m,beta);
1093 = typeFreshPat(l,patBtyvs(fst(snd(q))));
1094 shouldBe(l,fst(snd(q)),NIL,genQual,aVar,beta);
1095 typeComp(l,m,e,qs1);
1098 leaveSkolVars(l,typeIs,typeOff,0);
1102 case DOQUAL : check(l,snd(q),NIL,genQual,m,newTyvars(1));
1103 typeComp(l,m,e,qs1);
1109 static Cell local typeMonadComp(l,e) /* type check monad comprehension */
1112 Int alpha = newTyvars(1);
1113 Int beta = newTyvars(1);
1114 Cell mon = ap(mkInt(beta),aVar);
1115 Cell m = assumeEvid(predMonad,beta);
1116 tyvar(beta)->kind = starToStar;
1118 bindTv(beta,typeList,0);
1121 typeComp(l,mon,snd(e),snd(snd(e)));
1122 bindTv(alpha,typeIs,typeOff);
1123 inferType(mon,alpha);
1124 return ap(MONADCOMP,pair(m,snd(e)));
1127 static Void local typeDo(l,e) /* type check do-notation */
1130 static String finGen = "final generator";
1131 Int alpha = newTyvars(1);
1132 Int beta = newTyvars(1);
1133 Cell mon = ap(mkInt(beta),aVar);
1134 Cell m = assumeEvid(predMonad,beta);
1135 tyvar(beta)->kind = starToStar;
1137 typeComp(l,mon,snd(e),snd(snd(e)));
1138 shouldBe(l,fst(snd(e)),NIL,finGen,mon,alpha);
1139 snd(e) = pair(m,snd(e));
1142 static Void local typeConFlds(l,e) /* Type check a construction */
1145 static String conExpr = "value construction";
1146 Name c = fst(snd(e));
1147 List fs = snd(snd(e));
1153 instantiate(name(c).type);
1154 for (; nonNull(predsAre); predsAre=tl(predsAre))
1155 assumeEvid(hd(predsAre),typeOff);
1156 if (whatIs(typeIs)==RANK2)
1157 typeIs = snd(snd(typeIs));
1162 for (; nonNull(fs); fs=tl(fs)) {
1164 for (i=sfunPos(fst(hd(fs)),c); --i>0; t=arg(t))
1166 t = dropRank1(arg(fun(t)),to,tf);
1168 snd(hd(fs)) = typeExpected(l,conExpr,snd(hd(fs)),t,to,tf,TRUE);
1170 check(l,snd(hd(fs)),e,conExpr,t,to);
1173 for (i=name(c).arity; i>0; i--)
1178 static Void local typeUpdFlds(line,e) /* Type check an update */
1179 Int line; /* (Written in what might seem a */
1180 Cell e; { /* bizarre manner for the benefit */
1181 static String update = "update"; /* of as yet unreleased extensions)*/
1182 List cs = snd3(snd(e)); /* List of constructors */
1183 List fs = thd3(snd(e)); /* List of field specifications */
1184 List ts = NIL; /* List of types for fields */
1186 Int alpha = newTyvars(2+n);
1190 /* Calculate type and translation for each expr in the field list */
1191 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1192 snd(hd(fs1)) = typeExpr(line,snd(hd(fs1)));
1193 bindTv(i,typeIs,typeOff);
1197 mapProc(markAssumList,defnBounds);
1198 mapProc(markAssumList,varsBounds);
1199 mapProc(markPred,preds);
1202 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1204 ts = cons(generalize(NIL,copyTyvar(i)),ts);
1208 /* Type check expression to be updated */
1209 fst3(snd(e)) = typeExpr(line,fst3(snd(e)));
1210 bindTv(alpha,typeIs,typeOff);
1212 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constrs */
1214 List ta = replicate(name(c).arity,NIL);
1218 tcMode = NEW_PATTERN; /* Domain type */
1219 instantiate(name(c).type);
1220 tcMode = EXPRESSION;
1223 for (; nonNull(predsAre); predsAre=tl(predsAre))
1224 assumeEvid(hd(predsAre),typeOff);
1226 if (whatIs(typeIs)==RANK2) {
1227 ERRMSG(line) "Sorry, record update syntax cannot currently be "
1228 "used for datatypes with polymorphic components"
1232 instantiate(name(c).type); /* Range type */
1235 for (; nonNull(predsAre); predsAre=tl(predsAre))
1236 assumeEvid(hd(predsAre),typeOff);
1238 for (fs1=fs, i=1; nonNull(fs1); fs1=tl(fs1), i++) {
1239 Int n = sfunPos(fst(hd(fs1)),c);
1246 for (; nonNull(ta); ta=tl(ta)) { /* For each cfun arg */
1247 if (nonNull(hd(ta))) { /* Field to updated? */
1248 Int n = intOf(hd(ta));
1251 for (; n-- > 1; f=tl(f), t=tl(t))
1256 shouldBe(line,snd(f),e,update,arg(fun(tr)),or);
1257 } /* Unmentioned component */
1258 else if (!unify(arg(fun(td)),od,arg(fun(tr)),or))
1259 internal("typeUpdFlds");
1265 inferType(td,od); /* Check domain type */
1266 shouldBe(line,fst3(snd(e)),e,update,aVar,alpha);
1267 inferType(tr,or); /* Check range type */
1268 shouldBe(line,e,NIL,update,aVar,alpha+1);
1270 /* (typeIs,typeOff) still carry the result type when we exit the loop */
1273 static Cell local typeFreshPat(l,p) /* find type of pattern, assigning */
1274 Int l; /* fresh type variables to each var */
1275 Cell p; { /* bound in the pattern */
1276 tcMode = NEW_PATTERN;
1278 tcMode = EXPRESSION;
1282 /* --------------------------------------------------------------------------
1283 * Type check group of bindings:
1284 * ------------------------------------------------------------------------*/
1286 static Void local typeBindings(bs) /* type check a binding group */
1288 Bool usesPatBindings = FALSE; /* TRUE => pattern binding in bs */
1289 Bool usesUntypedVar = FALSE; /* TRUE => var bind w/o type decl */
1292 /* The following loop is used to determine whether the monomorphism */
1293 /* restriction should be applied. It could be written marginally more */
1294 /* efficiently by using breaks, but clarity is more important here ... */
1296 for (bs1=bs; nonNull(bs1); bs1=tl(bs1)) { /* Analyse binding group */
1299 usesPatBindings = TRUE;
1300 else if (isNull(fst(hd(snd(snd(b))))) /* no arguments */
1301 && whatIs(fst(snd(b)))==IMPDEPS) /* implicitly typed*/
1302 usesUntypedVar = TRUE;
1305 if (usesPatBindings || usesUntypedVar)
1310 mapProc(removeTypeSigs,bs); /* Remove binding type info */
1311 hd(varsBounds) = revOnto(hd(defnBounds), /* transfer completed assmps*/
1312 hd(varsBounds)); /* out of defnBounds */
1313 hd(defnBounds) = NIL;
1317 static Void local removeTypeSigs(b) /* Remove type info from a binding */
1319 snd(b) = snd(snd(b));
1322 /* --------------------------------------------------------------------------
1323 * Type check a restricted binding group:
1324 * ------------------------------------------------------------------------*/
1326 static Void local monorestrict(bs) /* Type restricted binding group */
1328 List savePreds = preds;
1329 Int line = isVar(fst(hd(bs))) ? rhsLine(snd(hd(snd(snd(hd(bs))))))
1330 : rhsLine(snd(snd(snd(hd(bs)))));
1331 hd(defnBounds) = NIL;
1332 hd(depends) = NODEPENDS; /* No need for dependents here */
1334 preds = NIL; /* Type check the bindings */
1335 mapProc(restrictedBindAss,bs);
1336 mapProc(typeBind,bs);
1339 preds = revOnto(preds,savePreds);
1341 clearMarks(); /* Mark fixed variables */
1342 mapProc(markAssumList,tl(defnBounds));
1343 mapProc(markAssumList,tl(varsBounds));
1344 mapProc(markPred,preds);
1347 if (isNull(tl(defnBounds))) { /* Top-level may need defaulting */
1349 if (nonNull(preds) && resolveDefs(genvarAnyAss(hd(defnBounds))))
1354 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
1357 if (nonNull(preds)) { /* Look for unresolved overloading */
1358 Cell v = isVar(fst(hd(bs))) ? fst(hd(bs)) : hd(fst(hd(bs)));
1359 Cell ass = findInAssumList(textOf(v),hd(varsBounds));
1360 preds = scSimplify(preds);
1362 ERRMSG(line) "Unresolved top-level overloading" ETHEN
1363 ERRTEXT "\n*** Binding : %s", textToStr(textOf(v))
1366 ERRTEXT "\n*** Inferred type : " ETHEN ERRTYPE(snd(ass));
1368 ERRTEXT "\n*** Outstanding context : " ETHEN
1369 ERRCONTEXT(copyPreds(preds));
1375 map1Proc(genBind,NIL,bs); /* Generalize types of def'd vars */
1378 static Void local restrictedBindAss(b) /* Make assums for vars in binding */
1379 Cell b; { /* gp with restricted overloading */
1381 if (isVar(fst(b))) { /* function-binding? */
1382 Cell t = fst(snd(b));
1383 if (whatIs(t)==IMPDEPS) { /* Discard implicitly typed deps */
1384 fst(snd(b)) = t = NIL; /* in a restricted binding group. */
1386 fst(snd(b)) = localizeBtyvs(t);
1387 restrictedAss(rhsLine(snd(hd(snd(snd(b))))), fst(b), t);
1388 } else { /* pattern-binding? */
1390 List ts = fst(snd(b));
1391 Int line = rhsLine(snd(snd(snd(b))));
1393 for (; nonNull(vs); vs=tl(vs)) {
1395 restrictedAss(line,hd(vs),hd(ts)=localizeBtyvs(hd(ts)));
1398 restrictedAss(line,hd(vs),NIL);
1404 static Void local restrictedAss(l,v,t) /* Assume that type of binding var v*/
1405 Int l; /* is t (if nonNull) in restricted */
1406 Cell v; /* binding group */
1409 if (nonNull(predsAre)) {
1410 ERRMSG(l) "Explicit overloaded type for \"%s\"",textToStr(textOf(v))
1412 ERRTEXT " not permitted in restricted binding"
1417 /* --------------------------------------------------------------------------
1418 * Unrestricted binding group:
1419 * ------------------------------------------------------------------------*/
1421 static Void local unrestricted(bs) /* Type unrestricted binding group */
1423 List savePreds = preds;
1424 List imps = NIL; /* Implicitly typed bindings */
1425 List exps = NIL; /* Explicitly typed bindings */
1428 /* ----------------------------------------------------------------------
1429 * STEP 1: Separate implicitly typed bindings from explicitly typed
1430 * bindings and do a dependency analyis, where f depends on g iff f
1431 * is implicitly typed and involves a call to g.
1432 * --------------------------------------------------------------------*/
1434 for (; nonNull(bs); bs=tl(bs)) {
1436 if (whatIs(fst(snd(b)))==IMPDEPS)
1437 imps = cons(b,imps); /* N.B. New lists are built to */
1438 else /* avoid breaking the original */
1439 exps = cons(b,exps); /* list structure for bs. */
1442 for (bs=imps; nonNull(bs); bs=tl(bs)) {
1443 Cell b = hd(bs); /* Restrict implicitly typed dep */
1444 List ds = snd(fst(snd(b))); /* lists to bindings in imps */
1446 while (nonNull(ds)) {
1448 if (cellIsMember(hd(ds),imps)) {
1456 imps = itbscc(imps); /* Dependency analysis on imps */
1457 for (bs=imps; nonNull(bs); bs=tl(bs))
1458 for (bs1=hd(bs); nonNull(bs1); bs1=tl(bs1))
1459 fst(snd(hd(bs1))) = NIL; /* reset imps type fields */
1461 #ifdef DEBUG_DEPENDS
1462 Printf("Binding group:");
1463 for (bs1=imps; nonNull(bs1); bs1=tl(bs1)) {
1465 for (bs=hd(bs1); nonNull(bs); bs=tl(bs))
1466 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1469 if (nonNull(exps)) {
1471 for (bs=exps; nonNull(bs); bs=tl(bs))
1472 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1478 /* ----------------------------------------------------------------------
1479 * STEP 2: Add type assumptions about any explicitly typed variable.
1480 * --------------------------------------------------------------------*/
1482 for (bs=exps; nonNull(bs); bs=tl(bs)) {
1483 fst(snd(hd(bs))) = localizeBtyvs(fst(snd(hd(bs))));
1484 hd(varsBounds) = cons(pair(fst(hd(bs)),fst(snd(hd(bs)))),
1488 /* ----------------------------------------------------------------------
1489 * STEP 3: Calculate types for each group of implicitly typed bindings.
1490 * --------------------------------------------------------------------*/
1492 for (; nonNull(imps); imps=tl(imps)) {
1493 Cell b = hd(hd(imps));
1494 Int line = isVar(fst(b)) ? rhsLine(snd(hd(snd(snd(b)))))
1495 : rhsLine(snd(snd(snd(b))));
1496 hd(defnBounds) = NIL;
1498 for (bs1=hd(imps); nonNull(bs1); bs1=tl(bs1))
1499 newDefnBind(fst(hd(bs1)),NIL);
1502 mapProc(typeBind,hd(imps));
1505 mapProc(markAssumList,tl(defnBounds));
1506 mapProc(markAssumList,tl(varsBounds));
1507 mapProc(markPred,savePreds);
1511 savePreds = elimOuterPreds(savePreds);
1512 if (nonNull(preds) && resolveDefs(genvarAllAss(hd(defnBounds)))) {
1513 savePreds = elimOuterPreds(savePreds);
1516 map1Proc(genBind,preds,hd(imps));
1517 if (nonNull(preds)) {
1518 map1Proc(addEvidParams,preds,hd(depends));
1519 map1Proc(qualifyBinding,preds,hd(imps));
1522 h98CheckType(line,"inferred type",
1523 fst(hd(hd(defnBounds))),snd(hd(hd(defnBounds))));
1524 hd(varsBounds) = revOnto(hd(defnBounds),hd(varsBounds));
1527 /* ----------------------------------------------------------------------
1528 * STEP 4: Now infer a type for each explicitly typed variable and
1529 * check for compatibility with the declared type.
1530 * --------------------------------------------------------------------*/
1532 for (; nonNull(exps); exps=tl(exps)) {
1533 static String extbind = "explicitly typed binding";
1535 List alts = snd(snd(b));
1536 Int line = rhsLine(snd(hd(alts)));
1542 hd(defnBounds) = NIL;
1543 hd(depends) = NODEPENDS;
1546 instantiate(fst(snd(b)));
1549 t = dropRank2(typeIs,o,m);
1550 ps = makePredAss(predsAre,o);
1552 enterPendingBtyvs();
1553 for (; nonNull(alts); alts=tl(alts))
1554 typeAlt(extbind,fst(b),hd(alts),t,o,m);
1555 leavePendingBtyvs();
1557 if (nonNull(ps)) /* Add dict params, if necessary */
1558 qualifyBinding(ps,b);
1561 mapProc(markAssumList,tl(defnBounds));
1562 mapProc(markAssumList,tl(varsBounds));
1563 mapProc(markPred,savePreds);
1566 savePreds = elimPredsUsing(ps,savePreds);
1567 if (nonNull(preds)) {
1571 vs = cons(mkInt(o+i),vs);
1572 if (resolveDefs(vs))
1573 savePreds = elimPredsUsing(ps,savePreds);
1574 if (nonNull(preds)) {
1577 if (nonNull(preds) && resolveDefs(vs))
1578 savePreds = elimPredsUsing(ps,savePreds);
1582 resetGenerics(); /* Make sure we're general enough */
1584 t = generalize(ps,liftRank2(t,o,m));
1586 if (!sameSchemes(t,fst(snd(b))))
1587 tooGeneral(line,fst(b),fst(snd(b)),t);
1588 h98CheckType(line,"inferred type",fst(b),t);
1590 if (nonNull(preds)) /* Check context was strong enough */
1591 cantEstablish(line,extbind,fst(b),t,ps);
1594 preds = savePreds; /* Restore predicates */
1595 hd(defnBounds) = NIL;
1598 #define SCC itbscc /* scc for implicitly typed binds */
1599 #define LOWLINK itblowlink
1600 #define DEPENDS(t) fst(snd(t))
1601 #define SETDEPENDS(c,v) fst(snd(c))=v
1608 static Void local addEvidParams(qs,v) /* overwrite VARID/OPCELL v with */
1609 List qs; /* application of variable to evid. */
1610 Cell v; { /* parameters given by qs */
1615 internal("addEvidParams");
1617 for (nv=mkVar(textOf(v)); nonNull(tl(qs)); qs=tl(qs))
1618 nv = ap(nv,thd3(hd(qs)));
1620 snd(v) = thd3(hd(qs));
1624 /* --------------------------------------------------------------------------
1625 * Type check bodies of class and instance declarations:
1626 * ------------------------------------------------------------------------*/
1628 static Void local typeClassDefn(c) /* Type check implementations of */
1629 Class c; { /* defaults for class c */
1631 /* ----------------------------------------------------------------------
1632 * Generate code for default dictionary builder function:
1634 * class.C sc1 ... scn d = let v1 ... = ...
1636 * in Make.C sc1 ... scn v1 ... vm
1638 * where sci are superclass dictionary parameters, vj are implementations
1639 * for member functions, either taken from defaults, or using "error" to
1640 * produce a suitable error message. (Additional line number values must
1641 * be added at appropriate places but, for clarity, these are not shown
1643 * --------------------------------------------------------------------*/
1645 Int beta = newKindedVars(cclass(c).kinds);
1646 List params = makePredAss(cclass(c).supers,beta);
1647 Cell body = cclass(c).dcon;
1649 List mems = cclass(c).members;
1650 List defs = cclass(c).defaults;
1651 List dsels = cclass(c).dsels;
1652 Cell d = inventDictVar();
1655 Cell l = mkInt(cclass(c).line);
1658 for (ps=params; nonNull(ps); ps=tl(ps)) {
1659 Cell v = thd3(hd(ps));
1661 pat = ap(pat,inventVar());
1662 args = cons(v,args);
1664 args = revOnto(args,singleton(d));
1665 params = appendOnto(params,
1666 singleton(triple(cclass(c).head,mkInt(beta),d)));
1668 for (; nonNull(mems); mems=tl(mems)) {
1669 Cell v = inventVar(); /* Pick a name for component */
1672 if (nonNull(defs)) { /* Look for default implementation */
1677 if (isNull(imp)) { /* Generate undefined member msg */
1678 static String header = "Undefined member: ";
1679 String name = textToStr(name(hd(mems)).text);
1680 char msg[FILENAME_MAX+1];
1684 for (i=0; i<FILENAME_MAX && header[i]!='\0'; i++)
1686 for (j=0; (i+j)<FILENAME_MAX && name[j]!='\0'; j++)
1690 imp = pair(v,singleton(pair(NIL,ap(l,ap(nameError,
1691 mkStr(findText(msg)))))));
1693 else { /* Use default implementation */
1695 typeMember("default member binding",
1703 locs = cons(imp,locs);
1709 body = ap(LETREC,pair(singleton(locs),body));
1710 name(cclass(c).dbuild).defn
1711 = singleton(pair(args,body));
1713 name(cclass(c).dbuild).inlineMe = TRUE;
1714 genDefns = cons(cclass(c).dbuild,genDefns);
1715 cclass(c).defaults = NIL;
1717 /* ----------------------------------------------------------------------
1718 * Generate code for superclass and member function selectors:
1719 * --------------------------------------------------------------------*/
1721 args = getArgs(pat);
1722 pat = singleton(pat);
1723 for (; nonNull(dsels); dsels=tl(dsels)) {
1724 name(hd(dsels)).defn = singleton(pair(pat,ap(l,hd(args))));
1725 name(hd(dsels)).inlineMe = TRUE;
1727 genDefns = cons(hd(dsels),genDefns);
1729 for (mems=cclass(c).members; nonNull(mems); mems=tl(mems)) {
1730 name(hd(mems)).defn = singleton(pair(pat,ap(mkInt(name(hd(mems)).line),
1733 genDefns = cons(hd(mems),genDefns);
1737 static Void local typeInstDefn(in) /* Type check implementations of */
1738 Inst in; { /* member functions for instance in*/
1740 /* ----------------------------------------------------------------------
1741 * Generate code for instance specific dictionary builder function:
1743 * inst.maker d1 ... dn = let sc1 = ...
1748 * d = f (class.C sc1 ... scm d)
1749 * omit if the / f (Make.C sc1' ... scm' v1' ... vk')
1750 * instance decl { = let vj ... = ...
1751 * has no imps \ in Make.C sc1' ... scm' ... vj ...
1754 * where sci are superclass dictionaries, d and f are new names, vj
1755 * is a newly generated name corresponding to the implementation of a
1756 * member function. (Additional line number values must be added at
1757 * appropriate places but, for clarity, these are not shown above.)
1758 * --------------------------------------------------------------------*/
1760 Int alpha = newKindedVars(cclass(inst(in).c).kinds);
1761 List supers = makePredAss(cclass(inst(in).c).supers,alpha);
1762 Int beta = newKindedVars(inst(in).kinds);
1763 List params = makePredAss(inst(in).specifics,beta);
1764 Cell d = inventDictVar();
1765 List evids = cons(triple(inst(in).head,mkInt(beta),d),
1766 appendOnto(dupList(params),supers));
1768 List imps = inst(in).implements;
1769 Cell l = mkInt(inst(in).line);
1770 Cell dictDef = cclass(inst(in).c).dbuild;
1775 if (!unifyPred(cclass(inst(in).c).head,alpha,inst(in).head,beta))
1776 internal("typeInstDefn");
1778 for (ps=params; nonNull(ps); ps=tl(ps)) /* Build arglist */
1779 args = cons(thd3(hd(ps)),args);
1782 for (ps=supers; nonNull(ps); ps=tl(ps)) { /* Superclass dictionaries */
1784 Cell ev = scEntail(params,fst3(pi),intOf(snd3(pi)),0);
1786 ev = inEntail(evids,fst3(pi),intOf(snd3(pi)),0);
1789 ERRMSG(inst(in).line) "Cannot build superclass instance" ETHEN
1790 ERRTEXT "\n*** Instance : " ETHEN
1791 ERRPRED(copyPred(inst(in).head,beta));
1792 ERRTEXT "\n*** Context supplied : " ETHEN
1793 ERRCONTEXT(copyPreds(params));
1794 ERRTEXT "\n*** Required superclass : " ETHEN
1795 ERRPRED(copyPred(fst3(pi),intOf(snd3(pi))));
1799 locs = cons(pair(thd3(pi),singleton(pair(NIL,ap(l,ev)))),locs);
1800 dictDef = ap(dictDef,thd3(pi));
1802 dictDef = ap(dictDef,d);
1804 if (isNull(imps)) /* No implementations */
1805 locs = cons(pair(d,singleton(pair(NIL,ap(l,dictDef)))),locs);
1806 else { /* Implementations supplied*/
1807 List mems = cclass(inst(in).c).members;
1808 Cell f = inventVar();
1809 Cell pat = cclass(inst(in).c).dcon;
1813 locs = cons(pair(d,singleton(pair(NIL,ap(l,ap(f,dictDef))))),
1816 for (ps=supers; nonNull(ps); ps=tl(ps)){/* Add param for each sc */
1817 Cell v = inventVar();
1822 for (; nonNull(mems); mems=tl(mems)) { /* For each member: */
1823 Cell v = inventVar();
1826 if (nonNull(imps)) { /* Look for implementation */
1831 if (isNull(imp)) { /* If none, f will copy */
1832 pat = ap(pat,v); /* its argument unchanged */
1835 else { /* Otherwise, add the impl */
1836 pat = ap(pat,WILDCARD); /* to f as a local defn */
1838 typeMember("instance member binding",
1844 locs1 = cons(pair(v,snd(imp)),locs1);
1848 if (nonNull(locs1)) /* Build the body of f */
1849 res = ap(LETREC,pair(singleton(locs1),res));
1850 pat = singleton(pat); /* And the arglist for f */
1851 locs = cons(pair(f,singleton(pair(pat,res))),locs);
1855 name(inst(in).builder).defn /* Register builder imp */
1856 = singleton(pair(args,ap(LETREC,pair(singleton(locs),d))));
1858 name(inst(in).builder).inlineMe = TRUE;
1859 name(inst(in).builder).isDBuilder = TRUE;
1860 genDefns = cons(inst(in).builder,genDefns);
1863 static Void local typeMember(wh,mem,alts,evids,head,beta)
1864 String wh; /* Type check alternatives alts of */
1865 Name mem; /* member mem for inst type head */
1866 Cell alts; /* at offset beta using predicate */
1867 List evids; /* assignment evids */
1870 Int line = rhsLine(snd(hd(alts)));
1879 Printf("\nType check member: ");
1880 printExp(stdout,mem);
1882 printType(stdout,name(mem).type);
1883 Printf("\n for the instance: ");
1884 printPred(stdout,head);
1888 instantiate(name(mem).type); /* Find required type */
1891 t = dropRank2(typeIs,o,m);
1892 ps = makePredAss(predsAre,o);
1893 if (!unifyPred(hd(predsAre),typeOff,head,beta))
1894 internal("typeMember1");
1897 rt = generalize(qs,liftRank2(t,o,m));
1900 Printf("Required type is: ");
1901 printType(stdout,rt);
1905 hd(defnBounds) = NIL; /* Type check each alternative */
1906 hd(depends) = NODEPENDS;
1907 enterPendingBtyvs();
1908 for (preds=NIL; nonNull(alts); alts=tl(alts)) {
1909 typeAlt(wh,mem,hd(alts),t,o,m);
1910 qualify(tl(ps),hd(alts)); /* Add any extra dict params */
1912 leavePendingBtyvs();
1914 evids = appendOnto(dupList(tl(ps)), /* Build full complement of dicts */
1917 qs = elimPredsUsing(evids,NIL);
1918 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
1919 qs = elimPredsUsing(evids,qs);
1922 "Implementation of %s requires extra context",
1923 textToStr(name(mem).text) ETHEN
1924 ERRTEXT "\n*** Expected type : " ETHEN ERRTYPE(rt);
1925 ERRTEXT "\n*** Missing context : " ETHEN ERRCONTEXT(copyPreds(qs));
1930 resetGenerics(); /* Make sure we're general enough */
1932 t = generalize(ps,liftRank2(t,o,m));
1934 Printf(" Inferred type is: ");
1935 printType(stdout,t);
1938 if (!sameSchemes(t,rt))
1939 tooGeneral(line,mem,rt,t);
1941 cantEstablish(line,wh,mem,t,ps);
1944 /* --------------------------------------------------------------------------
1945 * Type check bodies of bindings:
1946 * ------------------------------------------------------------------------*/
1948 static Void local typeBind(b) /* Type check binding */
1950 if (isVar(fst(b))) { /* function binding */
1951 Cell ass = findTopBinding(fst(b));
1955 internal("typeBind");
1957 beta = intOf(defType(snd(ass)));
1958 enterPendingBtyvs();
1959 map2Proc(typeDefAlt,beta,fst(b),snd(snd(b)));
1960 leavePendingBtyvs();
1962 else { /* pattern binding */
1963 static String lhsPat = "lhs pattern";
1964 static String rhs = "right hand side";
1965 Int beta = newTyvars(1);
1966 Pair pb = snd(snd(b));
1967 Int l = rhsLine(snd(pb));
1969 tcMode = OLD_PATTERN;
1970 enterPendingBtyvs();
1971 fst(pb) = patBtyvs(fst(pb));
1972 check(l,fst(pb),NIL,lhsPat,aVar,beta);
1973 tcMode = EXPRESSION;
1974 snd(pb) = typeRhs(snd(pb));
1975 shouldBe(l,rhsExpr(snd(pb)),NIL,rhs,aVar,beta);
1977 leavePendingBtyvs();
1981 static Void local typeDefAlt(beta,v,a) /* type check alt in func. binding */
1985 static String valDef = "function binding";
1986 typeAlt(valDef,v,a,aVar,beta,0);
1989 static Cell local typeRhs(e) /* check type of rhs of definition */
1991 switch (whatIs(e)) {
1992 case GUARDED : { Int beta = newTyvars(1);
1993 map1Proc(guardedType,beta,snd(e));
1998 case LETREC : enterBindings();
2000 mapProc(typeBindings,fst(snd(e)));
2001 snd(snd(e)) = typeRhs(snd(snd(e)));
2003 leaveSkolVars(rhsLine(snd(snd(e))),typeIs,typeOff,0);
2006 case RSIGN : fst(snd(e)) = typeRhs(fst(snd(e)));
2007 shouldBe(rhsLine(fst(snd(e))),
2008 rhsExpr(fst(snd(e))),NIL,
2013 default : snd(e) = typeExpr(intOf(fst(e)),snd(e));
2019 static Void local guardedType(beta,gded)/* check type of guard (li,(gd,ex))*/
2020 Int beta; /* should have gd :: Bool, */
2021 Cell gded; { /* ex :: (var,beta) */
2022 static String guarded = "guarded expression";
2023 static String guard = "guard";
2024 Int line = intOf(fst(gded));
2027 check(line,fst(gded),NIL,guard,typeBool,0);
2028 check(line,snd(gded),NIL,guarded,aVar,beta);
2031 Cell rhsExpr(rhs) /* find first expression on a rhs */
2033 switch (whatIs(rhs)) {
2034 case GUARDED : return snd(snd(hd(snd(rhs))));
2035 case LETREC : return rhsExpr(snd(snd(rhs)));
2036 case RSIGN : return rhsExpr(fst(snd(rhs)));
2037 default : return snd(rhs);
2041 Int rhsLine(rhs) /* find line number associated with */
2042 Cell rhs; { /* a right hand side */
2043 switch (whatIs(rhs)) {
2044 case GUARDED : return intOf(fst(hd(snd(rhs))));
2045 case LETREC : return rhsLine(snd(snd(rhs)));
2046 case RSIGN : return rhsLine(fst(snd(rhs)));
2047 default : return intOf(fst(rhs));
2051 /* --------------------------------------------------------------------------
2052 * Calculate generalization of types and compare with declared type schemes:
2053 * ------------------------------------------------------------------------*/
2055 static Void local genBind(ps,b) /* Generalize the type of each var */
2056 List ps; /* defined in binding b, qualifying*/
2057 Cell b; { /* each with the predicates in ps. */
2059 Cell t = fst(snd(b));
2062 genAss(rhsLine(snd(hd(snd(snd(b))))),ps,v,t);
2064 Int line = rhsLine(snd(snd(snd(b))));
2065 for (; nonNull(v); v=tl(v)) {
2071 genAss(line,ps,hd(v),ty);
2076 static Void local genAss(l,ps,v,dt) /* Calculate inferred type of v and*/
2077 Int l; /* compare with declared type, dt, */
2078 List ps; /* if given & check for ambiguity. */
2081 Cell ass = findTopBinding(v);
2086 snd(ass) = genTest(l,v,ps,dt,aVar,intOf(defType(snd(ass))));
2091 printType(stdout,snd(ass));
2096 static Type local genTest(l,v,ps,dt,t,o)/* Generalize and test inferred */
2097 Int l; /* type (t,o) with context ps */
2098 Cell v; /* against declared type dt for v. */
2103 Type bt = NIL; /* Body of inferred type */
2104 Type it = NIL; /* Full inferred type */
2106 resetGenerics(); /* Calculate Haskell typing */
2109 it = generalize(ps,bt);
2111 if (nonNull(dt)) { /* If a declared type was given, */
2112 instantiate(dt); /* check body for match. */
2113 if (!equalTypes(typeIs,bt))
2114 tooGeneral(l,v,dt,it);
2116 else if (nonNull(ps)) /* Otherwise test for ambiguity in */
2117 if (isAmbiguous(it)) /* inferred type. */
2118 ambigError(l,"inferred type",v,it);
2123 static Type local generalize(qs,t) /* calculate generalization of t */
2124 List qs; /* having already marked fixed vars*/
2125 Type t; { /* with qualifying preds qs */
2127 t = ap(QUAL,pair(qs,t));
2128 if (nonNull(genericVars)) {
2130 List vs = genericVars;
2131 for (; nonNull(vs); vs=tl(vs)) {
2132 Tyvar *tyv = tyvar(intOf(hd(vs)));
2133 Kind ka = tyv->kind;
2136 t = mkPolyType(k,t);
2138 Printf("Generalized type: ");
2139 printType(stdout,t);
2141 printKind(stdout,k);
2148 static Bool local equalTypes(t1,t2) /* Compare simple types for equality*/
2151 et: if (whatIs(t1)!=whatIs(t2))
2154 switch (whatIs(t1)) {
2160 case TUPLE : return t1==t2;
2162 case INTCELL : return intOf(t1)!=intOf(t2);
2164 case AP : if (equalTypes(fun(t1),fun(t2))) {
2171 default : internal("equalTypes");
2174 return TRUE;/*NOTREACHED*/
2177 /* --------------------------------------------------------------------------
2178 * Entry points to type checker:
2179 * ------------------------------------------------------------------------*/
2181 Type typeCheckExp(useDefs) /* Type check top level expression */
2182 Bool useDefs; { /* using defaults if reqd */
2188 emptySubstitution();
2190 inputExpr = typeExpr(0,inputExpr);
2196 preds = scSimplify(preds);
2197 if (useDefs && nonNull(preds)) {
2200 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
2204 ctxt = copyPreds(preds);
2205 type = generalize(ctxt,copyType(type,beta));
2206 inputExpr = qualifyExpr(0,preds,inputExpr);
2207 h98CheckType(0,"inferred type",inputExpr,type);
2209 emptySubstitution();
2213 Void typeCheckDefns() { /* Type check top level bindings */
2214 Target t = length(selDefns) + length(valDefns) +
2215 length(instDefns) + length(classDefns);
2220 emptySubstitution();
2223 setGoal("Type checking",t);
2225 for (gs=selDefns; nonNull(gs); gs=tl(gs)) {
2226 mapOver(typeSel,hd(gs));
2229 for (gs=valDefns; nonNull(gs); gs=tl(gs)) {
2230 typeDefnGroup(hd(gs));
2234 for (gs=classDefns; nonNull(gs); gs=tl(gs)) {
2235 emptySubstitution();
2236 typeClassDefn(hd(gs));
2239 for (gs=instDefns; nonNull(gs); gs=tl(gs)) {
2240 emptySubstitution();
2241 typeInstDefn(hd(gs));
2246 emptySubstitution();
2250 static Void local typeDefnGroup(bs) /* type check group of value defns */
2251 List bs; { /* (one top level scc) */
2253 // printf("\n\n+++ DefnGroup ++++++++++++++++++++++++++++\n");
2254 //{ List qq; for (qq=bs;nonNull(qq);qq=tl(qq)){
2259 emptySubstitution();
2260 hd(defnBounds) = NIL;
2263 typeBindings(bs); /* find types for vars in bindings */
2265 if (nonNull(preds)) {
2266 Cell v = fst(hd(hd(varsBounds)));
2267 Name n = findName(textOf(v));
2268 Int l = nonNull(n) ? name(n).line : 0;
2269 preds = scSimplify(preds);
2270 ERRMSG(l) "Instance%s of ", (length(preds)==1 ? "" : "s") ETHEN
2271 ERRCONTEXT(copyPreds(preds));
2272 ERRTEXT " required for definition of " ETHEN
2273 ERREXPR(nonNull(n)?n:v);
2278 if (nonNull(hd(skolVars))) {
2280 Name n = findName(isVar(fst(b)) ? textOf(fst(b)) : textOf(hd(fst(b))));
2281 Int l = nonNull(n) ? name(n).line : 0;
2282 leaveSkolVars(l,typeUnit,0,0);
2286 for (as=hd(varsBounds); nonNull(as); as=tl(as)) {
2287 Cell a = hd(as); /* add infered types to environment*/
2288 Name n = findName(textOf(fst(a)));
2290 internal("typeDefnGroup");
2291 name(n).type = snd(a);
2293 hd(varsBounds) = NIL;
2296 static Pair local typeSel(s) /* Calculate a suitable type for a */
2297 Name s; { /* particular selector, s. */
2298 List cns = name(s).defn;
2299 Int line = name(s).line;
2300 Type dom = NIL; /* Inferred domain */
2301 Type rng = NIL; /* Inferred range */
2302 Cell nv = inventVar();
2308 Printf("Selector %s, cns=",textToStr(name(s).text));
2309 printExp(stdout,cns);
2313 emptySubstitution();
2316 for (; nonNull(cns); cns=tl(cns)) {
2317 Name c = fst(hd(cns));
2318 Int n = intOf(snd(hd(cns)));
2319 Int a = name(c).arity;
2326 instantiate(name(c).type); /* Instantiate constructor type */
2329 for (; nonNull(predsAre); predsAre=tl(predsAre))
2330 assumeEvid(hd(predsAre),o1);
2332 if (whatIs(typeIs)==RANK2) /* Skip rank2 annotation, if any */
2333 typeIs = snd(snd(typeIs));
2334 for (; --n>0; a--) { /* Get range */
2335 pat = ap(pat,WILDCARD);
2336 typeIs = arg(typeIs);
2338 rng1 = dropRank1(arg(fun(typeIs)),o1,m1);
2340 typeIs = arg(typeIs);
2341 while (--a>0) { /* And then look for domain */
2342 pat = ap(pat,WILDCARD);
2343 typeIs = arg(typeIs);
2347 if (isNull(dom)) { /* Save first domain type and then */
2348 dom = dom1; /* unify with subsequent domains to*/
2349 o = o1; /* match up preds and range types */
2352 else if (!unify(dom1,o1,dom,o))
2353 internal("typeSel1");
2355 if (isNull(rng)) /* Compare component types */
2357 else if (!sameSchemes(rng1,rng)) {
2359 rng = liftRank1(rng,o,m);
2360 rng1 = liftRank1(rng1,o1,m1);
2361 ERRMSG(name(s).line) "Mismatch in field types for selector \"%s\"",
2362 textToStr(name(s).text) ETHEN
2363 ERRTEXT "\n*** Field type : " ETHEN ERRTYPE(rng1);
2364 ERRTEXT "\n*** Does not match : " ETHEN ERRTYPE(rng);
2368 alts = cons(pair(singleton(pat),pair(mkInt(line),nv)),alts);
2372 if (isNull(dom) || isNull(rng)) /* Should have been initialized by */
2373 internal("typeSel2"); /* now, assuming length cns >= 1. */
2375 clearMarks(); /* No fixed variables here */
2376 preds = scSimplify(preds); /* Simplify context */
2377 dom = copyType(dom,o); /* Calculate domain type */
2379 rng = copyType(typeIs,typeOff);
2380 if (nonNull(predsAre)) {
2381 List ps = makePredAss(predsAre,typeOff);
2383 for (; nonNull(alts1); alts1=tl(alts1)) {
2386 for (; nonNull(qs); qs=tl(qs))
2387 body = ap(body,thd3(hd(qs)));
2388 snd(snd(hd(alts1))) = body;
2390 preds = appendOnto(preds,ps);
2392 name(s).type = generalize(copyPreds(preds),fn(dom,rng));
2393 name(s).arity = 1 + length(preds);
2394 map1Proc(qualify,preds,alts);
2397 Printf("Inferred arity = %d, type = ",name(s).arity);
2398 printType(stdout,name(s).type);
2402 return pair(s,alts);
2406 /* --------------------------------------------------------------------------
2407 * Local function prototypes:
2408 * ------------------------------------------------------------------------*/
2410 static Type local basicType Args((Char));
2413 static Type stateVar = NIL;
2414 static Type alphaVar = NIL;
2415 static Type betaVar = NIL;
2416 static Type gammaVar = NIL;
2417 static Int nextVar = 0;
2419 static Void clearTyVars( void )
2428 static Type mkStateVar( void )
2430 if (isNull(stateVar)) {
2431 stateVar = mkOffset(nextVar++);
2436 static Type mkAlphaVar( void )
2438 if (isNull(alphaVar)) {
2439 alphaVar = mkOffset(nextVar++);
2444 static Type mkBetaVar( void )
2446 if (isNull(betaVar)) {
2447 betaVar = mkOffset(nextVar++);
2452 static Type mkGammaVar( void )
2454 if (isNull(gammaVar)) {
2455 gammaVar = mkOffset(nextVar++);
2460 static Type local basicType(k)
2477 case ARR_REP: return ap(typePrimArray,mkAlphaVar());
2478 case BARR_REP: return typePrimByteArray;
2479 case REF_REP: return ap2(typeRef,mkStateVar(),mkAlphaVar());
2480 case MUTARR_REP: return ap2(typePrimMutableArray,mkStateVar(),mkAlphaVar());
2481 case MUTBARR_REP: return ap(typePrimMutableByteArray,mkStateVar());
2482 #ifdef PROVIDE_STABLE
2484 return ap(typeStable,mkAlphaVar());
2488 return ap(typeWeak,mkAlphaVar());
2490 return ap(typeIO,typeUnit);
2492 #ifdef PROVIDE_FOREIGN
2496 #ifdef PROVIDE_CONCURRENT
2498 return typeThreadId;
2500 return ap(typeMVar,mkAlphaVar());
2505 return fn(typeException,mkAlphaVar());
2507 return typeException;
2509 return mkAlphaVar(); /* polymorphic */
2511 return mkBetaVar(); /* polymorphic */
2513 return mkGammaVar(); /* polymorphic */
2515 printf("Kind: '%c'\n",k);
2516 internal("basicType");
2518 assert(0); return 0; /* NOTREACHED */
2521 /* Generate type of primop based on list of arg types and result types:
2523 * eg primType "II" "II" = Int -> Int -> (Int,Int)
2526 Type primType( Int /*AsmMonad*/ monad, String a_kinds, String r_kinds )
2530 List tvars = NIL; /* for polymorphic types */
2535 /* build result types */
2536 for(; *r_kinds; ++r_kinds) {
2537 rs = cons(basicType(*r_kinds),rs);
2539 /* Construct tuple of results */
2540 if (length(rs) == 0) {
2542 } else if (length(rs) == 1) {
2545 r = mkTuple(length(rs));
2546 for(rs = rev(rs); nonNull(rs); rs=tl(rs)) {
2550 /* Construct list of arguments */
2551 for(; *a_kinds; ++a_kinds) {
2552 as = cons(basicType(*a_kinds),as);
2554 /* Apply any monad magic */
2555 if (monad == MONAD_IO) {
2557 } else if (monad == MONAD_ST) {
2558 r = ap2(typeST,mkStateVar(),r);
2560 /* glue it all together */
2561 for(; nonNull(as); as=tl(as)) {
2564 tvars = offsetTyvarsIn(r,NIL);
2565 if (nonNull(tvars)) {
2566 assert(length(tvars) == nextVar);
2567 r = mkPolyType(simpleKind(length(tvars)),r);
2571 printType(stdout,r); printf("\n");
2577 /* forall a1 .. am. TC a1 ... am -> Int */
2578 Type conToTagType(t)
2583 for (i=0; i<tycon(t).arity; ++i) {
2584 Offset tv = mkOffset(i);
2586 tvars = cons(tv,tvars);
2588 ty = fn(ty,typeInt);
2589 if (nonNull(tvars)) {
2590 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2595 /* forall a1 .. am. Int -> TC a1 ... am */
2596 Type tagToConType(t)
2601 for (i=0; i<tycon(t).arity; ++i) {
2602 Offset tv = mkOffset(i);
2604 tvars = cons(tv,tvars);
2606 ty = fn(typeInt,ty);
2607 if (nonNull(tvars)) {
2608 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2613 /* --------------------------------------------------------------------------
2614 * Type checker control:
2615 * ------------------------------------------------------------------------*/
2617 Void typeChecker(what)
2620 case RESET : tcMode = EXPRESSION;
2627 case MARK : mark(daSccs);
2643 mark(predFractional);
2649 case INSTALL : typeChecker(RESET);
2650 dummyVar = inventVar();
2652 setCurrModule(modulePrelude);
2654 starToStar = simpleKind(1);
2656 typeUnit = addPrimTycon(findText("()"),
2657 STAR,0,DATATYPE,NIL);
2658 typeArrow = addPrimTycon(findText("(->)"),
2661 typeList = addPrimTycon(findText("[]"),
2665 arrow = fn(aVar,bVar);
2666 listof = ap(typeList,aVar);
2667 boundPair = ap(ap(mkTuple(2),aVar),aVar);
2669 nameUnit = addPrimCfun(findText("()"),0,0,typeUnit);
2670 tycon(typeUnit).defn
2671 = singleton(nameUnit);
2673 nameNil = addPrimCfun(findText("[]"),0,1,
2674 mkPolyType(starToStar,
2676 nameCons = addPrimCfun(findText(":"),2,2,
2677 mkPolyType(starToStar,
2681 name(nameNil).parent =
2682 name(nameCons).parent = typeList;
2684 name(nameCons).syntax
2685 = mkSyntax(RIGHT_ASS,5);
2687 tycon(typeList).defn
2688 = cons(nameNil,cons(nameCons,NIL));
2690 typeVarToVar = fn(aVar,aVar);
2692 typeNoRow = addPrimTycon(findText("EmptyRow"),
2693 ROW,0,DATATYPE,NIL);
2694 typeRec = addPrimTycon(findText("Rec"),
2697 nameNoRec = addPrimCfun(findText("EmptyRec"),0,0,
2698 ap(typeRec,typeNoRow));
2700 /* bogus definitions to avoid changing the prelude */
2701 addPrimCfun(findText("Rec"), 0,0,typeUnit);
2702 addPrimCfun(findText("EmptyRow"), 0,0,typeUnit);
2703 addPrimCfun(findText("EmptyRec"), 0,0,typeUnit);
2709 /*-------------------------------------------------------------------------*/