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/10 14:53:00 $
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));
728 case ADDPAT : { Int alpha = newTyvars(1);
729 inferType(typeVarToVar,alpha);
730 return ap(e,assumeEvid(predIntegral,alpha));
733 default : internal("typeExpr");
739 /* --------------------------------------------------------------------------
740 * Typing rules for particular special forms:
741 * ------------------------------------------------------------------------*/
743 static Cell local typeAp(l,e) /* Type check application, which */
744 Int l; /* may be headed with a variable */
745 Cell e; { /* requires polymorphism, qualified*/
746 static String app = "application"; /* types, and possible rank2 args. */
757 case NAME : typeIs = name(h).type;
761 case VARIDCELL : if (tcMode==NEW_PATTERN) {
762 inferType(aVar,newVarsBind(e));
765 Cell v = findAssum(textOf(h));
768 typeIs = (tcMode==OLD_PATTERN)
773 h = findName(textOf(h));
776 typeIs = name(h).type;
782 case IPVAR : { Text t = textOf(h);
783 Int alpha = newTyvars(1);
784 Cell ip = pair(ap(IPCELL,t),aVar);
785 Cell ev = assumeEvid(ip,alpha);
786 typeIs = mkInt(alpha);
792 default : h = typeExpr(l,h);
796 if (isNull(typeIs)) {
800 instantiate(typeIs); /* Deal with polymorphism ... */
801 if (nonNull(predsAre)) { /* ... and with qualified types. */
803 for (; nonNull(predsAre); predsAre=tl(predsAre)) {
804 evs = cons(assumeEvid(hd(predsAre),typeOff),evs);
806 if (!isName(h) || !isCfun(h)) {
807 h = applyToArgs(h,rev(evs));
811 if (whatIs(typeIs)==CDICTS) { /* Deal with local dictionaries */
812 List evs = makePredAss(fst(snd(typeIs)),typeOff);
814 typeIs = snd(snd(typeIs));
815 for (; nonNull(ps); ps=tl(ps)) {
816 h = ap(h,thd3(hd(ps)));
818 if (tcMode==EXPRESSION) {
819 preds = revOnto(evs,preds);
821 hd(localEvs) = revOnto(evs,hd(localEvs));
825 if (whatIs(typeIs)==EXIST) { /* Deal with existential arguments */
826 Int n = intOf(fst(snd(typeIs)));
827 typeIs = snd(snd(typeIs));
828 if (!isCfun(getHead(h)) || n>typeFree) {
830 } else if (tcMode!=EXPRESSION) {
831 Int alpha = typeOff + typeFree;
833 bindTv(alpha-n,SKOLEM,0);
834 hd(skolVars) = cons(pair(mkInt(alpha-n),e),hd(skolVars));
839 if (whatIs(typeIs)==RANK2) { /* Deal with rank 2 arguments */
842 Int nr2 = intOf(fst(snd(typeIs)));
843 Type body = snd(snd(typeIs));
847 if (n<nr2) { /* Must have enough arguments */
848 ERRMSG(l) "Use of " ETHEN ERREXPR(h);
850 ERRTEXT " in " ETHEN ERREXPR(e);
852 ERRTEXT " requires at least %d argument%s\n",
853 nr2, (nr2==1 ? "" : "s")
857 for (i=nr2; i<n; ++i) /* Find rank two arguments */
860 for (as=getArgs(as); nonNull(as); as=tl(as), body=arg(body)) {
861 Type expect = dropRank1(arg(fun(body)),alpha,m);
862 if (isPolyOrQualType(expect)) {
863 if (tcMode==EXPRESSION) /* poly/qual type in expr */
864 hd(as) = typeExpected(l,app,hd(as),expect,alpha,m,TRUE);
865 else if (hd(as)!=WILDCARD) { /* Pattern binding/match */
866 if (!isVar(hd(as))) {
867 ERRMSG(l) "Argument " ETHEN ERREXPR(arg(as));
868 ERRTEXT " in pattern " ETHEN ERREXPR(e);
869 ERRTEXT " where a variable is required\n"
872 if (tcMode==NEW_PATTERN) { /* Pattern match */
875 addVarAssump(dummyVar,mkInt(alpha+i));
878 addVarAssump(hd(as),expect);
880 else { /* Pattern binding */
881 Text t = textOf(hd(as));
882 Cell a = findInAssumList(t,hd(defnBounds));
886 if (nonNull(predsAre)) {
887 ERRMSG(l) "Cannot use pattern binding for " ETHEN
889 ERRTEXT " as a component with a qualified type\n"
892 shouldBe(l,hd(as),e,app,aVar,intOf(defType(snd(a))));
896 else { /* Not a poly/qual type */
897 spCheck(l,hd(as),e,app,expect,alpha);
899 h = ap(h,hd(as)); /* Save checked argument */
901 inferType(body,alpha);
905 if (n>0) { /* Deal with remaining args */
906 Int beta = funcType(n); /* check h::t1->t2->...->tn->rn+1 */
907 shouldBe(l,h,e,app,aVar,beta);
908 for (i=n; i>0; --i) { /* check e_i::t_i for each i */
909 spCheck(l,arg(a),e,app,aVar,beta+2*i-1);
913 tyvarType(beta+2*n); /* Inferred type is r_n+1 */
916 if (isNull(p)) /* Replace head with translation */
924 static Cell local typeExpected(l,wh,e,reqd,alpha,n,addEvid)
925 Int l; /* Type check expression e in wh */
926 String wh; /* at line l, expecting type reqd, */
927 Cell e; /* and treating vars alpha through */
928 Type reqd; /* (alpha+n-1) as fixed. */
931 Bool addEvid; { /* TRUE => add \ev -> ... */
932 List savePreds = preds;
943 ps = makePredAss(predsAre,o);
946 check(l,e,NIL,wh,t,o);
950 mapProc(markAssumList,defnBounds);
951 mapProc(markAssumList,varsBounds);
952 mapProc(markPred,savePreds);
955 if (n > 0) { /* mark alpha thru alpha+n-1, plus any */
956 /* type vars that are functionally */
957 List us = NIL, vs = NIL; /* dependent on them */
958 List fds = calcFunDepsPreds(preds);
959 for (i=0; i<n; i++) {
960 Type t1 = zonkTyvar(alpha+i);
961 us = zonkTyvarsIn(t1,us);
964 for (; nonNull(vs); vs=tl(vs))
965 markTyvar(intOf(hd(vs)));
969 savePreds = elimPredsUsing(ps,savePreds);
970 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
971 savePreds = elimPredsUsing(ps,savePreds);
972 if (nonNull(preds)) {
973 Type ty = copyType(t,o);
974 List qs = copyPreds(ps);
975 cantEstablish(l,wh,e,ty,qs);
980 if (copyTyvar(o+i)!=mkOffset(i)) {
981 List qs = copyPreds(ps);
982 Type it = copyType(t,o);
983 tooGeneral(l,e,reqd,generalize(qs,it));
987 e = qualifyExpr(l,ps,e);
991 preds = revOnto(ps,savePreds);
997 static Void local typeAlt(wh,e,a,t,o,m) /* Type check abstraction (Alt) */
998 String wh; /* a = ( [p1, ..., pn], rhs ) */
1005 List ps = fst(a) = patBtyvs(fst(a));
1007 Int l = rhsLine(snd(a));
1014 if (whatIs(t)==RANK2) {
1015 if (n<(nr2=intOf(fst(snd(t))))) {
1016 ERRMSG(l) "Definition requires at least %d parameters on lhs",
1023 while (getHead(t)==typeArrow && argCount==2 && nonNull(ps)) {
1024 Type ta = arg(fun(t));
1025 if (isPolyOrQualType(ta)) {
1026 if (hd(ps)!=WILDCARD) {
1027 if (!isVar(hd(ps))) {
1028 ERRMSG(l) "Argument " ETHEN ERREXPR(hd(ps));
1029 ERRTEXT " used where a variable or wildcard is required\n"
1032 if (m>0 && !added) {
1035 addVarAssump(dummyVar,mkInt(o+i));
1038 addVarAssump(hd(ps),ta);
1042 hd(ps) = typeFreshPat(l,hd(ps));
1043 shouldBe(l,hd(ps),NIL,wh,ta,o);
1052 snd(a) = typeRhs(snd(a));
1054 Int beta = funcType(n);
1057 hd(ps) = typeFreshPat(l,hd(ps));
1058 bindTv(beta+2*i+1,typeIs,typeOff);
1061 snd(a) = typeRhs(snd(a));
1062 bindTv(beta+2*n,typeIs,typeOff);
1066 if (!unify(typeIs,typeOff,t,o)) {
1069 req = liftRank2(origt,o,m);
1070 liftRank2Args(as,o,m);
1071 got = ap(RANK2,pair(mkInt(nr2),revOnto(as,copyType(typeIs,typeOff))));
1072 reportTypeError(l,e,NIL,wh,got,req);
1077 leaveSkolVars(l,origt,o,m);
1080 static Int local funcType(n) /*return skeleton for function type*/
1081 Int n; { /*with n arguments, taking the form*/
1082 Int beta = newTyvars(2*n+1); /* r1 t1 r2 t2 ... rn tn rn+1 */
1083 Int i; /* with r_i := t_i -> r_i+1 */
1085 bindTv(beta+2*i,arrow,beta+2*i+1);
1089 static Void local typeCase(l,beta,c) /* type check case: pat -> rhs */
1090 Int l; /* (case given by c == (pat,rhs)) */
1091 Int beta; /* need: pat :: (var,beta) */
1092 Cell c; { /* rhs :: (var,beta+1) */
1093 static String casePat = "case pattern";
1094 static String caseExpr = "case expression";
1098 fst(c) = typeFreshPat(l,patBtyvs(fst(c)));
1099 shouldBe(l,fst(c),NIL,casePat,aVar,beta);
1100 snd(c) = typeRhs(snd(c));
1101 shouldBe(l,rhsExpr(snd(c)),NIL,caseExpr,aVar,beta+1);
1105 leaveSkolVars(l,typeIs,typeOff,0);
1108 static Void local typeComp(l,m,e,qs) /* type check comprehension */
1110 Type m; /* monad (mkOffset(0)) */
1113 static String boolQual = "boolean qualifier";
1114 static String genQual = "generator";
1120 if (isNull(qs)) { /* no qualifiers left */
1121 spTypeExpr(l,fst(e));
1125 switch (whatIs(q)) {
1126 case BOOLQUAL : spCheck(l,snd(q),NIL,boolQual,typeBool,0);
1127 typeComp(l,m,e,qs1);
1130 case QWHERE : enterBindings();
1132 mapProc(typeBindings,snd(q));
1133 typeComp(l,m,e,qs1);
1135 leaveSkolVars(l,typeIs,typeOff,0);
1138 case FROMQUAL : { Int beta = newTyvars(1);
1140 spCheck(l,snd(snd(q)),NIL,genQual,m,beta);
1143 = typeFreshPat(l,patBtyvs(fst(snd(q))));
1144 shouldBe(l,fst(snd(q)),NIL,genQual,aVar,beta);
1145 typeComp(l,m,e,qs1);
1148 leaveSkolVars(l,typeIs,typeOff,0);
1152 case DOQUAL : spCheck(l,snd(q),NIL,genQual,m,newTyvars(1));
1153 typeComp(l,m,e,qs1);
1159 static Cell local typeMonadComp(l,e) /* type check monad comprehension */
1162 Int alpha = newTyvars(1);
1163 Int beta = newTyvars(1);
1164 Cell mon = ap(mkInt(beta),aVar);
1165 Cell m = assumeEvid(predMonad,beta);
1166 tyvar(beta)->kind = starToStar;
1168 bindTv(beta,typeList,0);
1172 typeComp(l,mon,snd(e),snd(snd(e)));
1173 bindTv(alpha,typeIs,typeOff);
1174 inferType(mon,alpha);
1175 return ap(MONADCOMP,pair(m,snd(e)));
1178 static Void local typeDo(l,e) /* type check do-notation */
1181 static String finGen = "final generator";
1182 Int alpha = newTyvars(1);
1183 Int beta = newTyvars(1);
1184 Cell mon = ap(mkInt(beta),aVar);
1185 Cell m = assumeEvid(predMonad,beta);
1186 tyvar(beta)->kind = starToStar;
1188 typeComp(l,mon,snd(e),snd(snd(e)));
1189 shouldBe(l,fst(snd(e)),NIL,finGen,mon,alpha);
1190 snd(e) = pair(m,snd(e));
1193 static Void local typeConFlds(l,e) /* Type check a construction */
1196 static String conExpr = "value construction";
1197 Name c = fst(snd(e));
1198 List fs = snd(snd(e));
1207 instantiate(name(c).type);
1208 for (; nonNull(predsAre); predsAre=tl(predsAre))
1209 assumeEvid(hd(predsAre),typeOff);
1210 if (whatIs(typeIs)==RANK2)
1211 typeIs = snd(snd(typeIs));
1216 for (; nonNull(fs); fs=tl(fs)) {
1218 for (i=sfunPos(fst(hd(fs)),c); --i>0; t=arg(t))
1220 t = dropRank1(arg(fun(t)),to,tf);
1221 if (isPolyOrQualType(t))
1222 snd(hd(fs)) = typeExpected(l,conExpr,snd(hd(fs)),t,to,tf,TRUE);
1224 spCheck(l,snd(hd(fs)),e,conExpr,t,to);
1227 for (i=name(c).arity; i>0; i--)
1232 static Void local typeUpdFlds(line,e) /* Type check an update */
1233 Int line; /* (Written in what might seem a */
1234 Cell e; { /* bizarre manner for the benefit */
1235 static String update = "update"; /* of as yet unreleased extensions)*/
1236 List cs = snd3(snd(e)); /* List of constructors */
1237 List fs = thd3(snd(e)); /* List of field specifications */
1238 List ts = NIL; /* List of types for fields */
1240 Int alpha = newTyvars(2+n);
1247 /* Calculate type and translation for each expr in the field list */
1248 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1249 spTypeExpr(line,snd(hd(fs1)));
1250 bindTv(i,typeIs,typeOff);
1254 mapProc(markAssumList,defnBounds);
1255 mapProc(markAssumList,varsBounds);
1256 mapProc(markPred,preds);
1259 for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1261 ts = cons(generalize(NIL,copyTyvar(i)),ts);
1265 /* Type check expression to be updated */
1266 spTypeExpr(line,fst3(snd(e)));
1267 bindTv(alpha,typeIs,typeOff);
1269 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constrs */
1271 List ta = replicate(name(c).arity,NIL);
1275 tcMode = NEW_PATTERN; /* Domain type */
1276 instantiate(name(c).type);
1277 tcMode = EXPRESSION;
1280 for (; nonNull(predsAre); predsAre=tl(predsAre))
1281 assumeEvid(hd(predsAre),typeOff);
1283 if (whatIs(typeIs)==RANK2) {
1284 ERRMSG(line) "Sorry, record update syntax cannot currently be "
1285 "used for datatypes with polymorphic components"
1289 instantiate(name(c).type); /* Range type */
1292 for (; nonNull(predsAre); predsAre=tl(predsAre))
1293 assumeEvid(hd(predsAre),typeOff);
1295 for (fs1=fs, i=1; nonNull(fs1); fs1=tl(fs1), i++) {
1296 Int n = sfunPos(fst(hd(fs1)),c);
1303 for (; nonNull(ta); ta=tl(ta)) { /* For each cfun arg */
1304 if (nonNull(hd(ta))) { /* Field to updated? */
1305 Int n = intOf(hd(ta));
1308 for (; n-- > 1; f=tl(f), t=tl(t))
1313 shouldBe(line,snd(f),e,update,arg(fun(tr)),or);
1314 } /* Unmentioned component */
1315 else if (!unify(arg(fun(td)),od,arg(fun(tr)),or))
1316 internal("typeUpdFlds");
1322 inferType(td,od); /* Check domain type */
1323 shouldBe(line,fst3(snd(e)),e,update,aVar,alpha);
1324 inferType(tr,or); /* Check range type */
1325 shouldBe(line,e,NIL,update,aVar,alpha+1);
1327 /* (typeIs,typeOff) still carry the result type when we exit the loop */
1331 static Cell local typeWith(line,e) /* Type check a with */
1334 List fs = snd(snd(e)); /* List of field specifications */
1336 Int alpha = newTyvars(2+n);
1341 List dpreds = NIL, dp;
1344 /* Type check expression to be updated */
1345 fst(snd(e)) = typeExpr(line,fst(snd(e)));
1346 bindTv(alpha,typeIs,typeOff);
1349 /* elim duplicate uses of imp params */
1350 preds = scSimplify(preds);
1351 /* extract preds that we're going to bind */
1352 for (fs1=fs; nonNull(fs1); fs1=tl(fs1)) {
1353 Text t = textOf(fst(hd(fs1)));
1354 Cell p = findIPEvid(t);
1355 dpreds = cons(p, dpreds);
1359 /* maybe give a warning message here... */
1362 dpreds = rev(dpreds);
1364 /* Calculate type and translation for each expr in the field list */
1365 for (fs1=fs, dp=dpreds, i=alpha+2; nonNull(fs1); fs1=tl(fs1), dp=tl(dp), i++) {
1366 static String with = "with";
1368 snd(hd(fs1)) = typeExpr(line,snd(hd(fs1)));
1369 bindTv(i,typeIs,typeOff);
1371 shouldBe(line,fst(hd(fs1)),e,with,snd(fst3(ev)),intOf(snd3(ev)));
1372 bs = cons(cons(pair(thd3(ev), cons(triple(NIL, mkInt(line), snd(hd(fs1))), NIL)), NIL), bs);
1377 return (ap(LETREC,pair(bs,fst(snd(e)))));
1381 static Cell local typeFreshPat(l,p) /* find type of pattern, assigning */
1382 Int l; /* fresh type variables to each var */
1383 Cell p; { /* bound in the pattern */
1384 tcMode = NEW_PATTERN;
1386 tcMode = EXPRESSION;
1390 /* --------------------------------------------------------------------------
1391 * Type check group of bindings:
1392 * ------------------------------------------------------------------------*/
1394 static Void local typeBindings(bs) /* type check a binding group */
1396 Bool usesPatBindings = FALSE; /* TRUE => pattern binding in bs */
1397 Bool usesUntypedVar = FALSE; /* TRUE => var bind w/o type decl */
1400 /* The following loop is used to determine whether the monomorphism */
1401 /* restriction should be applied. It could be written marginally more */
1402 /* efficiently by using breaks, but clarity is more important here ... */
1404 for (bs1=bs; nonNull(bs1); bs1=tl(bs1)) { /* Analyse binding group */
1407 usesPatBindings = TRUE;
1408 else if (isNull(fst(hd(snd(snd(b))))) /* no arguments */
1409 && whatIs(fst(snd(b)))==IMPDEPS) /* implicitly typed*/
1410 usesUntypedVar = TRUE;
1413 if (usesPatBindings || usesUntypedVar)
1418 mapProc(removeTypeSigs,bs); /* Remove binding type info */
1419 hd(varsBounds) = revOnto(hd(defnBounds), /* transfer completed assmps*/
1420 hd(varsBounds)); /* out of defnBounds */
1421 hd(defnBounds) = NIL;
1425 static Void local removeTypeSigs(b) /* Remove type info from a binding */
1427 snd(b) = snd(snd(b));
1430 /* --------------------------------------------------------------------------
1431 * Type check a restricted binding group:
1432 * ------------------------------------------------------------------------*/
1434 static Void local monorestrict(bs) /* Type restricted binding group */
1436 List savePreds = preds;
1437 Int line = isVar(fst(hd(bs))) ? rhsLine(snd(hd(snd(snd(hd(bs))))))
1438 : rhsLine(snd(snd(snd(hd(bs)))));
1439 hd(defnBounds) = NIL;
1440 hd(depends) = NODEPENDS; /* No need for dependents here */
1442 preds = NIL; /* Type check the bindings */
1443 mapProc(restrictedBindAss,bs);
1444 mapProc(typeBind,bs);
1445 improve(line,NIL,preds);
1448 preds = revOnto(preds,savePreds);
1450 clearMarks(); /* Mark fixed variables */
1451 mapProc(markAssumList,tl(defnBounds));
1452 mapProc(markAssumList,tl(varsBounds));
1453 mapProc(markPred,preds);
1456 if (isNull(tl(defnBounds))) { /* Top-level may need defaulting */
1458 if (nonNull(preds) && resolveDefs(genvarAnyAss(hd(defnBounds))))
1463 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
1466 if (nonNull(preds)) { /* Look for unresolved overloading */
1467 Cell v = isVar(fst(hd(bs))) ? fst(hd(bs)) : hd(fst(hd(bs)));
1468 Cell ass = findInAssumList(textOf(v),hd(varsBounds));
1469 preds = scSimplify(preds);
1471 ERRMSG(line) "Unresolved top-level overloading" ETHEN
1472 ERRTEXT "\n*** Binding : %s", textToStr(textOf(v))
1475 ERRTEXT "\n*** Inferred type : " ETHEN ERRTYPE(snd(ass));
1477 ERRTEXT "\n*** Outstanding context : " ETHEN
1478 ERRCONTEXT(copyPreds(preds));
1484 map1Proc(genBind,NIL,bs); /* Generalize types of def'd vars */
1487 static Void local restrictedBindAss(b) /* Make assums for vars in binding */
1488 Cell b; { /* gp with restricted overloading */
1490 if (isVar(fst(b))) { /* function-binding? */
1491 Cell t = fst(snd(b));
1492 if (whatIs(t)==IMPDEPS) { /* Discard implicitly typed deps */
1493 fst(snd(b)) = t = NIL; /* in a restricted binding group. */
1495 fst(snd(b)) = localizeBtyvs(t);
1496 restrictedAss(rhsLine(snd(hd(snd(snd(b))))), fst(b), t);
1497 } else { /* pattern-binding? */
1499 List ts = fst(snd(b));
1500 Int line = rhsLine(snd(snd(snd(b))));
1502 for (; nonNull(vs); vs=tl(vs)) {
1504 restrictedAss(line,hd(vs),hd(ts)=localizeBtyvs(hd(ts)));
1507 restrictedAss(line,hd(vs),NIL);
1513 static Void local restrictedAss(l,v,t) /* Assume that type of binding var v*/
1514 Int l; /* is t (if nonNull) in restricted */
1515 Cell v; /* binding group */
1518 if (nonNull(predsAre)) {
1519 ERRMSG(l) "Explicit overloaded type for \"%s\"",textToStr(textOf(v))
1521 ERRTEXT " not permitted in restricted binding"
1526 /* --------------------------------------------------------------------------
1527 * Unrestricted binding group:
1528 * ------------------------------------------------------------------------*/
1530 static Void local unrestricted(bs) /* Type unrestricted binding group */
1532 List savePreds = preds;
1533 List imps = NIL; /* Implicitly typed bindings */
1534 List exps = NIL; /* Explicitly typed bindings */
1537 /* ----------------------------------------------------------------------
1538 * STEP 1: Separate implicitly typed bindings from explicitly typed
1539 * bindings and do a dependency analyis, where f depends on g iff f
1540 * is implicitly typed and involves a call to g.
1541 * --------------------------------------------------------------------*/
1543 for (; nonNull(bs); bs=tl(bs)) {
1545 if (whatIs(fst(snd(b)))==IMPDEPS)
1546 imps = cons(b,imps); /* N.B. New lists are built to */
1547 else /* avoid breaking the original */
1548 exps = cons(b,exps); /* list structure for bs. */
1551 for (bs=imps; nonNull(bs); bs=tl(bs)) {
1552 Cell b = hd(bs); /* Restrict implicitly typed dep */
1553 List ds = snd(fst(snd(b))); /* lists to bindings in imps */
1555 while (nonNull(ds)) {
1557 if (cellIsMember(hd(ds),imps)) {
1565 imps = itbscc(imps); /* Dependency analysis on imps */
1566 for (bs=imps; nonNull(bs); bs=tl(bs))
1567 for (bs1=hd(bs); nonNull(bs1); bs1=tl(bs1))
1568 fst(snd(hd(bs1))) = NIL; /* reset imps type fields */
1570 #ifdef DEBUG_DEPENDS
1571 Printf("Binding group:");
1572 for (bs1=imps; nonNull(bs1); bs1=tl(bs1)) {
1574 for (bs=hd(bs1); nonNull(bs); bs=tl(bs))
1575 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1578 if (nonNull(exps)) {
1580 for (bs=exps; nonNull(bs); bs=tl(bs))
1581 Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1587 /* ----------------------------------------------------------------------
1588 * STEP 2: Add type assumptions about any explicitly typed variable.
1589 * --------------------------------------------------------------------*/
1591 for (bs=exps; nonNull(bs); bs=tl(bs)) {
1592 fst(snd(hd(bs))) = localizeBtyvs(fst(snd(hd(bs))));
1593 hd(varsBounds) = cons(pair(fst(hd(bs)),fst(snd(hd(bs)))),
1597 /* ----------------------------------------------------------------------
1598 * STEP 3: Calculate types for each group of implicitly typed bindings.
1599 * --------------------------------------------------------------------*/
1601 for (; nonNull(imps); imps=tl(imps)) {
1602 Cell b = hd(hd(imps));
1603 Int line = isVar(fst(b)) ? rhsLine(snd(hd(snd(snd(b)))))
1604 : rhsLine(snd(snd(snd(b))));
1605 hd(defnBounds) = NIL;
1607 for (bs1=hd(imps); nonNull(bs1); bs1=tl(bs1))
1608 newDefnBind(fst(hd(bs1)),NIL);
1611 mapProc(typeBind,hd(imps));
1612 improve(line,NIL,preds);
1615 mapProc(markAssumList,tl(defnBounds));
1616 mapProc(markAssumList,tl(varsBounds));
1617 mapProc(markPred,savePreds);
1621 savePreds = elimOuterPreds(savePreds);
1622 if (nonNull(preds) && resolveDefs(genvarAllAss(hd(defnBounds)))) {
1623 savePreds = elimOuterPreds(savePreds);
1626 map1Proc(genBind,preds,hd(imps));
1627 if (nonNull(preds)) {
1628 map1Proc(addEvidParams,preds,hd(depends));
1629 map1Proc(qualifyBinding,preds,hd(imps));
1632 h98CheckType(line,"inferred type",
1633 fst(hd(hd(defnBounds))),snd(hd(hd(defnBounds))));
1634 hd(varsBounds) = revOnto(hd(defnBounds),hd(varsBounds));
1637 /* ----------------------------------------------------------------------
1638 * STEP 4: Now infer a type for each explicitly typed variable and
1639 * check for compatibility with the declared type.
1640 * --------------------------------------------------------------------*/
1642 for (; nonNull(exps); exps=tl(exps)) {
1643 static String extbind = "explicitly typed binding";
1645 List alts = snd(snd(b));
1646 Int line = rhsLine(snd(hd(alts)));
1652 hd(defnBounds) = NIL;
1653 hd(depends) = NODEPENDS;
1656 instantiate(fst(snd(b)));
1659 t = dropRank2(typeIs,o,m);
1660 ps = makePredAss(predsAre,o);
1662 enterPendingBtyvs();
1663 for (; nonNull(alts); alts=tl(alts))
1664 typeAlt(extbind,fst(b),hd(alts),t,o,m);
1665 improve(line,ps,preds);
1666 leavePendingBtyvs();
1668 if (nonNull(ps)) /* Add dict params, if necessary */
1669 qualifyBinding(ps,b);
1672 mapProc(markAssumList,tl(defnBounds));
1673 mapProc(markAssumList,tl(varsBounds));
1674 mapProc(markPred,savePreds);
1678 savePreds = elimPredsUsing(ps,savePreds);
1679 if (nonNull(preds)) {
1683 vs = cons(mkInt(o+i),vs);
1684 if (resolveDefs(vs)) {
1685 savePreds = elimPredsUsing(ps,savePreds);
1687 if (nonNull(preds)) {
1690 if (nonNull(preds) && resolveDefs(vs))
1691 savePreds = elimPredsUsing(ps,savePreds);
1695 resetGenerics(); /* Make sure we're general enough */
1697 t = generalize(ps,liftRank2(t,o,m));
1699 if (!sameSchemes(t,fst(snd(b))))
1700 tooGeneral(line,fst(b),fst(snd(b)),t);
1701 h98CheckType(line,"inferred type",fst(b),t);
1703 if (nonNull(preds)) /* Check context was strong enough */
1704 cantEstablish(line,extbind,fst(b),t,ps);
1707 preds = savePreds; /* Restore predicates */
1708 hd(defnBounds) = NIL;
1711 #define SCC itbscc /* scc for implicitly typed binds */
1712 #define LOWLINK itblowlink
1713 #define DEPENDS(t) fst(snd(t))
1714 #define SETDEPENDS(c,v) fst(snd(c))=v
1721 static Void local addEvidParams(qs,v) /* overwrite VARID/OPCELL v with */
1722 List qs; /* application of variable to evid. */
1723 Cell v; { /* parameters given by qs */
1728 internal("addEvidParams");
1730 for (nv=mkVar(textOf(v)); nonNull(tl(qs)); qs=tl(qs))
1731 nv = ap(nv,thd3(hd(qs)));
1733 snd(v) = thd3(hd(qs));
1737 /* --------------------------------------------------------------------------
1738 * Type check bodies of class and instance declarations:
1739 * ------------------------------------------------------------------------*/
1741 static Void local typeClassDefn(c) /* Type check implementations of */
1742 Class c; { /* defaults for class c */
1744 /* ----------------------------------------------------------------------
1745 * Generate code for default dictionary builder functions:
1746 * --------------------------------------------------------------------*/
1748 Int beta = newKindedVars(cclass(c).kinds);
1749 Cell d = inventDictVar();
1750 List dparam = singleton(triple(cclass(c).head,mkInt(beta),d));
1751 List mems = cclass(c).members;
1752 List defs = cclass(c).defaults;
1753 List dsels = cclass(c).dsels;
1754 Cell pat = cclass(c).dcon;
1755 Int width = cclass(c).numSupers + cclass(c).numMembers;
1756 char buf[FILENAME_MAX+1];
1760 if (isNull(defs) && nonNull(mems)) {
1761 defs = cclass(c).defaults = cons(NIL,NIL);
1764 for (; nonNull(mems); mems=tl(mems)) {
1765 /* static String deftext = "default_"; */
1766 static String deftext = "$dm";
1767 String s = textToStr(name(hd(mems)).text);
1770 for (; i<FILENAME_MAX && deftext[i]!='\0'; i++) {
1771 buf[i] = deftext[i];
1773 for(; (i+j)<FILENAME_MAX && s[j]!='\0'; j++) {
1777 n = newName(findText(buf),c);
1779 if (isNull(hd(defs))) { /* No default definition */
1780 static String header = "Undefined member: ";
1781 for (i=0; i<FILENAME_MAX && header[i]!='\0'; i++)
1783 for (j=0; (i+j)<FILENAME_MAX && s[j]!='\0'; j++)
1786 name(n).line = cclass(c).line;
1788 name(n).defn = singleton(pair(singleton(d),
1789 ap(mkInt(cclass(c).line),
1792 findText(buf)))))));
1793 } else { /* User supplied default defn */
1794 List alts = snd(hd(defs));
1795 Int line = rhsLine(snd(hd(alts)));
1797 typeMember("default member binding",
1804 name(n).line = line;
1805 name(n).arity = 1+length(fst(hd(alts)));
1806 name(n).defn = alts;
1808 for (; nonNull(alts); alts=tl(alts)) {
1809 fst(hd(alts)) = cons(d,fst(hd(alts)));
1814 genDefns = cons(n,genDefns);
1815 if (isNull(tl(defs)) && nonNull(tl(mems))) {
1816 tl(defs) = cons(NIL,NIL);
1821 /* ----------------------------------------------------------------------
1822 * Generate code for superclass and member function selectors:
1823 * --------------------------------------------------------------------*/
1825 for (i=0; i<width; i++) {
1826 pat = ap(pat,inventVar());
1828 pat = singleton(pat);
1829 for (i=0; nonNull(dsels); dsels=tl(dsels)) {
1830 name(hd(dsels)).defn = singleton(pair(pat,
1831 ap(mkInt(cclass(c).line),
1832 nthArg(i++,hd(pat)))));
1833 genDefns = cons(hd(dsels),genDefns);
1835 for (mems=cclass(c).members; nonNull(mems); mems=tl(mems)) {
1836 name(hd(mems)).defn = singleton(pair(pat,
1837 ap(mkInt(name(hd(mems)).line),
1838 nthArg(i++,hd(pat)))));
1839 genDefns = cons(hd(mems),genDefns);
1843 static Void local typeInstDefn(in) /* Type check implementations of */
1844 Inst in; { /* member functions for instance in*/
1846 /* ----------------------------------------------------------------------
1847 * Generate code for instance specific dictionary builder function:
1849 * inst.maker d1 ... dn = let sc1 = ...
1855 * d = Make.C sc1 ... scm v1 ... vk
1858 * where sci are superclass dictionaries, d is a new name, vj
1859 * is a newly generated name corresponding to the implementation of a
1860 * member function. (Additional line number values must be added at
1861 * appropriate places but, for clarity, these are not shown above.)
1862 * If no implementation of a particular vj is available, then we use
1863 * the default implementation, partially applied to d.
1864 * --------------------------------------------------------------------*/
1866 Int alpha = newKindedVars(cclass(inst(in).c).kinds);
1867 List supers = makePredAss(cclass(inst(in).c).supers,alpha);
1868 Int beta = newKindedVars(inst(in).kinds);
1869 List params = makePredAss(inst(in).specifics,beta);
1870 Cell d = inventDictVar();
1872 List evids = cons(triple(inst(in).head,mkInt(beta),d),
1873 appendOnto(dupList(params),supers));
1875 List evids = dupList(params);
1877 List imps = inst(in).implements;
1878 Cell l = mkInt(inst(in).line);
1879 Cell dictDef = cclass(inst(in).c).dcon;
1880 List mems = cclass(inst(in).c).members;
1881 List defs = cclass(inst(in).c).defaults;
1886 if (!unifyPred(cclass(inst(in).c).head,alpha,inst(in).head,beta))
1887 internal("typeInstDefn");
1889 for (ps=params; nonNull(ps); ps=tl(ps)) /* Build arglist */
1890 args = cons(thd3(hd(ps)),args);
1893 for (ps=supers; nonNull(ps); ps=tl(ps)) { /* Superclass dictionaries */
1896 #if EXPLAIN_INSTANCE_RESOLUTION
1898 fputs("scEntail: ", stdout);
1899 printContext(stdout,copyPreds(params));
1900 fputs(" ||- ", stdout);
1901 printPred(stdout, copyPred(fst3(pi),intOf(snd3(pi))));
1902 fputc('\n', stdout);
1905 ev = scEntail(params,fst3(pi),intOf(snd3(pi)),0);
1907 #if EXPLAIN_INSTANCE_RESOLUTION
1909 fputs("inEntail: ", stdout);
1910 printContext(stdout,copyPreds(evids));
1911 fputs(" ||- ", stdout);
1912 printPred(stdout, copyPred(fst3(pi),intOf(snd3(pi))));
1913 fputc('\n', stdout);
1916 ev = inEntail(evids,fst3(pi),intOf(snd3(pi)),0);
1920 ERRMSG(inst(in).line) "Cannot build superclass instance" ETHEN
1921 ERRTEXT "\n*** Instance : " ETHEN
1922 ERRPRED(copyPred(inst(in).head,beta));
1923 ERRTEXT "\n*** Context supplied : " ETHEN
1924 ERRCONTEXT(copyPreds(params));
1925 ERRTEXT "\n*** Required superclass : " ETHEN
1926 ERRPRED(copyPred(fst3(pi),intOf(snd3(pi))));
1930 locs = cons(pair(thd3(pi),singleton(pair(NIL,ap(l,ev)))),locs);
1931 dictDef = ap(dictDef,thd3(pi));
1934 for (; nonNull(defs); defs=tl(defs)) {
1936 if (nonNull(imps)) {
1941 dictDef = ap(dictDef,ap(hd(defs),d));
1943 Cell v = inventVar();
1944 dictDef = ap(dictDef,v);
1945 typeMember("instance member binding",
1951 locs = cons(pair(v,snd(imp)),locs);
1955 locs = cons(pair(d,singleton(pair(NIL,ap(l,dictDef)))),locs);
1957 name(inst(in).builder).defn /* Register builder imp */
1958 = singleton(pair(args,ap(LETREC,pair(singleton(locs),
1961 /* Invent a GHC-compatible name for the instance decl */
1963 char buf[FILENAME_MAX+1];
1967 Cell qq = inst(in).head;
1969 static String zdftext = "$f";
1972 pp = cons(arg(qq),pp);
1975 // pp is now the fwd list of args(?) to this pred
1978 for (j = 0; i<FILENAME_MAX && zdftext[j]!='\0'; i++, j++) {
1979 buf[i] = zdftext[j];
1981 str = textToStr(cclass(inst(in).c).text);
1982 for (j = 0; i<FILENAME_MAX && str[j]!='\0'; i++, j++) {
1987 while (isAp(qq)) qq = fun(qq);
1988 switch (whatIs(qq)) {
1989 case TYCON: str = textToStr(tycon(qq).text); break;
1990 case TUPLE: str = textToStr(ghcTupleText(qq)); break;
1991 case OFFSET: sprintf(buf2,"%d",offsetOf(qq));
1994 default: internal("typeInstDefn: making GHC name"); break;
1996 for (j = 0; i<FILENAME_MAX && str[j]!='\0'; i++, j++) {
2002 name(inst(in).builder).text = findText(buf);
2003 //fprintf ( stderr, "result = %s\n", buf );
2006 genDefns = cons(inst(in).builder,genDefns);
2009 static Void local typeMember(wh,mem,alts,evids,head,beta)
2010 String wh; /* Type check alternatives alts of */
2011 Name mem; /* member mem for inst type head */
2012 Cell alts; /* at offset beta using predicate */
2013 List evids; /* assignment evids */
2016 Int line = rhsLine(snd(hd(alts)));
2025 Printf("\nType check member: ");
2026 printExp(stdout,mem);
2028 printType(stdout,name(mem).type);
2029 Printf("\n for the instance: ");
2030 printPred(stdout,head);
2034 instantiate(name(mem).type); /* Find required type */
2037 t = dropRank2(typeIs,o,m);
2038 ps = makePredAss(predsAre,o);
2039 if (!unifyPred(hd(predsAre),typeOff,head,beta))
2040 internal("typeMember1");
2043 rt = generalize(qs,liftRank2(t,o,m));
2046 Printf("Required type is: ");
2047 printType(stdout,rt);
2051 hd(defnBounds) = NIL; /* Type check each alternative */
2052 hd(depends) = NODEPENDS;
2053 enterPendingBtyvs();
2054 for (preds=NIL; nonNull(alts); alts=tl(alts)) {
2055 typeAlt(wh,mem,hd(alts),t,o,m);
2056 qualify(tl(ps),hd(alts)); /* Add any extra dict params */
2058 improve(line,evids,preds);
2059 leavePendingBtyvs();
2061 evids = appendOnto(dupList(tl(ps)), /* Build full complement of dicts */
2065 qs = elimPredsUsing(evids,NIL);
2066 if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
2067 qs = elimPredsUsing(evids,qs);
2070 "Implementation of %s requires extra context",
2071 textToStr(name(mem).text) ETHEN
2072 ERRTEXT "\n*** Expected type : " ETHEN ERRTYPE(rt);
2073 ERRTEXT "\n*** Missing context : " ETHEN ERRCONTEXT(copyPreds(qs));
2078 resetGenerics(); /* Make sure we're general enough */
2080 t = generalize(ps,liftRank2(t,o,m));
2082 Printf(" Inferred type is: ");
2083 printType(stdout,t);
2086 if (!sameSchemes(t,rt))
2087 tooGeneral(line,mem,rt,t);
2088 if (nonNull(preds)) {
2089 preds = scSimplify(preds);
2090 cantEstablish(line,wh,mem,t,ps);
2094 /* --------------------------------------------------------------------------
2095 * Type check bodies of bindings:
2096 * ------------------------------------------------------------------------*/
2098 static Void local typeBind(b) /* Type check binding */
2100 if (isVar(fst(b))) { /* function binding */
2101 Cell ass = findTopBinding(fst(b));
2105 internal("typeBind");
2107 beta = intOf(defType(snd(ass)));
2108 enterPendingBtyvs();
2109 map2Proc(typeDefAlt,beta,fst(b),snd(snd(b)));
2110 leavePendingBtyvs();
2112 else { /* pattern binding */
2113 static String lhsPat = "lhs pattern";
2114 static String rhs = "right hand side";
2115 Int beta = newTyvars(1);
2116 Pair pb = snd(snd(b));
2117 Int l = rhsLine(snd(pb));
2119 tcMode = OLD_PATTERN;
2120 enterPendingBtyvs();
2121 fst(pb) = patBtyvs(fst(pb));
2122 check(l,fst(pb),NIL,lhsPat,aVar,beta);
2123 tcMode = EXPRESSION;
2124 snd(pb) = typeRhs(snd(pb));
2125 shouldBe(l,rhsExpr(snd(pb)),NIL,rhs,aVar,beta);
2127 leavePendingBtyvs();
2131 static Void local typeDefAlt(beta,v,a) /* type check alt in func. binding */
2135 static String valDef = "function binding";
2136 typeAlt(valDef,v,a,aVar,beta,0);
2139 static Cell local typeRhs(e) /* check type of rhs of definition */
2141 switch (whatIs(e)) {
2142 case GUARDED : { Int beta = newTyvars(1);
2143 map1Proc(guardedType,beta,snd(e));
2148 case LETREC : enterBindings();
2150 mapProc(typeBindings,fst(snd(e)));
2151 snd(snd(e)) = typeRhs(snd(snd(e)));
2153 leaveSkolVars(rhsLine(snd(snd(e))),typeIs,typeOff,0);
2156 case RSIGN : fst(snd(e)) = typeRhs(fst(snd(e)));
2157 shouldBe(rhsLine(fst(snd(e))),
2158 rhsExpr(fst(snd(e))),NIL,
2163 default : snd(e) = typeExpr(intOf(fst(e)),snd(e));
2169 static Void local guardedType(beta,gded)/* check type of guard (li,(gd,ex))*/
2170 Int beta; /* should have gd :: Bool, */
2171 Cell gded; { /* ex :: (var,beta) */
2172 static String guarded = "guarded expression";
2173 static String guard = "guard";
2174 Int line = intOf(fst(gded));
2180 spCheck(line,fst(gded),NIL,guard,typeBool,0);
2181 spCheck(line,snd(gded),NIL,guarded,aVar,beta);
2184 Cell rhsExpr(rhs) /* find first expression on a rhs */
2187 switch (whatIs(rhs)) {
2188 case GUARDED : return snd(snd(hd(snd(rhs))));
2189 case LETREC : return rhsExpr(snd(snd(rhs)));
2190 case RSIGN : return rhsExpr(fst(snd(rhs)));
2191 default : return snd(rhs);
2195 Int rhsLine(rhs) /* find line number associated with */
2196 Cell rhs; { /* a right hand side */
2198 switch (whatIs(rhs)) {
2199 case GUARDED : return intOf(fst(hd(snd(rhs))));
2200 case LETREC : return rhsLine(snd(snd(rhs)));
2201 case RSIGN : return rhsLine(fst(snd(rhs)));
2202 default : return intOf(fst(rhs));
2206 /* --------------------------------------------------------------------------
2207 * Calculate generalization of types and compare with declared type schemes:
2208 * ------------------------------------------------------------------------*/
2210 static Void local genBind(ps,b) /* Generalize the type of each var */
2211 List ps; /* defined in binding b, qualifying*/
2212 Cell b; { /* each with the predicates in ps. */
2214 Cell t = fst(snd(b));
2217 genAss(rhsLine(snd(hd(snd(snd(b))))),ps,v,t);
2219 Int line = rhsLine(snd(snd(snd(b))));
2220 for (; nonNull(v); v=tl(v)) {
2226 genAss(line,ps,hd(v),ty);
2231 static Void local genAss(l,ps,v,dt) /* Calculate inferred type of v and*/
2232 Int l; /* compare with declared type, dt, */
2233 List ps; /* if given & check for ambiguity. */
2236 Cell ass = findTopBinding(v);
2241 snd(ass) = genTest(l,v,ps,dt,aVar,intOf(defType(snd(ass))));
2246 printType(stdout,snd(ass));
2251 static Type local genTest(l,v,ps,dt,t,o)/* Generalize and test inferred */
2252 Int l; /* type (t,o) with context ps */
2253 Cell v; /* against declared type dt for v. */
2258 Type bt = NIL; /* Body of inferred type */
2259 Type it = NIL; /* Full inferred type */
2261 resetGenerics(); /* Calculate Haskell typing */
2264 it = generalize(ps,bt);
2266 if (nonNull(dt)) { /* If a declared type was given, */
2267 instantiate(dt); /* check body for match. */
2268 if (!equalTypes(typeIs,bt))
2269 tooGeneral(l,v,dt,it);
2271 else if (nonNull(ps)) /* Otherwise test for ambiguity in */
2272 if (isAmbiguous(it)) /* inferred type. */
2273 ambigError(l,"inferred type",v,it);
2278 static Type local generalize(qs,t) /* calculate generalization of t */
2279 List qs; /* having already marked fixed vars*/
2280 Type t; { /* with qualifying preds qs */
2282 t = ap(QUAL,pair(qs,t));
2283 if (nonNull(genericVars)) {
2285 List vs = genericVars;
2286 for (; nonNull(vs); vs=tl(vs)) {
2287 Tyvar *tyv = tyvar(intOf(hd(vs)));
2288 Kind ka = tyv->kind;
2291 t = mkPolyType(k,t);
2293 Printf("Generalized type: ");
2294 printType(stdout,t);
2296 printKind(stdout,k);
2303 static Bool local equalTypes(t1,t2) /* Compare simple types for equality*/
2306 et: if (whatIs(t1)!=whatIs(t2))
2309 switch (whatIs(t1)) {
2315 case TUPLE : return t1==t2;
2317 case INTCELL : return intOf(t1)!=intOf(t2);
2319 case AP : if (equalTypes(fun(t1),fun(t2))) {
2326 default : internal("equalTypes");
2329 return TRUE;/*NOTREACHED*/
2332 /* --------------------------------------------------------------------------
2333 * Entry points to type checker:
2334 * ------------------------------------------------------------------------*/
2336 Type typeCheckExp(useDefs) /* Type check top level expression */
2337 Bool useDefs; { /* using defaults if reqd */
2343 emptySubstitution();
2345 inputExpr = typeExpr(0,inputExpr);
2349 improve(0,NIL,preds);
2352 preds = scSimplify(preds);
2353 if (useDefs && nonNull(preds)) {
2356 if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4? */
2360 ctxt = copyPreds(preds);
2361 type = generalize(ctxt,copyType(type,beta));
2362 inputExpr = qualifyExpr(0,preds,inputExpr);
2363 h98CheckType(0,"inferred type",inputExpr,type);
2365 emptySubstitution();
2369 Void typeCheckDefns() { /* Type check top level bindings */
2370 Target t = length(selDefns) + length(valDefns) +
2371 length(instDefns) + length(classDefns);
2376 emptySubstitution();
2379 setGoal("Type checking",t);
2381 for (gs=selDefns; nonNull(gs); gs=tl(gs)) {
2382 mapOver(typeSel,hd(gs));
2385 for (gs=valDefns; nonNull(gs); gs=tl(gs)) {
2386 typeDefnGroup(hd(gs));
2390 for (gs=classDefns; nonNull(gs); gs=tl(gs)) {
2391 emptySubstitution();
2392 typeClassDefn(hd(gs));
2395 for (gs=instDefns; nonNull(gs); gs=tl(gs)) {
2396 emptySubstitution();
2397 typeInstDefn(hd(gs));
2402 emptySubstitution();
2406 static Void local typeDefnGroup(bs) /* type check group of value defns */
2407 List bs; { /* (one top level scc) */
2410 emptySubstitution();
2411 hd(defnBounds) = NIL;
2414 typeBindings(bs); /* find types for vars in bindings */
2416 if (nonNull(preds)) {
2417 Cell v = fst(hd(hd(varsBounds)));
2418 Name n = findName(textOf(v));
2419 Int l = nonNull(n) ? name(n).line : 0;
2420 preds = scSimplify(preds);
2421 ERRMSG(l) "Instance%s of ", (length(preds)==1 ? "" : "s") ETHEN
2422 ERRCONTEXT(copyPreds(preds));
2423 ERRTEXT " required for definition of " ETHEN
2424 ERREXPR(nonNull(n)?n:v);
2429 if (nonNull(hd(skolVars))) {
2431 Name n = findName(isVar(fst(b)) ? textOf(fst(b)) : textOf(hd(fst(b))));
2432 Int l = nonNull(n) ? name(n).line : 0;
2433 leaveSkolVars(l,typeUnit,0,0);
2437 for (as=hd(varsBounds); nonNull(as); as=tl(as)) {
2438 Cell a = hd(as); /* add infered types to environment*/
2439 Name n = findName(textOf(fst(a)));
2441 internal("typeDefnGroup");
2442 name(n).type = snd(a);
2444 hd(varsBounds) = NIL;
2447 static Pair local typeSel(s) /* Calculate a suitable type for a */
2448 Name s; { /* particular selector, s. */
2449 List cns = name(s).defn;
2450 Int line = name(s).line;
2451 Type dom = NIL; /* Inferred domain */
2452 Type rng = NIL; /* Inferred range */
2453 Cell nv = inventVar();
2455 Int o = 0; /* bogus init to keep gcc -O happy */
2456 Int m = 0; /* bogus init to keep gcc -O happy */
2459 Printf("Selector %s, cns=",textToStr(name(s).text));
2460 printExp(stdout,cns);
2464 emptySubstitution();
2467 for (; nonNull(cns); cns=tl(cns)) {
2468 Name c = fst(hd(cns));
2469 Int n = intOf(snd(hd(cns)));
2470 Int a = name(c).arity;
2477 instantiate(name(c).type); /* Instantiate constructor type */
2480 for (; nonNull(predsAre); predsAre=tl(predsAre))
2481 assumeEvid(hd(predsAre),o1);
2483 if (whatIs(typeIs)==RANK2) /* Skip rank2 annotation, if any */
2484 typeIs = snd(snd(typeIs));
2485 for (; --n>0; a--) { /* Get range */
2486 pat = ap(pat,WILDCARD);
2487 typeIs = arg(typeIs);
2489 rng1 = dropRank1(arg(fun(typeIs)),o1,m1);
2491 typeIs = arg(typeIs);
2492 while (--a>0) { /* And then look for domain */
2493 pat = ap(pat,WILDCARD);
2494 typeIs = arg(typeIs);
2498 if (isNull(dom)) { /* Save first domain type and then */
2499 dom = dom1; /* unify with subsequent domains to*/
2500 o = o1; /* match up preds and range types */
2503 else if (!unify(dom1,o1,dom,o))
2504 internal("typeSel1");
2506 if (isNull(rng)) /* Compare component types */
2508 else if (!sameSchemes(rng1,rng)) {
2510 rng = liftRank1(rng,o,m);
2511 rng1 = liftRank1(rng1,o1,m1);
2512 ERRMSG(name(s).line) "Mismatch in field types for selector \"%s\"",
2513 textToStr(name(s).text) ETHEN
2514 ERRTEXT "\n*** Field type : " ETHEN ERRTYPE(rng1);
2515 ERRTEXT "\n*** Does not match : " ETHEN ERRTYPE(rng);
2519 alts = cons(pair(singleton(pat),pair(mkInt(line),nv)),alts);
2523 if (isNull(dom) || isNull(rng)) /* Should have been initialized by */
2524 internal("typeSel2"); /* now, assuming length cns >= 1. */
2526 clearMarks(); /* No fixed variables here */
2527 preds = scSimplify(preds); /* Simplify context */
2528 dom = copyType(dom,o); /* Calculate domain type */
2530 rng = copyType(typeIs,typeOff);
2531 if (nonNull(predsAre)) {
2532 List ps = makePredAss(predsAre,typeOff);
2534 for (; nonNull(alts1); alts1=tl(alts1)) {
2537 for (; nonNull(qs); qs=tl(qs))
2538 body = ap(body,thd3(hd(qs)));
2539 snd(snd(hd(alts1))) = body;
2541 preds = appendOnto(preds,ps);
2543 name(s).type = generalize(copyPreds(preds),fn(dom,rng));
2544 name(s).arity = 1 + length(preds);
2545 map1Proc(qualify,preds,alts);
2548 Printf("Inferred arity = %d, type = ",name(s).arity);
2549 printType(stdout,name(s).type);
2553 return pair(s,alts);
2557 /* --------------------------------------------------------------------------
2558 * Local function prototypes:
2559 * ------------------------------------------------------------------------*/
2561 static Type local basicType Args((Char));
2564 static Type stateVar = NIL;
2565 static Type alphaVar = NIL;
2566 static Type betaVar = NIL;
2567 static Type gammaVar = NIL;
2568 static Type deltaVar = NIL;
2569 static Int nextVar = 0;
2571 static Void clearTyVars( void )
2581 static Type mkStateVar( void )
2583 if (isNull(stateVar)) {
2584 stateVar = mkOffset(nextVar++);
2589 static Type mkAlphaVar( void )
2591 if (isNull(alphaVar)) {
2592 alphaVar = mkOffset(nextVar++);
2597 static Type mkBetaVar( void )
2599 if (isNull(betaVar)) {
2600 betaVar = mkOffset(nextVar++);
2605 static Type mkGammaVar( void )
2607 if (isNull(gammaVar)) {
2608 gammaVar = mkOffset(nextVar++);
2613 static Type mkDeltaVar( void )
2615 if (isNull(deltaVar)) {
2616 deltaVar = mkOffset(nextVar++);
2621 static Type local basicType(k)
2639 return ap(typePrimArray,mkAlphaVar());
2641 return typePrimByteArray;
2643 return ap2(typeRef,mkStateVar(),mkAlphaVar());
2645 return ap2(typePrimMutableArray,mkStateVar(),mkAlphaVar());
2647 return ap(typePrimMutableByteArray,mkStateVar());
2649 return ap(typeStable,mkAlphaVar());
2652 return ap(typeWeak,mkAlphaVar());
2654 return ap(typeIO,typeUnit);
2656 #ifdef PROVIDE_FOREIGN
2661 return typeThreadId;
2663 return ap(typeMVar,mkAlphaVar());
2667 return fn(typeException,mkAlphaVar());
2669 return typeException;
2671 return mkAlphaVar(); /* polymorphic */
2673 return mkBetaVar(); /* polymorphic */
2675 return mkGammaVar(); /* polymorphic */
2677 return mkDeltaVar(); /* polymorphic */
2679 printf("Kind: '%c'\n",k);
2680 internal("basicType");
2682 assert(0); return 0; /* NOTREACHED */
2685 /* Generate type of primop based on list of arg types and result types:
2687 * eg primType "II" "II" = Int -> Int -> (Int,Int)
2690 Type primType( Int /*AsmMonad*/ monad, String a_kinds, String r_kinds )
2694 List tvars = NIL; /* for polymorphic types */
2699 /* build result types */
2700 for(; *r_kinds; ++r_kinds) {
2701 rs = cons(basicType(*r_kinds),rs);
2703 /* Construct tuple of results */
2704 if (length(rs) == 0) {
2706 } else if (length(rs) == 1) {
2709 r = mkTuple(length(rs));
2710 for(rs = rev(rs); nonNull(rs); rs=tl(rs)) {
2714 /* Construct list of arguments */
2715 for(; *a_kinds; ++a_kinds) {
2716 as = cons(basicType(*a_kinds),as);
2718 /* Apply any monad magic */
2719 if (monad == MONAD_IO) {
2721 } else if (monad == MONAD_ST) {
2722 r = ap2(typeST,mkStateVar(),r);
2724 /* glue it all together */
2725 for(; nonNull(as); as=tl(as)) {
2728 tvars = offsetTyvarsIn(r,NIL);
2729 if (nonNull(tvars)) {
2730 assert(length(tvars) == nextVar);
2731 r = mkPolyType(simpleKind(length(tvars)),r);
2735 printType(stdout,r); printf("\n");
2741 /* forall a1 .. am. TC a1 ... am -> Int */
2742 Type conToTagType(t)
2747 for (i=0; i<tycon(t).arity; ++i) {
2748 Offset tv = mkOffset(i);
2750 tvars = cons(tv,tvars);
2752 ty = fn(ty,typeInt);
2753 if (nonNull(tvars)) {
2754 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2759 /* forall a1 .. am. Int -> TC a1 ... am */
2760 Type tagToConType(t)
2765 for (i=0; i<tycon(t).arity; ++i) {
2766 Offset tv = mkOffset(i);
2768 tvars = cons(tv,tvars);
2770 ty = fn(typeInt,ty);
2771 if (nonNull(tvars)) {
2772 ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2777 /* --------------------------------------------------------------------------
2778 * Type checker control:
2779 * ------------------------------------------------------------------------*/
2781 Void typeChecker(what)
2784 case RESET : tcMode = EXPRESSION;
2792 case MARK : mark(defnBounds);
2808 mark(predFractional);
2818 setCurrModule(modulePrelude);
2819 dummyVar = inventVar();
2820 typeUnit = mkTuple(0);
2821 arrow = fn(aVar,bVar);
2822 listof = ap(typeList,aVar);
2823 boundPair = ap(ap(mkTuple(2),aVar),aVar);
2824 nameUnit = findQualNameWithoutConsultingExportList
2825 (mkQVar(findText("PrelBase"),
2827 typeVarToVar = fn(aVar,aVar);
2835 Module m = findFakeModule(findText("PrelBase"));
2838 starToStar = simpleKind(1);
2839 typeList = addPrimTycon(findText("[]"),
2843 listof = ap(typeList,aVar);
2844 nameNil = addPrimCfun(findText("[]"),0,1,
2845 mkPolyType(starToStar,
2847 nameCons = addPrimCfun(findText(":"),2,2,
2848 mkPolyType(starToStar,
2852 name(nameNil).parent =
2853 name(nameCons).parent = typeList;
2855 name(nameCons).syntax
2856 = mkSyntax(RIGHT_ASS,5);
2858 tycon(typeList).defn
2859 = cons(nameNil,cons(nameCons,NIL));
2862 dummyVar = inventVar();
2864 setCurrModule(modulePrelude);
2866 starToStar = simpleKind(1);
2868 typeUnit = findTycon(findText("()"));
2869 assert(nonNull(typeUnit));
2871 typeArrow = addPrimTycon(findText("(->)"),
2874 typeList = addPrimTycon(findText("[]"),
2878 arrow = fn(aVar,bVar);
2879 listof = ap(typeList,aVar);
2880 boundPair = ap(ap(mkTuple(2),aVar),aVar);
2882 nameUnit = addPrimCfun(findText("()"),0,0,typeUnit);
2883 tycon(typeUnit).defn
2884 = singleton(nameUnit);
2886 nameNil = addPrimCfun(findText("[]"),0,1,
2887 mkPolyType(starToStar,
2889 nameCons = addPrimCfun(findText(":"),2,2,
2890 mkPolyType(starToStar,
2894 name(nameNil).parent =
2895 name(nameCons).parent = typeList;
2897 name(nameCons).syntax
2898 = mkSyntax(RIGHT_ASS,5);
2900 tycon(typeList).defn
2901 = cons(nameNil,cons(nameCons,NIL));
2903 typeVarToVar = fn(aVar,aVar);
2905 typeNoRow = addPrimTycon(findText("EmptyRow"),
2906 ROW,0,DATATYPE,NIL);
2907 typeRec = addPrimTycon(findText("Rec"),
2910 nameNoRec = addPrimCfun(findText("EmptyRec"),0,0,
2911 ap(typeRec,typeNoRow));
2913 /* bogus definitions to avoid changing the prelude */
2914 addPrimCfun(findText("Rec"), 0,0,typeUnit);
2915 addPrimCfun(findText("EmptyRow"), 0,0,typeUnit);
2916 addPrimCfun(findText("EmptyRec"), 0,0,typeUnit);
2924 /*-------------------------------------------------------------------------*/