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/06 00:01:27 $
14 * ------------------------------------------------------------------------*/
16 #include "hugsbasictypes.h"
21 #include "Assembler.h" /* for AsmCTypes */
23 /*#define DEBUG_TYPES*/
24 /*#define DEBUG_KINDS*/
25 /*#define DEBUG_DEFAULTS*/
26 /*#define DEBUG_SELS*/
27 /*#define DEBUG_DEPENDS*/
28 /*#define DEBUG_DERIVING*/
30 /* --------------------------------------------------------------------------
31 * Local function prototypes:
32 * ------------------------------------------------------------------------*/
34 static Void local emptyAssumption ( Void );
35 static Void local enterBindings ( Void );
36 static Void local leaveBindings ( Void );
37 static Int local defType ( Cell );
38 static Type local useType ( Cell );
39 static Void local markAssumList ( List );
40 static Cell local findAssum ( Text );
41 static Pair local findInAssumList ( Text,List );
42 static List local intsIntersect ( List,List );
43 static List local genvarAllAss ( List );
44 static List local genvarAnyAss ( List );
45 static Int local newVarsBind ( Cell );
46 static Void local newDefnBind ( Cell,Type );
48 static Void local enterPendingBtyvs ( Void );
49 static Void local leavePendingBtyvs ( Void );
50 static Cell local patBtyvs ( Cell );
51 static Void local doneBtyvs ( Int );
52 static Void local enterSkolVars ( Void );
53 static Void local leaveSkolVars ( Int,Type,Int,Int );
55 static Void local typeError ( Int,Cell,Cell,String,Type,Int );
56 static Void local reportTypeError ( Int,Cell,Cell,String,Type,Type );
57 static Void local cantEstablish ( Int,String,Cell,Type,List );
58 static Void local tooGeneral ( Int,Cell,Type,Type );
60 static Cell local typeExpr ( Int,Cell );
62 static Cell local typeAp ( Int,Cell );
63 static Type local typeExpected ( Int,String,Cell,Type,Int,Int,Bool );
64 static Void local typeAlt ( String,Cell,Cell,Type,Int,Int );
65 static Int local funcType ( Int );
66 static Void local typeCase ( Int,Int,Cell );
67 static Void local typeComp ( Int,Type,Cell,List );
68 static Cell local typeMonadComp ( Int,Cell );
69 static Void local typeDo ( Int,Cell );
70 static Void local typeConFlds ( Int,Cell );
71 static Void local typeUpdFlds ( Int,Cell );
73 static Cell local typeWith ( Int,Cell );
75 static Cell local typeFreshPat ( Int,Cell );
77 static Void local typeBindings ( List );
78 static Void local removeTypeSigs ( Cell );
80 static Void local monorestrict ( List );
81 static Void local restrictedBindAss ( Cell );
82 static Void local restrictedAss ( Int,Cell,Type );
84 static Void local unrestricted ( List );
85 static List local itbscc ( List );
86 static Void local addEvidParams ( List,Cell );
88 static Void local typeClassDefn ( Class );
89 static Void local typeInstDefn ( Inst );
90 static Void local typeMember ( String,Name,Cell,List,Cell,Int );
92 static Void local typeBind ( Cell );
93 static Void local typeDefAlt ( Int,Cell,Pair );
94 static Cell local typeRhs ( Cell );
95 static Void local guardedType ( Int,Cell );
97 static Void local genBind ( List,Cell );
98 static Void local genAss ( Int,List,Cell,Type );
99 static Type local genTest ( Int,Cell,List,Type,Type,Int );
100 static Type local generalize ( List,Type );
101 static Bool local equalTypes ( Type,Type );
103 static Void local typeDefnGroup ( List );
104 static Pair local typeSel ( Name );
108 /* --------------------------------------------------------------------------
111 * A basic typing statement is a pair (Var,Type) and an assumption contains
112 * an ordered list of basic typing statements in which the type for a given
113 * variable is given by the most recently added assumption about that var.
115 * In practice, the assumption set is split between a pair of lists, one
116 * holding assumptions for vars defined in bindings, the other for vars
117 * defined in patterns/binding parameters etc. The reason for this
118 * separation is that vars defined in bindings may be overloaded (with the
119 * overloading being unknown until the whole binding is typed), whereas the
120 * vars defined in patterns have no overloading. A form of dependency
121 * analysis (at least as far as calculating dependents within the same group
122 * of value bindings) is required to implement this. Where it is known that
123 * no overloaded values are defined in a binding (i.e., when the `dreaded
124 * monomorphism restriction' strikes), the list used to record dependents
125 * is flagged with a NODEPENDS tag to avoid gathering dependents at that
128 * To interleave between vars for bindings and vars for patterns, we use
129 * a list of lists of typing statements for each. These lists are always
130 * the same length. The implementation here is very similar to that of the
131 * dependency analysis used in the static analysis component of this system.
133 * To deal with polymorphic recursion, variables defined in bindings can be
134 * assigned types of the form (POLYREC,(def,use)), where def is a type
135 * variable for the type of the defining occurence, and use is a type
136 * scheme for (recursive) calls/uses of the variable.
137 * ------------------------------------------------------------------------*/
139 static List defnBounds; /*::[[(Var,Type)]] possibly ovrlded*/
140 static List varsBounds; /*::[[(Var,Type)]] not overloaded */
141 static List depends; /*::[?[Var]] dependents/NODEPENDS */
142 static List skolVars; /*::[[Var]] skolem vars */
143 static List localEvs; /*::[[(Pred,offset,ev)]] */
144 static List savedPs; /*::[[(Pred,offset,ev)]] */
145 static Cell dummyVar; /* Used to put extra tvars into ass*/
147 Bool catchAmbigs = FALSE; /* TRUE => functions with ambig. */
148 /* types produce error */
151 #define saveVarsAss() List saveAssump = hd(varsBounds)
152 #define restoreVarsAss() hd(varsBounds) = saveAssump
153 #define addVarAssump(v,t) hd(varsBounds) = cons(pair(v,t),hd(varsBounds))
154 #define findTopBinding(v) findInAssumList(textOf(v),hd(defnBounds))
156 static Void local emptyAssumption() { /* set empty type assumption */
165 static Void local enterBindings() { /* Add new level to assumption sets */
166 defnBounds = cons(NIL,defnBounds);
167 varsBounds = cons(NIL,varsBounds);
168 depends = cons(NIL,depends);
171 static Void local leaveBindings() { /* Drop one level of assumptions */
172 defnBounds = tl(defnBounds);
173 varsBounds = tl(varsBounds);
174 depends = tl(depends);
177 static Int local defType(a) /* Return type for defining occ. */
178 Cell a; { /* of a var from assumption pair */
179 return (isPair(a) && fst(a)==POLYREC) ? fst(snd(a)) : a;
182 static Type local useType(a) /* Return type for use of a var */
183 Cell a; { /* defined in an assumption */
184 return (isPair(a) && fst(a)==POLYREC) ? snd(snd(a)) : a;
187 static Void local markAssumList(as) /* Mark all types in assumption set*/
188 List as; { /* :: [(Var, Type)] */
189 for (; nonNull(as); as=tl(as)) { /* No need to mark generic types; */
190 Type t = defType(snd(hd(as))); /* the only free variables in those*/
191 if (!isPolyType(t)) /* must have been free earlier too */
196 static Cell local findAssum(t) /* Find most recent assumption about*/
197 Text t; { /* variable named t, if any */
198 List defnBounds1 = defnBounds; /* return translated variable, with */
199 List varsBounds1 = varsBounds; /* type in typeIs */
200 List depends1 = depends;
202 while (nonNull(defnBounds1)) {
203 Pair ass = findInAssumList(t,hd(varsBounds1));/* search varsBounds */
209 ass = findInAssumList(t,hd(defnBounds1)); /* search defnBounds */
214 if (hd(depends1)!=NODEPENDS && /* save dependent? */
215 isNull(v=varIsMember(t,hd(depends1))))
216 /* N.B. make new copy of variable and store this on list of*/
217 /* dependents, and in the assumption so that all uses of */
218 /* the variable will be at the same node, if we need to */
219 /* overwrite the call of a function with a translation... */
220 hd(depends1) = cons(v=mkVar(t),hd(depends1));
225 defnBounds1 = tl(defnBounds1); /* look in next level*/
226 varsBounds1 = tl(varsBounds1); /* of assumption set */
227 depends1 = tl(depends1);
232 static Pair local findInAssumList(t,as)/* Search for assumption for var */
233 Text t; /* named t in list of assumptions as*/
235 for (; nonNull(as); as=tl(as))
236 if (textOf(fst(hd(as)))==t)
241 static List local intsIntersect(as,bs) /* calculate intersection of lists */
242 List as, bs; { /* of integers (as sets) */
243 List ts = NIL; /* destructively modifies as */
245 if (intIsMember(intOf(hd(as)),bs)) {
256 static List local genvarAllAss(as) /* calculate generic vars that are */
257 List as; { /* in every type in assumptions as */
258 List vs = genvarTyvar(intOf(defType(snd(hd(as)))),NIL);
259 for (as=tl(as); nonNull(as) && nonNull(vs); as=tl(as))
260 vs = intsIntersect(vs,genvarTyvar(intOf(defType(snd(hd(as)))),NIL));
264 static List local genvarAnyAss(as) /* calculate generic vars that are */
265 List as; { /* in any type in assumptions as */
266 List vs = genvarTyvar(intOf(defType(snd(hd(as)))),NIL);
267 for (as=tl(as); nonNull(as); as=tl(as))
268 vs = genvarTyvar(intOf(defType(snd(hd(as)))),vs);
272 static Int local newVarsBind(v) /* make new assump for pattern var */
274 Int beta = newTyvars(1);
275 addVarAssump(v,mkInt(beta));
277 Printf("variable, assume ");
279 Printf(" :: _%d\n",beta);
284 static Void local newDefnBind(v,type) /* make new assump for defn var */
285 Cell v; /* and set type if given (nonNull) */
287 Int beta = newTyvars(1);
288 Cell ta = mkInt(beta);
290 if (nonNull(type) && isPolyType(type))
291 ta = pair(POLYREC,pair(ta,type));
292 hd(defnBounds) = cons(pair(v,ta), hd(defnBounds));
294 Printf("definition, assume ");
296 Printf(" :: _%d\n",beta);
298 bindTv(beta,typeIs,typeOff); /* Bind beta to new type skeleton */
301 /* --------------------------------------------------------------------------
303 * ------------------------------------------------------------------------*/
307 /* --------------------------------------------------------------------------
308 * Bound and skolemized type variables:
309 * ------------------------------------------------------------------------*/
311 static List pendingBtyvs = NIL;
313 static Void local enterPendingBtyvs() {
315 pendingBtyvs = cons(NIL,pendingBtyvs);
318 static Void local leavePendingBtyvs() {
319 List pts = hd(pendingBtyvs);
320 pendingBtyvs = tl(pendingBtyvs);
321 for (; nonNull(pts); pts=tl(pts)) {
322 Int line = intOf(fst(hd(pts)));
323 List vs = snd(hd(pts));
326 for (; nonNull(vs); vs=tl(vs)) {
327 Cell v = fst(hd(vs));
328 Cell t = copyTyvar(intOf(snd(hd(vs))));
330 ERRMSG(line) "Type annotation uses variable " ETHEN ERREXPR(v);
331 ERRTEXT " where a more specific type " ETHEN ERRTYPE(t);
332 ERRTEXT " was inferred"
335 else if (offsetOf(t)!=i) {
336 List us = snd(hd(pts));
339 internal("leavePendingBtyvs");
342 ERRMSG(line) "Type annotation uses distinct variables " ETHEN
343 ERREXPR(v); ERRTEXT " and " ETHEN ERREXPR(fst(hd(us)));
344 ERRTEXT " where a single variable was inferred"
354 static Cell local patBtyvs(p) /* Strip bound type vars from pat */
356 if (whatIs(p)==BIGLAM) {
357 List bts = hd(btyvars) = fst(snd(p));
358 for (p=snd(snd(p)); nonNull(bts); bts=tl(bts)) {
359 Int beta = newTyvars(1);
360 tyvar(beta)->kind = snd(hd(bts));
361 snd(hd(bts)) = mkInt(beta);
367 static Void local doneBtyvs(l)
369 if (nonNull(hd(btyvars))) { /* Save bound tyvars */
370 hd(pendingBtyvs) = cons(pair(mkInt(l),hd(btyvars)),hd(pendingBtyvs));
375 static Void local enterSkolVars() {
376 skolVars = cons(NIL,skolVars);
377 localEvs = cons(NIL,localEvs);
378 savedPs = cons(preds,savedPs);
382 static Void local leaveSkolVars(l,t,o,m)
387 if (nonNull(hd(localEvs))) { /* Check for local predicates */
388 List sks = hd(skolVars);
391 internal("leaveSkolVars");
393 markAllVars(); /* Mark all variables in current */
394 do { /* substitution, then unmark sks. */
395 tyvar(intOf(fst(hd(sks))))->offs = UNUSED_GENERIC;
397 } while (nonNull(sks));
399 sps = elimPredsUsing(hd(localEvs),sps);
400 preds = revOnto(preds,sps);
403 if (nonNull(hd(skolVars))) { /* Check that Skolem vars do not */
404 List vs; /* escape their scope */
407 clearMarks(); /* Look for occurences in the */
408 for (; i<m; i++) /* inferred type */
412 for (vs=hd(skolVars); nonNull(vs); vs=tl(vs)) {
413 Int vn = intOf(fst(hd(vs)));
414 if (tyvar(vn)->offs == FIXED_TYVAR) {
415 Cell tv = copyTyvar(vn);
416 Type ty = liftRank2(t,o,m);
417 ERRMSG(l) "Existentially quantified variable in inferred type"
419 ERRTEXT "\n*** Variable : " ETHEN ERRTYPE(tv);
420 ERRTEXT "\n*** From pattern : " ETHEN ERREXPR(snd(hd(vs)));
421 ERRTEXT "\n*** Result type : " ETHEN ERRTYPE(ty);
427 markBtyvs(); /* Now check assumptions */
428 mapProc(markAssumList,defnBounds);
429 mapProc(markAssumList,varsBounds);
431 for (vs=hd(skolVars); nonNull(vs); vs=tl(vs)) {
432 Int vn = intOf(fst(hd(vs)));
433 if (tyvar(vn)->offs == FIXED_TYVAR) {
435 "Existentially quantified variable escapes from pattern "
436 ETHEN ERREXPR(snd(hd(vs)));
442 localEvs = tl(localEvs);
443 skolVars = tl(skolVars);
444 preds = revOnto(preds,hd(savedPs));
445 savedPs = tl(savedPs);
448 /* --------------------------------------------------------------------------
450 * ------------------------------------------------------------------------*/
452 static Void local typeError(l,e,in,wh,t,o)
453 Int l; /* line number near type error */
454 String wh; /* place in which error occurs */
455 Cell e; /* source of error */
456 Cell in; /* context if any (NIL if not) */
457 Type t; /* should be of type (t,o) */
458 Int o; { /* type inferred is (typeIs,typeOff) */
460 clearMarks(); /* types printed here are monotypes */
461 /* use marking to give sensible names*/
463 { List vs = genericVars;
464 for (; nonNull(vs); vs=tl(vs)) {
465 Int v = intOf(hd(vs));
466 Printf("%c :: ", ('a'+tyvar(v)->offs));
467 printKind(stdout,tyvar(v)->kind);
473 reportTypeError(l,e,in,wh,copyType(typeIs,typeOff),copyType(t,o));
476 static Void local reportTypeError(l,e,in,wh,inft,expt)
477 Int l; /* Error printing part of typeError*/
481 ERRMSG(l) "Type error in %s", wh ETHEN
483 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(in);
485 ERRTEXT "\n*** Term : " ETHEN ERREXPR(e);
486 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(inft);
487 ERRTEXT "\n*** Does not match : " ETHEN ERRTYPE(expt);
489 ERRTEXT "\n*** Because : %s", unifyFails ETHEN
495 #define shouldBe(l,e,in,where,t,o) if (!unify(typeIs,typeOff,t,o)) \
496 typeError(l,e,in,where,t,o);
497 #define check(l,e,in,where,t,o) e=typeExpr(l,e); shouldBe(l,e,in,where,t,o)
498 #define inferType(t,o) typeIs=t; typeOff=o
500 #define spTypeExpr(l,e) svPreds = preds; preds = NIL; e = typeExpr(l,e); preds = revOnto(preds,svPreds);
501 #define spCheck(l,e,in,where,t,o) svPreds = preds; preds = NIL; check(l,e,in,where,t,o); preds = revOnto(preds,svPreds);
503 #define spTypeExpr(l,e) e = typeExpr(l,e);
504 #define spCheck(l,e,in,where,t,o) check(l,e,in,where,t,o);
507 static Void local cantEstablish(line,wh,e,t,ps)
508 Int line; /* Complain when declared preds */
509 String wh; /* are not sufficient to discharge */
510 Cell e; /* or defer the inferred context. */
513 ERRMSG(line) "Cannot justify constraints in %s", wh ETHEN
514 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
515 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(t);
516 ERRTEXT "\n*** Given context : " ETHEN ERRCONTEXT(ps);
517 ERRTEXT "\n*** Constraints : " ETHEN ERRCONTEXT(copyPreds(preds));
522 static Void local tooGeneral(l,e,dt,it) /* explicit type sig. too general */
526 ERRMSG(l) "Inferred type is not general enough" ETHEN
527 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
528 ERRTEXT "\n*** Expected type : " ETHEN ERRTYPE(dt);
529 ERRTEXT "\n*** Inferred type : " ETHEN ERRTYPE(it);
534 /* --------------------------------------------------------------------------
535 * Typing of expressions:
536 * ------------------------------------------------------------------------*/
538 #define EXPRESSION 0 /* type checking expression */
539 #define NEW_PATTERN 1 /* pattern, introducing new vars */
540 #define OLD_PATTERN 2 /* pattern, involving bound vars */
541 static int tcMode = EXPRESSION;
544 static Cell local mytypeExpr ( Int,Cell));
545 static Cell local typeExpr(l,e)
548 static int number = 0;
550 int mynumber = number++;
553 Printf("%d) to check: ",mynumber);
556 retv = mytypeExpr(l,e);
557 Printf("%d) result: ",mynumber);
558 printType(stdout,debugType(typeIs,typeOff));
559 Printf("\n%d) preds: ",mynumber);
560 printContext(stdout,debugContext(preds));
564 static Cell local mytypeExpr(l,e) /* Determine type of expr/pattern */
566 static Cell local typeExpr(l,e) /* Determine type of expr/pattern */
570 static String cond = "conditional";
571 static String list = "list";
572 static String discr = "case discriminant";
573 static String aspat = "as (@) pattern";
574 static String typeSig = "type annotation";
575 static String lambda = "lambda expression";
582 /* The following cases can occur in either pattern or expr. mode */
593 case TUPLE : typeTuple(e);
596 case BIGCELL : { Int alpha = newTyvars(1);
597 inferType(aVar,alpha);
598 return ap(ap(nameFromInteger,
599 assumeEvid(predNum,alpha)),
603 case INTCELL : { Int alpha = newTyvars(1);
604 inferType(aVar,alpha);
605 return ap(ap(nameFromInt,
606 assumeEvid(predNum,alpha)),
610 case FLOATCELL : { Int alpha = newTyvars(1);
611 inferType(aVar,alpha);
612 return ap(ap(nameFromDouble,
613 assumeEvid(predFractional,alpha)),
617 case STRCELL : inferType(typeString,0);
620 case CHARCELL : inferType(typeChar,0);
623 case CONFLDS : typeConFlds(l,e);
626 case ESIGN : snd(snd(e)) = localizeBtyvs(snd(snd(e)));
627 return typeExpected(l,typeSig,
628 fst(snd(e)),snd(snd(e)),
632 case EXT : { Int beta = newTyvars(2);
633 Cell pi = ap(e,aVar);
636 ap(typeRec,ap(ap(e,aVar),bVar))));
637 tyvar(beta+1)->kind = ROW;
639 return ap(e,assumeEvid(pi,beta+1));
643 /* The following cases can only occur in expr mode */
645 case UPDFLDS : typeUpdFlds(l,e);
649 case WITHEXP : return typeWith(l,e);
652 case COND : { Int beta = newTyvars(1);
653 check(l,fst3(snd(e)),e,cond,typeBool,0);
654 spCheck(l,snd3(snd(e)),e,cond,aVar,beta);
655 spCheck(l,thd3(snd(e)),e,cond,aVar,beta);
660 case LETREC : enterBindings();
662 mapProc(typeBindings,fst(snd(e)));
663 spTypeExpr(l,snd(snd(e)));
665 leaveSkolVars(l,typeIs,typeOff,0);
668 case FINLIST : { Int beta = newTyvars(1);
670 for (xs=snd(e); nonNull(xs); xs=tl(xs)) {
671 spCheck(l,hd(xs),e,list,aVar,beta);
673 inferType(listof,beta);
677 case DOCOMP : typeDo(l,e);
680 case COMP : return typeMonadComp(l,e);
682 case CASE : { Int beta = newTyvars(2); /* discr result */
683 check(l,fst(snd(e)),NIL,discr,aVar,beta);
684 map2Proc(typeCase,l,beta,snd(snd(e)));
689 case LAMBDA : { Int beta = newTyvars(1);
691 typeAlt(lambda,e,snd(e),aVar,beta,1);
698 case RECSEL : { Int beta = newTyvars(2);
699 Cell pi = ap(snd(e),aVar);
700 Type t = fn(ap(typeRec,
703 tyvar(beta+1)->kind = ROW;
705 return ap(e,assumeEvid(pi,beta+1));
709 /* The remaining cases can only occur in pattern mode: */
711 case WILDCARD : inferType(aVar,newTyvars(1));
714 case ASPAT : { Int beta = newTyvars(1);
715 snd(snd(e)) = typeExpr(l,snd(snd(e)));
716 bindTv(beta,typeIs,typeOff);
717 check(l,fst(snd(e)),e,aspat,aVar,beta);
722 case LAZYPAT : snd(e) = typeExpr(l,snd(e));
725 case ADDPAT : { Int alpha = newTyvars(1);
726 inferType(typeVarToVar,alpha);
727 return ap(e,assumeEvid(predIntegral,alpha));
730 default : internal("typeExpr");
736 /* --------------------------------------------------------------------------
737 * Typing rules for particular special forms:
738 * ------------------------------------------------------------------------*/
740 static Cell local typeAp(l,e) /* Type check application, which */
741 Int l; /* may be headed with a variable */
742 Cell e; { /* requires polymorphism, qualified*/
743 static String app = "application"; /* types, and possible rank2 args. */
754 case NAME : typeIs = name(h).type;
758 case VARIDCELL : if (tcMode==NEW_PATTERN) {
759 inferType(aVar,newVarsBind(e));
762 Cell v = findAssum(textOf(h));
765 typeIs = (tcMode==OLD_PATTERN)
770 h = findName(textOf(h));
773 typeIs = name(h).type;
779 case IPVAR : { Text t = textOf(h);
780 Int alpha = newTyvars(1);
781 Cell ip = pair(ap(IPCELL,t),aVar);
782 Cell ev = assumeEvid(ip,alpha);
783 typeIs = mkInt(alpha);
789 default : h = typeExpr(l,h);
793 if (isNull(typeIs)) {
797 instantiate(typeIs); /* Deal with polymorphism ... */
798 if (nonNull(predsAre)) { /* ... and with qualified types. */
800 for (; nonNull(predsAre); predsAre=tl(predsAre)) {
801 evs = cons(assumeEvid(hd(predsAre),typeOff),evs);
803 if (!isName(h) || !isCfun(h)) {
804 h = applyToArgs(h,rev(evs));
808 if (whatIs(typeIs)==CDICTS) { /* Deal with local dictionaries */
809 List evs = makePredAss(fst(snd(typeIs)),typeOff);
811 typeIs = snd(snd(typeIs));
812 for (; nonNull(ps); ps=tl(ps)) {
813 h = ap(h,thd3(hd(ps)));
815 if (tcMode==EXPRESSION) {
816 preds = revOnto(evs,preds);
818 hd(localEvs) = revOnto(evs,hd(localEvs));
822 if (whatIs(typeIs)==EXIST) { /* Deal with existential arguments */
823 Int n = intOf(fst(snd(typeIs)));
824 typeIs = snd(snd(typeIs));
825 if (!isCfun(getHead(h)) || n>typeFree) {
827 } else if (tcMode!=EXPRESSION) {
828 Int alpha = typeOff + typeFree;
830 bindTv(alpha-n,SKOLEM,0);
831 hd(skolVars) = cons(pair(mkInt(alpha-n),e),hd(skolVars));
836 if (whatIs(typeIs)==RANK2) { /* Deal with rank 2 arguments */
839 Int nr2 = intOf(fst(snd(typeIs)));
840 Type body = snd(snd(typeIs));
844 if (n<nr2) { /* Must have enough arguments */
845 ERRMSG(l) "Use of " ETHEN ERREXPR(h);
847 ERRTEXT " in " ETHEN ERREXPR(e);
849 ERRTEXT " requires at least %d argument%s\n",
850 nr2, (nr2==1 ? "" : "s")
854 for (i=nr2; i<n; ++i) /* Find rank two arguments */
857 for (as=getArgs(as); nonNull(as); as=tl(as), body=arg(body)) {
858 Type expect = dropRank1(arg(fun(body)),alpha,m);
859 if (isPolyOrQualType(expect)) {
860 if (tcMode==EXPRESSION) /* poly/qual type in expr */
861 hd(as) = typeExpected(l,app,hd(as),expect,alpha,m,TRUE);
862 else if (hd(as)!=WILDCARD) { /* Pattern binding/match */
863 if (!isVar(hd(as))) {
864 ERRMSG(l) "Argument " ETHEN ERREXPR(arg(as));
865 ERRTEXT " in pattern " ETHEN ERREXPR(e);
866 ERRTEXT " where a variable is required\n"
869 if (tcMode==NEW_PATTERN) { /* Pattern match */
872 addVarAssump(dummyVar,mkInt(alpha+i));
875 addVarAssump(hd(as),expect);
877 else { /* Pattern binding */
878 Text t = textOf(hd(as));
879 Cell a = findInAssumList(t,hd(defnBounds));
883 if (nonNull(predsAre)) {
884 ERRMSG(l) "Cannot use pattern binding for " ETHEN
886 ERRTEXT " as a component with a qualified type\n"
889 shouldBe(l,hd(as),e,app,aVar,intOf(defType(snd(a))));
893 else { /* Not a poly/qual type */
894 spCheck(l,hd(as),e,app,expect,alpha);
896 h = ap(h,hd(as)); /* Save checked argument */
898 inferType(body,alpha);
902 if (n>0) { /* Deal with remaining args */
903 Int beta = funcType(n); /* check h::t1->t2->...->tn->rn+1 */
904 shouldBe(l,h,e,app,aVar,beta);
905 for (i=n; i>0; --i) { /* check e_i::t_i for each i */
906 spCheck(l,arg(a),e,app,aVar,beta+2*i-1);
910 tyvarType(beta+2*n); /* Inferred type is r_n+1 */
913 if (isNull(p)) /* Replace head with translation */
921 static Cell local typeExpected(l,wh,e,reqd,alpha,n,addEvid)
922 Int l; /* Type check expression e in wh */
923 String wh; /* at line l, expecting type reqd, */
924 Cell e; /* and treating vars alpha through */
925 Type reqd; /* (alpha+n-1) as fixed. */
928 Bool addEvid; { /* TRUE => add \ev -> ... */
929 List savePreds = preds;
940 ps = makePredAss(predsAre,o);
943 check(l,e,NIL,wh,t,o);
947 mapProc(markAssumList,defnBounds);
948 mapProc(markAssumList,varsBounds);
949 mapProc(markPred,savePreds);
952 if (n > 0) { /* mark alpha thru alpha+n-1, plus any */
953 /* type vars that are functionally */
954 List us = NIL, vs = NIL; /* dependent on them */
955 List fds = calcFunDepsPreds(preds);
956 for (i=0; i<n; i++) {
957 Type t1 = zonkTyvar(alpha+i);
958 us = zonkTyvarsIn(t1,us);
961 for (; nonNull(vs); vs=tl(vs))
962 markTyvar(intOf(hd(vs)));
966 savePreds = elimPredsUsing(ps,savePreds);
967 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
968 savePreds = elimPredsUsing(ps,savePreds);
969 if (nonNull(preds)) {
970 Type ty = copyType(t,o);
971 List qs = copyPreds(ps);
972 cantEstablish(l,wh,e,ty,qs);
977 if (copyTyvar(o+i)!=mkOffset(i)) {
978 List qs = copyPreds(ps);
979 Type it = copyType(t,o);
980 tooGeneral(l,e,reqd,generalize(qs,it));
984 e = qualifyExpr(l,ps,e);
988 preds = revOnto(ps,savePreds);
994 static Void local typeAlt(wh,e,a,t,o,m) /* Type check abstraction (Alt) */
995 String wh; /* a = ( [p1, ..., pn], rhs ) */
1002 List ps = fst(a) = patBtyvs(fst(a));
1004 Int l = rhsLine(snd(a));
1011 if (whatIs(t)==RANK2) {
1012 if (n<(nr2=intOf(fst(snd(t))))) {
1013 ERRMSG(l) "Definition requires at least %d parameters on lhs",
1020 while (getHead(t)==typeArrow && argCount==2 && nonNull(ps)) {
1021 Type ta = arg(fun(t));
1022 if (isPolyOrQualType(ta)) {
1023 if (hd(ps)!=WILDCARD) {
1024 if (!isVar(hd(ps))) {
1025 ERRMSG(l) "Argument " ETHEN ERREXPR(hd(ps));
1026 ERRTEXT " used where a variable or wildcard is required\n"
1029 if (m>0 && !added) {
1032 addVarAssump(dummyVar,mkInt(o+i));
1035 addVarAssump(hd(ps),ta);
1039 hd(ps) = typeFreshPat(l,hd(ps));
1040 shouldBe(l,hd(ps),NIL,wh,ta,o);
1049 snd(a) = typeRhs(snd(a));
1051 Int beta = funcType(n);
1054 hd(ps) = typeFreshPat(l,hd(ps));
1055 bindTv(beta+2*i+1,typeIs,typeOff);
1058 snd(a) = typeRhs(snd(a));
1059 bindTv(beta+2*n,typeIs,typeOff);
1063 if (!unify(typeIs,typeOff,t,o)) {
1066 req = liftRank2(origt,o,m);
1067 liftRank2Args(as,o,m);
1068 got = ap(RANK2,pair(mkInt(nr2),revOnto(as,copyType(typeIs,typeOff))));
1069 reportTypeError(l,e,NIL,wh,got,req);
1074 leaveSkolVars(l,origt,o,m);
1077 static Int local funcType(n) /*return skeleton for function type*/
1078 Int n; { /*with n arguments, taking the form*/
1079 Int beta = newTyvars(2*n+1); /* r1 t1 r2 t2 ... rn tn rn+1 */
1080 Int i; /* with r_i := t_i -> r_i+1 */
1082 bindTv(beta+2*i,arrow,beta+2*i+1);
1086 static Void local typeCase(l,beta,c) /* type check case: pat -> rhs */
1087 Int l; /* (case given by c == (pat,rhs)) */
1088 Int beta; /* need: pat :: (var,beta) */
1089 Cell c; { /* rhs :: (var,beta+1) */
1090 static String casePat = "case pattern";
1091 static String caseExpr = "case expression";
1095 fst(c) = typeFreshPat(l,patBtyvs(fst(c)));
1096 shouldBe(l,fst(c),NIL,casePat,aVar,beta);
1097 snd(c) = typeRhs(snd(c));
1098 shouldBe(l,rhsExpr(snd(c)),NIL,caseExpr,aVar,beta+1);
1102 leaveSkolVars(l,typeIs,typeOff,0);
1105 static Void local typeComp(l,m,e,qs) /* type check comprehension */
1107 Type m; /* monad (mkOffset(0)) */
1110 static String boolQual = "boolean qualifier";
1111 static String genQual = "generator";
1117 if (isNull(qs)) { /* no qualifiers left */
1118 spTypeExpr(l,fst(e));
1122 switch (whatIs(q)) {
1123 case BOOLQUAL : spCheck(l,snd(q),NIL,boolQual,typeBool,0);
1124 typeComp(l,m,e,qs1);
1127 case QWHERE : enterBindings();
1129 mapProc(typeBindings,snd(q));
1130 typeComp(l,m,e,qs1);
1132 leaveSkolVars(l,typeIs,typeOff,0);
1135 case FROMQUAL : { Int beta = newTyvars(1);
1137 spCheck(l,snd(snd(q)),NIL,genQual,m,beta);
1140 = typeFreshPat(l,patBtyvs(fst(snd(q))));
1141 shouldBe(l,fst(snd(q)),NIL,genQual,aVar,beta);
1142 typeComp(l,m,e,qs1);
1145 leaveSkolVars(l,typeIs,typeOff,0);
1149 case DOQUAL : spCheck(l,snd(q),NIL,genQual,m,newTyvars(1));
1150 typeComp(l,m,e,qs1);
1156 static Cell local typeMonadComp(l,e) /* type check monad comprehension */
1159 Int alpha = newTyvars(1);
1160 Int beta = newTyvars(1);
1161 Cell mon = ap(mkInt(beta),aVar);
1162 Cell m = assumeEvid(predMonad,beta);
1163 tyvar(beta)->kind = starToStar;
1165 bindTv(beta,typeList,0);
1169 typeComp(l,mon,snd(e),snd(snd(e)));
1170 bindTv(alpha,typeIs,typeOff);
1171 inferType(mon,alpha);
1172 return ap(MONADCOMP,pair(m,snd(e)));
1175 static Void local typeDo(l,e) /* type check do-notation */
1178 static String finGen = "final generator";
1179 Int alpha = newTyvars(1);
1180 Int beta = newTyvars(1);
1181 Cell mon = ap(mkInt(beta),aVar);
1182 Cell m = assumeEvid(predMonad,beta);
1183 tyvar(beta)->kind = starToStar;
1185 typeComp(l,mon,snd(e),snd(snd(e)));
1186 shouldBe(l,fst(snd(e)),NIL,finGen,mon,alpha);
1187 snd(e) = pair(m,snd(e));
1190 static Void local typeConFlds(l,e) /* Type check a construction */
1193 static String conExpr = "value construction";
1194 Name c = fst(snd(e));
1195 List fs = snd(snd(e));
1204 instantiate(name(c).type);
1205 for (; nonNull(predsAre); predsAre=tl(predsAre))
1206 assumeEvid(hd(predsAre),typeOff);
1207 if (whatIs(typeIs)==RANK2)
1208 typeIs = snd(snd(typeIs));
1213 for (; nonNull(fs); fs=tl(fs)) {
1215 for (i=sfunPos(fst(hd(fs)),c); --i>0; t=arg(t))
1217 t = dropRank1(arg(fun(t)),to,tf);
1218 if (isPolyOrQualType(t))
1219 snd(hd(fs)) = typeExpected(l,conExpr,snd(hd(fs)),t,to,tf,TRUE);
1221 spCheck(l,snd(hd(fs)),e,conExpr,t,to);
1224 for (i=name(c).arity; i>0; i--)
1229 static Void local typeUpdFlds(line,e) /* Type check an update */
1230 Int line; /* (Written in what might seem a */
1231 Cell e; { /* bizarre manner for the benefit */
1232 static String update = "update"; /* of as yet unreleased extensions)*/
1233 List cs = snd3(snd(e)); /* List of constructors */
1234 List fs = thd3(snd(e)); /* List of field specifications */
1235 List ts = NIL; /* List of types for fields */
1237 Int alpha = newTyvars(2+n);
1244 /* Calculate type and translation for each expr in the field list */
1245 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1246 spTypeExpr(line,snd(hd(fs1)));
1247 bindTv(i,typeIs,typeOff);
1251 mapProc(markAssumList,defnBounds);
1252 mapProc(markAssumList,varsBounds);
1253 mapProc(markPred,preds);
1256 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1258 ts = cons(generalize(NIL,copyTyvar(i)),ts);
1262 /* Type check expression to be updated */
1263 spTypeExpr(line,fst3(snd(e)));
1264 bindTv(alpha,typeIs,typeOff);
1266 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constrs */
1268 List ta = replicate(name(c).arity,NIL);
1272 tcMode = NEW_PATTERN; /* Domain type */
1273 instantiate(name(c).type);
1274 tcMode = EXPRESSION;
1277 for (; nonNull(predsAre); predsAre=tl(predsAre))
1278 assumeEvid(hd(predsAre),typeOff);
1280 if (whatIs(typeIs)==RANK2) {
1281 ERRMSG(line) "Sorry, record update syntax cannot currently be "
1282 "used for datatypes with polymorphic components"
1286 instantiate(name(c).type); /* Range type */
1289 for (; nonNull(predsAre); predsAre=tl(predsAre))
1290 assumeEvid(hd(predsAre),typeOff);
1292 for (fs1=fs, i=1; nonNull(fs1); fs1=tl(fs1), i++) {
1293 Int n = sfunPos(fst(hd(fs1)),c);
1300 for (; nonNull(ta); ta=tl(ta)) { /* For each cfun arg */
1301 if (nonNull(hd(ta))) { /* Field to updated? */
1302 Int n = intOf(hd(ta));
1305 for (; n-- > 1; f=tl(f), t=tl(t))
1310 shouldBe(line,snd(f),e,update,arg(fun(tr)),or);
1311 } /* Unmentioned component */
1312 else if (!unify(arg(fun(td)),od,arg(fun(tr)),or))
1313 internal("typeUpdFlds");
1319 inferType(td,od); /* Check domain type */
1320 shouldBe(line,fst3(snd(e)),e,update,aVar,alpha);
1321 inferType(tr,or); /* Check range type */
1322 shouldBe(line,e,NIL,update,aVar,alpha+1);
1324 /* (typeIs,typeOff) still carry the result type when we exit the loop */
1328 static Cell local typeWith(line,e) /* Type check a with */
1331 List fs = snd(snd(e)); /* List of field specifications */
1333 Int alpha = newTyvars(2+n);
1338 List dpreds = NIL, dp;
1341 /* Type check expression to be updated */
1342 fst(snd(e)) = typeExpr(line,fst(snd(e)));
1343 bindTv(alpha,typeIs,typeOff);
1346 /* elim duplicate uses of imp params */
1347 preds = scSimplify(preds);
1348 /* extract preds that we're going to bind */
1349 for (fs1=fs; nonNull(fs1); fs1=tl(fs1)) {
1350 Text t = textOf(fst(hd(fs1)));
1351 Cell p = findIPEvid(t);
1352 dpreds = cons(p, dpreds);
1356 /* maybe give a warning message here... */
1359 dpreds = rev(dpreds);
1361 /* Calculate type and translation for each expr in the field list */
1362 for (fs1=fs, dp=dpreds, i=alpha+2; nonNull(fs1); fs1=tl(fs1), dp=tl(dp), i++) {
1363 static String with = "with";
1365 snd(hd(fs1)) = typeExpr(line,snd(hd(fs1)));
1366 bindTv(i,typeIs,typeOff);
1368 shouldBe(line,fst(hd(fs1)),e,with,snd(fst3(ev)),intOf(snd3(ev)));
1369 bs = cons(cons(pair(thd3(ev), cons(triple(NIL, mkInt(line), snd(hd(fs1))), NIL)), NIL), bs);
1374 return (ap(LETREC,pair(bs,fst(snd(e)))));
1378 static Cell local typeFreshPat(l,p) /* find type of pattern, assigning */
1379 Int l; /* fresh type variables to each var */
1380 Cell p; { /* bound in the pattern */
1381 tcMode = NEW_PATTERN;
1383 tcMode = EXPRESSION;
1387 /* --------------------------------------------------------------------------
1388 * Type check group of bindings:
1389 * ------------------------------------------------------------------------*/
1391 static Void local typeBindings(bs) /* type check a binding group */
1393 Bool usesPatBindings = FALSE; /* TRUE => pattern binding in bs */
1394 Bool usesUntypedVar = FALSE; /* TRUE => var bind w/o type decl */
1397 /* The following loop is used to determine whether the monomorphism */
1398 /* restriction should be applied. It could be written marginally more */
1399 /* efficiently by using breaks, but clarity is more important here ... */
1401 for (bs1=bs; nonNull(bs1); bs1=tl(bs1)) { /* Analyse binding group */
1404 usesPatBindings = TRUE;
1405 else if (isNull(fst(hd(snd(snd(b))))) /* no arguments */
1406 && whatIs(fst(snd(b)))==IMPDEPS) /* implicitly typed*/
1407 usesUntypedVar = TRUE;
1410 if (usesPatBindings || usesUntypedVar)
1415 mapProc(removeTypeSigs,bs); /* Remove binding type info */
1416 hd(varsBounds) = revOnto(hd(defnBounds), /* transfer completed assmps*/
1417 hd(varsBounds)); /* out of defnBounds */
1418 hd(defnBounds) = NIL;
1422 static Void local removeTypeSigs(b) /* Remove type info from a binding */
1424 snd(b) = snd(snd(b));
1427 /* --------------------------------------------------------------------------
1428 * Type check a restricted binding group:
1429 * ------------------------------------------------------------------------*/
1431 static Void local monorestrict(bs) /* Type restricted binding group */
1433 List savePreds = preds;
1434 Int line = isVar(fst(hd(bs))) ? rhsLine(snd(hd(snd(snd(hd(bs))))))
1435 : rhsLine(snd(snd(snd(hd(bs)))));
1436 hd(defnBounds) = NIL;
1437 hd(depends) = NODEPENDS; /* No need for dependents here */
1439 preds = NIL; /* Type check the bindings */
1440 mapProc(restrictedBindAss,bs);
1441 mapProc(typeBind,bs);
1442 improve(line,NIL,preds);
1445 preds = revOnto(preds,savePreds);
1447 clearMarks(); /* Mark fixed variables */
1448 mapProc(markAssumList,tl(defnBounds));
1449 mapProc(markAssumList,tl(varsBounds));
1450 mapProc(markPred,preds);
1453 if (isNull(tl(defnBounds))) { /* Top-level may need defaulting */
1455 if (nonNull(preds) && resolveDefs(genvarAnyAss(hd(defnBounds))))
1460 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
1463 if (nonNull(preds)) { /* Look for unresolved overloading */
1464 Cell v = isVar(fst(hd(bs))) ? fst(hd(bs)) : hd(fst(hd(bs)));
1465 Cell ass = findInAssumList(textOf(v),hd(varsBounds));
1466 preds = scSimplify(preds);
1468 ERRMSG(line) "Unresolved top-level overloading" ETHEN
1469 ERRTEXT "\n*** Binding : %s", textToStr(textOf(v))
1472 ERRTEXT "\n*** Inferred type : " ETHEN ERRTYPE(snd(ass));
1474 ERRTEXT "\n*** Outstanding context : " ETHEN
1475 ERRCONTEXT(copyPreds(preds));
1481 map1Proc(genBind,NIL,bs); /* Generalize types of def'd vars */
1484 static Void local restrictedBindAss(b) /* Make assums for vars in binding */
1485 Cell b; { /* gp with restricted overloading */
1487 if (isVar(fst(b))) { /* function-binding? */
1488 Cell t = fst(snd(b));
1489 if (whatIs(t)==IMPDEPS) { /* Discard implicitly typed deps */
1490 fst(snd(b)) = t = NIL; /* in a restricted binding group. */
1492 fst(snd(b)) = localizeBtyvs(t);
1493 restrictedAss(rhsLine(snd(hd(snd(snd(b))))), fst(b), t);
1494 } else { /* pattern-binding? */
1496 List ts = fst(snd(b));
1497 Int line = rhsLine(snd(snd(snd(b))));
1499 for (; nonNull(vs); vs=tl(vs)) {
1501 restrictedAss(line,hd(vs),hd(ts)=localizeBtyvs(hd(ts)));
1504 restrictedAss(line,hd(vs),NIL);
1510 static Void local restrictedAss(l,v,t) /* Assume that type of binding var v*/
1511 Int l; /* is t (if nonNull) in restricted */
1512 Cell v; /* binding group */
1515 if (nonNull(predsAre)) {
1516 ERRMSG(l) "Explicit overloaded type for \"%s\"",textToStr(textOf(v))
1518 ERRTEXT " not permitted in restricted binding"
1523 /* --------------------------------------------------------------------------
1524 * Unrestricted binding group:
1525 * ------------------------------------------------------------------------*/
1527 static Void local unrestricted(bs) /* Type unrestricted binding group */
1529 List savePreds = preds;
1530 List imps = NIL; /* Implicitly typed bindings */
1531 List exps = NIL; /* Explicitly typed bindings */
1534 /* ----------------------------------------------------------------------
1535 * STEP 1: Separate implicitly typed bindings from explicitly typed
1536 * bindings and do a dependency analyis, where f depends on g iff f
1537 * is implicitly typed and involves a call to g.
1538 * --------------------------------------------------------------------*/
1540 for (; nonNull(bs); bs=tl(bs)) {
1542 if (whatIs(fst(snd(b)))==IMPDEPS)
1543 imps = cons(b,imps); /* N.B. New lists are built to */
1544 else /* avoid breaking the original */
1545 exps = cons(b,exps); /* list structure for bs. */
1548 for (bs=imps; nonNull(bs); bs=tl(bs)) {
1549 Cell b = hd(bs); /* Restrict implicitly typed dep */
1550 List ds = snd(fst(snd(b))); /* lists to bindings in imps */
1552 while (nonNull(ds)) {
1554 if (cellIsMember(hd(ds),imps)) {
1562 imps = itbscc(imps); /* Dependency analysis on imps */
1563 for (bs=imps; nonNull(bs); bs=tl(bs))
1564 for (bs1=hd(bs); nonNull(bs1); bs1=tl(bs1))
1565 fst(snd(hd(bs1))) = NIL; /* reset imps type fields */
1567 #ifdef DEBUG_DEPENDS
1568 Printf("Binding group:");
1569 for (bs1=imps; nonNull(bs1); bs1=tl(bs1)) {
1571 for (bs=hd(bs1); nonNull(bs); bs=tl(bs))
1572 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1575 if (nonNull(exps)) {
1577 for (bs=exps; nonNull(bs); bs=tl(bs))
1578 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1584 /* ----------------------------------------------------------------------
1585 * STEP 2: Add type assumptions about any explicitly typed variable.
1586 * --------------------------------------------------------------------*/
1588 for (bs=exps; nonNull(bs); bs=tl(bs)) {
1589 fst(snd(hd(bs))) = localizeBtyvs(fst(snd(hd(bs))));
1590 hd(varsBounds) = cons(pair(fst(hd(bs)),fst(snd(hd(bs)))),
1594 /* ----------------------------------------------------------------------
1595 * STEP 3: Calculate types for each group of implicitly typed bindings.
1596 * --------------------------------------------------------------------*/
1598 for (; nonNull(imps); imps=tl(imps)) {
1599 Cell b = hd(hd(imps));
1600 Int line = isVar(fst(b)) ? rhsLine(snd(hd(snd(snd(b)))))
1601 : rhsLine(snd(snd(snd(b))));
1602 hd(defnBounds) = NIL;
1604 for (bs1=hd(imps); nonNull(bs1); bs1=tl(bs1))
1605 newDefnBind(fst(hd(bs1)),NIL);
1608 mapProc(typeBind,hd(imps));
1609 improve(line,NIL,preds);
1612 mapProc(markAssumList,tl(defnBounds));
1613 mapProc(markAssumList,tl(varsBounds));
1614 mapProc(markPred,savePreds);
1618 savePreds = elimOuterPreds(savePreds);
1619 if (nonNull(preds) && resolveDefs(genvarAllAss(hd(defnBounds)))) {
1620 savePreds = elimOuterPreds(savePreds);
1623 map1Proc(genBind,preds,hd(imps));
1624 if (nonNull(preds)) {
1625 map1Proc(addEvidParams,preds,hd(depends));
1626 map1Proc(qualifyBinding,preds,hd(imps));
1629 h98CheckType(line,"inferred type",
1630 fst(hd(hd(defnBounds))),snd(hd(hd(defnBounds))));
1631 hd(varsBounds) = revOnto(hd(defnBounds),hd(varsBounds));
1634 /* ----------------------------------------------------------------------
1635 * STEP 4: Now infer a type for each explicitly typed variable and
1636 * check for compatibility with the declared type.
1637 * --------------------------------------------------------------------*/
1639 for (; nonNull(exps); exps=tl(exps)) {
1640 static String extbind = "explicitly typed binding";
1642 List alts = snd(snd(b));
1643 Int line = rhsLine(snd(hd(alts)));
1649 hd(defnBounds) = NIL;
1650 hd(depends) = NODEPENDS;
1653 instantiate(fst(snd(b)));
1656 t = dropRank2(typeIs,o,m);
1657 ps = makePredAss(predsAre,o);
1659 enterPendingBtyvs();
1660 for (; nonNull(alts); alts=tl(alts))
1661 typeAlt(extbind,fst(b),hd(alts),t,o,m);
1662 improve(line,ps,preds);
1663 leavePendingBtyvs();
1665 if (nonNull(ps)) /* Add dict params, if necessary */
1666 qualifyBinding(ps,b);
1669 mapProc(markAssumList,tl(defnBounds));
1670 mapProc(markAssumList,tl(varsBounds));
1671 mapProc(markPred,savePreds);
1675 savePreds = elimPredsUsing(ps,savePreds);
1676 if (nonNull(preds)) {
1680 vs = cons(mkInt(o+i),vs);
1681 if (resolveDefs(vs)) {
1682 savePreds = elimPredsUsing(ps,savePreds);
1684 if (nonNull(preds)) {
1687 if (nonNull(preds) && resolveDefs(vs))
1688 savePreds = elimPredsUsing(ps,savePreds);
1692 resetGenerics(); /* Make sure we're general enough */
1694 t = generalize(ps,liftRank2(t,o,m));
1696 if (!sameSchemes(t,fst(snd(b))))
1697 tooGeneral(line,fst(b),fst(snd(b)),t);
1698 h98CheckType(line,"inferred type",fst(b),t);
1700 if (nonNull(preds)) /* Check context was strong enough */
1701 cantEstablish(line,extbind,fst(b),t,ps);
1704 preds = savePreds; /* Restore predicates */
1705 hd(defnBounds) = NIL;
1708 #define SCC itbscc /* scc for implicitly typed binds */
1709 #define LOWLINK itblowlink
1710 #define DEPENDS(t) fst(snd(t))
1711 #define SETDEPENDS(c,v) fst(snd(c))=v
1718 static Void local addEvidParams(qs,v) /* overwrite VARID/OPCELL v with */
1719 List qs; /* application of variable to evid. */
1720 Cell v; { /* parameters given by qs */
1725 internal("addEvidParams");
1727 for (nv=mkVar(textOf(v)); nonNull(tl(qs)); qs=tl(qs))
1728 nv = ap(nv,thd3(hd(qs)));
1730 snd(v) = thd3(hd(qs));
1734 /* --------------------------------------------------------------------------
1735 * Type check bodies of class and instance declarations:
1736 * ------------------------------------------------------------------------*/
1738 static Void local typeClassDefn(c) /* Type check implementations of */
1739 Class c; { /* defaults for class c */
1741 /* ----------------------------------------------------------------------
1742 * Generate code for default dictionary builder functions:
1743 * --------------------------------------------------------------------*/
1745 Int beta = newKindedVars(cclass(c).kinds);
1746 Cell d = inventDictVar();
1747 List dparam = singleton(triple(cclass(c).head,mkInt(beta),d));
1748 List mems = cclass(c).members;
1749 List defs = cclass(c).defaults;
1750 List dsels = cclass(c).dsels;
1751 Cell pat = cclass(c).dcon;
1752 Int width = cclass(c).numSupers + cclass(c).numMembers;
1753 char buf[FILENAME_MAX+1];
1757 if (isNull(defs) && nonNull(mems)) {
1758 defs = cclass(c).defaults = cons(NIL,NIL);
1761 for (; nonNull(mems); mems=tl(mems)) {
1762 /* static String deftext = "default_"; */
1763 static String deftext = "$dm";
1764 String s = textToStr(name(hd(mems)).text);
1767 for (; i<FILENAME_MAX && deftext[i]!='\0'; i++) {
1768 buf[i] = deftext[i];
1770 for(; (i+j)<FILENAME_MAX && s[j]!='\0'; j++) {
1774 n = newName(findText(buf),c);
1776 if (isNull(hd(defs))) { /* No default definition */
1777 static String header = "Undefined member: ";
1778 for (i=0; i<FILENAME_MAX && header[i]!='\0'; i++)
1780 for (j=0; (i+j)<FILENAME_MAX && s[j]!='\0'; j++)
1783 name(n).line = cclass(c).line;
1785 name(n).defn = singleton(pair(singleton(d),
1786 ap(mkInt(cclass(c).line),
1789 findText(buf)))))));
1790 } else { /* User supplied default defn */
1791 List alts = snd(hd(defs));
1792 Int line = rhsLine(snd(hd(alts)));
1794 typeMember("default member binding",
1801 name(n).line = line;
1802 name(n).arity = 1+length(fst(hd(alts)));
1803 name(n).defn = alts;
1805 for (; nonNull(alts); alts=tl(alts)) {
1806 fst(hd(alts)) = cons(d,fst(hd(alts)));
1811 genDefns = cons(n,genDefns);
1812 if (isNull(tl(defs)) && nonNull(tl(mems))) {
1813 tl(defs) = cons(NIL,NIL);
1818 /* ----------------------------------------------------------------------
1819 * Generate code for superclass and member function selectors:
1820 * --------------------------------------------------------------------*/
1822 for (i=0; i<width; i++) {
1823 pat = ap(pat,inventVar());
1825 pat = singleton(pat);
1826 for (i=0; nonNull(dsels); dsels=tl(dsels)) {
1827 name(hd(dsels)).defn = singleton(pair(pat,
1828 ap(mkInt(cclass(c).line),
1829 nthArg(i++,hd(pat)))));
1830 genDefns = cons(hd(dsels),genDefns);
1832 for (mems=cclass(c).members; nonNull(mems); mems=tl(mems)) {
1833 name(hd(mems)).defn = singleton(pair(pat,
1834 ap(mkInt(name(hd(mems)).line),
1835 nthArg(i++,hd(pat)))));
1836 genDefns = cons(hd(mems),genDefns);
1840 static Void local typeInstDefn(in) /* Type check implementations of */
1841 Inst in; { /* member functions for instance in*/
1843 /* ----------------------------------------------------------------------
1844 * Generate code for instance specific dictionary builder function:
1846 * inst.maker d1 ... dn = let sc1 = ...
1852 * d = Make.C sc1 ... scm v1 ... vk
1855 * where sci are superclass dictionaries, d is a new name, vj
1856 * is a newly generated name corresponding to the implementation of a
1857 * member function. (Additional line number values must be added at
1858 * appropriate places but, for clarity, these are not shown above.)
1859 * If no implementation of a particular vj is available, then we use
1860 * the default implementation, partially applied to d.
1861 * --------------------------------------------------------------------*/
1863 Int alpha = newKindedVars(cclass(inst(in).c).kinds);
1864 List supers = makePredAss(cclass(inst(in).c).supers,alpha);
1865 Int beta = newKindedVars(inst(in).kinds);
1866 List params = makePredAss(inst(in).specifics,beta);
1867 Cell d = inventDictVar();
1869 List evids = cons(triple(inst(in).head,mkInt(beta),d),
1870 appendOnto(dupList(params),supers));
1872 List evids = dupList(params);
1874 List imps = inst(in).implements;
1875 Cell l = mkInt(inst(in).line);
1876 Cell dictDef = cclass(inst(in).c).dcon;
1877 List mems = cclass(inst(in).c).members;
1878 List defs = cclass(inst(in).c).defaults;
1883 if (!unifyPred(cclass(inst(in).c).head,alpha,inst(in).head,beta))
1884 internal("typeInstDefn");
1886 for (ps=params; nonNull(ps); ps=tl(ps)) /* Build arglist */
1887 args = cons(thd3(hd(ps)),args);
1890 for (ps=supers; nonNull(ps); ps=tl(ps)) { /* Superclass dictionaries */
1893 #if EXPLAIN_INSTANCE_RESOLUTION
1895 fputs("scEntail: ", stdout);
1896 printContext(stdout,copyPreds(params));
1897 fputs(" ||- ", stdout);
1898 printPred(stdout, copyPred(fst3(pi),intOf(snd3(pi))));
1899 fputc('\n', stdout);
1902 ev = scEntail(params,fst3(pi),intOf(snd3(pi)),0);
1904 #if EXPLAIN_INSTANCE_RESOLUTION
1906 fputs("inEntail: ", stdout);
1907 printContext(stdout,copyPreds(evids));
1908 fputs(" ||- ", stdout);
1909 printPred(stdout, copyPred(fst3(pi),intOf(snd3(pi))));
1910 fputc('\n', stdout);
1913 ev = inEntail(evids,fst3(pi),intOf(snd3(pi)),0);
1917 ERRMSG(inst(in).line) "Cannot build superclass instance" ETHEN
1918 ERRTEXT "\n*** Instance : " ETHEN
1919 ERRPRED(copyPred(inst(in).head,beta));
1920 ERRTEXT "\n*** Context supplied : " ETHEN
1921 ERRCONTEXT(copyPreds(params));
1922 ERRTEXT "\n*** Required superclass : " ETHEN
1923 ERRPRED(copyPred(fst3(pi),intOf(snd3(pi))));
1927 locs = cons(pair(thd3(pi),singleton(pair(NIL,ap(l,ev)))),locs);
1928 dictDef = ap(dictDef,thd3(pi));
1931 for (; nonNull(defs); defs=tl(defs)) {
1933 if (nonNull(imps)) {
1938 dictDef = ap(dictDef,ap(hd(defs),d));
1940 Cell v = inventVar();
1941 dictDef = ap(dictDef,v);
1942 typeMember("instance member binding",
1948 locs = cons(pair(v,snd(imp)),locs);
1952 locs = cons(pair(d,singleton(pair(NIL,ap(l,dictDef)))),locs);
1954 name(inst(in).builder).defn /* Register builder imp */
1955 = singleton(pair(args,ap(LETREC,pair(singleton(locs),
1958 /* Invent a GHC-compatible name for the instance decl */
1960 char buf[FILENAME_MAX+1];
1964 Cell qq = inst(in).head;
1966 static String zdftext = "$f";
1969 pp = cons(arg(qq),pp);
1972 // pp is now the fwd list of args(?) to this pred
1975 for (j = 0; i<FILENAME_MAX && zdftext[j]!='\0'; i++, j++) {
1976 buf[i] = zdftext[j];
1978 str = textToStr(cclass(inst(in).c).text);
1979 for (j = 0; i<FILENAME_MAX && str[j]!='\0'; i++, j++) {
1984 while (isAp(qq)) qq = fun(qq);
1985 switch (whatIs(qq)) {
1986 case TYCON: str = textToStr(tycon(qq).text); break;
1987 case TUPLE: str = textToStr(ghcTupleText(qq)); break;
1988 case OFFSET: sprintf(buf2,"%d",offsetOf(qq));
1991 default: internal("typeInstDefn: making GHC name"); break;
1993 for (j = 0; i<FILENAME_MAX && str[j]!='\0'; i++, j++) {
1999 name(inst(in).builder).text = findText(buf);
2000 //fprintf ( stderr, "result = %s\n", buf );
2003 genDefns = cons(inst(in).builder,genDefns);
2006 static Void local typeMember(wh,mem,alts,evids,head,beta)
2007 String wh; /* Type check alternatives alts of */
2008 Name mem; /* member mem for inst type head */
2009 Cell alts; /* at offset beta using predicate */
2010 List evids; /* assignment evids */
2013 Int line = rhsLine(snd(hd(alts)));
2022 Printf("\nType check member: ");
2023 printExp(stdout,mem);
2025 printType(stdout,name(mem).type);
2026 Printf("\n for the instance: ");
2027 printPred(stdout,head);
2031 instantiate(name(mem).type); /* Find required type */
2034 t = dropRank2(typeIs,o,m);
2035 ps = makePredAss(predsAre,o);
2036 if (!unifyPred(hd(predsAre),typeOff,head,beta))
2037 internal("typeMember1");
2040 rt = generalize(qs,liftRank2(t,o,m));
2043 Printf("Required type is: ");
2044 printType(stdout,rt);
2048 hd(defnBounds) = NIL; /* Type check each alternative */
2049 hd(depends) = NODEPENDS;
2050 enterPendingBtyvs();
2051 for (preds=NIL; nonNull(alts); alts=tl(alts)) {
2052 typeAlt(wh,mem,hd(alts),t,o,m);
2053 qualify(tl(ps),hd(alts)); /* Add any extra dict params */
2055 improve(line,evids,preds);
2056 leavePendingBtyvs();
2058 evids = appendOnto(dupList(tl(ps)), /* Build full complement of dicts */
2062 qs = elimPredsUsing(evids,NIL);
2063 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
2064 qs = elimPredsUsing(evids,qs);
2067 "Implementation of %s requires extra context",
2068 textToStr(name(mem).text) ETHEN
2069 ERRTEXT "\n*** Expected type : " ETHEN ERRTYPE(rt);
2070 ERRTEXT "\n*** Missing context : " ETHEN ERRCONTEXT(copyPreds(qs));
2075 resetGenerics(); /* Make sure we're general enough */
2077 t = generalize(ps,liftRank2(t,o,m));
2079 Printf(" Inferred type is: ");
2080 printType(stdout,t);
2083 if (!sameSchemes(t,rt))
2084 tooGeneral(line,mem,rt,t);
2085 if (nonNull(preds)) {
2086 preds = scSimplify(preds);
2087 cantEstablish(line,wh,mem,t,ps);
2091 /* --------------------------------------------------------------------------
2092 * Type check bodies of bindings:
2093 * ------------------------------------------------------------------------*/
2095 static Void local typeBind(b) /* Type check binding */
2097 if (isVar(fst(b))) { /* function binding */
2098 Cell ass = findTopBinding(fst(b));
2102 internal("typeBind");
2104 beta = intOf(defType(snd(ass)));
2105 enterPendingBtyvs();
2106 map2Proc(typeDefAlt,beta,fst(b),snd(snd(b)));
2107 leavePendingBtyvs();
2109 else { /* pattern binding */
2110 static String lhsPat = "lhs pattern";
2111 static String rhs = "right hand side";
2112 Int beta = newTyvars(1);
2113 Pair pb = snd(snd(b));
2114 Int l = rhsLine(snd(pb));
2116 tcMode = OLD_PATTERN;
2117 enterPendingBtyvs();
2118 fst(pb) = patBtyvs(fst(pb));
2119 check(l,fst(pb),NIL,lhsPat,aVar,beta);
2120 tcMode = EXPRESSION;
2121 snd(pb) = typeRhs(snd(pb));
2122 shouldBe(l,rhsExpr(snd(pb)),NIL,rhs,aVar,beta);
2124 leavePendingBtyvs();
2128 static Void local typeDefAlt(beta,v,a) /* type check alt in func. binding */
2132 static String valDef = "function binding";
2133 typeAlt(valDef,v,a,aVar,beta,0);
2136 static Cell local typeRhs(e) /* check type of rhs of definition */
2138 switch (whatIs(e)) {
2139 case GUARDED : { Int beta = newTyvars(1);
2140 map1Proc(guardedType,beta,snd(e));
2145 case LETREC : enterBindings();
2147 mapProc(typeBindings,fst(snd(e)));
2148 snd(snd(e)) = typeRhs(snd(snd(e)));
2150 leaveSkolVars(rhsLine(snd(snd(e))),typeIs,typeOff,0);
2153 case RSIGN : fst(snd(e)) = typeRhs(fst(snd(e)));
2154 shouldBe(rhsLine(fst(snd(e))),
2155 rhsExpr(fst(snd(e))),NIL,
2160 default : snd(e) = typeExpr(intOf(fst(e)),snd(e));
2166 static Void local guardedType(beta,gded)/* check type of guard (li,(gd,ex))*/
2167 Int beta; /* should have gd :: Bool, */
2168 Cell gded; { /* ex :: (var,beta) */
2169 static String guarded = "guarded expression";
2170 static String guard = "guard";
2171 Int line = intOf(fst(gded));
2177 spCheck(line,fst(gded),NIL,guard,typeBool,0);
2178 spCheck(line,snd(gded),NIL,guarded,aVar,beta);
2181 Cell rhsExpr(rhs) /* find first expression on a rhs */
2184 switch (whatIs(rhs)) {
2185 case GUARDED : return snd(snd(hd(snd(rhs))));
2186 case LETREC : return rhsExpr(snd(snd(rhs)));
2187 case RSIGN : return rhsExpr(fst(snd(rhs)));
2188 default : return snd(rhs);
2192 Int rhsLine(rhs) /* find line number associated with */
2193 Cell rhs; { /* a right hand side */
2195 switch (whatIs(rhs)) {
2196 case GUARDED : return intOf(fst(hd(snd(rhs))));
2197 case LETREC : return rhsLine(snd(snd(rhs)));
2198 case RSIGN : return rhsLine(fst(snd(rhs)));
2199 default : return intOf(fst(rhs));
2203 /* --------------------------------------------------------------------------
2204 * Calculate generalization of types and compare with declared type schemes:
2205 * ------------------------------------------------------------------------*/
2207 static Void local genBind(ps,b) /* Generalize the type of each var */
2208 List ps; /* defined in binding b, qualifying*/
2209 Cell b; { /* each with the predicates in ps. */
2211 Cell t = fst(snd(b));
2214 genAss(rhsLine(snd(hd(snd(snd(b))))),ps,v,t);
2216 Int line = rhsLine(snd(snd(snd(b))));
2217 for (; nonNull(v); v=tl(v)) {
2223 genAss(line,ps,hd(v),ty);
2228 static Void local genAss(l,ps,v,dt) /* Calculate inferred type of v and*/
2229 Int l; /* compare with declared type, dt, */
2230 List ps; /* if given & check for ambiguity. */
2233 Cell ass = findTopBinding(v);
2238 snd(ass) = genTest(l,v,ps,dt,aVar,intOf(defType(snd(ass))));
2243 printType(stdout,snd(ass));
2248 static Type local genTest(l,v,ps,dt,t,o)/* Generalize and test inferred */
2249 Int l; /* type (t,o) with context ps */
2250 Cell v; /* against declared type dt for v. */
2255 Type bt = NIL; /* Body of inferred type */
2256 Type it = NIL; /* Full inferred type */
2258 resetGenerics(); /* Calculate Haskell typing */
2261 it = generalize(ps,bt);
2263 if (nonNull(dt)) { /* If a declared type was given, */
2264 instantiate(dt); /* check body for match. */
2265 if (!equalTypes(typeIs,bt))
2266 tooGeneral(l,v,dt,it);
2268 else if (nonNull(ps)) /* Otherwise test for ambiguity in */
2269 if (isAmbiguous(it)) /* inferred type. */
2270 ambigError(l,"inferred type",v,it);
2275 static Type local generalize(qs,t) /* calculate generalization of t */
2276 List qs; /* having already marked fixed vars*/
2277 Type t; { /* with qualifying preds qs */
2279 t = ap(QUAL,pair(qs,t));
2280 if (nonNull(genericVars)) {
2282 List vs = genericVars;
2283 for (; nonNull(vs); vs=tl(vs)) {
2284 Tyvar *tyv = tyvar(intOf(hd(vs)));
2285 Kind ka = tyv->kind;
2288 t = mkPolyType(k,t);
2290 Printf("Generalized type: ");
2291 printType(stdout,t);
2293 printKind(stdout,k);
2300 static Bool local equalTypes(t1,t2) /* Compare simple types for equality*/
2303 et: if (whatIs(t1)!=whatIs(t2))
2306 switch (whatIs(t1)) {
2312 case TUPLE : return t1==t2;
2314 case INTCELL : return intOf(t1)!=intOf(t2);
2316 case AP : if (equalTypes(fun(t1),fun(t2))) {
2323 default : internal("equalTypes");
2326 return TRUE;/*NOTREACHED*/
2329 /* --------------------------------------------------------------------------
2330 * Entry points to type checker:
2331 * ------------------------------------------------------------------------*/
2333 Type typeCheckExp(useDefs) /* Type check top level expression */
2334 Bool useDefs; { /* using defaults if reqd */
2340 emptySubstitution();
2342 inputExpr = typeExpr(0,inputExpr);
2346 improve(0,NIL,preds);
2349 preds = scSimplify(preds);
2350 if (useDefs && nonNull(preds)) {
2353 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
2357 ctxt = copyPreds(preds);
2358 type = generalize(ctxt,copyType(type,beta));
2359 inputExpr = qualifyExpr(0,preds,inputExpr);
2360 h98CheckType(0,"inferred type",inputExpr,type);
2362 emptySubstitution();
2366 Void typeCheckDefns() { /* Type check top level bindings */
2367 Target t = length(selDefns) + length(valDefns) +
2368 length(instDefns) + length(classDefns);
2373 emptySubstitution();
2376 setGoal("Type checking",t);
2378 for (gs=selDefns; nonNull(gs); gs=tl(gs)) {
2379 mapOver(typeSel,hd(gs));
2382 for (gs=valDefns; nonNull(gs); gs=tl(gs)) {
2383 typeDefnGroup(hd(gs));
2387 for (gs=classDefns; nonNull(gs); gs=tl(gs)) {
2388 emptySubstitution();
2389 typeClassDefn(hd(gs));
2392 for (gs=instDefns; nonNull(gs); gs=tl(gs)) {
2393 emptySubstitution();
2394 typeInstDefn(hd(gs));
2399 emptySubstitution();
2403 static Void local typeDefnGroup(bs) /* type check group of value defns */
2404 List bs; { /* (one top level scc) */
2407 emptySubstitution();
2408 hd(defnBounds) = NIL;
2411 typeBindings(bs); /* find types for vars in bindings */
2413 if (nonNull(preds)) {
2414 Cell v = fst(hd(hd(varsBounds)));
2415 Name n = findName(textOf(v));
2416 Int l = nonNull(n) ? name(n).line : 0;
2417 preds = scSimplify(preds);
2418 ERRMSG(l) "Instance%s of ", (length(preds)==1 ? "" : "s") ETHEN
2419 ERRCONTEXT(copyPreds(preds));
2420 ERRTEXT " required for definition of " ETHEN
2421 ERREXPR(nonNull(n)?n:v);
2426 if (nonNull(hd(skolVars))) {
2428 Name n = findName(isVar(fst(b)) ? textOf(fst(b)) : textOf(hd(fst(b))));
2429 Int l = nonNull(n) ? name(n).line : 0;
2430 leaveSkolVars(l,typeUnit,0,0);
2434 for (as=hd(varsBounds); nonNull(as); as=tl(as)) {
2435 Cell a = hd(as); /* add infered types to environment*/
2436 Name n = findName(textOf(fst(a)));
2438 internal("typeDefnGroup");
2439 name(n).type = snd(a);
2441 hd(varsBounds) = NIL;
2444 static Pair local typeSel(s) /* Calculate a suitable type for a */
2445 Name s; { /* particular selector, s. */
2446 List cns = name(s).defn;
2447 Int line = name(s).line;
2448 Type dom = NIL; /* Inferred domain */
2449 Type rng = NIL; /* Inferred range */
2450 Cell nv = inventVar();
2452 Int o = 0; /* bogus init to keep gcc -O happy */
2453 Int m = 0; /* bogus init to keep gcc -O happy */
2456 Printf("Selector %s, cns=",textToStr(name(s).text));
2457 printExp(stdout,cns);
2461 emptySubstitution();
2464 for (; nonNull(cns); cns=tl(cns)) {
2465 Name c = fst(hd(cns));
2466 Int n = intOf(snd(hd(cns)));
2467 Int a = name(c).arity;
2474 instantiate(name(c).type); /* Instantiate constructor type */
2477 for (; nonNull(predsAre); predsAre=tl(predsAre))
2478 assumeEvid(hd(predsAre),o1);
2480 if (whatIs(typeIs)==RANK2) /* Skip rank2 annotation, if any */
2481 typeIs = snd(snd(typeIs));
2482 for (; --n>0; a--) { /* Get range */
2483 pat = ap(pat,WILDCARD);
2484 typeIs = arg(typeIs);
2486 rng1 = dropRank1(arg(fun(typeIs)),o1,m1);
2488 typeIs = arg(typeIs);
2489 while (--a>0) { /* And then look for domain */
2490 pat = ap(pat,WILDCARD);
2491 typeIs = arg(typeIs);
2495 if (isNull(dom)) { /* Save first domain type and then */
2496 dom = dom1; /* unify with subsequent domains to*/
2497 o = o1; /* match up preds and range types */
2500 else if (!unify(dom1,o1,dom,o))
2501 internal("typeSel1");
2503 if (isNull(rng)) /* Compare component types */
2505 else if (!sameSchemes(rng1,rng)) {
2507 rng = liftRank1(rng,o,m);
2508 rng1 = liftRank1(rng1,o1,m1);
2509 ERRMSG(name(s).line) "Mismatch in field types for selector \"%s\"",
2510 textToStr(name(s).text) ETHEN
2511 ERRTEXT "\n*** Field type : " ETHEN ERRTYPE(rng1);
2512 ERRTEXT "\n*** Does not match : " ETHEN ERRTYPE(rng);
2516 alts = cons(pair(singleton(pat),pair(mkInt(line),nv)),alts);
2520 if (isNull(dom) || isNull(rng)) /* Should have been initialized by */
2521 internal("typeSel2"); /* now, assuming length cns >= 1. */
2523 clearMarks(); /* No fixed variables here */
2524 preds = scSimplify(preds); /* Simplify context */
2525 dom = copyType(dom,o); /* Calculate domain type */
2527 rng = copyType(typeIs,typeOff);
2528 if (nonNull(predsAre)) {
2529 List ps = makePredAss(predsAre,typeOff);
2531 for (; nonNull(alts1); alts1=tl(alts1)) {
2534 for (; nonNull(qs); qs=tl(qs))
2535 body = ap(body,thd3(hd(qs)));
2536 snd(snd(hd(alts1))) = body;
2538 preds = appendOnto(preds,ps);
2540 name(s).type = generalize(copyPreds(preds),fn(dom,rng));
2541 name(s).arity = 1 + length(preds);
2542 map1Proc(qualify,preds,alts);
2545 Printf("Inferred arity = %d, type = ",name(s).arity);
2546 printType(stdout,name(s).type);
2550 return pair(s,alts);
2554 /* --------------------------------------------------------------------------
2555 * Local function prototypes:
2556 * ------------------------------------------------------------------------*/
2558 static Type local basicType ( Char );
2561 static Type stateVar = NIL;
2562 static Type alphaVar = NIL;
2563 static Type betaVar = NIL;
2564 static Type gammaVar = NIL;
2565 static Type deltaVar = NIL;
2566 static Int nextVar = 0;
2568 static Void clearTyVars( void )
2578 static Type mkStateVar( void )
2580 if (isNull(stateVar)) {
2581 stateVar = mkOffset(nextVar++);
2586 static Type mkAlphaVar( void )
2588 if (isNull(alphaVar)) {
2589 alphaVar = mkOffset(nextVar++);
2594 static Type mkBetaVar( void )
2596 if (isNull(betaVar)) {
2597 betaVar = mkOffset(nextVar++);
2602 static Type mkGammaVar( void )
2604 if (isNull(gammaVar)) {
2605 gammaVar = mkOffset(nextVar++);
2610 static Type mkDeltaVar( void )
2612 if (isNull(deltaVar)) {
2613 deltaVar = mkOffset(nextVar++);
2618 static Type local basicType(k)
2636 return ap(typePrimArray,mkAlphaVar());
2638 return typePrimByteArray;
2640 return ap2(typeRef,mkStateVar(),mkAlphaVar());
2642 return ap2(typePrimMutableArray,mkStateVar(),mkAlphaVar());
2644 return ap(typePrimMutableByteArray,mkStateVar());
2646 return ap(typeStable,mkAlphaVar());
2649 return ap(typeWeak,mkAlphaVar());
2651 return ap(typeIO,typeUnit);
2653 #ifdef PROVIDE_FOREIGN
2658 return typeThreadId;
2660 return ap(typeMVar,mkAlphaVar());
2664 return fn(typeException,mkAlphaVar());
2666 return typeException;
2668 return mkAlphaVar(); /* polymorphic */
2670 return mkBetaVar(); /* polymorphic */
2672 return mkGammaVar(); /* polymorphic */
2674 return mkDeltaVar(); /* polymorphic */
2676 printf("Kind: '%c'\n",k);
2677 internal("basicType");
2679 assert(0); return 0; /* NOTREACHED */
2682 /* Generate type of primop based on list of arg types and result types:
2684 * eg primType "II" "II" = Int -> Int -> (Int,Int)
2687 Type primType( Int /*AsmMonad*/ monad, String a_kinds, String r_kinds )
2691 List tvars = NIL; /* for polymorphic types */
2696 /* build result types */
2697 for(; *r_kinds; ++r_kinds) {
2698 rs = cons(basicType(*r_kinds),rs);
2700 /* Construct tuple of results */
2701 if (length(rs) == 0) {
2703 } else if (length(rs) == 1) {
2706 r = mkTuple(length(rs));
2707 for(rs = rev(rs); nonNull(rs); rs=tl(rs)) {
2711 /* Construct list of arguments */
2712 for(; *a_kinds; ++a_kinds) {
2713 as = cons(basicType(*a_kinds),as);
2715 /* Apply any monad magic */
2716 if (monad == MONAD_IO) {
2718 } else if (monad == MONAD_ST) {
2719 r = ap2(typeST,mkStateVar(),r);
2721 /* glue it all together */
2722 for(; nonNull(as); as=tl(as)) {
2725 tvars = offsetTyvarsIn(r,NIL);
2726 if (nonNull(tvars)) {
2727 assert(length(tvars) == nextVar);
2728 r = mkPolyType(simpleKind(length(tvars)),r);
2733 /* forall a1 .. am. TC a1 ... am -> Int */
2734 Type conToTagType(t)
2739 for (i=0; i<tycon(t).arity; ++i) {
2740 Offset tv = mkOffset(i);
2742 tvars = cons(tv,tvars);
2744 ty = fn(ty,typeInt);
2745 if (nonNull(tvars)) {
2746 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2751 /* forall a1 .. am. Int -> TC a1 ... am */
2752 Type tagToConType(t)
2757 for (i=0; i<tycon(t).arity; ++i) {
2758 Offset tv = mkOffset(i);
2760 tvars = cons(tv,tvars);
2762 ty = fn(typeInt,ty);
2763 if (nonNull(tvars)) {
2764 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2769 /* --------------------------------------------------------------------------
2770 * Type checker control:
2771 * ------------------------------------------------------------------------*/
2773 Void typeChecker(what)
2776 case RESET : tcMode = EXPRESSION;
2784 case MARK : mark(defnBounds);
2800 mark(predFractional);
2810 setCurrModule(modulePrelude);
2811 dummyVar = inventVar();
2812 typeUnit = mkTuple(0);
2813 arrow = fn(aVar,bVar);
2814 listof = ap(typeList,aVar);
2815 boundPair = ap(ap(mkTuple(2),aVar),aVar);
2816 nameUnit = findQualNameWithoutConsultingExportList
2817 (mkQVar(findText("PrelBase"),
2819 typeVarToVar = fn(aVar,aVar);
2827 Module m = findFakeModule(findText("PrelBase"));
2830 starToStar = simpleKind(1);
2831 typeList = addPrimTycon(findText("[]"),
2835 listof = ap(typeList,aVar);
2836 nameNil = addPrimCfun(findText("[]"),0,1,
2837 mkPolyType(starToStar,
2839 nameCons = addPrimCfun(findText(":"),2,2,
2840 mkPolyType(starToStar,
2844 name(nameNil).parent =
2845 name(nameCons).parent = typeList;
2847 name(nameCons).syntax
2848 = mkSyntax(RIGHT_ASS,5);
2850 tycon(typeList).defn
2851 = cons(nameNil,cons(nameCons,NIL));
2854 dummyVar = inventVar();
2856 setCurrModule(modulePrelPrim);
2858 starToStar = simpleKind(1);
2860 typeUnit = findTycon(findText("()"));
2861 assert(nonNull(typeUnit));
2863 typeArrow = addPrimTycon(findText("(->)"),
2866 typeList = addPrimTycon(findText("[]"),
2870 arrow = fn(aVar,bVar);
2871 listof = ap(typeList,aVar);
2872 boundPair = ap(ap(mkTuple(2),aVar),aVar);
2874 nameUnit = addPrimCfun(findText("()"),0,0,typeUnit);
2875 tycon(typeUnit).defn
2876 = singleton(nameUnit);
2878 nameNil = addPrimCfun(findText("[]"),0,1,
2879 mkPolyType(starToStar,
2881 nameCons = addPrimCfun(findText(":"),2,2,
2882 mkPolyType(starToStar,
2886 name(nameNil).parent =
2887 name(nameCons).parent = typeList;
2889 name(nameCons).syntax
2890 = mkSyntax(RIGHT_ASS,5);
2892 tycon(typeList).defn
2893 = cons(nameNil,cons(nameCons,NIL));
2895 typeVarToVar = fn(aVar,aVar);
2897 typeNoRow = addPrimTycon(findText("EmptyRow"),
2898 ROW,0,DATATYPE,NIL);
2899 typeRec = addPrimTycon(findText("Rec"),
2902 nameNoRec = addPrimCfun(findText("EmptyRec"),0,0,
2903 ap(typeRec,typeNoRow));
2905 /* bogus definitions to avoid changing the prelude */
2906 addPrimCfun(findText("Rec"), 0,0,typeUnit);
2907 addPrimCfun(findText("EmptyRow"), 0,0,typeUnit);
2908 addPrimCfun(findText("EmptyRec"), 0,0,typeUnit);
2916 /*-------------------------------------------------------------------------*/