2 /* --------------------------------------------------------------------------
3 * This is the Hugs type checker
5 * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
6 * Yale Haskell Group, and the Oregon Graduate Institute of Science and
7 * Technology, 1994-1999, All rights reserved. It is distributed as
8 * free software under the license in the file "License", which is
9 * included in the distribution.
11 * $RCSfile: type.c,v $
13 * $Date: 2000/04/27 16:35:30 $
14 * ------------------------------------------------------------------------*/
16 #include "hugsbasictypes.h"
21 #include "Rts.h" /* to make StgPtr visible in Assembler.h */
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*/
31 /* --------------------------------------------------------------------------
32 * Local function prototypes:
33 * ------------------------------------------------------------------------*/
35 static Void local emptyAssumption ( Void );
36 static Void local enterBindings ( Void );
37 static Void local leaveBindings ( Void );
38 static Int local defType ( Cell );
39 static Type local useType ( Cell );
40 static Void local markAssumList ( List );
41 static Cell local findAssum ( Text );
42 static Pair local findInAssumList ( Text,List );
43 static List local intsIntersect ( List,List );
44 static List local genvarAllAss ( List );
45 static List local genvarAnyAss ( List );
46 static Int local newVarsBind ( Cell );
47 static Void local newDefnBind ( Cell,Type );
49 static Void local enterPendingBtyvs ( Void );
50 static Void local leavePendingBtyvs ( Void );
51 static Cell local patBtyvs ( Cell );
52 static Void local doneBtyvs ( Int );
53 static Void local enterSkolVars ( Void );
54 static Void local leaveSkolVars ( Int,Type,Int,Int );
56 static Void local typeError ( Int,Cell,Cell,String,Type,Int );
57 static Void local reportTypeError ( Int,Cell,Cell,String,Type,Type );
58 static Void local cantEstablish ( Int,String,Cell,Type,List );
59 static Void local tooGeneral ( Int,Cell,Type,Type );
61 static Cell local typeExpr ( Int,Cell );
63 static Cell local typeAp ( Int,Cell );
64 static Type local typeExpected ( Int,String,Cell,Type,Int,Int,Bool );
65 static Void local typeAlt ( String,Cell,Cell,Type,Int,Int );
66 static Int local funcType ( Int );
67 static Void local typeCase ( Int,Int,Cell );
68 static Void local typeComp ( Int,Type,Cell,List );
69 static Cell local typeMonadComp ( Int,Cell );
70 static Void local typeDo ( Int,Cell );
71 static Void local typeConFlds ( Int,Cell );
72 static Void local typeUpdFlds ( Int,Cell );
74 static Cell local typeWith ( Int,Cell );
76 static Cell local typeFreshPat ( Int,Cell );
78 static Void local typeBindings ( List );
79 static Void local removeTypeSigs ( Cell );
81 static Void local monorestrict ( List );
82 static Void local restrictedBindAss ( Cell );
83 static Void local restrictedAss ( Int,Cell,Type );
85 static Void local unrestricted ( List );
86 static List local itbscc ( List );
87 static Void local addEvidParams ( List,Cell );
89 static Void local typeClassDefn ( Class );
90 static Void local typeInstDefn ( Inst );
91 static Void local typeMember ( String,Name,Cell,List,Cell,Int );
93 static Void local typeBind ( Cell );
94 static Void local typeDefAlt ( Int,Cell,Pair );
95 static Cell local typeRhs ( Cell );
96 static Void local guardedType ( Int,Cell );
98 static Void local genBind ( List,Cell );
99 static Void local genAss ( Int,List,Cell,Type );
100 static Type local genTest ( Int,Cell,List,Type,Type,Int );
101 static Type local generalize ( List,Type );
102 static Bool local equalTypes ( Type,Type );
104 static Void local typeDefnGroup ( List );
105 static Pair local typeSel ( Name );
109 /* --------------------------------------------------------------------------
112 * A basic typing statement is a pair (Var,Type) and an assumption contains
113 * an ordered list of basic typing statements in which the type for a given
114 * variable is given by the most recently added assumption about that var.
116 * In practice, the assumption set is split between a pair of lists, one
117 * holding assumptions for vars defined in bindings, the other for vars
118 * defined in patterns/binding parameters etc. The reason for this
119 * separation is that vars defined in bindings may be overloaded (with the
120 * overloading being unknown until the whole binding is typed), whereas the
121 * vars defined in patterns have no overloading. A form of dependency
122 * analysis (at least as far as calculating dependents within the same group
123 * of value bindings) is required to implement this. Where it is known that
124 * no overloaded values are defined in a binding (i.e., when the `dreaded
125 * monomorphism restriction' strikes), the list used to record dependents
126 * is flagged with a NODEPENDS tag to avoid gathering dependents at that
129 * To interleave between vars for bindings and vars for patterns, we use
130 * a list of lists of typing statements for each. These lists are always
131 * the same length. The implementation here is very similar to that of the
132 * dependency analysis used in the static analysis component of this system.
134 * To deal with polymorphic recursion, variables defined in bindings can be
135 * assigned types of the form (POLYREC,(def,use)), where def is a type
136 * variable for the type of the defining occurence, and use is a type
137 * scheme for (recursive) calls/uses of the variable.
138 * ------------------------------------------------------------------------*/
140 static List defnBounds; /*::[[(Var,Type)]] possibly ovrlded*/
141 static List varsBounds; /*::[[(Var,Type)]] not overloaded */
142 static List depends; /*::[?[Var]] dependents/NODEPENDS */
143 static List skolVars; /*::[[Var]] skolem vars */
144 static List localEvs; /*::[[(Pred,offset,ev)]] */
145 static List savedPs; /*::[[(Pred,offset,ev)]] */
146 static Cell dummyVar; /* Used to put extra tvars into ass*/
148 Bool catchAmbigs = FALSE; /* TRUE => functions with ambig. */
149 /* types produce error */
152 #define saveVarsAss() List saveAssump = hd(varsBounds)
153 #define restoreVarsAss() hd(varsBounds) = saveAssump
154 #define addVarAssump(v,t) hd(varsBounds) = cons(pair(v,t),hd(varsBounds))
155 #define findTopBinding(v) findInAssumList(textOf(v),hd(defnBounds))
157 static Void local emptyAssumption() { /* set empty type assumption */
166 static Void local enterBindings() { /* Add new level to assumption sets */
167 defnBounds = cons(NIL,defnBounds);
168 varsBounds = cons(NIL,varsBounds);
169 depends = cons(NIL,depends);
172 static Void local leaveBindings() { /* Drop one level of assumptions */
173 defnBounds = tl(defnBounds);
174 varsBounds = tl(varsBounds);
175 depends = tl(depends);
178 static Int local defType(a) /* Return type for defining occ. */
179 Cell a; { /* of a var from assumption pair */
180 return (isPair(a) && fst(a)==POLYREC) ? fst(snd(a)) : a;
183 static Type local useType(a) /* Return type for use of a var */
184 Cell a; { /* defined in an assumption */
185 return (isPair(a) && fst(a)==POLYREC) ? snd(snd(a)) : a;
188 static Void local markAssumList(as) /* Mark all types in assumption set*/
189 List as; { /* :: [(Var, Type)] */
190 for (; nonNull(as); as=tl(as)) { /* No need to mark generic types; */
191 Type t = defType(snd(hd(as))); /* the only free variables in those*/
192 if (!isPolyType(t)) /* must have been free earlier too */
197 static Cell local findAssum(t) /* Find most recent assumption about*/
198 Text t; { /* variable named t, if any */
199 List defnBounds1 = defnBounds; /* return translated variable, with */
200 List varsBounds1 = varsBounds; /* type in typeIs */
201 List depends1 = depends;
203 while (nonNull(defnBounds1)) {
204 Pair ass = findInAssumList(t,hd(varsBounds1));/* search varsBounds */
210 ass = findInAssumList(t,hd(defnBounds1)); /* search defnBounds */
215 if (hd(depends1)!=NODEPENDS && /* save dependent? */
216 isNull(v=varIsMember(t,hd(depends1))))
217 /* N.B. make new copy of variable and store this on list of*/
218 /* dependents, and in the assumption so that all uses of */
219 /* the variable will be at the same node, if we need to */
220 /* overwrite the call of a function with a translation... */
221 hd(depends1) = cons(v=mkVar(t),hd(depends1));
226 defnBounds1 = tl(defnBounds1); /* look in next level*/
227 varsBounds1 = tl(varsBounds1); /* of assumption set */
228 depends1 = tl(depends1);
233 static Pair local findInAssumList(t,as)/* Search for assumption for var */
234 Text t; /* named t in list of assumptions as*/
236 for (; nonNull(as); as=tl(as))
237 if (textOf(fst(hd(as)))==t)
242 static List local intsIntersect(as,bs) /* calculate intersection of lists */
243 List as, bs; { /* of integers (as sets) */
244 List ts = NIL; /* destructively modifies as */
246 if (intIsMember(intOf(hd(as)),bs)) {
257 static List local genvarAllAss(as) /* calculate generic vars that are */
258 List as; { /* in every type in assumptions as */
259 List vs = genvarTyvar(intOf(defType(snd(hd(as)))),NIL);
260 for (as=tl(as); nonNull(as) && nonNull(vs); as=tl(as))
261 vs = intsIntersect(vs,genvarTyvar(intOf(defType(snd(hd(as)))),NIL));
265 static List local genvarAnyAss(as) /* calculate generic vars that are */
266 List as; { /* in any type in assumptions as */
267 List vs = genvarTyvar(intOf(defType(snd(hd(as)))),NIL);
268 for (as=tl(as); nonNull(as); as=tl(as))
269 vs = genvarTyvar(intOf(defType(snd(hd(as)))),vs);
273 static Int local newVarsBind(v) /* make new assump for pattern var */
275 Int beta = newTyvars(1);
276 addVarAssump(v,mkInt(beta));
278 Printf("variable, assume ");
280 Printf(" :: _%d\n",beta);
285 static Void local newDefnBind(v,type) /* make new assump for defn var */
286 Cell v; /* and set type if given (nonNull) */
288 Int beta = newTyvars(1);
289 Cell ta = mkInt(beta);
291 if (nonNull(type) && isPolyType(type))
292 ta = pair(POLYREC,pair(ta,type));
293 hd(defnBounds) = cons(pair(v,ta), hd(defnBounds));
295 Printf("definition, assume ");
297 Printf(" :: _%d\n",beta);
299 bindTv(beta,typeIs,typeOff); /* Bind beta to new type skeleton */
302 /* --------------------------------------------------------------------------
304 * ------------------------------------------------------------------------*/
308 /* --------------------------------------------------------------------------
309 * Bound and skolemized type variables:
310 * ------------------------------------------------------------------------*/
312 static List pendingBtyvs = NIL;
314 static Void local enterPendingBtyvs() {
316 pendingBtyvs = cons(NIL,pendingBtyvs);
319 static Void local leavePendingBtyvs() {
320 List pts = hd(pendingBtyvs);
321 pendingBtyvs = tl(pendingBtyvs);
322 for (; nonNull(pts); pts=tl(pts)) {
323 Int line = intOf(fst(hd(pts)));
324 List vs = snd(hd(pts));
327 for (; nonNull(vs); vs=tl(vs)) {
328 Cell v = fst(hd(vs));
329 Cell t = copyTyvar(intOf(snd(hd(vs))));
331 ERRMSG(line) "Type annotation uses variable " ETHEN ERREXPR(v);
332 ERRTEXT " where a more specific type " ETHEN ERRTYPE(t);
333 ERRTEXT " was inferred"
336 else if (offsetOf(t)!=i) {
337 List us = snd(hd(pts));
340 internal("leavePendingBtyvs");
343 ERRMSG(line) "Type annotation uses distinct variables " ETHEN
344 ERREXPR(v); ERRTEXT " and " ETHEN ERREXPR(fst(hd(us)));
345 ERRTEXT " where a single variable was inferred"
355 static Cell local patBtyvs(p) /* Strip bound type vars from pat */
357 if (whatIs(p)==BIGLAM) {
358 List bts = hd(btyvars) = fst(snd(p));
359 for (p=snd(snd(p)); nonNull(bts); bts=tl(bts)) {
360 Int beta = newTyvars(1);
361 tyvar(beta)->kind = snd(hd(bts));
362 snd(hd(bts)) = mkInt(beta);
368 static Void local doneBtyvs(l)
370 if (nonNull(hd(btyvars))) { /* Save bound tyvars */
371 hd(pendingBtyvs) = cons(pair(mkInt(l),hd(btyvars)),hd(pendingBtyvs));
376 static Void local enterSkolVars() {
377 skolVars = cons(NIL,skolVars);
378 localEvs = cons(NIL,localEvs);
379 savedPs = cons(preds,savedPs);
383 static Void local leaveSkolVars(l,t,o,m)
388 if (nonNull(hd(localEvs))) { /* Check for local predicates */
389 List sks = hd(skolVars);
392 internal("leaveSkolVars");
394 markAllVars(); /* Mark all variables in current */
395 do { /* substitution, then unmark sks. */
396 tyvar(intOf(fst(hd(sks))))->offs = UNUSED_GENERIC;
398 } while (nonNull(sks));
400 sps = elimPredsUsing(hd(localEvs),sps);
401 preds = revOnto(preds,sps);
404 if (nonNull(hd(skolVars))) { /* Check that Skolem vars do not */
405 List vs; /* escape their scope */
408 clearMarks(); /* Look for occurences in the */
409 for (; i<m; i++) /* inferred type */
413 for (vs=hd(skolVars); nonNull(vs); vs=tl(vs)) {
414 Int vn = intOf(fst(hd(vs)));
415 if (tyvar(vn)->offs == FIXED_TYVAR) {
416 Cell tv = copyTyvar(vn);
417 Type ty = liftRank2(t,o,m);
418 ERRMSG(l) "Existentially quantified variable in inferred type"
420 ERRTEXT "\n*** Variable : " ETHEN ERRTYPE(tv);
421 ERRTEXT "\n*** From pattern : " ETHEN ERREXPR(snd(hd(vs)));
422 ERRTEXT "\n*** Result type : " ETHEN ERRTYPE(ty);
428 markBtyvs(); /* Now check assumptions */
429 mapProc(markAssumList,defnBounds);
430 mapProc(markAssumList,varsBounds);
432 for (vs=hd(skolVars); nonNull(vs); vs=tl(vs)) {
433 Int vn = intOf(fst(hd(vs)));
434 if (tyvar(vn)->offs == FIXED_TYVAR) {
436 "Existentially quantified variable escapes from pattern "
437 ETHEN ERREXPR(snd(hd(vs)));
443 localEvs = tl(localEvs);
444 skolVars = tl(skolVars);
445 preds = revOnto(preds,hd(savedPs));
446 savedPs = tl(savedPs);
449 /* --------------------------------------------------------------------------
451 * ------------------------------------------------------------------------*/
453 static Void local typeError(l,e,in,wh,t,o)
454 Int l; /* line number near type error */
455 String wh; /* place in which error occurs */
456 Cell e; /* source of error */
457 Cell in; /* context if any (NIL if not) */
458 Type t; /* should be of type (t,o) */
459 Int o; { /* type inferred is (typeIs,typeOff) */
461 clearMarks(); /* types printed here are monotypes */
462 /* use marking to give sensible names*/
464 { List vs = genericVars;
465 for (; nonNull(vs); vs=tl(vs)) {
466 Int v = intOf(hd(vs));
467 Printf("%c :: ", ('a'+tyvar(v)->offs));
468 printKind(stdout,tyvar(v)->kind);
474 reportTypeError(l,e,in,wh,copyType(typeIs,typeOff),copyType(t,o));
477 static Void local reportTypeError(l,e,in,wh,inft,expt)
478 Int l; /* Error printing part of typeError*/
482 ERRMSG(l) "Type error in %s", wh ETHEN
484 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(in);
486 ERRTEXT "\n*** Term : " ETHEN ERREXPR(e);
487 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(inft);
488 ERRTEXT "\n*** Does not match : " ETHEN ERRTYPE(expt);
490 ERRTEXT "\n*** Because : %s", unifyFails ETHEN
496 #define shouldBe(l,e,in,where,t,o) if (!unify(typeIs,typeOff,t,o)) \
497 typeError(l,e,in,where,t,o);
498 #define check(l,e,in,where,t,o) e=typeExpr(l,e); shouldBe(l,e,in,where,t,o)
499 #define inferType(t,o) typeIs=t; typeOff=o
501 #define spTypeExpr(l,e) svPreds = preds; preds = NIL; e = typeExpr(l,e); preds = revOnto(preds,svPreds);
502 #define spCheck(l,e,in,where,t,o) svPreds = preds; preds = NIL; check(l,e,in,where,t,o); preds = revOnto(preds,svPreds);
504 #define spTypeExpr(l,e) e = typeExpr(l,e);
505 #define spCheck(l,e,in,where,t,o) check(l,e,in,where,t,o);
508 static Void local cantEstablish(line,wh,e,t,ps)
509 Int line; /* Complain when declared preds */
510 String wh; /* are not sufficient to discharge */
511 Cell e; /* or defer the inferred context. */
514 ERRMSG(line) "Cannot justify constraints in %s", wh ETHEN
515 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
516 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(t);
517 ERRTEXT "\n*** Given context : " ETHEN ERRCONTEXT(ps);
518 ERRTEXT "\n*** Constraints : " ETHEN ERRCONTEXT(copyPreds(preds));
523 static Void local tooGeneral(l,e,dt,it) /* explicit type sig. too general */
527 ERRMSG(l) "Inferred type is not general enough" ETHEN
528 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
529 ERRTEXT "\n*** Expected type : " ETHEN ERRTYPE(dt);
530 ERRTEXT "\n*** Inferred type : " ETHEN ERRTYPE(it);
535 /* --------------------------------------------------------------------------
536 * Typing of expressions:
537 * ------------------------------------------------------------------------*/
539 #define EXPRESSION 0 /* type checking expression */
540 #define NEW_PATTERN 1 /* pattern, introducing new vars */
541 #define OLD_PATTERN 2 /* pattern, involving bound vars */
542 static int tcMode = EXPRESSION;
545 static Cell local mytypeExpr ( Int,Cell));
546 static Cell local typeExpr(l,e)
549 static int number = 0;
551 int mynumber = number++;
554 Printf("%d) to check: ",mynumber);
557 retv = mytypeExpr(l,e);
558 Printf("%d) result: ",mynumber);
559 printType(stdout,debugType(typeIs,typeOff));
560 Printf("\n%d) preds: ",mynumber);
561 printContext(stdout,debugContext(preds));
565 static Cell local mytypeExpr(l,e) /* Determine type of expr/pattern */
567 static Cell local typeExpr(l,e) /* Determine type of expr/pattern */
571 static String cond = "conditional";
572 static String list = "list";
573 static String discr = "case discriminant";
574 static String aspat = "as (@) pattern";
575 static String typeSig = "type annotation";
576 static String lambda = "lambda expression";
583 /* The following cases can occur in either pattern or expr. mode */
594 case TUPLE : typeTuple(e);
597 case BIGCELL : { Int alpha = newTyvars(1);
598 inferType(aVar,alpha);
599 return ap(ap(nameFromInteger,
600 assumeEvid(predNum,alpha)),
604 case INTCELL : { Int alpha = newTyvars(1);
605 inferType(aVar,alpha);
606 return ap(ap(nameFromInt,
607 assumeEvid(predNum,alpha)),
611 case FLOATCELL : { Int alpha = newTyvars(1);
612 inferType(aVar,alpha);
613 return ap(ap(nameFromDouble,
614 assumeEvid(predFractional,alpha)),
618 case STRCELL : inferType(typeString,0);
621 case CHARCELL : inferType(typeChar,0);
624 case CONFLDS : typeConFlds(l,e);
627 case ESIGN : snd(snd(e)) = localizeBtyvs(snd(snd(e)));
628 return typeExpected(l,typeSig,
629 fst(snd(e)),snd(snd(e)),
633 case EXT : { Int beta = newTyvars(2);
634 Cell pi = ap(e,aVar);
637 ap(typeRec,ap(ap(e,aVar),bVar))));
638 tyvar(beta+1)->kind = ROW;
640 return ap(e,assumeEvid(pi,beta+1));
644 /* The following cases can only occur in expr mode */
646 case UPDFLDS : typeUpdFlds(l,e);
650 case WITHEXP : return typeWith(l,e);
653 case COND : { Int beta = newTyvars(1);
654 check(l,fst3(snd(e)),e,cond,typeBool,0);
655 spCheck(l,snd3(snd(e)),e,cond,aVar,beta);
656 spCheck(l,thd3(snd(e)),e,cond,aVar,beta);
661 case LETREC : enterBindings();
663 mapProc(typeBindings,fst(snd(e)));
664 spTypeExpr(l,snd(snd(e)));
666 leaveSkolVars(l,typeIs,typeOff,0);
669 case FINLIST : { Int beta = newTyvars(1);
671 for (xs=snd(e); nonNull(xs); xs=tl(xs)) {
672 spCheck(l,hd(xs),e,list,aVar,beta);
674 inferType(listof,beta);
678 case DOCOMP : typeDo(l,e);
681 case COMP : return typeMonadComp(l,e);
683 case CASE : { Int beta = newTyvars(2); /* discr result */
684 check(l,fst(snd(e)),NIL,discr,aVar,beta);
685 map2Proc(typeCase,l,beta,snd(snd(e)));
690 case LAMBDA : { Int beta = newTyvars(1);
692 typeAlt(lambda,e,snd(e),aVar,beta,1);
699 case RECSEL : { Int beta = newTyvars(2);
700 Cell pi = ap(snd(e),aVar);
701 Type t = fn(ap(typeRec,
704 tyvar(beta+1)->kind = ROW;
706 return ap(e,assumeEvid(pi,beta+1));
710 /* The remaining cases can only occur in pattern mode: */
712 case WILDCARD : inferType(aVar,newTyvars(1));
715 case ASPAT : { Int beta = newTyvars(1);
716 snd(snd(e)) = typeExpr(l,snd(snd(e)));
717 bindTv(beta,typeIs,typeOff);
718 check(l,fst(snd(e)),e,aspat,aVar,beta);
723 case LAZYPAT : snd(e) = typeExpr(l,snd(e));
726 case ADDPAT : { Int alpha = newTyvars(1);
727 inferType(typeVarToVar,alpha);
728 return ap(e,assumeEvid(predIntegral,alpha));
731 default : internal("typeExpr");
737 /* --------------------------------------------------------------------------
738 * Typing rules for particular special forms:
739 * ------------------------------------------------------------------------*/
741 static Cell local typeAp(l,e) /* Type check application, which */
742 Int l; /* may be headed with a variable */
743 Cell e; { /* requires polymorphism, qualified*/
744 static String app = "application"; /* types, and possible rank2 args. */
755 case NAME : typeIs = name(h).type;
759 case VARIDCELL : if (tcMode==NEW_PATTERN) {
760 inferType(aVar,newVarsBind(e));
763 Cell v = findAssum(textOf(h));
766 typeIs = (tcMode==OLD_PATTERN)
771 h = findName(textOf(h));
774 typeIs = name(h).type;
780 case IPVAR : { Text t = textOf(h);
781 Int alpha = newTyvars(1);
782 Cell ip = pair(ap(IPCELL,t),aVar);
783 Cell ev = assumeEvid(ip,alpha);
784 typeIs = mkInt(alpha);
790 default : h = typeExpr(l,h);
794 if (isNull(typeIs)) {
798 instantiate(typeIs); /* Deal with polymorphism ... */
799 if (nonNull(predsAre)) { /* ... and with qualified types. */
801 for (; nonNull(predsAre); predsAre=tl(predsAre)) {
802 evs = cons(assumeEvid(hd(predsAre),typeOff),evs);
804 /* we now _always_ do this: if (!isName(h) || !isCfun(h)) */ {
805 h = applyToArgs(h,rev(evs));
809 if (whatIs(typeIs)==CDICTS) { /* Deal with local dictionaries */
810 List evs = makePredAss(fst(snd(typeIs)),typeOff);
812 typeIs = snd(snd(typeIs));
813 for (; nonNull(ps); ps=tl(ps)) {
814 h = ap(h,thd3(hd(ps)));
816 if (tcMode==EXPRESSION) {
817 preds = revOnto(evs,preds);
819 hd(localEvs) = revOnto(evs,hd(localEvs));
823 if (whatIs(typeIs)==EXIST) { /* Deal with existential arguments */
824 Int n = intOf(fst(snd(typeIs)));
825 typeIs = snd(snd(typeIs));
826 if (!isCfun(getHead(h)) || n>typeFree) {
828 } else if (tcMode!=EXPRESSION) {
829 Int alpha = typeOff + typeFree;
831 bindTv(alpha-n,SKOLEM,0);
832 hd(skolVars) = cons(pair(mkInt(alpha-n),e),hd(skolVars));
837 if (whatIs(typeIs)==RANK2) { /* Deal with rank 2 arguments */
840 Int nr2 = intOf(fst(snd(typeIs)));
841 Type body = snd(snd(typeIs));
845 if (n<nr2) { /* Must have enough arguments */
846 ERRMSG(l) "Use of " ETHEN ERREXPR(h);
848 ERRTEXT " in " ETHEN ERREXPR(e);
850 ERRTEXT " requires at least %d argument%s\n",
851 nr2, (nr2==1 ? "" : "s")
855 for (i=nr2; i<n; ++i) /* Find rank two arguments */
858 for (as=getArgs(as); nonNull(as); as=tl(as), body=arg(body)) {
859 Type expect = dropRank1(arg(fun(body)),alpha,m);
860 if (isPolyOrQualType(expect)) {
861 if (tcMode==EXPRESSION) /* poly/qual type in expr */
862 hd(as) = typeExpected(l,app,hd(as),expect,alpha,m,TRUE);
863 else if (hd(as)!=WILDCARD) { /* Pattern binding/match */
864 if (!isVar(hd(as))) {
865 ERRMSG(l) "Argument " ETHEN ERREXPR(arg(as));
866 ERRTEXT " in pattern " ETHEN ERREXPR(e);
867 ERRTEXT " where a variable is required\n"
870 if (tcMode==NEW_PATTERN) { /* Pattern match */
873 addVarAssump(dummyVar,mkInt(alpha+i));
876 addVarAssump(hd(as),expect);
878 else { /* Pattern binding */
879 Text t = textOf(hd(as));
880 Cell a = findInAssumList(t,hd(defnBounds));
884 if (nonNull(predsAre)) {
885 ERRMSG(l) "Cannot use pattern binding for " ETHEN
887 ERRTEXT " as a component with a qualified type\n"
890 shouldBe(l,hd(as),e,app,aVar,intOf(defType(snd(a))));
894 else { /* Not a poly/qual type */
895 spCheck(l,hd(as),e,app,expect,alpha);
897 h = ap(h,hd(as)); /* Save checked argument */
899 inferType(body,alpha);
903 if (n>0) { /* Deal with remaining args */
904 Int beta = funcType(n); /* check h::t1->t2->...->tn->rn+1 */
905 shouldBe(l,h,e,app,aVar,beta);
906 for (i=n; i>0; --i) { /* check e_i::t_i for each i */
907 spCheck(l,arg(a),e,app,aVar,beta+2*i-1);
911 tyvarType(beta+2*n); /* Inferred type is r_n+1 */
914 if (isNull(p)) /* Replace head with translation */
922 static Cell local typeExpected(l,wh,e,reqd,alpha,n,addEvid)
923 Int l; /* Type check expression e in wh */
924 String wh; /* at line l, expecting type reqd, */
925 Cell e; /* and treating vars alpha through */
926 Type reqd; /* (alpha+n-1) as fixed. */
929 Bool addEvid; { /* TRUE => add \ev -> ... */
930 List savePreds = preds;
941 ps = makePredAss(predsAre,o);
944 check(l,e,NIL,wh,t,o);
948 mapProc(markAssumList,defnBounds);
949 mapProc(markAssumList,varsBounds);
950 mapProc(markPred,savePreds);
953 if (n > 0) { /* mark alpha thru alpha+n-1, plus any */
954 /* type vars that are functionally */
955 List us = NIL, vs = NIL; /* dependent on them */
956 List fds = calcFunDepsPreds(preds);
957 for (i=0; i<n; i++) {
958 Type t1 = zonkTyvar(alpha+i);
959 us = zonkTyvarsIn(t1,us);
962 for (; nonNull(vs); vs=tl(vs))
963 markTyvar(intOf(hd(vs)));
967 savePreds = elimPredsUsing(ps,savePreds);
968 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
969 savePreds = elimPredsUsing(ps,savePreds);
970 if (nonNull(preds)) {
971 Type ty = copyType(t,o);
972 List qs = copyPreds(ps);
973 cantEstablish(l,wh,e,ty,qs);
978 if (copyTyvar(o+i)!=mkOffset(i)) {
979 List qs = copyPreds(ps);
980 Type it = copyType(t,o);
981 tooGeneral(l,e,reqd,generalize(qs,it));
985 e = qualifyExpr(l,ps,e);
989 preds = revOnto(ps,savePreds);
995 static Void local typeAlt(wh,e,a,t,o,m) /* Type check abstraction (Alt) */
996 String wh; /* a = ( [p1, ..., pn], rhs ) */
1003 List ps = fst(a) = patBtyvs(fst(a));
1005 Int l = rhsLine(snd(a));
1012 if (whatIs(t)==RANK2) {
1013 if (n<(nr2=intOf(fst(snd(t))))) {
1014 ERRMSG(l) "Definition requires at least %d parameters on lhs",
1021 while (getHead(t)==typeArrow && argCount==2 && nonNull(ps)) {
1022 Type ta = arg(fun(t));
1023 if (isPolyOrQualType(ta)) {
1024 if (hd(ps)!=WILDCARD) {
1025 if (!isVar(hd(ps))) {
1026 ERRMSG(l) "Argument " ETHEN ERREXPR(hd(ps));
1027 ERRTEXT " used where a variable or wildcard is required\n"
1030 if (m>0 && !added) {
1033 addVarAssump(dummyVar,mkInt(o+i));
1036 addVarAssump(hd(ps),ta);
1040 hd(ps) = typeFreshPat(l,hd(ps));
1041 shouldBe(l,hd(ps),NIL,wh,ta,o);
1050 snd(a) = typeRhs(snd(a));
1052 Int beta = funcType(n);
1055 hd(ps) = typeFreshPat(l,hd(ps));
1056 bindTv(beta+2*i+1,typeIs,typeOff);
1059 snd(a) = typeRhs(snd(a));
1060 bindTv(beta+2*n,typeIs,typeOff);
1064 if (!unify(typeIs,typeOff,t,o)) {
1067 req = liftRank2(origt,o,m);
1068 liftRank2Args(as,o,m);
1069 got = ap(RANK2,pair(mkInt(nr2),revOnto(as,copyType(typeIs,typeOff))));
1070 reportTypeError(l,e,NIL,wh,got,req);
1075 leaveSkolVars(l,origt,o,m);
1078 static Int local funcType(n) /*return skeleton for function type*/
1079 Int n; { /*with n arguments, taking the form*/
1080 Int beta = newTyvars(2*n+1); /* r1 t1 r2 t2 ... rn tn rn+1 */
1081 Int i; /* with r_i := t_i -> r_i+1 */
1083 bindTv(beta+2*i,arrow,beta+2*i+1);
1087 static Void local typeCase(l,beta,c) /* type check case: pat -> rhs */
1088 Int l; /* (case given by c == (pat,rhs)) */
1089 Int beta; /* need: pat :: (var,beta) */
1090 Cell c; { /* rhs :: (var,beta+1) */
1091 static String casePat = "case pattern";
1092 static String caseExpr = "case expression";
1096 fst(c) = typeFreshPat(l,patBtyvs(fst(c)));
1097 shouldBe(l,fst(c),NIL,casePat,aVar,beta);
1098 snd(c) = typeRhs(snd(c));
1099 shouldBe(l,rhsExpr(snd(c)),NIL,caseExpr,aVar,beta+1);
1103 leaveSkolVars(l,typeIs,typeOff,0);
1106 static Void local typeComp(l,m,e,qs) /* type check comprehension */
1108 Type m; /* monad (mkOffset(0)) */
1111 static String boolQual = "boolean qualifier";
1112 static String genQual = "generator";
1118 if (isNull(qs)) { /* no qualifiers left */
1119 spTypeExpr(l,fst(e));
1123 switch (whatIs(q)) {
1124 case BOOLQUAL : spCheck(l,snd(q),NIL,boolQual,typeBool,0);
1125 typeComp(l,m,e,qs1);
1128 case QWHERE : enterBindings();
1130 mapProc(typeBindings,snd(q));
1131 typeComp(l,m,e,qs1);
1133 leaveSkolVars(l,typeIs,typeOff,0);
1136 case FROMQUAL : { Int beta = newTyvars(1);
1138 spCheck(l,snd(snd(q)),NIL,genQual,m,beta);
1141 = typeFreshPat(l,patBtyvs(fst(snd(q))));
1142 shouldBe(l,fst(snd(q)),NIL,genQual,aVar,beta);
1143 typeComp(l,m,e,qs1);
1146 leaveSkolVars(l,typeIs,typeOff,0);
1150 case DOQUAL : spCheck(l,snd(q),NIL,genQual,m,newTyvars(1));
1151 typeComp(l,m,e,qs1);
1157 static Cell local typeMonadComp(l,e) /* type check monad comprehension */
1160 Int alpha = newTyvars(1);
1161 Int beta = newTyvars(1);
1162 Cell mon = ap(mkInt(beta),aVar);
1163 Cell m = assumeEvid(predMonad,beta);
1164 tyvar(beta)->kind = starToStar;
1166 bindTv(beta,typeList,0);
1170 typeComp(l,mon,snd(e),snd(snd(e)));
1171 bindTv(alpha,typeIs,typeOff);
1172 inferType(mon,alpha);
1173 return ap(MONADCOMP,pair(m,snd(e)));
1176 static Void local typeDo(l,e) /* type check do-notation */
1179 static String finGen = "final generator";
1180 Int alpha = newTyvars(1);
1181 Int beta = newTyvars(1);
1182 Cell mon = ap(mkInt(beta),aVar);
1183 Cell m = assumeEvid(predMonad,beta);
1184 tyvar(beta)->kind = starToStar;
1186 typeComp(l,mon,snd(e),snd(snd(e)));
1187 shouldBe(l,fst(snd(e)),NIL,finGen,mon,alpha);
1188 snd(e) = pair(m,snd(e));
1191 static Void local typeConFlds(l,e) /* Type check a construction */
1194 static String conExpr = "value construction";
1195 Name c = fst(snd(e));
1196 List fs = snd(snd(e));
1205 instantiate(name(c).type);
1206 for (; nonNull(predsAre); predsAre=tl(predsAre))
1207 assumeEvid(hd(predsAre),typeOff);
1208 if (whatIs(typeIs)==RANK2)
1209 typeIs = snd(snd(typeIs));
1214 for (; nonNull(fs); fs=tl(fs)) {
1216 for (i=sfunPos(fst(hd(fs)),c); --i>0; t=arg(t))
1218 t = dropRank1(arg(fun(t)),to,tf);
1219 if (isPolyOrQualType(t))
1220 snd(hd(fs)) = typeExpected(l,conExpr,snd(hd(fs)),t,to,tf,TRUE);
1222 spCheck(l,snd(hd(fs)),e,conExpr,t,to);
1225 for (i=name(c).arity; i>0; i--)
1230 static Void local typeUpdFlds(line,e) /* Type check an update */
1231 Int line; /* (Written in what might seem a */
1232 Cell e; { /* bizarre manner for the benefit */
1233 static String update = "update"; /* of as yet unreleased extensions)*/
1234 List cs = snd3(snd(e)); /* List of constructors */
1235 List fs = thd3(snd(e)); /* List of field specifications */
1236 List ts = NIL; /* List of types for fields */
1238 Int alpha = newTyvars(2+n);
1245 /* Calculate type and translation for each expr in the field list */
1246 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1247 spTypeExpr(line,snd(hd(fs1)));
1248 bindTv(i,typeIs,typeOff);
1252 mapProc(markAssumList,defnBounds);
1253 mapProc(markAssumList,varsBounds);
1254 mapProc(markPred,preds);
1257 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1259 ts = cons(generalize(NIL,copyTyvar(i)),ts);
1263 /* Type check expression to be updated */
1264 spTypeExpr(line,fst3(snd(e)));
1265 bindTv(alpha,typeIs,typeOff);
1267 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constrs */
1269 List ta = replicate(name(c).arity,NIL);
1273 tcMode = NEW_PATTERN; /* Domain type */
1274 instantiate(name(c).type);
1275 tcMode = EXPRESSION;
1278 for (; nonNull(predsAre); predsAre=tl(predsAre))
1279 assumeEvid(hd(predsAre),typeOff);
1281 if (whatIs(typeIs)==RANK2) {
1282 ERRMSG(line) "Sorry, record update syntax cannot currently be "
1283 "used for datatypes with polymorphic components"
1287 instantiate(name(c).type); /* Range type */
1290 for (; nonNull(predsAre); predsAre=tl(predsAre))
1291 assumeEvid(hd(predsAre),typeOff);
1293 for (fs1=fs, i=1; nonNull(fs1); fs1=tl(fs1), i++) {
1294 Int n = sfunPos(fst(hd(fs1)),c);
1301 for (; nonNull(ta); ta=tl(ta)) { /* For each cfun arg */
1302 if (nonNull(hd(ta))) { /* Field to updated? */
1303 Int n = intOf(hd(ta));
1306 for (; n-- > 1; f=tl(f), t=tl(t))
1311 shouldBe(line,snd(f),e,update,arg(fun(tr)),or);
1312 } /* Unmentioned component */
1313 else if (!unify(arg(fun(td)),od,arg(fun(tr)),or))
1314 internal("typeUpdFlds");
1320 inferType(td,od); /* Check domain type */
1321 shouldBe(line,fst3(snd(e)),e,update,aVar,alpha);
1322 inferType(tr,or); /* Check range type */
1323 shouldBe(line,e,NIL,update,aVar,alpha+1);
1325 /* (typeIs,typeOff) still carry the result type when we exit the loop */
1329 static Cell local typeWith(line,e) /* Type check a with */
1332 List fs = snd(snd(e)); /* List of field specifications */
1334 Int alpha = newTyvars(2+n);
1339 List dpreds = NIL, dp;
1342 /* Type check expression to be updated */
1343 fst(snd(e)) = typeExpr(line,fst(snd(e)));
1344 bindTv(alpha,typeIs,typeOff);
1347 /* elim duplicate uses of imp params */
1348 preds = scSimplify(preds);
1349 /* extract preds that we're going to bind */
1350 for (fs1=fs; nonNull(fs1); fs1=tl(fs1)) {
1351 Text t = textOf(fst(hd(fs1)));
1352 Cell p = findIPEvid(t);
1353 dpreds = cons(p, dpreds);
1357 /* maybe give a warning message here... */
1360 dpreds = rev(dpreds);
1362 /* Calculate type and translation for each expr in the field list */
1363 for (fs1=fs, dp=dpreds, i=alpha+2; nonNull(fs1); fs1=tl(fs1), dp=tl(dp), i++) {
1364 static String with = "with";
1366 snd(hd(fs1)) = typeExpr(line,snd(hd(fs1)));
1367 bindTv(i,typeIs,typeOff);
1369 shouldBe(line,fst(hd(fs1)),e,with,snd(fst3(ev)),intOf(snd3(ev)));
1370 bs = cons(cons(pair(thd3(ev), cons(triple(NIL, mkInt(line), snd(hd(fs1))), NIL)), NIL), bs);
1375 return (ap(LETREC,pair(bs,fst(snd(e)))));
1379 static Cell local typeFreshPat(l,p) /* find type of pattern, assigning */
1380 Int l; /* fresh type variables to each var */
1381 Cell p; { /* bound in the pattern */
1382 tcMode = NEW_PATTERN;
1384 tcMode = EXPRESSION;
1388 /* --------------------------------------------------------------------------
1389 * Type check group of bindings:
1390 * ------------------------------------------------------------------------*/
1392 static Void local typeBindings(bs) /* type check a binding group */
1394 Bool usesPatBindings = FALSE; /* TRUE => pattern binding in bs */
1395 Bool usesUntypedVar = FALSE; /* TRUE => var bind w/o type decl */
1398 /* The following loop is used to determine whether the monomorphism */
1399 /* restriction should be applied. It could be written marginally more */
1400 /* efficiently by using breaks, but clarity is more important here ... */
1402 for (bs1=bs; nonNull(bs1); bs1=tl(bs1)) { /* Analyse binding group */
1405 usesPatBindings = TRUE;
1406 else if (isNull(fst(hd(snd(snd(b))))) /* no arguments */
1407 && whatIs(fst(snd(b)))==IMPDEPS) /* implicitly typed*/
1408 usesUntypedVar = TRUE;
1411 if (usesPatBindings || usesUntypedVar)
1416 mapProc(removeTypeSigs,bs); /* Remove binding type info */
1417 hd(varsBounds) = revOnto(hd(defnBounds), /* transfer completed assmps*/
1418 hd(varsBounds)); /* out of defnBounds */
1419 hd(defnBounds) = NIL;
1423 static Void local removeTypeSigs(b) /* Remove type info from a binding */
1425 snd(b) = snd(snd(b));
1428 /* --------------------------------------------------------------------------
1429 * Type check a restricted binding group:
1430 * ------------------------------------------------------------------------*/
1432 static Void local monorestrict(bs) /* Type restricted binding group */
1434 List savePreds = preds;
1435 Int line = isVar(fst(hd(bs))) ? rhsLine(snd(hd(snd(snd(hd(bs))))))
1436 : rhsLine(snd(snd(snd(hd(bs)))));
1437 hd(defnBounds) = NIL;
1438 hd(depends) = NODEPENDS; /* No need for dependents here */
1440 preds = NIL; /* Type check the bindings */
1441 mapProc(restrictedBindAss,bs);
1442 mapProc(typeBind,bs);
1443 improve(line,NIL,preds);
1446 preds = revOnto(preds,savePreds);
1448 clearMarks(); /* Mark fixed variables */
1449 mapProc(markAssumList,tl(defnBounds));
1450 mapProc(markAssumList,tl(varsBounds));
1451 mapProc(markPred,preds);
1454 if (isNull(tl(defnBounds))) { /* Top-level may need defaulting */
1456 if (nonNull(preds) && resolveDefs(genvarAnyAss(hd(defnBounds))))
1461 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
1464 if (nonNull(preds)) { /* Look for unresolved overloading */
1465 Cell v = isVar(fst(hd(bs))) ? fst(hd(bs)) : hd(fst(hd(bs)));
1466 Cell ass = findInAssumList(textOf(v),hd(varsBounds));
1467 preds = scSimplify(preds);
1469 ERRMSG(line) "Unresolved top-level overloading" ETHEN
1470 ERRTEXT "\n*** Binding : %s", textToStr(textOf(v))
1473 ERRTEXT "\n*** Inferred type : " ETHEN ERRTYPE(snd(ass));
1475 ERRTEXT "\n*** Outstanding context : " ETHEN
1476 ERRCONTEXT(copyPreds(preds));
1482 map1Proc(genBind,NIL,bs); /* Generalize types of def'd vars */
1485 static Void local restrictedBindAss(b) /* Make assums for vars in binding */
1486 Cell b; { /* gp with restricted overloading */
1488 if (isVar(fst(b))) { /* function-binding? */
1489 Cell t = fst(snd(b));
1490 if (whatIs(t)==IMPDEPS) { /* Discard implicitly typed deps */
1491 fst(snd(b)) = t = NIL; /* in a restricted binding group. */
1493 fst(snd(b)) = localizeBtyvs(t);
1494 restrictedAss(rhsLine(snd(hd(snd(snd(b))))), fst(b), t);
1495 } else { /* pattern-binding? */
1497 List ts = fst(snd(b));
1498 Int line = rhsLine(snd(snd(snd(b))));
1500 for (; nonNull(vs); vs=tl(vs)) {
1502 restrictedAss(line,hd(vs),hd(ts)=localizeBtyvs(hd(ts)));
1505 restrictedAss(line,hd(vs),NIL);
1511 static Void local restrictedAss(l,v,t) /* Assume that type of binding var v*/
1512 Int l; /* is t (if nonNull) in restricted */
1513 Cell v; /* binding group */
1516 if (nonNull(predsAre)) {
1517 ERRMSG(l) "Explicit overloaded type for \"%s\"",textToStr(textOf(v))
1519 ERRTEXT " not permitted in restricted binding"
1524 /* --------------------------------------------------------------------------
1525 * Unrestricted binding group:
1526 * ------------------------------------------------------------------------*/
1528 static Void local unrestricted(bs) /* Type unrestricted binding group */
1530 List savePreds = preds;
1531 List imps = NIL; /* Implicitly typed bindings */
1532 List exps = NIL; /* Explicitly typed bindings */
1535 /* ----------------------------------------------------------------------
1536 * STEP 1: Separate implicitly typed bindings from explicitly typed
1537 * bindings and do a dependency analyis, where f depends on g iff f
1538 * is implicitly typed and involves a call to g.
1539 * --------------------------------------------------------------------*/
1541 for (; nonNull(bs); bs=tl(bs)) {
1543 if (whatIs(fst(snd(b)))==IMPDEPS)
1544 imps = cons(b,imps); /* N.B. New lists are built to */
1545 else /* avoid breaking the original */
1546 exps = cons(b,exps); /* list structure for bs. */
1549 for (bs=imps; nonNull(bs); bs=tl(bs)) {
1550 Cell b = hd(bs); /* Restrict implicitly typed dep */
1551 List ds = snd(fst(snd(b))); /* lists to bindings in imps */
1553 while (nonNull(ds)) {
1555 if (cellIsMember(hd(ds),imps)) {
1563 imps = itbscc(imps); /* Dependency analysis on imps */
1564 for (bs=imps; nonNull(bs); bs=tl(bs))
1565 for (bs1=hd(bs); nonNull(bs1); bs1=tl(bs1))
1566 fst(snd(hd(bs1))) = NIL; /* reset imps type fields */
1568 #ifdef DEBUG_DEPENDS
1569 Printf("Binding group:");
1570 for (bs1=imps; nonNull(bs1); bs1=tl(bs1)) {
1572 for (bs=hd(bs1); nonNull(bs); bs=tl(bs))
1573 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1576 if (nonNull(exps)) {
1578 for (bs=exps; nonNull(bs); bs=tl(bs))
1579 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1585 /* ----------------------------------------------------------------------
1586 * STEP 2: Add type assumptions about any explicitly typed variable.
1587 * --------------------------------------------------------------------*/
1589 for (bs=exps; nonNull(bs); bs=tl(bs)) {
1590 fst(snd(hd(bs))) = localizeBtyvs(fst(snd(hd(bs))));
1591 hd(varsBounds) = cons(pair(fst(hd(bs)),fst(snd(hd(bs)))),
1595 /* ----------------------------------------------------------------------
1596 * STEP 3: Calculate types for each group of implicitly typed bindings.
1597 * --------------------------------------------------------------------*/
1599 for (; nonNull(imps); imps=tl(imps)) {
1600 Cell b = hd(hd(imps));
1601 Int line = isVar(fst(b)) ? rhsLine(snd(hd(snd(snd(b)))))
1602 : rhsLine(snd(snd(snd(b))));
1603 hd(defnBounds) = NIL;
1605 for (bs1=hd(imps); nonNull(bs1); bs1=tl(bs1))
1606 newDefnBind(fst(hd(bs1)),NIL);
1609 mapProc(typeBind,hd(imps));
1610 improve(line,NIL,preds);
1613 mapProc(markAssumList,tl(defnBounds));
1614 mapProc(markAssumList,tl(varsBounds));
1615 mapProc(markPred,savePreds);
1619 savePreds = elimOuterPreds(savePreds);
1620 if (nonNull(preds) && resolveDefs(genvarAllAss(hd(defnBounds)))) {
1621 savePreds = elimOuterPreds(savePreds);
1624 map1Proc(genBind,preds,hd(imps));
1625 if (nonNull(preds)) {
1626 map1Proc(addEvidParams,preds,hd(depends));
1627 map1Proc(qualifyBinding,preds,hd(imps));
1630 h98CheckType(line,"inferred type",
1631 fst(hd(hd(defnBounds))),snd(hd(hd(defnBounds))));
1632 hd(varsBounds) = revOnto(hd(defnBounds),hd(varsBounds));
1635 /* ----------------------------------------------------------------------
1636 * STEP 4: Now infer a type for each explicitly typed variable and
1637 * check for compatibility with the declared type.
1638 * --------------------------------------------------------------------*/
1640 for (; nonNull(exps); exps=tl(exps)) {
1641 static String extbind = "explicitly typed binding";
1643 List alts = snd(snd(b));
1644 Int line = rhsLine(snd(hd(alts)));
1650 hd(defnBounds) = NIL;
1651 hd(depends) = NODEPENDS;
1654 instantiate(fst(snd(b)));
1657 t = dropRank2(typeIs,o,m);
1658 ps = makePredAss(predsAre,o);
1660 enterPendingBtyvs();
1661 for (; nonNull(alts); alts=tl(alts))
1662 typeAlt(extbind,fst(b),hd(alts),t,o,m);
1663 improve(line,ps,preds);
1664 leavePendingBtyvs();
1666 if (nonNull(ps)) /* Add dict params, if necessary */
1667 qualifyBinding(ps,b);
1670 mapProc(markAssumList,tl(defnBounds));
1671 mapProc(markAssumList,tl(varsBounds));
1672 mapProc(markPred,savePreds);
1676 savePreds = elimPredsUsing(ps,savePreds);
1677 if (nonNull(preds)) {
1681 vs = cons(mkInt(o+i),vs);
1682 if (resolveDefs(vs)) {
1683 savePreds = elimPredsUsing(ps,savePreds);
1685 if (nonNull(preds)) {
1688 if (nonNull(preds) && resolveDefs(vs))
1689 savePreds = elimPredsUsing(ps,savePreds);
1693 resetGenerics(); /* Make sure we're general enough */
1695 t = generalize(ps,liftRank2(t,o,m));
1697 if (!sameSchemes(t,fst(snd(b))))
1698 tooGeneral(line,fst(b),fst(snd(b)),t);
1699 h98CheckType(line,"inferred type",fst(b),t);
1701 if (nonNull(preds)) /* Check context was strong enough */
1702 cantEstablish(line,extbind,fst(b),t,ps);
1705 preds = savePreds; /* Restore predicates */
1706 hd(defnBounds) = NIL;
1709 #define SCC itbscc /* scc for implicitly typed binds */
1710 #define LOWLINK itblowlink
1711 #define DEPENDS(t) fst(snd(t))
1712 #define SETDEPENDS(c,v) fst(snd(c))=v
1719 static Void local addEvidParams(qs,v) /* overwrite VARID/OPCELL v with */
1720 List qs; /* application of variable to evid. */
1721 Cell v; { /* parameters given by qs */
1726 internal("addEvidParams");
1728 for (nv=mkVar(textOf(v)); nonNull(tl(qs)); qs=tl(qs))
1729 nv = ap(nv,thd3(hd(qs)));
1731 snd(v) = thd3(hd(qs));
1735 /* --------------------------------------------------------------------------
1736 * Type check bodies of class and instance declarations:
1737 * ------------------------------------------------------------------------*/
1739 static Void local typeClassDefn(c) /* Type check implementations of */
1740 Class c; { /* defaults for class c */
1742 /* ----------------------------------------------------------------------
1743 * Generate code for default dictionary builder functions:
1744 * --------------------------------------------------------------------*/
1746 Int beta = newKindedVars(cclass(c).kinds);
1747 Cell d = inventDictVar();
1748 List dparam = singleton(triple(cclass(c).head,mkInt(beta),d));
1749 List mems = cclass(c).members;
1750 List defs = cclass(c).defaults;
1751 List dsels = cclass(c).dsels;
1752 Cell pat = cclass(c).dcon;
1753 Int width = cclass(c).numSupers + cclass(c).numMembers;
1754 char buf[FILENAME_MAX+1];
1758 if (isNull(defs) && nonNull(mems)) {
1759 defs = cclass(c).defaults = cons(NIL,NIL);
1762 for (; nonNull(mems); mems=tl(mems)) {
1763 /* static String deftext = "default_"; */
1764 static String deftext = "$dm";
1765 String s = textToStr(name(hd(mems)).text);
1768 for (; i<FILENAME_MAX && deftext[i]!='\0'; i++) {
1769 buf[i] = deftext[i];
1771 for(; (i+j)<FILENAME_MAX && s[j]!='\0'; j++) {
1775 n = newName(findText(buf),c);
1777 if (isNull(hd(defs))) { /* No default definition */
1778 static String header = "Undefined member: ";
1779 for (i=0; i<FILENAME_MAX && header[i]!='\0'; i++)
1781 for (j=0; (i+j)<FILENAME_MAX && s[j]!='\0'; j++)
1784 name(n).line = cclass(c).line;
1786 name(n).defn = singleton(pair(singleton(d),
1787 ap(mkInt(cclass(c).line),
1790 findText(buf)))))));
1791 } else { /* User supplied default defn */
1792 List alts = snd(hd(defs));
1793 Int line = rhsLine(snd(hd(alts)));
1795 typeMember("default member binding",
1802 name(n).line = line;
1803 name(n).arity = 1+length(fst(hd(alts)));
1804 name(n).defn = alts;
1806 for (; nonNull(alts); alts=tl(alts)) {
1807 fst(hd(alts)) = cons(d,fst(hd(alts)));
1812 genDefns = cons(n,genDefns);
1813 if (isNull(tl(defs)) && nonNull(tl(mems))) {
1814 tl(defs) = cons(NIL,NIL);
1819 /* ----------------------------------------------------------------------
1820 * Generate code for superclass and member function selectors:
1821 * --------------------------------------------------------------------*/
1823 for (i=0; i<width; i++) {
1824 pat = ap(pat,inventVar());
1826 pat = singleton(pat);
1827 for (i=0; nonNull(dsels); dsels=tl(dsels)) {
1828 name(hd(dsels)).defn = singleton(pair(pat,
1829 ap(mkInt(cclass(c).line),
1830 nthArg(i++,hd(pat)))));
1831 genDefns = cons(hd(dsels),genDefns);
1833 for (mems=cclass(c).members; nonNull(mems); mems=tl(mems)) {
1834 name(hd(mems)).defn = singleton(pair(pat,
1835 ap(mkInt(name(hd(mems)).line),
1836 nthArg(i++,hd(pat)))));
1837 genDefns = cons(hd(mems),genDefns);
1841 static Void local typeInstDefn(in) /* Type check implementations of */
1842 Inst in; { /* member functions for instance in*/
1844 /* ----------------------------------------------------------------------
1845 * Generate code for instance specific dictionary builder function:
1847 * inst.maker d1 ... dn = let sc1 = ...
1853 * d = Make.C sc1 ... scm v1 ... vk
1856 * where sci are superclass dictionaries, d is a new name, vj
1857 * is a newly generated name corresponding to the implementation of a
1858 * member function. (Additional line number values must be added at
1859 * appropriate places but, for clarity, these are not shown above.)
1860 * If no implementation of a particular vj is available, then we use
1861 * the default implementation, partially applied to d.
1862 * --------------------------------------------------------------------*/
1864 Int alpha = newKindedVars(cclass(inst(in).c).kinds);
1865 List supers = makePredAss(cclass(inst(in).c).supers,alpha);
1866 Int beta = newKindedVars(inst(in).kinds);
1867 List params = makePredAss(inst(in).specifics,beta);
1868 Cell d = inventDictVar();
1870 List evids = cons(triple(inst(in).head,mkInt(beta),d),
1871 appendOnto(dupList(params),supers));
1873 List evids = dupList(params);
1875 List imps = inst(in).implements;
1876 Cell l = mkInt(inst(in).line);
1877 Cell dictDef = cclass(inst(in).c).dcon;
1878 List mems = cclass(inst(in).c).members;
1879 List defs = cclass(inst(in).c).defaults;
1884 if (!unifyPred(cclass(inst(in).c).head,alpha,inst(in).head,beta))
1885 internal("typeInstDefn");
1887 for (ps=params; nonNull(ps); ps=tl(ps)) /* Build arglist */
1888 args = cons(thd3(hd(ps)),args);
1891 for (ps=supers; nonNull(ps); ps=tl(ps)) { /* Superclass dictionaries */
1894 #if EXPLAIN_INSTANCE_RESOLUTION
1896 fputs("scEntail: ", stdout);
1897 printContext(stdout,copyPreds(params));
1898 fputs(" ||- ", stdout);
1899 printPred(stdout, copyPred(fst3(pi),intOf(snd3(pi))));
1900 fputc('\n', stdout);
1903 ev = scEntail(params,fst3(pi),intOf(snd3(pi)),0);
1905 #if EXPLAIN_INSTANCE_RESOLUTION
1907 fputs("inEntail: ", stdout);
1908 printContext(stdout,copyPreds(evids));
1909 fputs(" ||- ", stdout);
1910 printPred(stdout, copyPred(fst3(pi),intOf(snd3(pi))));
1911 fputc('\n', stdout);
1914 ev = inEntail(evids,fst3(pi),intOf(snd3(pi)),0);
1918 ERRMSG(inst(in).line) "Cannot build superclass instance" ETHEN
1919 ERRTEXT "\n*** Instance : " ETHEN
1920 ERRPRED(copyPred(inst(in).head,beta));
1921 ERRTEXT "\n*** Context supplied : " ETHEN
1922 ERRCONTEXT(copyPreds(params));
1923 ERRTEXT "\n*** Required superclass : " ETHEN
1924 ERRPRED(copyPred(fst3(pi),intOf(snd3(pi))));
1928 locs = cons(pair(thd3(pi),singleton(pair(NIL,ap(l,ev)))),locs);
1929 dictDef = ap(dictDef,thd3(pi));
1932 for (; nonNull(defs); defs=tl(defs)) {
1934 if (nonNull(imps)) {
1939 dictDef = ap(dictDef,ap(hd(defs),d));
1941 Cell v = inventVar();
1942 dictDef = ap(dictDef,v);
1943 typeMember("instance member binding",
1949 locs = cons(pair(v,snd(imp)),locs);
1953 locs = cons(pair(d,singleton(pair(NIL,ap(l,dictDef)))),locs);
1955 name(inst(in).builder).defn /* Register builder imp */
1956 = singleton(pair(args,ap(LETREC,pair(singleton(locs),
1959 /* Invent a GHC-compatible name for the instance decl */
1961 char buf[FILENAME_MAX+1];
1965 Cell qq = inst(in).head;
1967 static String zdftext = "$f";
1970 pp = cons(arg(qq),pp);
1973 // pp is now the fwd list of args(?) to this pred
1976 for (j = 0; i<FILENAME_MAX && zdftext[j]!='\0'; i++, j++) {
1977 buf[i] = zdftext[j];
1979 str = textToStr(cclass(inst(in).c).text);
1980 for (j = 0; i<FILENAME_MAX && str[j]!='\0'; i++, j++) {
1985 while (isAp(qq)) qq = fun(qq);
1986 switch (whatIs(qq)) {
1987 case TYCON: str = textToStr(tycon(qq).text); break;
1988 case TUPLE: str = textToStr(ghcTupleText(qq)); break;
1989 case OFFSET: sprintf(buf2,"%d",offsetOf(qq));
1992 default: internal("typeInstDefn: making GHC name"); break;
1994 for (j = 0; i<FILENAME_MAX && str[j]!='\0'; i++, j++) {
2000 name(inst(in).builder).text = findText(buf);
2001 //fprintf ( stderr, "result = %s\n", buf );
2004 genDefns = cons(inst(in).builder,genDefns);
2007 static Void local typeMember(wh,mem,alts,evids,head,beta)
2008 String wh; /* Type check alternatives alts of */
2009 Name mem; /* member mem for inst type head */
2010 Cell alts; /* at offset beta using predicate */
2011 List evids; /* assignment evids */
2014 Int line = rhsLine(snd(hd(alts)));
2023 Printf("\nType check member: ");
2024 printExp(stdout,mem);
2026 printType(stdout,name(mem).type);
2027 Printf("\n for the instance: ");
2028 printPred(stdout,head);
2032 instantiate(name(mem).type); /* Find required type */
2035 t = dropRank2(typeIs,o,m);
2036 ps = makePredAss(predsAre,o);
2037 if (!unifyPred(hd(predsAre),typeOff,head,beta))
2038 internal("typeMember1");
2041 rt = generalize(qs,liftRank2(t,o,m));
2044 Printf("Required type is: ");
2045 printType(stdout,rt);
2049 hd(defnBounds) = NIL; /* Type check each alternative */
2050 hd(depends) = NODEPENDS;
2051 enterPendingBtyvs();
2052 for (preds=NIL; nonNull(alts); alts=tl(alts)) {
2053 typeAlt(wh,mem,hd(alts),t,o,m);
2054 qualify(tl(ps),hd(alts)); /* Add any extra dict params */
2056 improve(line,evids,preds);
2057 leavePendingBtyvs();
2059 evids = appendOnto(dupList(tl(ps)), /* Build full complement of dicts */
2063 qs = elimPredsUsing(evids,NIL);
2064 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
2065 qs = elimPredsUsing(evids,qs);
2068 "Implementation of %s requires extra context",
2069 textToStr(name(mem).text) ETHEN
2070 ERRTEXT "\n*** Expected type : " ETHEN ERRTYPE(rt);
2071 ERRTEXT "\n*** Missing context : " ETHEN ERRCONTEXT(copyPreds(qs));
2076 resetGenerics(); /* Make sure we're general enough */
2078 t = generalize(ps,liftRank2(t,o,m));
2080 Printf(" Inferred type is: ");
2081 printType(stdout,t);
2084 if (!sameSchemes(t,rt))
2085 tooGeneral(line,mem,rt,t);
2086 if (nonNull(preds)) {
2087 preds = scSimplify(preds);
2088 cantEstablish(line,wh,mem,t,ps);
2092 /* --------------------------------------------------------------------------
2093 * Type check bodies of bindings:
2094 * ------------------------------------------------------------------------*/
2096 static Void local typeBind(b) /* Type check binding */
2098 if (isVar(fst(b))) { /* function binding */
2099 Cell ass = findTopBinding(fst(b));
2103 internal("typeBind");
2105 beta = intOf(defType(snd(ass)));
2106 enterPendingBtyvs();
2107 map2Proc(typeDefAlt,beta,fst(b),snd(snd(b)));
2108 leavePendingBtyvs();
2110 else { /* pattern binding */
2111 static String lhsPat = "lhs pattern";
2112 static String rhs = "right hand side";
2113 Int beta = newTyvars(1);
2114 Pair pb = snd(snd(b));
2115 Int l = rhsLine(snd(pb));
2117 tcMode = OLD_PATTERN;
2118 enterPendingBtyvs();
2119 fst(pb) = patBtyvs(fst(pb));
2120 check(l,fst(pb),NIL,lhsPat,aVar,beta);
2121 tcMode = EXPRESSION;
2122 snd(pb) = typeRhs(snd(pb));
2123 shouldBe(l,rhsExpr(snd(pb)),NIL,rhs,aVar,beta);
2125 leavePendingBtyvs();
2129 static Void local typeDefAlt(beta,v,a) /* type check alt in func. binding */
2133 static String valDef = "function binding";
2134 typeAlt(valDef,v,a,aVar,beta,0);
2137 static Cell local typeRhs(e) /* check type of rhs of definition */
2139 switch (whatIs(e)) {
2140 case GUARDED : { Int beta = newTyvars(1);
2141 map1Proc(guardedType,beta,snd(e));
2146 case LETREC : enterBindings();
2148 mapProc(typeBindings,fst(snd(e)));
2149 snd(snd(e)) = typeRhs(snd(snd(e)));
2151 leaveSkolVars(rhsLine(snd(snd(e))),typeIs,typeOff,0);
2154 case RSIGN : fst(snd(e)) = typeRhs(fst(snd(e)));
2155 shouldBe(rhsLine(fst(snd(e))),
2156 rhsExpr(fst(snd(e))),NIL,
2161 default : snd(e) = typeExpr(intOf(fst(e)),snd(e));
2167 static Void local guardedType(beta,gded)/* check type of guard (li,(gd,ex))*/
2168 Int beta; /* should have gd :: Bool, */
2169 Cell gded; { /* ex :: (var,beta) */
2170 static String guarded = "guarded expression";
2171 static String guard = "guard";
2172 Int line = intOf(fst(gded));
2178 spCheck(line,fst(gded),NIL,guard,typeBool,0);
2179 spCheck(line,snd(gded),NIL,guarded,aVar,beta);
2182 Cell rhsExpr(rhs) /* find first expression on a rhs */
2185 switch (whatIs(rhs)) {
2186 case GUARDED : return snd(snd(hd(snd(rhs))));
2187 case LETREC : return rhsExpr(snd(snd(rhs)));
2188 case RSIGN : return rhsExpr(fst(snd(rhs)));
2189 default : return snd(rhs);
2193 Int rhsLine(rhs) /* find line number associated with */
2194 Cell rhs; { /* a right hand side */
2196 switch (whatIs(rhs)) {
2197 case GUARDED : return intOf(fst(hd(snd(rhs))));
2198 case LETREC : return rhsLine(snd(snd(rhs)));
2199 case RSIGN : return rhsLine(fst(snd(rhs)));
2200 default : return intOf(fst(rhs));
2204 /* --------------------------------------------------------------------------
2205 * Calculate generalization of types and compare with declared type schemes:
2206 * ------------------------------------------------------------------------*/
2208 static Void local genBind(ps,b) /* Generalize the type of each var */
2209 List ps; /* defined in binding b, qualifying*/
2210 Cell b; { /* each with the predicates in ps. */
2212 Cell t = fst(snd(b));
2215 genAss(rhsLine(snd(hd(snd(snd(b))))),ps,v,t);
2217 Int line = rhsLine(snd(snd(snd(b))));
2218 for (; nonNull(v); v=tl(v)) {
2224 genAss(line,ps,hd(v),ty);
2229 static Void local genAss(l,ps,v,dt) /* Calculate inferred type of v and*/
2230 Int l; /* compare with declared type, dt, */
2231 List ps; /* if given & check for ambiguity. */
2234 Cell ass = findTopBinding(v);
2239 snd(ass) = genTest(l,v,ps,dt,aVar,intOf(defType(snd(ass))));
2244 printType(stdout,snd(ass));
2249 static Type local genTest(l,v,ps,dt,t,o)/* Generalize and test inferred */
2250 Int l; /* type (t,o) with context ps */
2251 Cell v; /* against declared type dt for v. */
2256 Type bt = NIL; /* Body of inferred type */
2257 Type it = NIL; /* Full inferred type */
2259 resetGenerics(); /* Calculate Haskell typing */
2262 it = generalize(ps,bt);
2264 if (nonNull(dt)) { /* If a declared type was given, */
2265 instantiate(dt); /* check body for match. */
2266 if (!equalTypes(typeIs,bt))
2267 tooGeneral(l,v,dt,it);
2269 else if (nonNull(ps)) /* Otherwise test for ambiguity in */
2270 if (isAmbiguous(it)) /* inferred type. */
2271 ambigError(l,"inferred type",v,it);
2276 static Type local generalize(qs,t) /* calculate generalization of t */
2277 List qs; /* having already marked fixed vars*/
2278 Type t; { /* with qualifying preds qs */
2280 t = ap(QUAL,pair(qs,t));
2281 if (nonNull(genericVars)) {
2283 List vs = genericVars;
2284 for (; nonNull(vs); vs=tl(vs)) {
2285 Tyvar *tyv = tyvar(intOf(hd(vs)));
2286 Kind ka = tyv->kind;
2289 t = mkPolyType(k,t);
2291 Printf("Generalized type: ");
2292 printType(stdout,t);
2294 printKind(stdout,k);
2301 static Bool local equalTypes(t1,t2) /* Compare simple types for equality*/
2304 et: if (whatIs(t1)!=whatIs(t2))
2307 switch (whatIs(t1)) {
2313 case TUPLE : return t1==t2;
2315 case INTCELL : return intOf(t1)!=intOf(t2);
2317 case AP : if (equalTypes(fun(t1),fun(t2))) {
2324 default : internal("equalTypes");
2327 return TRUE;/*NOTREACHED*/
2330 /* --------------------------------------------------------------------------
2331 * Entry points to type checker:
2332 * ------------------------------------------------------------------------*/
2334 Type typeCheckExp(useDefs) /* Type check top level expression */
2335 Bool useDefs; { /* using defaults if reqd */
2341 emptySubstitution();
2343 inputExpr = typeExpr(0,inputExpr);
2347 improve(0,NIL,preds);
2350 preds = scSimplify(preds);
2351 if (useDefs && nonNull(preds)) {
2354 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
2358 ctxt = copyPreds(preds);
2359 type = generalize(ctxt,copyType(type,beta));
2360 inputExpr = qualifyExpr(0,preds,inputExpr);
2361 h98CheckType(0,"inferred type",inputExpr,type);
2363 emptySubstitution();
2367 Void typeCheckDefns() { /* Type check top level bindings */
2368 Target t = length(selDefns) + length(valDefns) +
2369 length(instDefns) + length(classDefns);
2374 emptySubstitution();
2377 setGoal("Type checking",t);
2379 for (gs=selDefns; nonNull(gs); gs=tl(gs)) {
2380 mapOver(typeSel,hd(gs));
2383 for (gs=valDefns; nonNull(gs); gs=tl(gs)) {
2384 typeDefnGroup(hd(gs));
2388 for (gs=classDefns; nonNull(gs); gs=tl(gs)) {
2389 emptySubstitution();
2390 typeClassDefn(hd(gs));
2393 for (gs=instDefns; nonNull(gs); gs=tl(gs)) {
2394 emptySubstitution();
2395 typeInstDefn(hd(gs));
2400 emptySubstitution();
2404 static Void local typeDefnGroup(bs) /* type check group of value defns */
2405 List bs; { /* (one top level scc) */
2408 emptySubstitution();
2409 hd(defnBounds) = NIL;
2412 typeBindings(bs); /* find types for vars in bindings */
2414 if (nonNull(preds)) {
2415 Cell v = fst(hd(hd(varsBounds)));
2416 Name n = findName(textOf(v));
2417 Int l = nonNull(n) ? name(n).line : 0;
2418 preds = scSimplify(preds);
2419 ERRMSG(l) "Instance%s of ", (length(preds)==1 ? "" : "s") ETHEN
2420 ERRCONTEXT(copyPreds(preds));
2421 ERRTEXT " required for definition of " ETHEN
2422 ERREXPR(nonNull(n)?n:v);
2427 if (nonNull(hd(skolVars))) {
2429 Name n = findName(isVar(fst(b)) ? textOf(fst(b)) : textOf(hd(fst(b))));
2430 Int l = nonNull(n) ? name(n).line : 0;
2431 leaveSkolVars(l,typeUnit,0,0);
2435 for (as=hd(varsBounds); nonNull(as); as=tl(as)) {
2436 Cell a = hd(as); /* add infered types to environment*/
2437 Name n = findName(textOf(fst(a)));
2439 internal("typeDefnGroup");
2440 name(n).type = snd(a);
2442 hd(varsBounds) = NIL;
2445 static Pair local typeSel(s) /* Calculate a suitable type for a */
2446 Name s; { /* particular selector, s. */
2447 List cns = name(s).defn;
2448 Int line = name(s).line;
2449 Type dom = NIL; /* Inferred domain */
2450 Type rng = NIL; /* Inferred range */
2451 Cell nv = inventVar();
2453 Int o = 0; /* bogus init to keep gcc -O happy */
2454 Int m = 0; /* bogus init to keep gcc -O happy */
2457 Printf("Selector %s, cns=",textToStr(name(s).text));
2458 printExp(stdout,cns);
2462 emptySubstitution();
2465 for (; nonNull(cns); cns=tl(cns)) {
2466 Name c = fst(hd(cns));
2467 Int n = intOf(snd(hd(cns)));
2468 Int a = name(c).arity;
2475 instantiate(name(c).type); /* Instantiate constructor type */
2478 for (; nonNull(predsAre); predsAre=tl(predsAre))
2479 assumeEvid(hd(predsAre),o1);
2481 if (whatIs(typeIs)==RANK2) /* Skip rank2 annotation, if any */
2482 typeIs = snd(snd(typeIs));
2483 for (; --n>0; a--) { /* Get range */
2484 pat = ap(pat,WILDCARD);
2485 typeIs = arg(typeIs);
2487 rng1 = dropRank1(arg(fun(typeIs)),o1,m1);
2489 typeIs = arg(typeIs);
2490 while (--a>0) { /* And then look for domain */
2491 pat = ap(pat,WILDCARD);
2492 typeIs = arg(typeIs);
2496 if (isNull(dom)) { /* Save first domain type and then */
2497 dom = dom1; /* unify with subsequent domains to*/
2498 o = o1; /* match up preds and range types */
2501 else if (!unify(dom1,o1,dom,o))
2502 internal("typeSel1");
2504 if (isNull(rng)) /* Compare component types */
2506 else if (!sameSchemes(rng1,rng)) {
2508 rng = liftRank1(rng,o,m);
2509 rng1 = liftRank1(rng1,o1,m1);
2510 ERRMSG(name(s).line) "Mismatch in field types for selector \"%s\"",
2511 textToStr(name(s).text) ETHEN
2512 ERRTEXT "\n*** Field type : " ETHEN ERRTYPE(rng1);
2513 ERRTEXT "\n*** Does not match : " ETHEN ERRTYPE(rng);
2517 alts = cons(pair(singleton(pat),pair(mkInt(line),nv)),alts);
2521 if (isNull(dom) || isNull(rng)) /* Should have been initialized by */
2522 internal("typeSel2"); /* now, assuming length cns >= 1. */
2524 clearMarks(); /* No fixed variables here */
2525 preds = scSimplify(preds); /* Simplify context */
2526 dom = copyType(dom,o); /* Calculate domain type */
2528 rng = copyType(typeIs,typeOff);
2529 if (nonNull(predsAre)) {
2530 List ps = makePredAss(predsAre,typeOff);
2532 for (; nonNull(alts1); alts1=tl(alts1)) {
2535 for (; nonNull(qs); qs=tl(qs))
2536 body = ap(body,thd3(hd(qs)));
2537 snd(snd(hd(alts1))) = body;
2539 preds = appendOnto(preds,ps);
2541 name(s).type = generalize(copyPreds(preds),fn(dom,rng));
2542 name(s).arity = 1 + length(preds);
2543 map1Proc(qualify,preds,alts);
2546 Printf("Inferred arity = %d, type = ",name(s).arity);
2547 printType(stdout,name(s).type);
2551 return pair(s,alts);
2555 /* --------------------------------------------------------------------------
2556 * Local function prototypes:
2557 * ------------------------------------------------------------------------*/
2559 static Type local basicType ( Char );
2562 static Type stateVar = NIL;
2563 static Type alphaVar = NIL;
2564 static Type betaVar = NIL;
2565 static Type gammaVar = NIL;
2566 static Type deltaVar = NIL;
2567 static Int nextVar = 0;
2569 static Void clearTyVars( void )
2579 static Type mkStateVar( void )
2581 if (isNull(stateVar)) {
2582 stateVar = mkOffset(nextVar++);
2587 static Type mkAlphaVar( void )
2589 if (isNull(alphaVar)) {
2590 alphaVar = mkOffset(nextVar++);
2595 static Type mkBetaVar( void )
2597 if (isNull(betaVar)) {
2598 betaVar = mkOffset(nextVar++);
2603 static Type mkGammaVar( void )
2605 if (isNull(gammaVar)) {
2606 gammaVar = mkOffset(nextVar++);
2611 static Type mkDeltaVar( void )
2613 if (isNull(deltaVar)) {
2614 deltaVar = mkOffset(nextVar++);
2619 static Type local basicType(k)
2637 return ap(typePrimArray,mkAlphaVar());
2639 return typePrimByteArray;
2641 return ap2(typeRef,mkStateVar(),mkAlphaVar());
2643 return ap2(typePrimMutableArray,mkStateVar(),mkAlphaVar());
2645 return ap(typePrimMutableByteArray,mkStateVar());
2647 return ap(typeStable,mkAlphaVar());
2650 return ap(typeWeak,mkAlphaVar());
2652 return ap(typeIO,typeUnit);
2654 #ifdef PROVIDE_FOREIGN
2659 return typeThreadId;
2661 return ap(typeMVar,mkAlphaVar());
2665 return fn(typeException,mkAlphaVar());
2667 return typeException;
2669 return mkAlphaVar(); /* polymorphic */
2671 return mkBetaVar(); /* polymorphic */
2673 return mkGammaVar(); /* polymorphic */
2675 return mkDeltaVar(); /* polymorphic */
2677 printf("Kind: '%c'\n",k);
2678 internal("basicType");
2680 assert(0); return 0; /* NOTREACHED */
2683 /* Generate type of primop based on list of arg types and result types:
2685 * eg primType "II" "II" = Int -> Int -> (Int,Int)
2688 Type primType( Int /*AsmMonad*/ monad, String a_kinds, String r_kinds )
2692 List tvars = NIL; /* for polymorphic types */
2697 /* build result types */
2698 for(; *r_kinds; ++r_kinds) {
2699 rs = cons(basicType(*r_kinds),rs);
2701 /* Construct tuple of results */
2702 if (length(rs) == 0) {
2704 } else if (length(rs) == 1) {
2707 r = mkTuple(length(rs));
2708 for(rs = rev(rs); nonNull(rs); rs=tl(rs)) {
2712 /* Construct list of arguments */
2713 for(; *a_kinds; ++a_kinds) {
2714 as = cons(basicType(*a_kinds),as);
2716 /* Apply any monad magic */
2717 if (monad == MONAD_IO) {
2719 } else if (monad == MONAD_ST) {
2720 r = ap2(typeST,mkStateVar(),r);
2722 /* glue it all together */
2723 for(; nonNull(as); as=tl(as)) {
2726 tvars = offsetTyvarsIn(r,NIL);
2727 if (nonNull(tvars)) {
2728 assert(length(tvars) == nextVar);
2729 r = mkPolyType(simpleKind(length(tvars)),r);
2734 /* forall a1 .. am. TC a1 ... am -> Int */
2735 Type conToTagType(t)
2740 for (i=0; i<tycon(t).arity; ++i) {
2741 Offset tv = mkOffset(i);
2743 tvars = cons(tv,tvars);
2745 ty = fn(ty,typeInt);
2746 if (nonNull(tvars)) {
2747 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2752 /* forall a1 .. am. Int -> TC a1 ... am */
2753 Type tagToConType(t)
2758 for (i=0; i<tycon(t).arity; ++i) {
2759 Offset tv = mkOffset(i);
2761 tvars = cons(tv,tvars);
2763 ty = fn(typeInt,ty);
2764 if (nonNull(tvars)) {
2765 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2770 /* --------------------------------------------------------------------------
2771 * Type checker control:
2772 * ------------------------------------------------------------------------*/
2774 Void typeChecker(what)
2777 case RESET : tcMode = EXPRESSION;
2785 case MARK : mark(defnBounds);
2801 mark(predFractional);
2811 setCurrModule(modulePrelude);
2812 dummyVar = inventVar();
2813 typeUnit = mkTuple(0);
2814 arrow = fn(aVar,bVar);
2815 listof = ap(typeList,aVar);
2816 boundPair = ap(ap(mkTuple(2),aVar),aVar);
2817 nameUnit = findQualNameWithoutConsultingExportList
2818 (mkQVar(findText("PrelBase"),
2820 typeVarToVar = fn(aVar,aVar);
2828 Module m = findFakeModule(findText("PrelBase"));
2831 starToStar = simpleKind(1);
2832 typeList = addPrimTycon(findText("[]"),
2836 listof = ap(typeList,aVar);
2837 nameNil = addPrimCfun(findText("[]"),0,1,
2838 mkPolyType(starToStar,
2840 nameCons = addPrimCfun(findText(":"),2,2,
2841 mkPolyType(starToStar,
2845 name(nameNil).parent =
2846 name(nameCons).parent = typeList;
2848 name(nameCons).syntax
2849 = mkSyntax(RIGHT_ASS,5);
2851 tycon(typeList).defn
2852 = cons(nameNil,cons(nameCons,NIL));
2855 dummyVar = inventVar();
2857 setCurrModule(modulePrelPrim);
2859 starToStar = simpleKind(1);
2861 typeUnit = findTycon(findText("()"));
2862 assert(nonNull(typeUnit));
2864 typeArrow = addPrimTycon(findText("(->)"),
2867 typeList = addPrimTycon(findText("[]"),
2871 arrow = fn(aVar,bVar);
2872 listof = ap(typeList,aVar);
2873 boundPair = ap(ap(mkTuple(2),aVar),aVar);
2875 nameUnit = addPrimCfun(findText("()"),0,0,typeUnit);
2876 tycon(typeUnit).defn
2877 = singleton(nameUnit);
2879 nameNil = addPrimCfun(findText("[]"),0,1,
2880 mkPolyType(starToStar,
2882 nameCons = addPrimCfun(findText(":"),2,2,
2883 mkPolyType(starToStar,
2887 name(nameNil).parent =
2888 name(nameCons).parent = typeList;
2890 name(nameCons).syntax
2891 = mkSyntax(RIGHT_ASS,5);
2893 tycon(typeList).defn
2894 = cons(nameNil,cons(nameCons,NIL));
2896 typeVarToVar = fn(aVar,aVar);
2898 typeNoRow = addPrimTycon(findText("EmptyRow"),
2899 ROW,0,DATATYPE,NIL);
2900 typeRec = addPrimTycon(findText("Rec"),
2903 nameNoRec = addPrimCfun(findText("EmptyRec"),0,0,
2904 ap(typeRec,typeNoRow));
2906 /* bogus definitions to avoid changing the prelude */
2907 addPrimCfun(findText("Rec"), 0,0,typeUnit);
2908 addPrimCfun(findText("EmptyRow"), 0,0,typeUnit);
2909 addPrimCfun(findText("EmptyRec"), 0,0,typeUnit);
2917 /*-------------------------------------------------------------------------*/