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/03/06 08:38:05 $
14 * ------------------------------------------------------------------------*/
23 #include "Assembler.h" /* for AsmCTypes */
25 /*#define DEBUG_TYPES*/
26 /*#define DEBUG_KINDS*/
27 /*#define DEBUG_DEFAULTS*/
28 /*#define DEBUG_SELS*/
29 /*#define DEBUG_DEPENDS*/
30 /*#define DEBUG_DERIVING*/
31 /*#define DEBUG_CODE*/
33 Bool catchAmbigs = FALSE; /* TRUE => functions with ambig. */
34 /* types produce error */
37 /* --------------------------------------------------------------------------
38 * Local function prototypes:
39 * ------------------------------------------------------------------------*/
41 static Void local emptyAssumption Args((Void));
42 static Void local enterBindings Args((Void));
43 static Void local leaveBindings Args((Void));
44 static Int local defType Args((Cell));
45 static Type local useType Args((Cell));
46 static Void local markAssumList Args((List));
47 static Cell local findAssum Args((Text));
48 static Pair local findInAssumList Args((Text,List));
49 static List local intsIntersect Args((List,List));
50 static List local genvarAllAss Args((List));
51 static List local genvarAnyAss Args((List));
52 static Int local newVarsBind Args((Cell));
53 static Void local newDefnBind Args((Cell,Type));
55 static Void local enterPendingBtyvs Args((Void));
56 static Void local leavePendingBtyvs Args((Void));
57 static Cell local patBtyvs Args((Cell));
58 static Void local doneBtyvs Args((Int));
59 static Void local enterSkolVars Args((Void));
60 static Void local leaveSkolVars Args((Int,Type,Int,Int));
62 static Void local typeError Args((Int,Cell,Cell,String,Type,Int));
63 static Void local reportTypeError Args((Int,Cell,Cell,String,Type,Type));
64 static Void local cantEstablish Args((Int,String,Cell,Type,List));
65 static Void local tooGeneral Args((Int,Cell,Type,Type));
67 static Cell local typeExpr Args((Int,Cell));
69 static Cell local typeAp Args((Int,Cell));
70 static Type local typeExpected Args((Int,String,Cell,Type,Int,Int,Bool));
71 static Void local typeAlt Args((String,Cell,Cell,Type,Int,Int));
72 static Int local funcType Args((Int));
73 static Void local typeCase Args((Int,Int,Cell));
74 static Void local typeComp Args((Int,Type,Cell,List));
75 static Cell local typeMonadComp Args((Int,Cell));
76 static Void local typeDo Args((Int,Cell));
77 static Void local typeConFlds Args((Int,Cell));
78 static Void local typeUpdFlds Args((Int,Cell));
80 static Cell local typeWith Args((Int,Cell));
82 static Cell local typeFreshPat Args((Int,Cell));
84 static Void local typeBindings Args((List));
85 static Void local removeTypeSigs Args((Cell));
87 static Void local monorestrict Args((List));
88 static Void local restrictedBindAss Args((Cell));
89 static Void local restrictedAss Args((Int,Cell,Type));
91 static Void local unrestricted Args((List));
92 static List local itbscc Args((List));
93 static Void local addEvidParams Args((List,Cell));
95 static Void local typeClassDefn Args((Class));
96 static Void local typeInstDefn Args((Inst));
97 static Void local typeMember Args((String,Name,Cell,List,Cell,Int));
99 static Void local typeBind Args((Cell));
100 static Void local typeDefAlt Args((Int,Cell,Pair));
101 static Cell local typeRhs Args((Cell));
102 static Void local guardedType Args((Int,Cell));
104 static Void local genBind Args((List,Cell));
105 static Void local genAss Args((Int,List,Cell,Type));
106 static Type local genTest Args((Int,Cell,List,Type,Type,Int));
107 static Type local generalize Args((List,Type));
108 static Bool local equalTypes Args((Type,Type));
110 static Void local typeDefnGroup Args((List));
111 static Pair local typeSel Args((Name));
115 /* --------------------------------------------------------------------------
118 * A basic typing statement is a pair (Var,Type) and an assumption contains
119 * an ordered list of basic typing statements in which the type for a given
120 * variable is given by the most recently added assumption about that var.
122 * In practice, the assumption set is split between a pair of lists, one
123 * holding assumptions for vars defined in bindings, the other for vars
124 * defined in patterns/binding parameters etc. The reason for this
125 * separation is that vars defined in bindings may be overloaded (with the
126 * overloading being unknown until the whole binding is typed), whereas the
127 * vars defined in patterns have no overloading. A form of dependency
128 * analysis (at least as far as calculating dependents within the same group
129 * of value bindings) is required to implement this. Where it is known that
130 * no overloaded values are defined in a binding (i.e., when the `dreaded
131 * monomorphism restriction' strikes), the list used to record dependents
132 * is flagged with a NODEPENDS tag to avoid gathering dependents at that
135 * To interleave between vars for bindings and vars for patterns, we use
136 * a list of lists of typing statements for each. These lists are always
137 * the same length. The implementation here is very similar to that of the
138 * dependency analysis used in the static analysis component of this system.
140 * To deal with polymorphic recursion, variables defined in bindings can be
141 * assigned types of the form (POLYREC,(def,use)), where def is a type
142 * variable for the type of the defining occurence, and use is a type
143 * scheme for (recursive) calls/uses of the variable.
144 * ------------------------------------------------------------------------*/
146 static List defnBounds; /*::[[(Var,Type)]] possibly ovrlded*/
147 static List varsBounds; /*::[[(Var,Type)]] not overloaded */
148 static List depends; /*::[?[Var]] dependents/NODEPENDS */
149 static List skolVars; /*::[[Var]] skolem vars */
150 static List localEvs; /*::[[(Pred,offset,ev)]] */
151 static List savedPs; /*::[[(Pred,offset,ev)]] */
152 static Cell dummyVar; /* Used to put extra tvars into ass*/
154 #define saveVarsAss() List saveAssump = hd(varsBounds)
155 #define restoreVarsAss() hd(varsBounds) = saveAssump
156 #define addVarAssump(v,t) hd(varsBounds) = cons(pair(v,t),hd(varsBounds))
157 #define findTopBinding(v) findInAssumList(textOf(v),hd(defnBounds))
159 static Void local emptyAssumption() { /* set empty type assumption */
168 static Void local enterBindings() { /* Add new level to assumption sets */
169 defnBounds = cons(NIL,defnBounds);
170 varsBounds = cons(NIL,varsBounds);
171 depends = cons(NIL,depends);
174 static Void local leaveBindings() { /* Drop one level of assumptions */
175 defnBounds = tl(defnBounds);
176 varsBounds = tl(varsBounds);
177 depends = tl(depends);
180 static Int local defType(a) /* Return type for defining occ. */
181 Cell a; { /* of a var from assumption pair */
182 return (isPair(a) && fst(a)==POLYREC) ? fst(snd(a)) : a;
185 static Type local useType(a) /* Return type for use of a var */
186 Cell a; { /* defined in an assumption */
187 return (isPair(a) && fst(a)==POLYREC) ? snd(snd(a)) : a;
190 static Void local markAssumList(as) /* Mark all types in assumption set*/
191 List as; { /* :: [(Var, Type)] */
192 for (; nonNull(as); as=tl(as)) { /* No need to mark generic types; */
193 Type t = defType(snd(hd(as))); /* the only free variables in those*/
194 if (!isPolyType(t)) /* must have been free earlier too */
199 static Cell local findAssum(t) /* Find most recent assumption about*/
200 Text t; { /* variable named t, if any */
201 List defnBounds1 = defnBounds; /* return translated variable, with */
202 List varsBounds1 = varsBounds; /* type in typeIs */
203 List depends1 = depends;
205 while (nonNull(defnBounds1)) {
206 Pair ass = findInAssumList(t,hd(varsBounds1));/* search varsBounds */
212 ass = findInAssumList(t,hd(defnBounds1)); /* search defnBounds */
217 if (hd(depends1)!=NODEPENDS && /* save dependent? */
218 isNull(v=varIsMember(t,hd(depends1))))
219 /* N.B. make new copy of variable and store this on list of*/
220 /* dependents, and in the assumption so that all uses of */
221 /* the variable will be at the same node, if we need to */
222 /* overwrite the call of a function with a translation... */
223 hd(depends1) = cons(v=mkVar(t),hd(depends1));
228 defnBounds1 = tl(defnBounds1); /* look in next level*/
229 varsBounds1 = tl(varsBounds1); /* of assumption set */
230 depends1 = tl(depends1);
235 static Pair local findInAssumList(t,as)/* Search for assumption for var */
236 Text t; /* named t in list of assumptions as*/
238 for (; nonNull(as); as=tl(as))
239 if (textOf(fst(hd(as)))==t)
244 static List local intsIntersect(as,bs) /* calculate intersection of lists */
245 List as, bs; { /* of integers (as sets) */
246 List ts = NIL; /* destructively modifies as */
248 if (intIsMember(intOf(hd(as)),bs)) {
259 static List local genvarAllAss(as) /* calculate generic vars that are */
260 List as; { /* in every type in assumptions as */
261 List vs = genvarTyvar(intOf(defType(snd(hd(as)))),NIL);
262 for (as=tl(as); nonNull(as) && nonNull(vs); as=tl(as))
263 vs = intsIntersect(vs,genvarTyvar(intOf(defType(snd(hd(as)))),NIL));
267 static List local genvarAnyAss(as) /* calculate generic vars that are */
268 List as; { /* in any type in assumptions as */
269 List vs = genvarTyvar(intOf(defType(snd(hd(as)))),NIL);
270 for (as=tl(as); nonNull(as); as=tl(as))
271 vs = genvarTyvar(intOf(defType(snd(hd(as)))),vs);
275 static Int local newVarsBind(v) /* make new assump for pattern var */
277 Int beta = newTyvars(1);
278 addVarAssump(v,mkInt(beta));
280 Printf("variable, assume ");
282 Printf(" :: _%d\n",beta);
287 static Void local newDefnBind(v,type) /* make new assump for defn var */
288 Cell v; /* and set type if given (nonNull) */
290 Int beta = newTyvars(1);
291 Cell ta = mkInt(beta);
293 if (nonNull(type) && isPolyType(type))
294 ta = pair(POLYREC,pair(ta,type));
295 hd(defnBounds) = cons(pair(v,ta), hd(defnBounds));
297 Printf("definition, assume ");
299 Printf(" :: _%d\n",beta);
301 bindTv(beta,typeIs,typeOff); /* Bind beta to new type skeleton */
304 /* --------------------------------------------------------------------------
306 * ------------------------------------------------------------------------*/
310 /* --------------------------------------------------------------------------
311 * Bound and skolemized type variables:
312 * ------------------------------------------------------------------------*/
314 static List pendingBtyvs = NIL;
316 static Void local enterPendingBtyvs() {
318 pendingBtyvs = cons(NIL,pendingBtyvs);
321 static Void local leavePendingBtyvs() {
322 List pts = hd(pendingBtyvs);
323 pendingBtyvs = tl(pendingBtyvs);
324 for (; nonNull(pts); pts=tl(pts)) {
325 Int line = intOf(fst(hd(pts)));
326 List vs = snd(hd(pts));
329 for (; nonNull(vs); vs=tl(vs)) {
330 Cell v = fst(hd(vs));
331 Cell t = copyTyvar(intOf(snd(hd(vs))));
333 ERRMSG(line) "Type annotation uses variable " ETHEN ERREXPR(v);
334 ERRTEXT " where a more specific type " ETHEN ERRTYPE(t);
335 ERRTEXT " was inferred"
338 else if (offsetOf(t)!=i) {
339 List us = snd(hd(pts));
342 internal("leavePendingBtyvs");
345 ERRMSG(line) "Type annotation uses distinct variables " ETHEN
346 ERREXPR(v); ERRTEXT " and " ETHEN ERREXPR(fst(hd(us)));
347 ERRTEXT " where a single variable was inferred"
357 static Cell local patBtyvs(p) /* Strip bound type vars from pat */
359 if (whatIs(p)==BIGLAM) {
360 List bts = hd(btyvars) = fst(snd(p));
361 for (p=snd(snd(p)); nonNull(bts); bts=tl(bts)) {
362 Int beta = newTyvars(1);
363 tyvar(beta)->kind = snd(hd(bts));
364 snd(hd(bts)) = mkInt(beta);
370 static Void local doneBtyvs(l)
372 if (nonNull(hd(btyvars))) { /* Save bound tyvars */
373 hd(pendingBtyvs) = cons(pair(mkInt(l),hd(btyvars)),hd(pendingBtyvs));
378 static Void local enterSkolVars() {
379 skolVars = cons(NIL,skolVars);
380 localEvs = cons(NIL,localEvs);
381 savedPs = cons(preds,savedPs);
385 static Void local leaveSkolVars(l,t,o,m)
390 if (nonNull(hd(localEvs))) { /* Check for local predicates */
391 List sks = hd(skolVars);
394 internal("leaveSkolVars");
396 markAllVars(); /* Mark all variables in current */
397 do { /* substitution, then unmark sks. */
398 tyvar(intOf(fst(hd(sks))))->offs = UNUSED_GENERIC;
400 } while (nonNull(sks));
402 sps = elimPredsUsing(hd(localEvs),sps);
403 preds = revOnto(preds,sps);
406 if (nonNull(hd(skolVars))) { /* Check that Skolem vars do not */
407 List vs; /* escape their scope */
410 clearMarks(); /* Look for occurences in the */
411 for (; i<m; i++) /* inferred type */
415 for (vs=hd(skolVars); nonNull(vs); vs=tl(vs)) {
416 Int vn = intOf(fst(hd(vs)));
417 if (tyvar(vn)->offs == FIXED_TYVAR) {
418 Cell tv = copyTyvar(vn);
419 Type ty = liftRank2(t,o,m);
420 ERRMSG(l) "Existentially quantified variable in inferred type"
422 ERRTEXT "\n*** Variable : " ETHEN ERRTYPE(tv);
423 ERRTEXT "\n*** From pattern : " ETHEN ERREXPR(snd(hd(vs)));
424 ERRTEXT "\n*** Result type : " ETHEN ERRTYPE(ty);
430 markBtyvs(); /* Now check assumptions */
431 mapProc(markAssumList,defnBounds);
432 mapProc(markAssumList,varsBounds);
434 for (vs=hd(skolVars); nonNull(vs); vs=tl(vs)) {
435 Int vn = intOf(fst(hd(vs)));
436 if (tyvar(vn)->offs == FIXED_TYVAR) {
438 "Existentially quantified variable escapes from pattern "
439 ETHEN ERREXPR(snd(hd(vs)));
445 localEvs = tl(localEvs);
446 skolVars = tl(skolVars);
447 preds = revOnto(preds,hd(savedPs));
448 savedPs = tl(savedPs);
451 /* --------------------------------------------------------------------------
453 * ------------------------------------------------------------------------*/
455 static Void local typeError(l,e,in,wh,t,o)
456 Int l; /* line number near type error */
457 String wh; /* place in which error occurs */
458 Cell e; /* source of error */
459 Cell in; /* context if any (NIL if not) */
460 Type t; /* should be of type (t,o) */
461 Int o; { /* type inferred is (typeIs,typeOff) */
463 clearMarks(); /* types printed here are monotypes */
464 /* use marking to give sensible names*/
466 { List vs = genericVars;
467 for (; nonNull(vs); vs=tl(vs)) {
468 Int v = intOf(hd(vs));
469 Printf("%c :: ", ('a'+tyvar(v)->offs));
470 printKind(stdout,tyvar(v)->kind);
476 reportTypeError(l,e,in,wh,copyType(typeIs,typeOff),copyType(t,o));
479 static Void local reportTypeError(l,e,in,wh,inft,expt)
480 Int l; /* Error printing part of typeError*/
484 ERRMSG(l) "Type error in %s", wh ETHEN
486 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(in);
488 ERRTEXT "\n*** Term : " ETHEN ERREXPR(e);
489 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(inft);
490 ERRTEXT "\n*** Does not match : " ETHEN ERRTYPE(expt);
492 ERRTEXT "\n*** Because : %s", unifyFails ETHEN
498 #define shouldBe(l,e,in,where,t,o) if (!unify(typeIs,typeOff,t,o)) \
499 typeError(l,e,in,where,t,o);
500 #define check(l,e,in,where,t,o) e=typeExpr(l,e); shouldBe(l,e,in,where,t,o)
501 #define inferType(t,o) typeIs=t; typeOff=o
503 #define spTypeExpr(l,e) svPreds = preds; preds = NIL; e = typeExpr(l,e); preds = revOnto(preds,svPreds);
504 #define spCheck(l,e,in,where,t,o) svPreds = preds; preds = NIL; check(l,e,in,where,t,o); preds = revOnto(preds,svPreds);
506 #define spTypeExpr(l,e) e = typeExpr(l,e);
507 #define spCheck(l,e,in,where,t,o) check(l,e,in,where,t,o);
510 static Void local cantEstablish(line,wh,e,t,ps)
511 Int line; /* Complain when declared preds */
512 String wh; /* are not sufficient to discharge */
513 Cell e; /* or defer the inferred context. */
516 ERRMSG(line) "Cannot justify constraints in %s", wh ETHEN
517 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
518 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(t);
519 ERRTEXT "\n*** Given context : " ETHEN ERRCONTEXT(ps);
520 ERRTEXT "\n*** Constraints : " ETHEN ERRCONTEXT(copyPreds(preds));
525 static Void local tooGeneral(l,e,dt,it) /* explicit type sig. too general */
529 ERRMSG(l) "Inferred type is not general enough" ETHEN
530 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
531 ERRTEXT "\n*** Expected type : " ETHEN ERRTYPE(dt);
532 ERRTEXT "\n*** Inferred type : " ETHEN ERRTYPE(it);
537 /* --------------------------------------------------------------------------
538 * Typing of expressions:
539 * ------------------------------------------------------------------------*/
541 #define EXPRESSION 0 /* type checking expression */
542 #define NEW_PATTERN 1 /* pattern, introducing new vars */
543 #define OLD_PATTERN 2 /* pattern, involving bound vars */
544 static int tcMode = EXPRESSION;
547 static Cell local mytypeExpr Args((Int,Cell));
548 static Cell local typeExpr(l,e)
551 static int number = 0;
553 int mynumber = number++;
556 Printf("%d) to check: ",mynumber);
559 retv = mytypeExpr(l,e);
560 Printf("%d) result: ",mynumber);
561 printType(stdout,debugType(typeIs,typeOff));
562 Printf("\n%d) preds: ",mynumber);
563 printContext(stdout,debugContext(preds));
567 static Cell local mytypeExpr(l,e) /* Determine type of expr/pattern */
569 static Cell local typeExpr(l,e) /* Determine type of expr/pattern */
573 static String cond = "conditional";
574 static String list = "list";
575 static String discr = "case discriminant";
576 static String aspat = "as (@) pattern";
577 static String typeSig = "type annotation";
578 static String lambda = "lambda expression";
585 /* The following cases can occur in either pattern or expr. mode */
596 case TUPLE : typeTuple(e);
599 case BIGCELL : { Int alpha = newTyvars(1);
600 inferType(aVar,alpha);
601 return ap(ap(nameFromInteger,
602 assumeEvid(predNum,alpha)),
606 case INTCELL : { Int alpha = newTyvars(1);
607 inferType(aVar,alpha);
608 return ap(ap(nameFromInt,
609 assumeEvid(predNum,alpha)),
613 case FLOATCELL : { Int alpha = newTyvars(1);
614 inferType(aVar,alpha);
615 return ap(ap(nameFromDouble,
616 assumeEvid(predFractional,alpha)),
620 case STRCELL : inferType(typeString,0);
623 case CHARCELL : inferType(typeChar,0);
626 case CONFLDS : typeConFlds(l,e);
629 case ESIGN : snd(snd(e)) = localizeBtyvs(snd(snd(e)));
630 return typeExpected(l,typeSig,
631 fst(snd(e)),snd(snd(e)),
635 case EXT : { Int beta = newTyvars(2);
636 Cell pi = ap(e,aVar);
639 ap(typeRec,ap(ap(e,aVar),bVar))));
640 tyvar(beta+1)->kind = ROW;
642 return ap(e,assumeEvid(pi,beta+1));
646 /* The following cases can only occur in expr mode */
648 case UPDFLDS : typeUpdFlds(l,e);
652 case WITHEXP : return typeWith(l,e);
655 case COND : { Int beta = newTyvars(1);
656 check(l,fst3(snd(e)),e,cond,typeBool,0);
657 spCheck(l,snd3(snd(e)),e,cond,aVar,beta);
658 spCheck(l,thd3(snd(e)),e,cond,aVar,beta);
663 case LETREC : enterBindings();
665 mapProc(typeBindings,fst(snd(e)));
666 spTypeExpr(l,snd(snd(e)));
668 leaveSkolVars(l,typeIs,typeOff,0);
671 case FINLIST : { Int beta = newTyvars(1);
673 for (xs=snd(e); nonNull(xs); xs=tl(xs)) {
674 spCheck(l,hd(xs),e,list,aVar,beta);
676 inferType(listof,beta);
680 case DOCOMP : typeDo(l,e);
683 case COMP : return typeMonadComp(l,e);
685 case CASE : { Int beta = newTyvars(2); /* discr result */
686 check(l,fst(snd(e)),NIL,discr,aVar,beta);
687 map2Proc(typeCase,l,beta,snd(snd(e)));
692 case LAMBDA : { Int beta = newTyvars(1);
694 typeAlt(lambda,e,snd(e),aVar,beta,1);
701 case RECSEL : { Int beta = newTyvars(2);
702 Cell pi = ap(snd(e),aVar);
703 Type t = fn(ap(typeRec,
706 tyvar(beta+1)->kind = ROW;
708 return ap(e,assumeEvid(pi,beta+1));
712 /* The remaining cases can only occur in pattern mode: */
714 case WILDCARD : inferType(aVar,newTyvars(1));
717 case ASPAT : { Int beta = newTyvars(1);
718 snd(snd(e)) = typeExpr(l,snd(snd(e)));
719 bindTv(beta,typeIs,typeOff);
720 check(l,fst(snd(e)),e,aspat,aVar,beta);
725 case LAZYPAT : snd(e) = typeExpr(l,snd(e));
729 case ADDPAT : { Int alpha = newTyvars(1);
730 inferType(typeVarToVar,alpha);
731 return ap(e,assumeEvid(predIntegral,alpha));
735 default : internal("typeExpr");
741 /* --------------------------------------------------------------------------
742 * Typing rules for particular special forms:
743 * ------------------------------------------------------------------------*/
745 static Cell local typeAp(l,e) /* Type check application, which */
746 Int l; /* may be headed with a variable */
747 Cell e; { /* requires polymorphism, qualified*/
748 static String app = "application"; /* types, and possible rank2 args. */
759 case NAME : typeIs = name(h).type;
763 case VARIDCELL : if (tcMode==NEW_PATTERN) {
764 inferType(aVar,newVarsBind(e));
767 Cell v = findAssum(textOf(h));
770 typeIs = (tcMode==OLD_PATTERN)
775 h = findName(textOf(h));
778 typeIs = name(h).type;
784 case IPVAR : { Text t = textOf(h);
785 Int alpha = newTyvars(1);
786 Cell ip = pair(ap(IPCELL,t),aVar);
787 Cell ev = assumeEvid(ip,alpha);
788 typeIs = mkInt(alpha);
794 default : h = typeExpr(l,h);
798 if (isNull(typeIs)) {
802 instantiate(typeIs); /* Deal with polymorphism ... */
803 if (nonNull(predsAre)) { /* ... and with qualified types. */
805 for (; nonNull(predsAre); predsAre=tl(predsAre)) {
806 evs = cons(assumeEvid(hd(predsAre),typeOff),evs);
808 if (!isName(h) || !isCfun(h)) {
809 h = applyToArgs(h,rev(evs));
813 if (whatIs(typeIs)==CDICTS) { /* Deal with local dictionaries */
814 List evs = makePredAss(fst(snd(typeIs)),typeOff);
816 typeIs = snd(snd(typeIs));
817 for (; nonNull(ps); ps=tl(ps)) {
818 h = ap(h,thd3(hd(ps)));
820 if (tcMode==EXPRESSION) {
821 preds = revOnto(evs,preds);
823 hd(localEvs) = revOnto(evs,hd(localEvs));
827 if (whatIs(typeIs)==EXIST) { /* Deal with existential arguments */
828 Int n = intOf(fst(snd(typeIs)));
829 typeIs = snd(snd(typeIs));
830 if (!isCfun(getHead(h)) || n>typeFree) {
832 } else if (tcMode!=EXPRESSION) {
833 Int alpha = typeOff + typeFree;
835 bindTv(alpha-n,SKOLEM,0);
836 hd(skolVars) = cons(pair(mkInt(alpha-n),e),hd(skolVars));
841 if (whatIs(typeIs)==RANK2) { /* Deal with rank 2 arguments */
844 Int nr2 = intOf(fst(snd(typeIs)));
845 Type body = snd(snd(typeIs));
849 if (n<nr2) { /* Must have enough arguments */
850 ERRMSG(l) "Use of " ETHEN ERREXPR(h);
852 ERRTEXT " in " ETHEN ERREXPR(e);
854 ERRTEXT " requires at least %d argument%s\n",
855 nr2, (nr2==1 ? "" : "s")
859 for (i=nr2; i<n; ++i) /* Find rank two arguments */
862 for (as=getArgs(as); nonNull(as); as=tl(as), body=arg(body)) {
863 Type expect = dropRank1(arg(fun(body)),alpha,m);
864 if (isPolyOrQualType(expect)) {
865 if (tcMode==EXPRESSION) /* poly/qual type in expr */
866 hd(as) = typeExpected(l,app,hd(as),expect,alpha,m,TRUE);
867 else if (hd(as)!=WILDCARD) { /* Pattern binding/match */
868 if (!isVar(hd(as))) {
869 ERRMSG(l) "Argument " ETHEN ERREXPR(arg(as));
870 ERRTEXT " in pattern " ETHEN ERREXPR(e);
871 ERRTEXT " where a variable is required\n"
874 if (tcMode==NEW_PATTERN) { /* Pattern match */
877 addVarAssump(dummyVar,mkInt(alpha+i));
880 addVarAssump(hd(as),expect);
882 else { /* Pattern binding */
883 Text t = textOf(hd(as));
884 Cell a = findInAssumList(t,hd(defnBounds));
888 if (nonNull(predsAre)) {
889 ERRMSG(l) "Cannot use pattern binding for " ETHEN
891 ERRTEXT " as a component with a qualified type\n"
894 shouldBe(l,hd(as),e,app,aVar,intOf(defType(snd(a))));
898 else { /* Not a poly/qual type */
899 spCheck(l,hd(as),e,app,expect,alpha);
901 h = ap(h,hd(as)); /* Save checked argument */
903 inferType(body,alpha);
907 if (n>0) { /* Deal with remaining args */
908 Int beta = funcType(n); /* check h::t1->t2->...->tn->rn+1 */
909 shouldBe(l,h,e,app,aVar,beta);
910 for (i=n; i>0; --i) { /* check e_i::t_i for each i */
911 spCheck(l,arg(a),e,app,aVar,beta+2*i-1);
915 tyvarType(beta+2*n); /* Inferred type is r_n+1 */
918 if (isNull(p)) /* Replace head with translation */
926 static Cell local typeExpected(l,wh,e,reqd,alpha,n,addEvid)
927 Int l; /* Type check expression e in wh */
928 String wh; /* at line l, expecting type reqd, */
929 Cell e; /* and treating vars alpha through */
930 Type reqd; /* (alpha+n-1) as fixed. */
933 Bool addEvid; { /* TRUE => add \ev -> ... */
934 List savePreds = preds;
945 ps = makePredAss(predsAre,o);
948 check(l,e,NIL,wh,t,o);
952 mapProc(markAssumList,defnBounds);
953 mapProc(markAssumList,varsBounds);
954 mapProc(markPred,savePreds);
957 if (n > 0) { /* mark alpha thru alpha+n-1, plus any */
958 /* type vars that are functionally */
959 List us = NIL, vs = NIL; /* dependent on them */
960 List fds = calcFunDepsPreds(preds);
961 for (i=0; i<n; i++) {
962 Type t1 = zonkTyvar(alpha+i);
963 us = zonkTyvarsIn(t1,us);
966 for (; nonNull(vs); vs=tl(vs))
967 markTyvar(intOf(hd(vs)));
971 savePreds = elimPredsUsing(ps,savePreds);
972 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
973 savePreds = elimPredsUsing(ps,savePreds);
974 if (nonNull(preds)) {
975 Type ty = copyType(t,o);
976 List qs = copyPreds(ps);
977 cantEstablish(l,wh,e,ty,qs);
982 if (copyTyvar(o+i)!=mkOffset(i)) {
983 List qs = copyPreds(ps);
984 Type it = copyType(t,o);
985 tooGeneral(l,e,reqd,generalize(qs,it));
989 e = qualifyExpr(l,ps,e);
993 preds = revOnto(ps,savePreds);
999 static Void local typeAlt(wh,e,a,t,o,m) /* Type check abstraction (Alt) */
1000 String wh; /* a = ( [p1, ..., pn], rhs ) */
1007 List ps = fst(a) = patBtyvs(fst(a));
1009 Int l = rhsLine(snd(a));
1016 if (whatIs(t)==RANK2) {
1017 if (n<(nr2=intOf(fst(snd(t))))) {
1018 ERRMSG(l) "Definition requires at least %d parameters on lhs",
1025 while (getHead(t)==typeArrow && argCount==2 && nonNull(ps)) {
1026 Type ta = arg(fun(t));
1027 if (isPolyOrQualType(ta)) {
1028 if (hd(ps)!=WILDCARD) {
1029 if (!isVar(hd(ps))) {
1030 ERRMSG(l) "Argument " ETHEN ERREXPR(hd(ps));
1031 ERRTEXT " used where a variable or wildcard is required\n"
1034 if (m>0 && !added) {
1037 addVarAssump(dummyVar,mkInt(o+i));
1040 addVarAssump(hd(ps),ta);
1044 hd(ps) = typeFreshPat(l,hd(ps));
1045 shouldBe(l,hd(ps),NIL,wh,ta,o);
1054 snd(a) = typeRhs(snd(a));
1056 Int beta = funcType(n);
1059 hd(ps) = typeFreshPat(l,hd(ps));
1060 bindTv(beta+2*i+1,typeIs,typeOff);
1063 snd(a) = typeRhs(snd(a));
1064 bindTv(beta+2*n,typeIs,typeOff);
1068 if (!unify(typeIs,typeOff,t,o)) {
1071 req = liftRank2(origt,o,m);
1072 liftRank2Args(as,o,m);
1073 got = ap(RANK2,pair(mkInt(nr2),revOnto(as,copyType(typeIs,typeOff))));
1074 reportTypeError(l,e,NIL,wh,got,req);
1079 leaveSkolVars(l,origt,o,m);
1082 static Int local funcType(n) /*return skeleton for function type*/
1083 Int n; { /*with n arguments, taking the form*/
1084 Int beta = newTyvars(2*n+1); /* r1 t1 r2 t2 ... rn tn rn+1 */
1085 Int i; /* with r_i := t_i -> r_i+1 */
1087 bindTv(beta+2*i,arrow,beta+2*i+1);
1091 static Void local typeCase(l,beta,c) /* type check case: pat -> rhs */
1092 Int l; /* (case given by c == (pat,rhs)) */
1093 Int beta; /* need: pat :: (var,beta) */
1094 Cell c; { /* rhs :: (var,beta+1) */
1095 static String casePat = "case pattern";
1096 static String caseExpr = "case expression";
1100 fst(c) = typeFreshPat(l,patBtyvs(fst(c)));
1101 shouldBe(l,fst(c),NIL,casePat,aVar,beta);
1102 snd(c) = typeRhs(snd(c));
1103 shouldBe(l,rhsExpr(snd(c)),NIL,caseExpr,aVar,beta+1);
1107 leaveSkolVars(l,typeIs,typeOff,0);
1110 static Void local typeComp(l,m,e,qs) /* type check comprehension */
1112 Type m; /* monad (mkOffset(0)) */
1115 static String boolQual = "boolean qualifier";
1116 static String genQual = "generator";
1122 if (isNull(qs)) { /* no qualifiers left */
1123 spTypeExpr(l,fst(e));
1127 switch (whatIs(q)) {
1128 case BOOLQUAL : spCheck(l,snd(q),NIL,boolQual,typeBool,0);
1129 typeComp(l,m,e,qs1);
1132 case QWHERE : enterBindings();
1134 mapProc(typeBindings,snd(q));
1135 typeComp(l,m,e,qs1);
1137 leaveSkolVars(l,typeIs,typeOff,0);
1140 case FROMQUAL : { Int beta = newTyvars(1);
1142 spCheck(l,snd(snd(q)),NIL,genQual,m,beta);
1145 = typeFreshPat(l,patBtyvs(fst(snd(q))));
1146 shouldBe(l,fst(snd(q)),NIL,genQual,aVar,beta);
1147 typeComp(l,m,e,qs1);
1150 leaveSkolVars(l,typeIs,typeOff,0);
1154 case DOQUAL : spCheck(l,snd(q),NIL,genQual,m,newTyvars(1));
1155 typeComp(l,m,e,qs1);
1161 static Cell local typeMonadComp(l,e) /* type check monad comprehension */
1164 Int alpha = newTyvars(1);
1165 Int beta = newTyvars(1);
1166 Cell mon = ap(mkInt(beta),aVar);
1167 Cell m = assumeEvid(predMonad,beta);
1168 tyvar(beta)->kind = starToStar;
1170 bindTv(beta,typeList,0);
1174 typeComp(l,mon,snd(e),snd(snd(e)));
1175 bindTv(alpha,typeIs,typeOff);
1176 inferType(mon,alpha);
1177 return ap(MONADCOMP,pair(m,snd(e)));
1180 static Void local typeDo(l,e) /* type check do-notation */
1183 static String finGen = "final generator";
1184 Int alpha = newTyvars(1);
1185 Int beta = newTyvars(1);
1186 Cell mon = ap(mkInt(beta),aVar);
1187 Cell m = assumeEvid(predMonad,beta);
1188 tyvar(beta)->kind = starToStar;
1190 typeComp(l,mon,snd(e),snd(snd(e)));
1191 shouldBe(l,fst(snd(e)),NIL,finGen,mon,alpha);
1192 snd(e) = pair(m,snd(e));
1195 static Void local typeConFlds(l,e) /* Type check a construction */
1198 static String conExpr = "value construction";
1199 Name c = fst(snd(e));
1200 List fs = snd(snd(e));
1209 instantiate(name(c).type);
1210 for (; nonNull(predsAre); predsAre=tl(predsAre))
1211 assumeEvid(hd(predsAre),typeOff);
1212 if (whatIs(typeIs)==RANK2)
1213 typeIs = snd(snd(typeIs));
1218 for (; nonNull(fs); fs=tl(fs)) {
1220 for (i=sfunPos(fst(hd(fs)),c); --i>0; t=arg(t))
1222 t = dropRank1(arg(fun(t)),to,tf);
1223 if (isPolyOrQualType(t))
1224 snd(hd(fs)) = typeExpected(l,conExpr,snd(hd(fs)),t,to,tf,TRUE);
1226 spCheck(l,snd(hd(fs)),e,conExpr,t,to);
1229 for (i=name(c).arity; i>0; i--)
1234 static Void local typeUpdFlds(line,e) /* Type check an update */
1235 Int line; /* (Written in what might seem a */
1236 Cell e; { /* bizarre manner for the benefit */
1237 static String update = "update"; /* of as yet unreleased extensions)*/
1238 List cs = snd3(snd(e)); /* List of constructors */
1239 List fs = thd3(snd(e)); /* List of field specifications */
1240 List ts = NIL; /* List of types for fields */
1242 Int alpha = newTyvars(2+n);
1249 /* Calculate type and translation for each expr in the field list */
1250 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1251 spTypeExpr(line,snd(hd(fs1)));
1252 bindTv(i,typeIs,typeOff);
1256 mapProc(markAssumList,defnBounds);
1257 mapProc(markAssumList,varsBounds);
1258 mapProc(markPred,preds);
1261 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1263 ts = cons(generalize(NIL,copyTyvar(i)),ts);
1267 /* Type check expression to be updated */
1268 spTypeExpr(line,fst3(snd(e)));
1269 bindTv(alpha,typeIs,typeOff);
1271 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constrs */
1273 List ta = replicate(name(c).arity,NIL);
1277 tcMode = NEW_PATTERN; /* Domain type */
1278 instantiate(name(c).type);
1279 tcMode = EXPRESSION;
1282 for (; nonNull(predsAre); predsAre=tl(predsAre))
1283 assumeEvid(hd(predsAre),typeOff);
1285 if (whatIs(typeIs)==RANK2) {
1286 ERRMSG(line) "Sorry, record update syntax cannot currently be "
1287 "used for datatypes with polymorphic components"
1291 instantiate(name(c).type); /* Range type */
1294 for (; nonNull(predsAre); predsAre=tl(predsAre))
1295 assumeEvid(hd(predsAre),typeOff);
1297 for (fs1=fs, i=1; nonNull(fs1); fs1=tl(fs1), i++) {
1298 Int n = sfunPos(fst(hd(fs1)),c);
1305 for (; nonNull(ta); ta=tl(ta)) { /* For each cfun arg */
1306 if (nonNull(hd(ta))) { /* Field to updated? */
1307 Int n = intOf(hd(ta));
1310 for (; n-- > 1; f=tl(f), t=tl(t))
1315 shouldBe(line,snd(f),e,update,arg(fun(tr)),or);
1316 } /* Unmentioned component */
1317 else if (!unify(arg(fun(td)),od,arg(fun(tr)),or))
1318 internal("typeUpdFlds");
1324 inferType(td,od); /* Check domain type */
1325 shouldBe(line,fst3(snd(e)),e,update,aVar,alpha);
1326 inferType(tr,or); /* Check range type */
1327 shouldBe(line,e,NIL,update,aVar,alpha+1);
1329 /* (typeIs,typeOff) still carry the result type when we exit the loop */
1333 static Cell local typeWith(line,e) /* Type check a with */
1336 List fs = snd(snd(e)); /* List of field specifications */
1338 Int alpha = newTyvars(2+n);
1343 List dpreds = NIL, dp;
1346 /* Type check expression to be updated */
1347 fst(snd(e)) = typeExpr(line,fst(snd(e)));
1348 bindTv(alpha,typeIs,typeOff);
1351 /* elim duplicate uses of imp params */
1352 preds = scSimplify(preds);
1353 /* extract preds that we're going to bind */
1354 for (fs1=fs; nonNull(fs1); fs1=tl(fs1)) {
1355 Text t = textOf(fst(hd(fs1)));
1356 Cell p = findIPEvid(t);
1357 dpreds = cons(p, dpreds);
1361 /* maybe give a warning message here... */
1364 dpreds = rev(dpreds);
1366 /* Calculate type and translation for each expr in the field list */
1367 for (fs1=fs, dp=dpreds, i=alpha+2; nonNull(fs1); fs1=tl(fs1), dp=tl(dp), i++) {
1368 static String with = "with";
1370 snd(hd(fs1)) = typeExpr(line,snd(hd(fs1)));
1371 bindTv(i,typeIs,typeOff);
1373 shouldBe(line,fst(hd(fs1)),e,with,snd(fst3(ev)),intOf(snd3(ev)));
1374 bs = cons(cons(pair(thd3(ev), cons(triple(NIL, mkInt(line), snd(hd(fs1))), NIL)), NIL), bs);
1379 return (ap(LETREC,pair(bs,fst(snd(e)))));
1383 static Cell local typeFreshPat(l,p) /* find type of pattern, assigning */
1384 Int l; /* fresh type variables to each var */
1385 Cell p; { /* bound in the pattern */
1386 tcMode = NEW_PATTERN;
1388 tcMode = EXPRESSION;
1392 /* --------------------------------------------------------------------------
1393 * Type check group of bindings:
1394 * ------------------------------------------------------------------------*/
1396 static Void local typeBindings(bs) /* type check a binding group */
1398 Bool usesPatBindings = FALSE; /* TRUE => pattern binding in bs */
1399 Bool usesUntypedVar = FALSE; /* TRUE => var bind w/o type decl */
1402 /* The following loop is used to determine whether the monomorphism */
1403 /* restriction should be applied. It could be written marginally more */
1404 /* efficiently by using breaks, but clarity is more important here ... */
1406 for (bs1=bs; nonNull(bs1); bs1=tl(bs1)) { /* Analyse binding group */
1409 usesPatBindings = TRUE;
1410 else if (isNull(fst(hd(snd(snd(b))))) /* no arguments */
1411 && whatIs(fst(snd(b)))==IMPDEPS) /* implicitly typed*/
1412 usesUntypedVar = TRUE;
1415 if (usesPatBindings || usesUntypedVar)
1420 mapProc(removeTypeSigs,bs); /* Remove binding type info */
1421 hd(varsBounds) = revOnto(hd(defnBounds), /* transfer completed assmps*/
1422 hd(varsBounds)); /* out of defnBounds */
1423 hd(defnBounds) = NIL;
1427 static Void local removeTypeSigs(b) /* Remove type info from a binding */
1429 snd(b) = snd(snd(b));
1432 /* --------------------------------------------------------------------------
1433 * Type check a restricted binding group:
1434 * ------------------------------------------------------------------------*/
1436 static Void local monorestrict(bs) /* Type restricted binding group */
1438 List savePreds = preds;
1439 Int line = isVar(fst(hd(bs))) ? rhsLine(snd(hd(snd(snd(hd(bs))))))
1440 : rhsLine(snd(snd(snd(hd(bs)))));
1441 hd(defnBounds) = NIL;
1442 hd(depends) = NODEPENDS; /* No need for dependents here */
1444 preds = NIL; /* Type check the bindings */
1445 mapProc(restrictedBindAss,bs);
1446 mapProc(typeBind,bs);
1447 improve(line,NIL,preds);
1450 preds = revOnto(preds,savePreds);
1452 clearMarks(); /* Mark fixed variables */
1453 mapProc(markAssumList,tl(defnBounds));
1454 mapProc(markAssumList,tl(varsBounds));
1455 mapProc(markPred,preds);
1458 if (isNull(tl(defnBounds))) { /* Top-level may need defaulting */
1460 if (nonNull(preds) && resolveDefs(genvarAnyAss(hd(defnBounds))))
1465 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
1468 if (nonNull(preds)) { /* Look for unresolved overloading */
1469 Cell v = isVar(fst(hd(bs))) ? fst(hd(bs)) : hd(fst(hd(bs)));
1470 Cell ass = findInAssumList(textOf(v),hd(varsBounds));
1471 preds = scSimplify(preds);
1473 ERRMSG(line) "Unresolved top-level overloading" ETHEN
1474 ERRTEXT "\n*** Binding : %s", textToStr(textOf(v))
1477 ERRTEXT "\n*** Inferred type : " ETHEN ERRTYPE(snd(ass));
1479 ERRTEXT "\n*** Outstanding context : " ETHEN
1480 ERRCONTEXT(copyPreds(preds));
1486 map1Proc(genBind,NIL,bs); /* Generalize types of def'd vars */
1489 static Void local restrictedBindAss(b) /* Make assums for vars in binding */
1490 Cell b; { /* gp with restricted overloading */
1492 if (isVar(fst(b))) { /* function-binding? */
1493 Cell t = fst(snd(b));
1494 if (whatIs(t)==IMPDEPS) { /* Discard implicitly typed deps */
1495 fst(snd(b)) = t = NIL; /* in a restricted binding group. */
1497 fst(snd(b)) = localizeBtyvs(t);
1498 restrictedAss(rhsLine(snd(hd(snd(snd(b))))), fst(b), t);
1499 } else { /* pattern-binding? */
1501 List ts = fst(snd(b));
1502 Int line = rhsLine(snd(snd(snd(b))));
1504 for (; nonNull(vs); vs=tl(vs)) {
1506 restrictedAss(line,hd(vs),hd(ts)=localizeBtyvs(hd(ts)));
1509 restrictedAss(line,hd(vs),NIL);
1515 static Void local restrictedAss(l,v,t) /* Assume that type of binding var v*/
1516 Int l; /* is t (if nonNull) in restricted */
1517 Cell v; /* binding group */
1520 if (nonNull(predsAre)) {
1521 ERRMSG(l) "Explicit overloaded type for \"%s\"",textToStr(textOf(v))
1523 ERRTEXT " not permitted in restricted binding"
1528 /* --------------------------------------------------------------------------
1529 * Unrestricted binding group:
1530 * ------------------------------------------------------------------------*/
1532 static Void local unrestricted(bs) /* Type unrestricted binding group */
1534 List savePreds = preds;
1535 List imps = NIL; /* Implicitly typed bindings */
1536 List exps = NIL; /* Explicitly typed bindings */
1539 /* ----------------------------------------------------------------------
1540 * STEP 1: Separate implicitly typed bindings from explicitly typed
1541 * bindings and do a dependency analyis, where f depends on g iff f
1542 * is implicitly typed and involves a call to g.
1543 * --------------------------------------------------------------------*/
1545 for (; nonNull(bs); bs=tl(bs)) {
1547 if (whatIs(fst(snd(b)))==IMPDEPS)
1548 imps = cons(b,imps); /* N.B. New lists are built to */
1549 else /* avoid breaking the original */
1550 exps = cons(b,exps); /* list structure for bs. */
1553 for (bs=imps; nonNull(bs); bs=tl(bs)) {
1554 Cell b = hd(bs); /* Restrict implicitly typed dep */
1555 List ds = snd(fst(snd(b))); /* lists to bindings in imps */
1557 while (nonNull(ds)) {
1559 if (cellIsMember(hd(ds),imps)) {
1567 imps = itbscc(imps); /* Dependency analysis on imps */
1568 for (bs=imps; nonNull(bs); bs=tl(bs))
1569 for (bs1=hd(bs); nonNull(bs1); bs1=tl(bs1))
1570 fst(snd(hd(bs1))) = NIL; /* reset imps type fields */
1572 #ifdef DEBUG_DEPENDS
1573 Printf("Binding group:");
1574 for (bs1=imps; nonNull(bs1); bs1=tl(bs1)) {
1576 for (bs=hd(bs1); nonNull(bs); bs=tl(bs))
1577 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1580 if (nonNull(exps)) {
1582 for (bs=exps; nonNull(bs); bs=tl(bs))
1583 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1589 /* ----------------------------------------------------------------------
1590 * STEP 2: Add type assumptions about any explicitly typed variable.
1591 * --------------------------------------------------------------------*/
1593 for (bs=exps; nonNull(bs); bs=tl(bs)) {
1594 fst(snd(hd(bs))) = localizeBtyvs(fst(snd(hd(bs))));
1595 hd(varsBounds) = cons(pair(fst(hd(bs)),fst(snd(hd(bs)))),
1599 /* ----------------------------------------------------------------------
1600 * STEP 3: Calculate types for each group of implicitly typed bindings.
1601 * --------------------------------------------------------------------*/
1603 for (; nonNull(imps); imps=tl(imps)) {
1604 Cell b = hd(hd(imps));
1605 Int line = isVar(fst(b)) ? rhsLine(snd(hd(snd(snd(b)))))
1606 : rhsLine(snd(snd(snd(b))));
1607 hd(defnBounds) = NIL;
1609 for (bs1=hd(imps); nonNull(bs1); bs1=tl(bs1))
1610 newDefnBind(fst(hd(bs1)),NIL);
1613 mapProc(typeBind,hd(imps));
1614 improve(line,NIL,preds);
1617 mapProc(markAssumList,tl(defnBounds));
1618 mapProc(markAssumList,tl(varsBounds));
1619 mapProc(markPred,savePreds);
1623 savePreds = elimOuterPreds(savePreds);
1624 if (nonNull(preds) && resolveDefs(genvarAllAss(hd(defnBounds)))) {
1625 savePreds = elimOuterPreds(savePreds);
1628 map1Proc(genBind,preds,hd(imps));
1629 if (nonNull(preds)) {
1630 map1Proc(addEvidParams,preds,hd(depends));
1631 map1Proc(qualifyBinding,preds,hd(imps));
1634 h98CheckType(line,"inferred type",
1635 fst(hd(hd(defnBounds))),snd(hd(hd(defnBounds))));
1636 hd(varsBounds) = revOnto(hd(defnBounds),hd(varsBounds));
1639 /* ----------------------------------------------------------------------
1640 * STEP 4: Now infer a type for each explicitly typed variable and
1641 * check for compatibility with the declared type.
1642 * --------------------------------------------------------------------*/
1644 for (; nonNull(exps); exps=tl(exps)) {
1645 static String extbind = "explicitly typed binding";
1647 List alts = snd(snd(b));
1648 Int line = rhsLine(snd(hd(alts)));
1654 hd(defnBounds) = NIL;
1655 hd(depends) = NODEPENDS;
1658 instantiate(fst(snd(b)));
1661 t = dropRank2(typeIs,o,m);
1662 ps = makePredAss(predsAre,o);
1664 enterPendingBtyvs();
1665 for (; nonNull(alts); alts=tl(alts))
1666 typeAlt(extbind,fst(b),hd(alts),t,o,m);
1667 improve(line,ps,preds);
1668 leavePendingBtyvs();
1670 if (nonNull(ps)) /* Add dict params, if necessary */
1671 qualifyBinding(ps,b);
1674 mapProc(markAssumList,tl(defnBounds));
1675 mapProc(markAssumList,tl(varsBounds));
1676 mapProc(markPred,savePreds);
1680 savePreds = elimPredsUsing(ps,savePreds);
1681 if (nonNull(preds)) {
1685 vs = cons(mkInt(o+i),vs);
1686 if (resolveDefs(vs)) {
1687 savePreds = elimPredsUsing(ps,savePreds);
1689 if (nonNull(preds)) {
1692 if (nonNull(preds) && resolveDefs(vs))
1693 savePreds = elimPredsUsing(ps,savePreds);
1697 resetGenerics(); /* Make sure we're general enough */
1699 t = generalize(ps,liftRank2(t,o,m));
1701 if (!sameSchemes(t,fst(snd(b))))
1702 tooGeneral(line,fst(b),fst(snd(b)),t);
1703 h98CheckType(line,"inferred type",fst(b),t);
1705 if (nonNull(preds)) /* Check context was strong enough */
1706 cantEstablish(line,extbind,fst(b),t,ps);
1709 preds = savePreds; /* Restore predicates */
1710 hd(defnBounds) = NIL;
1713 #define SCC itbscc /* scc for implicitly typed binds */
1714 #define LOWLINK itblowlink
1715 #define DEPENDS(t) fst(snd(t))
1716 #define SETDEPENDS(c,v) fst(snd(c))=v
1723 static Void local addEvidParams(qs,v) /* overwrite VARID/OPCELL v with */
1724 List qs; /* application of variable to evid. */
1725 Cell v; { /* parameters given by qs */
1730 internal("addEvidParams");
1732 for (nv=mkVar(textOf(v)); nonNull(tl(qs)); qs=tl(qs))
1733 nv = ap(nv,thd3(hd(qs)));
1735 snd(v) = thd3(hd(qs));
1739 /* --------------------------------------------------------------------------
1740 * Type check bodies of class and instance declarations:
1741 * ------------------------------------------------------------------------*/
1743 static Void local typeClassDefn(c) /* Type check implementations of */
1744 Class c; { /* defaults for class c */
1746 /* ----------------------------------------------------------------------
1747 * Generate code for default dictionary builder functions:
1748 * --------------------------------------------------------------------*/
1750 Int beta = newKindedVars(cclass(c).kinds);
1751 Cell d = inventDictVar();
1752 List dparam = singleton(triple(cclass(c).head,mkInt(beta),d));
1753 List mems = cclass(c).members;
1754 List defs = cclass(c).defaults;
1755 List dsels = cclass(c).dsels;
1756 Cell pat = cclass(c).dcon;
1757 Int width = cclass(c).numSupers + cclass(c).numMembers;
1758 char buf[FILENAME_MAX+1];
1762 if (isNull(defs) && nonNull(mems)) {
1763 defs = cclass(c).defaults = cons(NIL,NIL);
1766 for (; nonNull(mems); mems=tl(mems)) {
1767 /* static String deftext = "default_"; */
1768 static String deftext = "$dm";
1769 String s = textToStr(name(hd(mems)).text);
1772 for (; i<FILENAME_MAX && deftext[i]!='\0'; i++) {
1773 buf[i] = deftext[i];
1775 for(; (i+j)<FILENAME_MAX && s[j]!='\0'; j++) {
1779 n = newName(findText(buf),c);
1781 if (isNull(hd(defs))) { /* No default definition */
1782 static String header = "Undefined member: ";
1783 for (i=0; i<FILENAME_MAX && header[i]!='\0'; i++)
1785 for (j=0; (i+j)<FILENAME_MAX && s[j]!='\0'; j++)
1788 name(n).line = cclass(c).line;
1790 name(n).defn = singleton(pair(singleton(d),
1791 ap(mkInt(cclass(c).line),
1794 findText(buf)))))));
1795 } else { /* User supplied default defn */
1796 List alts = snd(hd(defs));
1797 Int line = rhsLine(snd(hd(alts)));
1799 typeMember("default member binding",
1806 name(n).line = line;
1807 name(n).arity = 1+length(fst(hd(alts)));
1808 name(n).defn = alts;
1810 for (; nonNull(alts); alts=tl(alts)) {
1811 fst(hd(alts)) = cons(d,fst(hd(alts)));
1816 genDefns = cons(n,genDefns);
1817 if (isNull(tl(defs)) && nonNull(tl(mems))) {
1818 tl(defs) = cons(NIL,NIL);
1823 /* ----------------------------------------------------------------------
1824 * Generate code for superclass and member function selectors:
1825 * --------------------------------------------------------------------*/
1827 for (i=0; i<width; i++) {
1828 pat = ap(pat,inventVar());
1830 pat = singleton(pat);
1831 for (i=0; nonNull(dsels); dsels=tl(dsels)) {
1832 name(hd(dsels)).defn = singleton(pair(pat,
1833 ap(mkInt(cclass(c).line),
1834 nthArg(i++,hd(pat)))));
1835 genDefns = cons(hd(dsels),genDefns);
1837 for (mems=cclass(c).members; nonNull(mems); mems=tl(mems)) {
1838 name(hd(mems)).defn = singleton(pair(pat,
1839 ap(mkInt(name(hd(mems)).line),
1840 nthArg(i++,hd(pat)))));
1841 genDefns = cons(hd(mems),genDefns);
1845 static Void local typeInstDefn(in) /* Type check implementations of */
1846 Inst in; { /* member functions for instance in*/
1848 /* ----------------------------------------------------------------------
1849 * Generate code for instance specific dictionary builder function:
1851 * inst.maker d1 ... dn = let sc1 = ...
1857 * d = Make.C sc1 ... scm v1 ... vk
1860 * where sci are superclass dictionaries, d is a new name, vj
1861 * is a newly generated name corresponding to the implementation of a
1862 * member function. (Additional line number values must be added at
1863 * appropriate places but, for clarity, these are not shown above.)
1864 * If no implementation of a particular vj is available, then we use
1865 * the default implementation, partially applied to d.
1866 * --------------------------------------------------------------------*/
1868 Int alpha = newKindedVars(cclass(inst(in).c).kinds);
1869 List supers = makePredAss(cclass(inst(in).c).supers,alpha);
1870 Int beta = newKindedVars(inst(in).kinds);
1871 List params = makePredAss(inst(in).specifics,beta);
1872 Cell d = inventDictVar();
1874 List evids = cons(triple(inst(in).head,mkInt(beta),d),
1875 appendOnto(dupList(params),supers));
1877 List evids = dupList(params);
1879 List imps = inst(in).implements;
1880 Cell l = mkInt(inst(in).line);
1881 Cell dictDef = cclass(inst(in).c).dcon;
1882 List mems = cclass(inst(in).c).members;
1883 List defs = cclass(inst(in).c).defaults;
1888 if (!unifyPred(cclass(inst(in).c).head,alpha,inst(in).head,beta))
1889 internal("typeInstDefn");
1891 for (ps=params; nonNull(ps); ps=tl(ps)) /* Build arglist */
1892 args = cons(thd3(hd(ps)),args);
1895 for (ps=supers; nonNull(ps); ps=tl(ps)) { /* Superclass dictionaries */
1898 #if EXPLAIN_INSTANCE_RESOLUTION
1900 fputs("scEntail: ", stdout);
1901 printContext(stdout,copyPreds(params));
1902 fputs(" ||- ", stdout);
1903 printPred(stdout, copyPred(fst3(pi),intOf(snd3(pi))));
1904 fputc('\n', stdout);
1907 ev = scEntail(params,fst3(pi),intOf(snd3(pi)),0);
1909 #if EXPLAIN_INSTANCE_RESOLUTION
1911 fputs("inEntail: ", stdout);
1912 printContext(stdout,copyPreds(evids));
1913 fputs(" ||- ", stdout);
1914 printPred(stdout, copyPred(fst3(pi),intOf(snd3(pi))));
1915 fputc('\n', stdout);
1918 ev = inEntail(evids,fst3(pi),intOf(snd3(pi)),0);
1922 ERRMSG(inst(in).line) "Cannot build superclass instance" ETHEN
1923 ERRTEXT "\n*** Instance : " ETHEN
1924 ERRPRED(copyPred(inst(in).head,beta));
1925 ERRTEXT "\n*** Context supplied : " ETHEN
1926 ERRCONTEXT(copyPreds(params));
1927 ERRTEXT "\n*** Required superclass : " ETHEN
1928 ERRPRED(copyPred(fst3(pi),intOf(snd3(pi))));
1932 locs = cons(pair(thd3(pi),singleton(pair(NIL,ap(l,ev)))),locs);
1933 dictDef = ap(dictDef,thd3(pi));
1936 for (; nonNull(defs); defs=tl(defs)) {
1938 if (nonNull(imps)) {
1943 dictDef = ap(dictDef,ap(hd(defs),d));
1945 Cell v = inventVar();
1946 dictDef = ap(dictDef,v);
1947 typeMember("instance member binding",
1953 locs = cons(pair(v,snd(imp)),locs);
1957 locs = cons(pair(d,singleton(pair(NIL,ap(l,dictDef)))),locs);
1959 name(inst(in).builder).defn /* Register builder imp */
1960 = singleton(pair(args,ap(LETREC,pair(singleton(locs),
1963 /* Invent a GHC-compatible name for the instance decl */
1965 char buf[FILENAME_MAX+1];
1968 Cell qq = inst(in).head;
1970 static String zdftext = "$f";
1973 pp = cons(arg(qq),pp);
1976 // pp is now the fwd list of args(?) to this pred
1979 for (j = 0; i<FILENAME_MAX && zdftext[j]!='\0'; i++, j++) {
1980 buf[i] = zdftext[j];
1982 str = textToStr(cclass(inst(in).c).text);
1983 for (j = 0; i<FILENAME_MAX && str[j]!='\0'; i++, j++) {
1986 for (; nonNull(pp); pp=tl(pp)) {
1988 while (isAp(qq)) qq = fun(qq);
1989 switch (whatIs(qq)) {
1990 case TYCON: str = textToStr(tycon(qq).text); break;
1991 case TUPLE: str = textToStr(ghcTupleText(qq)); break;
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 Args((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);
2733 printType(stdout,r); printf("\n");
2739 /* forall a1 .. am. TC a1 ... am -> Int */
2740 Type conToTagType(t)
2745 for (i=0; i<tycon(t).arity; ++i) {
2746 Offset tv = mkOffset(i);
2748 tvars = cons(tv,tvars);
2750 ty = fn(ty,typeInt);
2751 if (nonNull(tvars)) {
2752 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2757 /* forall a1 .. am. Int -> TC a1 ... am */
2758 Type tagToConType(t)
2763 for (i=0; i<tycon(t).arity; ++i) {
2764 Offset tv = mkOffset(i);
2766 tvars = cons(tv,tvars);
2768 ty = fn(typeInt,ty);
2769 if (nonNull(tvars)) {
2770 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2775 /* --------------------------------------------------------------------------
2776 * Type checker control:
2777 * ------------------------------------------------------------------------*/
2779 Void typeChecker(what)
2782 case RESET : tcMode = EXPRESSION;
2790 case MARK : mark(defnBounds);
2806 mark(predFractional);
2816 setCurrModule(modulePrelude);
2817 dummyVar = inventVar();
2818 typeUnit = mkTuple(0);
2819 arrow = fn(aVar,bVar);
2820 listof = ap(typeList,aVar);
2821 boundPair = ap(ap(mkTuple(2),aVar),aVar);
2822 nameUnit = findQualNameWithoutConsultingExportList
2823 (mkQVar(findText("PrelBase"),
2825 typeVarToVar = fn(aVar,aVar);
2833 Module m = findFakeModule(findText("PrelBase"));
2836 starToStar = simpleKind(1);
2837 typeList = addPrimTycon(findText("[]"),
2841 listof = ap(typeList,aVar);
2842 nameNil = addPrimCfun(findText("[]"),0,1,
2843 mkPolyType(starToStar,
2845 nameCons = addPrimCfun(findText(":"),2,2,
2846 mkPolyType(starToStar,
2850 name(nameNil).parent =
2851 name(nameCons).parent = typeList;
2853 name(nameCons).syntax
2854 = mkSyntax(RIGHT_ASS,5);
2856 tycon(typeList).defn
2857 = cons(nameNil,cons(nameCons,NIL));
2860 dummyVar = inventVar();
2862 setCurrModule(modulePrelude);
2864 starToStar = simpleKind(1);
2866 typeUnit = findTycon(findText("()"));
2867 assert(nonNull(typeUnit));
2869 typeArrow = addPrimTycon(findText("(->)"),
2872 typeList = addPrimTycon(findText("[]"),
2876 arrow = fn(aVar,bVar);
2877 listof = ap(typeList,aVar);
2878 boundPair = ap(ap(mkTuple(2),aVar),aVar);
2880 nameUnit = addPrimCfun(findText("()"),0,0,typeUnit);
2881 tycon(typeUnit).defn
2882 = singleton(nameUnit);
2884 nameNil = addPrimCfun(findText("[]"),0,1,
2885 mkPolyType(starToStar,
2887 nameCons = addPrimCfun(findText(":"),2,2,
2888 mkPolyType(starToStar,
2892 name(nameNil).parent =
2893 name(nameCons).parent = typeList;
2895 name(nameCons).syntax
2896 = mkSyntax(RIGHT_ASS,5);
2898 tycon(typeList).defn
2899 = cons(nameNil,cons(nameCons,NIL));
2901 typeVarToVar = fn(aVar,aVar);
2903 typeNoRow = addPrimTycon(findText("EmptyRow"),
2904 ROW,0,DATATYPE,NIL);
2905 typeRec = addPrimTycon(findText("Rec"),
2908 nameNoRec = addPrimCfun(findText("EmptyRec"),0,0,
2909 ap(typeRec,typeNoRow));
2911 /* bogus definitions to avoid changing the prelude */
2912 addPrimCfun(findText("Rec"), 0,0,typeUnit);
2913 addPrimCfun(findText("EmptyRow"), 0,0,typeUnit);
2914 addPrimCfun(findText("EmptyRec"), 0,0,typeUnit);
2922 /*-------------------------------------------------------------------------*/