[project @ 1999-10-15 11:02:06 by sewardj]
[ghc-hetmet.git] / ghc / interpreter / type.c
1
2 /* --------------------------------------------------------------------------
3  * This is the Hugs type checker
4  *
5  * Hugs 98 is Copyright (c) Mark P Jones, Alastair Reid and the Yale
6  * Haskell Group 1994-99, and is distributed as Open Source software
7  * under the Artistic License; see the file "Artistic" that is included
8  * in the distribution for details.
9  *
10  * $RCSfile: type.c,v $
11  * $Revision: 1.8 $
12  * $Date: 1999/10/15 11:02:40 $
13  * ------------------------------------------------------------------------*/
14
15 #include "prelude.h"
16 #include "storage.h"
17 #include "backend.h"
18 #include "connect.h"
19 #include "link.h"
20 #include "errors.h"
21 #include "subst.h"
22 #include "Assembler.h" /* for AsmCTypes */
23
24 /*#define DEBUG_TYPES*/
25 /*#define DEBUG_KINDS*/
26 /*#define DEBUG_DEFAULTS*/
27 /*#define DEBUG_SELS*/
28 /*#define DEBUG_DEPENDS*/
29 /*#define DEBUG_DERIVING*/
30 /*#define DEBUG_CODE*/
31
32 Bool catchAmbigs       = FALSE;         /* TRUE => functions with ambig.   */
33                                         /*         types produce error     */
34
35
36 /* --------------------------------------------------------------------------
37  * Local function prototypes:
38  * ------------------------------------------------------------------------*/
39
40 static Void   local emptyAssumption   Args((Void));
41 static Void   local enterBindings     Args((Void));
42 static Void   local leaveBindings     Args((Void));
43 static Int    local defType           Args((Cell));
44 static Type   local useType           Args((Cell));
45 static Void   local markAssumList     Args((List));
46 static Cell   local findAssum         Args((Text));
47 static Pair   local findInAssumList   Args((Text,List));
48 static List   local intsIntersect     Args((List,List));
49 static List   local genvarAllAss      Args((List));
50 static List   local genvarAnyAss      Args((List));
51 static Int    local newVarsBind       Args((Cell));
52 static Void   local newDefnBind       Args((Cell,Type));
53
54 static Void   local enterPendingBtyvs Args((Void));
55 static Void   local leavePendingBtyvs Args((Void));
56 static Cell   local patBtyvs          Args((Cell));
57 static Void   local doneBtyvs         Args((Int));
58 static Void   local enterSkolVars     Args((Void));
59 static Void   local leaveSkolVars     Args((Int,Type,Int,Int));
60
61 static Void   local typeError         Args((Int,Cell,Cell,String,Type,Int));
62 static Void   local reportTypeError   Args((Int,Cell,Cell,String,Type,Type));
63 static Void   local cantEstablish     Args((Int,String,Cell,Type,List));
64 static Void   local tooGeneral        Args((Int,Cell,Type,Type));
65
66 static Cell   local typeExpr          Args((Int,Cell));
67
68 static Cell   local typeAp            Args((Int,Cell));
69 static Type   local typeExpected      Args((Int,String,Cell,Type,Int,Int,Bool));
70 static Void   local typeAlt           Args((String,Cell,Cell,Type,Int,Int));
71 static Int    local funcType          Args((Int));
72 static Void   local typeCase          Args((Int,Int,Cell));
73 static Void   local typeComp          Args((Int,Type,Cell,List));
74 static Cell   local typeMonadComp     Args((Int,Cell));
75 static Void   local typeDo            Args((Int,Cell));
76 static Void   local typeConFlds       Args((Int,Cell));
77 static Void   local typeUpdFlds       Args((Int,Cell));
78 static Cell   local typeFreshPat      Args((Int,Cell));
79
80 static Void   local typeBindings      Args((List));
81 static Void   local removeTypeSigs    Args((Cell));
82
83 static Void   local monorestrict      Args((List));
84 static Void   local restrictedBindAss Args((Cell));
85 static Void   local restrictedAss     Args((Int,Cell,Type));
86
87 static Void   local unrestricted      Args((List));
88 static List   local itbscc            Args((List));
89 static Void   local addEvidParams     Args((List,Cell));
90
91 static Void   local typeClassDefn     Args((Class));
92 static Void   local typeInstDefn      Args((Inst));
93 static Void   local typeMember        Args((String,Name,Cell,List,Cell,Int));
94
95 static Void   local typeBind          Args((Cell));
96 static Void   local typeDefAlt        Args((Int,Cell,Pair));
97 static Cell   local typeRhs           Args((Cell));
98 static Void   local guardedType       Args((Int,Cell));
99
100 static Void   local genBind           Args((List,Cell));
101 static Void   local genAss            Args((Int,List,Cell,Type));
102 static Type   local genTest           Args((Int,Cell,List,Type,Type,Int));
103 static Type   local generalize        Args((List,Type));
104 static Bool   local equalTypes        Args((Type,Type));
105
106 static Void   local typeDefnGroup     Args((List));
107 static Pair   local typeSel           Args((Name));
108
109
110
111 /* --------------------------------------------------------------------------
112  * Assumptions:
113  *
114  * A basic typing statement is a pair (Var,Type) and an assumption contains
115  * an ordered list of basic typing statements in which the type for a given
116  * variable is given by the most recently added assumption about that var.
117  *
118  * In practice, the assumption set is split between a pair of lists, one
119  * holding assumptions for vars defined in bindings, the other for vars
120  * defined in patterns/binding parameters etc.  The reason for this
121  * separation is that vars defined in bindings may be overloaded (with the
122  * overloading being unknown until the whole binding is typed), whereas the
123  * vars defined in patterns have no overloading.  A form of dependency
124  * analysis (at least as far as calculating dependents within the same group
125  * of value bindings) is required to implement this.  Where it is known that
126  * no overloaded values are defined in a binding (i.e., when the `dreaded
127  * monomorphism restriction' strikes), the list used to record dependents
128  * is flagged with a NODEPENDS tag to avoid gathering dependents at that
129  * level.
130  *
131  * To interleave between vars for bindings and vars for patterns, we use
132  * a list of lists of typing statements for each.  These lists are always
133  * the same length.  The implementation here is very similar to that of the
134  * dependency analysis used in the static analysis component of this system.
135  *
136  * To deal with polymorphic recursion, variables defined in bindings can be
137  * assigned types of the form (POLYREC,(def,use)), where def is a type
138  * variable for the type of the defining occurence, and use is a type
139  * scheme for (recursive) calls/uses of the variable.
140  * ------------------------------------------------------------------------*/
141
142 static List defnBounds;                 /*::[[(Var,Type)]] possibly ovrlded*/
143 static List varsBounds;                 /*::[[(Var,Type)]] not overloaded  */
144 static List depends;                    /*::[?[Var]] dependents/NODEPENDS  */
145 static List skolVars;                   /*::[[Var]] skolem vars            */
146 static List localEvs;                   /*::[[(Pred,offset,ev)]]           */
147 static List savedPs;                    /*::[[(Pred,offset,ev)]]           */
148 static Cell dummyVar;                   /* Used to put extra tvars into ass*/
149
150 #define saveVarsAss()     List saveAssump = hd(varsBounds)
151 #define restoreVarsAss()  hd(varsBounds)  = saveAssump
152 #define addVarAssump(v,t) hd(varsBounds)  = cons(pair(v,t),hd(varsBounds))
153 #define findTopBinding(v) findInAssumList(textOf(v),hd(defnBounds))
154
155 static Void local emptyAssumption() {   /* set empty type assumption       */
156     defnBounds = NIL;
157     varsBounds = NIL;
158     depends    = NIL;
159     skolVars   = NIL;
160     localEvs   = NIL;
161     savedPs    = NIL;
162 }
163
164 static Void local enterBindings() {    /* Add new level to assumption sets */
165     defnBounds = cons(NIL,defnBounds);
166     varsBounds = cons(NIL,varsBounds);
167     depends    = cons(NIL,depends);
168 }
169
170 static Void local leaveBindings() {    /* Drop one level of assumptions    */
171     defnBounds = tl(defnBounds);
172     varsBounds = tl(varsBounds);
173     depends    = tl(depends);
174 }
175
176 static Int local defType(a)             /* Return type for defining occ.   */
177 Cell a; {                               /* of a var from assumption pair  */
178     return (isPair(a) && fst(a)==POLYREC) ? fst(snd(a)) : a;
179 }
180
181 static Type local useType(a)            /* Return type for use of a var    */
182 Cell a; {                               /* defined in an assumption        */
183     return (isPair(a) && fst(a)==POLYREC) ? snd(snd(a)) : a;
184 }
185
186 static Void local markAssumList(as)     /* Mark all types in assumption set*/
187 List as; {                              /* :: [(Var, Type)]                */
188     for (; nonNull(as); as=tl(as)) {    /* No need to mark generic types;  */
189         Type t = defType(snd(hd(as)));  /* the only free variables in those*/
190         if (!isPolyType(t))             /* must have been free earlier too */
191             markType(t,0);
192     }
193 }
194
195 static Cell local findAssum(t)         /* Find most recent assumption about*/
196 Text t; {                              /* variable named t, if any         */
197     List defnBounds1 = defnBounds;     /* return translated variable, with */
198     List varsBounds1 = varsBounds;     /* type in typeIs                   */
199     List depends1    = depends;
200
201     while (nonNull(defnBounds1)) {
202         Pair ass = findInAssumList(t,hd(varsBounds1));/* search varsBounds */
203         if (nonNull(ass)) {
204             typeIs = snd(ass);
205             return fst(ass);
206         }
207
208         ass = findInAssumList(t,hd(defnBounds1));     /* search defnBounds */
209         if (nonNull(ass)) {
210             Cell v = fst(ass);
211             typeIs = snd(ass);
212
213             if (hd(depends1)!=NODEPENDS &&            /* save dependent?   */
214                   isNull(v=varIsMember(t,hd(depends1))))
215                 /* N.B. make new copy of variable and store this on list of*/
216                 /* dependents, and in the assumption so that all uses of   */
217                 /* the variable will be at the same node, if we need to    */
218                 /* overwrite the call of a function with a translation...  */
219                 hd(depends1) = cons(v=mkVar(t),hd(depends1));
220
221             return v;
222         }
223
224         defnBounds1 = tl(defnBounds1);                /* look in next level*/
225         varsBounds1 = tl(varsBounds1);                /* of assumption set */
226         depends1    = tl(depends1);
227     }
228     return NIL;
229 }
230
231 static Pair local findInAssumList(t,as)/* Search for assumption for var    */
232 Text t;                                /* named t in list of assumptions as*/
233 List as; {
234     for (; nonNull(as); as=tl(as))
235         if (textOf(fst(hd(as)))==t)
236             return hd(as);
237     return NIL;
238 }
239
240 static List local intsIntersect(as,bs)  /* calculate intersection of lists */
241 List as, bs; {                          /* of integers (as sets)           */
242     List ts = NIL;                      /* destructively modifies as       */
243     while (nonNull(as))
244         if (intIsMember(intOf(hd(as)),bs)) {
245             List temp = tl(as);
246             tl(as)    = ts;
247             ts        = as;
248             as        = temp;
249         }
250         else
251             as = tl(as);
252     return ts;
253 }
254
255 static List local genvarAllAss(as)      /* calculate generic vars that are */
256 List as; {                              /* in every type in assumptions as */
257     List vs = genvarTyvar(intOf(defType(snd(hd(as)))),NIL);
258     for (as=tl(as); nonNull(as) && nonNull(vs); as=tl(as))
259         vs = intsIntersect(vs,genvarTyvar(intOf(defType(snd(hd(as)))),NIL));
260     return vs;
261 }
262
263 static List local genvarAnyAss(as)      /* calculate generic vars that are */
264 List as; {                              /* in any type in assumptions as   */
265     List vs = genvarTyvar(intOf(defType(snd(hd(as)))),NIL);
266     for (as=tl(as); nonNull(as); as=tl(as))
267         vs = genvarTyvar(intOf(defType(snd(hd(as)))),vs);
268     return vs;
269 }
270
271 static Int local newVarsBind(v)        /* make new assump for pattern var  */
272 Cell v; {
273     Int beta = newTyvars(1);
274     addVarAssump(v,mkInt(beta));
275 #ifdef DEBUG_TYPES
276     Printf("variable, assume ");
277     printExp(stdout,v);
278     Printf(" :: _%d\n",beta);
279 #endif
280     return beta;
281 }
282
283 static Void local newDefnBind(v,type)  /* make new assump for defn var     */
284 Cell v;                                /* and set type if given (nonNull)  */
285 Type type; {
286     Int  beta      = newTyvars(1);
287     Cell ta        = mkInt(beta);
288     instantiate(type);
289     if (nonNull(type) && isPolyType(type))
290         ta = pair(POLYREC,pair(ta,type));
291     hd(defnBounds) = cons(pair(v,ta), hd(defnBounds));
292 #ifdef DEBUG_TYPES
293     Printf("definition, assume ");
294     printExp(stdout,v);
295     Printf(" :: _%d\n",beta);
296 #endif
297     bindTv(beta,typeIs,typeOff);       /* Bind beta to new type skeleton   */
298 }
299
300 /* --------------------------------------------------------------------------
301  * Predicates:
302  * ------------------------------------------------------------------------*/
303
304 #include "preds.c"
305
306 /* --------------------------------------------------------------------------
307  * Bound and skolemized type variables:
308  * ------------------------------------------------------------------------*/
309
310 static List pendingBtyvs = NIL;
311
312 static Void local enterPendingBtyvs() {
313     enterBtyvs();
314     pendingBtyvs = cons(NIL,pendingBtyvs);
315 }
316
317 static Void local leavePendingBtyvs() {
318     List pts     = hd(pendingBtyvs);
319     pendingBtyvs = tl(pendingBtyvs);
320     for (; nonNull(pts); pts=tl(pts)) {
321         Int  line = intOf(fst(hd(pts)));
322         List vs   = snd(hd(pts));
323         Int  i    = 0;
324         clearMarks();
325         for (; nonNull(vs); vs=tl(vs)) {
326             Cell v = fst(hd(vs));
327             Cell t = copyTyvar(intOf(snd(hd(vs))));
328             if (!isOffset(t)) {
329                 ERRMSG(line) "Type annotation uses variable " ETHEN ERREXPR(v);
330                 ERRTEXT      " where a more specific type "   ETHEN ERRTYPE(t);
331                 ERRTEXT      " was inferred"
332                 EEND;
333             }
334             else if (offsetOf(t)!=i) {
335                 List us = snd(hd(pts));
336                 Int  j  = offsetOf(t);
337                 if (j>=i)
338                     internal("leavePendingBtyvs");
339                 for (; j>0; j--)
340                     us = tl(us);
341                 ERRMSG(line) "Type annotation uses distinct variables " ETHEN
342                 ERREXPR(v);  ERRTEXT " and " ETHEN ERREXPR(fst(hd(us)));
343                 ERRTEXT      " where a single variable was inferred"
344                 EEND;
345             }
346             else
347                 i++;
348         }
349     }
350     leaveBtyvs();
351 }
352
353 static Cell local patBtyvs(p)           /* Strip bound type vars from pat  */
354 Cell p; {
355     if (whatIs(p)==BIGLAM) {
356         List bts = hd(btyvars) = fst(snd(p));
357         for (p=snd(snd(p)); nonNull(bts); bts=tl(bts)) {
358             Int beta          = newTyvars(1);
359             tyvar(beta)->kind = snd(hd(bts));
360             snd(hd(bts))      = mkInt(beta);
361         }
362     }
363     return p;
364 }
365
366 static Void local doneBtyvs(l)
367 Int l; {
368     if (nonNull(hd(btyvars))) {         /* Save bound tyvars               */
369         hd(pendingBtyvs) = cons(pair(mkInt(l),hd(btyvars)),hd(pendingBtyvs));
370         hd(btyvars)      = NIL;
371     }
372 }
373
374 static Void local enterSkolVars() {
375     skolVars = cons(NIL,skolVars);
376     localEvs = cons(NIL,localEvs);
377     savedPs  = cons(preds,savedPs);
378     preds    = NIL;
379 }
380
381 static Void local leaveSkolVars(l,t,o,m)
382 Int  l;
383 Type t;
384 Int  o;
385 Int  m; {
386     if (nonNull(hd(localEvs))) {        /* Check for local predicates      */
387         List sks = hd(skolVars);
388         List sps = NIL;
389         if (isNull(sks)) {
390             internal("leaveSkolVars");
391         }
392         markAllVars();                  /* Mark all variables in current   */
393         do {                            /* substitution, then unmark sks.  */
394             tyvar(intOf(fst(hd(sks))))->offs = UNUSED_GENERIC;
395             sks = tl(sks);
396         } while (nonNull(sks));
397         sps   = elimPredsUsing(hd(localEvs),sps);
398         preds = revOnto(preds,sps);
399     }
400
401     if (nonNull(hd(skolVars))) {        /* Check that Skolem vars do not   */
402         List vs;                        /* escape their scope              */
403         Int  i = 0;
404
405         clearMarks();                   /* Look for occurences in the      */
406         for (; i<m; i++)                /* inferred type                   */
407             markTyvar(o+i);
408         markType(t,o);
409
410         for (vs=hd(skolVars); nonNull(vs); vs=tl(vs)) {
411             Int vn = intOf(fst(hd(vs)));
412             if (tyvar(vn)->offs == FIXED_TYVAR) {
413                 Cell tv = copyTyvar(vn);
414                 Type ty = liftRank2(t,o,m);
415                 ERRMSG(l) "Existentially quantified variable in inferred type"
416                 ETHEN
417                 ERRTEXT   "\n*** Variable     : " ETHEN ERRTYPE(tv);
418                 ERRTEXT   "\n*** From pattern : " ETHEN ERREXPR(snd(hd(vs)));
419                 ERRTEXT   "\n*** Result type  : " ETHEN ERRTYPE(ty);
420                 ERRTEXT   "\n"
421                 EEND;
422             }
423         }
424
425         markBtyvs();                    /* Now check assumptions           */
426         mapProc(markAssumList,defnBounds);
427         mapProc(markAssumList,varsBounds);
428
429         for (vs=hd(skolVars); nonNull(vs); vs=tl(vs)) {
430             Int vn = intOf(fst(hd(vs)));
431             if (tyvar(vn)->offs == FIXED_TYVAR) {
432                 ERRMSG(l)
433                   "Existentially quantified variable escapes from pattern "
434                 ETHEN ERREXPR(snd(hd(vs)));
435                 ERRTEXT "\n"
436                 EEND;
437             }
438         }
439     }
440     localEvs = tl(localEvs);
441     skolVars = tl(skolVars);
442     preds    = revOnto(preds,hd(savedPs));
443     savedPs  = tl(savedPs);
444 }
445
446 /* --------------------------------------------------------------------------
447  * Type errors:
448  * ------------------------------------------------------------------------*/
449
450 static Void local typeError(l,e,in,wh,t,o)
451 Int    l;                             /* line number near type error       */
452 String wh;                            /* place in which error occurs       */
453 Cell   e;                             /* source of error                   */
454 Cell   in;                            /* context if any (NIL if not)       */
455 Type   t;                             /* should be of type (t,o)           */
456 Int    o; {                           /* type inferred is (typeIs,typeOff) */
457
458     clearMarks();                     /* types printed here are monotypes  */
459                                       /* use marking to give sensible names*/
460 #ifdef DEBUG_KINDS
461 { List vs = genericVars;
462   for (; nonNull(vs); vs=tl(vs)) {
463      Int v = intOf(hd(vs));
464      Printf("%c :: ", ('a'+tyvar(v)->offs));
465      printKind(stdout,tyvar(v)->kind);
466      Putchar('\n');
467   }
468 }
469 #endif
470
471     reportTypeError(l,e,in,wh,copyType(typeIs,typeOff),copyType(t,o));
472 }
473
474 static Void local reportTypeError(l,e,in,wh,inft,expt)
475 Int    l;                               /* Error printing part of typeError*/
476 Cell   e, in;
477 String wh;
478 Type   inft, expt; {
479     ERRMSG(l)   "Type error in %s", wh    ETHEN
480     if (nonNull(in)) {
481         ERRTEXT "\n*** Expression     : " ETHEN ERREXPR(in);
482     }
483     ERRTEXT     "\n*** Term           : " ETHEN ERREXPR(e);
484     ERRTEXT     "\n*** Type           : " ETHEN ERRTYPE(inft);
485     ERRTEXT     "\n*** Does not match : " ETHEN ERRTYPE(expt);
486     if (unifyFails) {
487         ERRTEXT "\n*** Because        : %s", unifyFails ETHEN
488     }
489     ERRTEXT "\n"
490     EEND;
491 }
492
493 #define shouldBe(l,e,in,where,t,o) if (!unify(typeIs,typeOff,t,o)) \
494                                        typeError(l,e,in,where,t,o);
495 #define check(l,e,in,where,t,o)    e=typeExpr(l,e); shouldBe(l,e,in,where,t,o)
496 #define inferType(t,o)             typeIs=t; typeOff=o
497
498 static Void local cantEstablish(line,wh,e,t,ps)
499 Int    line;                            /* Complain when declared preds    */
500 String wh;                              /* are not sufficient to discharge */
501 Cell   e;                               /* or defer the inferred context.  */
502 Type   t;
503 List   ps; {
504     ERRMSG(line) "Cannot justify constraints in %s", wh ETHEN
505     ERRTEXT      "\n*** Expression    : " ETHEN ERREXPR(e);
506     ERRTEXT      "\n*** Type          : " ETHEN ERRTYPE(t);
507     ERRTEXT      "\n*** Given context : " ETHEN ERRCONTEXT(ps);
508     ERRTEXT      "\n*** Constraints   : " ETHEN ERRCONTEXT(copyPreds(preds));
509     ERRTEXT "\n"
510     EEND;
511 }
512
513 static Void local tooGeneral(l,e,dt,it) /* explicit type sig. too general  */
514 Int  l;
515 Cell e;
516 Type dt, it; {
517     ERRMSG(l) "Inferred type is not general enough" ETHEN
518     ERRTEXT   "\n*** Expression    : " ETHEN ERREXPR(e);
519     ERRTEXT   "\n*** Expected type : " ETHEN ERRTYPE(dt);
520     ERRTEXT   "\n*** Inferred type : " ETHEN ERRTYPE(it);
521     ERRTEXT   "\n"
522     EEND;
523 }
524
525 /* --------------------------------------------------------------------------
526  * Typing of expressions:
527  * ------------------------------------------------------------------------*/
528
529 #define EXPRESSION  0                   /* type checking expression        */
530 #define NEW_PATTERN 1                   /* pattern, introducing new vars   */
531 #define OLD_PATTERN 2                   /* pattern, involving bound vars   */
532 static int tcMode = EXPRESSION;
533
534 #ifdef DEBUG_TYPES
535 static Cell local mytypeExpr    Args((Int,Cell));
536 static Cell local typeExpr(l,e)
537 Int l;
538 Cell e; {
539     static int number = 0;
540     Cell retv;
541     int  mynumber = number++;
542     Printf("%d) to check: ",mynumber);
543     printExp(stdout,e);
544     Putchar('\n');
545     retv = mytypeExpr(l,e);
546     Printf("%d) result: ",mynumber);
547     printType(stdout,debugType(typeIs,typeOff));
548     Putchar('\n');
549     return retv;
550 }
551 static Cell local mytypeExpr(l,e)       /* Determine type of expr/pattern  */
552 #else
553 static Cell local typeExpr(l,e)         /* Determine type of expr/pattern  */
554 #endif
555 Int  l;
556 Cell e; {
557     static String cond    = "conditional";
558     static String list    = "list";
559     static String discr   = "case discriminant";
560     static String aspat   = "as (@) pattern";
561     static String typeSig = "type annotation";
562     static String lambda  = "lambda expression";
563
564     switch (whatIs(e)) {
565
566         /* The following cases can occur in either pattern or expr. mode   */
567
568         case AP         :
569         case NAME       :
570         case VAROPCELL  :
571         case VARIDCELL  : return typeAp(l,e);
572
573         case TUPLE      : typeTuple(e);
574                           break;
575
576         case BIGCELL    : {   Int alpha = newTyvars(1);
577                               inferType(aVar,alpha);
578                               return ap(ap(nameFromInteger,
579                                            assumeEvid(predNum,alpha)),
580                                            e);
581                           }
582
583         case INTCELL    : {   Int alpha = newTyvars(1);
584                               inferType(aVar,alpha);
585                               return ap(ap(nameFromInt,
586                                            assumeEvid(predNum,alpha)),
587                                            e);
588                           }
589
590         case FLOATCELL  : {   Int alpha = newTyvars(1);
591                               inferType(aVar,alpha);
592                               return ap(ap(nameFromDouble,
593                                            assumeEvid(predFractional,alpha)),
594                                            e);
595                           }
596
597         case STRCELL    : inferType(typeString,0);
598                           break;
599
600         case CHARCELL   : inferType(typeChar,0);
601                           break;
602
603         case CONFLDS    : typeConFlds(l,e);
604                           break;
605
606         case ESIGN      : snd(snd(e)) = localizeBtyvs(snd(snd(e)));
607                           return typeExpected(l,typeSig,
608                                               fst(snd(e)),snd(snd(e)),
609                                               0,0,FALSE);
610
611 #if TREX
612         case EXT        : {   Int beta = newTyvars(2);
613                               Cell pi  = ap(e,aVar);
614                               Type t   = fn(aVar,
615                                          fn(ap(typeRec,bVar),
616                                             ap(typeRec,ap(ap(e,aVar),bVar))));
617                               tyvar(beta+1)->kind = ROW;
618                               inferType(t,beta);
619                               return ap(e,assumeEvid(pi,beta+1));
620                           }
621 #endif
622
623         /* The following cases can only occur in expr mode                 */
624
625         case UPDFLDS    : typeUpdFlds(l,e);
626                           break;
627
628         case COND       : {   Int beta = newTyvars(1);
629                               check(l,fst3(snd(e)),e,cond,typeBool,0);
630                               check(l,snd3(snd(e)),e,cond,aVar,beta);
631                               check(l,thd3(snd(e)),e,cond,aVar,beta);
632                               tyvarType(beta);
633                           }
634                           break;
635
636         case LETREC     : enterBindings();
637                           enterSkolVars();
638                           mapProc(typeBindings,fst(snd(e)));
639                           snd(snd(e)) = typeExpr(l,snd(snd(e)));
640                           leaveBindings();
641                           leaveSkolVars(l,typeIs,typeOff,0);
642                           break;
643
644         case FINLIST    : {   Int  beta = newTyvars(1);
645                               List xs;
646                               for (xs=snd(e); nonNull(xs); xs=tl(xs)) {
647                                  check(l,hd(xs),e,list,aVar,beta);
648                               }
649                               inferType(listof,beta);
650                           }
651                           break;
652
653         case DOCOMP     : typeDo(l,e);
654                           break;
655
656         case COMP       : return typeMonadComp(l,e);
657
658         case CASE       : {    Int beta = newTyvars(2);    /* discr result */
659                                check(l,fst(snd(e)),NIL,discr,aVar,beta);
660                                map2Proc(typeCase,l,beta,snd(snd(e)));
661                                tyvarType(beta+1);
662                           }
663                           break;
664
665         case LAMBDA     : {   Int beta = newTyvars(1);
666                               enterPendingBtyvs();
667                               typeAlt(lambda,e,snd(e),aVar,beta,1);
668                               leavePendingBtyvs();
669                               tyvarType(beta);
670                           }
671                           break;
672
673 #if TREX
674         case RECSEL     : {   Int beta = newTyvars(2);
675                               Cell pi  = ap(snd(e),aVar);
676                               Type t   = fn(ap(typeRec,
677                                                ap(ap(snd(e),aVar),
678                                                             bVar)),aVar);
679                               tyvar(beta+1)->kind = ROW;
680                               inferType(t,beta);
681                               return ap(e,assumeEvid(pi,beta+1));
682                           }
683 #endif
684
685         /* The remaining cases can only occur in pattern mode: */
686
687         case WILDCARD   : inferType(aVar,newTyvars(1));
688                           break;
689
690         case ASPAT      : {   Int beta = newTyvars(1);
691                               snd(snd(e)) = typeExpr(l,snd(snd(e)));
692                               bindTv(beta,typeIs,typeOff);
693                               check(l,fst(snd(e)),e,aspat,aVar,beta);
694                               tyvarType(beta);
695                           }
696                           break;
697
698         case LAZYPAT    : snd(e) = typeExpr(l,snd(e));
699                           break;
700
701 #if NPLUSK
702         case ADDPAT     : {   Int alpha = newTyvars(1);
703                               inferType(typeVarToVar,alpha);
704                               return ap(e,assumeEvid(predIntegral,alpha));
705                           }
706 #endif
707
708         default         : internal("typeExpr");
709    }
710
711    return e;
712 }
713
714 /* --------------------------------------------------------------------------
715  * Typing rules for particular special forms:
716  * ------------------------------------------------------------------------*/
717
718 static Cell local typeAp(l,e)           /* Type check application, which   */
719 Int  l;                                 /* may be headed with a variable   */
720 Cell e; {                               /* requires polymorphism, qualified*/
721     static String app = "application";  /* types, and possible rank2 args. */
722     Cell h = getHead(e);
723     Int  n = argCount;
724     Cell p = NIL;
725     Cell a = e;
726     Int  i;
727
728     switch (whatIs(h)) {
729         case NAME      : typeIs = name(h).type;
730                          break;
731
732         case VAROPCELL :
733         case VARIDCELL : if (tcMode==NEW_PATTERN) {
734                              inferType(aVar,newVarsBind(e));
735                          }
736                          else {
737                              Cell v = findAssum(textOf(h));
738                              if (nonNull(v)) {
739                                  h      = v;
740                                  typeIs = (tcMode==OLD_PATTERN)
741                                                 ? defType(typeIs)
742                                                 : useType(typeIs);
743                              }
744                              else {
745                                  h = findName(textOf(h));
746                                  if (isNull(h))
747                                      internal("typeAp0");
748                                  typeIs = name(h).type;
749                              }
750                          }
751                          break;
752
753         default        : h = typeExpr(l,h);
754                          break;
755     }
756
757     if (isNull(typeIs)) {
758         internal("typeAp1");
759     }
760
761     instantiate(typeIs);                /* Deal with polymorphism ...      */
762     if (nonNull(predsAre)) {            /* ... and with qualified types.   */
763         List evs = NIL;
764         for (; nonNull(predsAre); predsAre=tl(predsAre)) {
765             evs = cons(assumeEvid(hd(predsAre),typeOff),evs);
766         }
767         if (!isName(h) || !isCfun(h)) {
768             h = applyToArgs(h,rev(evs));
769         }
770     }
771
772     if (whatIs(typeIs)==CDICTS) {       /* Deal with local dictionaries    */
773         List evs = makePredAss(fst(snd(typeIs)),typeOff);
774         List ps  = evs;
775         typeIs   = snd(snd(typeIs));
776         for (; nonNull(ps); ps=tl(ps)) {
777             h = ap(h,thd3(hd(ps)));
778         }
779         if (tcMode==EXPRESSION) {
780             preds = revOnto(evs,preds);
781         } else {
782             hd(localEvs) = revOnto(evs,hd(localEvs));
783         }
784     }
785
786     if (whatIs(typeIs)==EXIST) {        /* Deal with existential arguments */
787         Int n  = intOf(fst(snd(typeIs)));
788         typeIs = snd(snd(typeIs));
789         if (!isCfun(getHead(h)) || n>typeFree) {
790             internal("typeAp2");
791         } else if (tcMode!=EXPRESSION) {
792             Int alpha = typeOff + typeFree;
793             for (; n>0; n--) {
794                 bindTv(alpha-n,SKOLEM,0);
795                 hd(skolVars) = cons(pair(mkInt(alpha-n),e),hd(skolVars));
796             }
797         }
798     }
799
800     if (whatIs(typeIs)==RANK2) {        /* Deal with rank 2 arguments      */
801         Int  alpha = typeOff;
802         Int  m     = typeFree;
803         Int  nr2   = intOf(fst(snd(typeIs)));
804         Type body  = snd(snd(typeIs));
805         List as    = e;
806         Bool added = FALSE;
807
808         if (n<nr2) {                    /* Must have enough arguments      */
809             ERRMSG(l)   "Use of " ETHEN ERREXPR(h);
810             if (n>1) {
811                 ERRTEXT " in "    ETHEN ERREXPR(e);
812             }
813             ERRTEXT     " requires at least %d argument%s\n",
814                         nr2, (nr2==1 ? "" : "s")
815             EEND;
816         }
817
818         for (i=nr2; i<n; ++i)           /* Find rank two arguments         */
819             as = fun(as);
820
821         for (as=getArgs(as); nonNull(as); as=tl(as), body=arg(body)) {
822             Type expect = dropRank1(arg(fun(body)),alpha,m);
823             if (isPolyType(expect)) {
824                 if (tcMode==EXPRESSION)         /* poly/qual type in expr  */
825                     hd(as) = typeExpected(l,app,hd(as),expect,alpha,m,TRUE);
826                 else if (hd(as)!=WILDCARD) {    /* Pattern binding/match   */
827                     if (!isVar(hd(as))) {
828                         ERRMSG(l) "Argument "    ETHEN ERREXPR(arg(as));
829                         ERRTEXT   " in pattern " ETHEN ERREXPR(e);
830                         ERRTEXT   " where a variable is required\n"
831                         EEND;
832                     }
833                     if (tcMode==NEW_PATTERN) {  /* Pattern match           */
834                         if (m>0 && !added) {
835                             for (i=0; i<m; i++)
836                                 addVarAssump(dummyVar,mkInt(alpha+i));
837                             added = TRUE;
838                         }
839                         addVarAssump(hd(as),expect);
840                     }
841                     else {                      /* Pattern binding         */
842                         Text t = textOf(hd(as));
843                         Cell a = findInAssumList(t,hd(defnBounds));
844                         if (isNull(a))
845                             internal("typeAp3");
846                         instantiate(expect);
847                         if (nonNull(predsAre)) {
848                             ERRMSG(l) "Cannot use pattern binding for " ETHEN
849                             ERREXPR(hd(as));
850                             ERRTEXT   " as a component with a qualified type\n"
851                             EEND;
852                         }
853                         shouldBe(l,hd(as),e,app,aVar,intOf(defType(snd(a))));
854                     }
855                 }
856             }
857             else {                              /* Not a poly/qual type    */
858                 check(l,hd(as),e,app,expect,alpha);
859             }
860             h = ap(h,hd(as));                   /* Save checked argument   */
861         }
862         inferType(body,alpha);
863         n -= nr2;
864     }
865
866     if (n>0) {                          /* Deal with remaining args        */
867         Int beta = funcType(n);         /* check h::t1->t2->...->tn->rn+1  */
868         shouldBe(l,h,e,app,aVar,beta);
869         for (i=n; i>0; --i) {           /* check e_i::t_i for each i       */
870             check(l,arg(a),e,app,aVar,beta+2*i-1);
871             p = a;
872             a = fun(a);
873         }
874         tyvarType(beta+2*n);            /* Inferred type is r_n+1          */
875     }
876
877     if (isNull(p))                      /* Replace head with translation   */
878         e = h;
879     else
880         fun(p) = h;
881
882     return e;
883 }
884
885 static Cell local typeExpected(l,wh,e,reqd,alpha,n,addEvid)
886 Int    l;                               /* Type check expression e in wh   */
887 String wh;                              /* at line l, expecting type reqd, */
888 Cell   e;                               /* and treating vars alpha through */
889 Type   reqd;                            /* (alpha+n-1) as fixed.           */
890 Int    alpha;
891 Int    n;
892 Bool   addEvid; {                       /* TRUE => add \ev -> ...          */
893     List savePreds = preds;
894     Type t;
895     Int  o;
896     Int  m;
897     List ps;
898     Int  i;
899
900     instantiate(reqd);
901     t     = typeIs;
902     o     = typeOff;
903     m     = typeFree;
904     ps    = makePredAss(predsAre,o);
905
906     preds = NIL;
907     check(l,e,NIL,wh,t,o);
908
909     clearMarks();
910     mapProc(markAssumList,defnBounds);
911     mapProc(markAssumList,varsBounds);
912     mapProc(markPred,savePreds);
913     markBtyvs();
914
915     for (i=0; i<n; i++)
916         markTyvar(alpha+i);
917
918     savePreds = elimPredsUsing(ps,savePreds);
919     if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
920         savePreds = elimPredsUsing(ps,savePreds);
921     if (nonNull(preds)) {
922         Type ty = copyType(t,o);
923         List qs = copyPreds(ps);
924         cantEstablish(l,wh,e,ty,qs);
925     }
926
927     resetGenerics();
928     for (i=0; i<m; i++)
929         if (copyTyvar(o+i)!=mkOffset(i)) {
930             List qs = copyPreds(ps);
931             Type it = copyType(t,o);
932             tooGeneral(l,e,reqd,generalize(qs,it));
933         }
934
935     if (addEvid) {
936         e     = qualifyExpr(l,ps,e);
937         preds = savePreds;
938     }
939     else
940         preds = revOnto(ps,savePreds);
941
942     inferType(t,o);
943     return e;
944 }
945
946 static Void local typeAlt(wh,e,a,t,o,m) /* Type check abstraction (Alt)    */
947 String wh;                              /* a = ( [p1, ..., pn], rhs )      */
948 Cell   e;
949 Cell   a;
950 Type   t;
951 Int    o;
952 Int    m; {
953     Type origt = t;
954     List ps    = fst(a) = patBtyvs(fst(a));
955     Int  n     = length(ps);
956     Int  l     = rhsLine(snd(a));
957     Int  nr2   = 0;
958     List as    = NIL;
959     Bool added = FALSE;
960
961     saveVarsAss();
962     enterSkolVars();
963     if (whatIs(t)==RANK2) {
964         if (n<(nr2=intOf(fst(snd(t))))) {
965             ERRMSG(l) "Definition requires at least %d parameters on lhs",
966                       intOf(fst(snd(t)))
967             EEND;
968         }
969         t = snd(snd(t));
970     }
971
972     while (getHead(t)==typeArrow && argCount==2 && nonNull(ps)) {
973         Type ta = arg(fun(t));
974         if (isPolyType(ta)) {
975             if (hd(ps)!=WILDCARD) {
976                 if (!isVar(hd(ps))) {
977                    ERRMSG(l) "Argument " ETHEN ERREXPR(hd(ps));
978                    ERRTEXT   " used where a variable or wildcard is required\n"
979                    EEND;
980                 }
981                 if (m>0 && !added) {
982                     Int i = 0;
983                     for (; i<m; i++)
984                         addVarAssump(dummyVar,mkInt(o+i));
985                     added = TRUE;
986                 }
987                 addVarAssump(hd(ps),ta);
988             }
989         }
990         else {
991             hd(ps) = typeFreshPat(l,hd(ps));
992             shouldBe(l,hd(ps),NIL,wh,ta,o);
993         }
994         t  = arg(t);
995         ps = tl(ps);
996         as = fn(ta,as);
997         n--;
998     }
999
1000     if (n==0)
1001         snd(a) = typeRhs(snd(a));
1002     else {
1003         Int beta = funcType(n);
1004         Int i    = 0;
1005         for (; i<n; ++i) {
1006             hd(ps) = typeFreshPat(l,hd(ps));
1007             bindTv(beta+2*i+1,typeIs,typeOff);
1008             ps = tl(ps);
1009         }
1010         snd(a) = typeRhs(snd(a));
1011         bindTv(beta+2*n,typeIs,typeOff);
1012         tyvarType(beta);
1013     }
1014
1015     if (!unify(typeIs,typeOff,t,o)) {
1016         Type req, got;
1017         clearMarks();
1018         req = liftRank2(origt,o,m);
1019         liftRank2Args(as,o,m);
1020         got = ap(RANK2,pair(mkInt(nr2),revOnto(as,copyType(typeIs,typeOff))));
1021         reportTypeError(l,e,NIL,wh,got,req);
1022     }
1023
1024     restoreVarsAss();
1025     doneBtyvs(l);
1026     leaveSkolVars(l,origt,o,m);
1027 }
1028
1029 static Int local funcType(n)            /*return skeleton for function type*/
1030 Int n; {                                /*with n arguments, taking the form*/
1031     Int beta = newTyvars(2*n+1);        /*    r1 t1 r2 t2 ... rn tn rn+1   */
1032     Int i;                              /* with r_i := t_i -> r_i+1        */
1033     for (i=0; i<n; ++i)
1034         bindTv(beta+2*i,arrow,beta+2*i+1);
1035     return beta;
1036 }
1037
1038 static Void local typeCase(l,beta,c)   /* type check case: pat -> rhs      */
1039 Int  l;                                /* (case given by c == (pat,rhs))   */
1040 Int  beta;                             /* need:  pat :: (var,beta)         */
1041 Cell c; {                              /*        rhs :: (var,beta+1)       */
1042     static String casePat  = "case pattern";
1043     static String caseExpr = "case expression";
1044
1045     saveVarsAss();
1046     enterSkolVars();
1047     fst(c) = typeFreshPat(l,patBtyvs(fst(c)));
1048     shouldBe(l,fst(c),NIL,casePat,aVar,beta);
1049     snd(c) = typeRhs(snd(c));
1050     shouldBe(l,rhsExpr(snd(c)),NIL,caseExpr,aVar,beta+1);
1051
1052     restoreVarsAss();
1053     doneBtyvs(l);
1054     leaveSkolVars(l,typeIs,typeOff,0);
1055 }
1056
1057 static Void local typeComp(l,m,e,qs)    /* type check comprehension        */
1058 Int  l;
1059 Type m;                                 /* monad (mkOffset(0))             */
1060 Cell e;
1061 List qs; {
1062     static String boolQual = "boolean qualifier";
1063     static String genQual  = "generator";
1064
1065     if (isNull(qs))                     /* no qualifiers left              */
1066         fst(e) = typeExpr(l,fst(e));
1067     else {
1068         Cell q   = hd(qs);
1069         List qs1 = tl(qs);
1070         switch (whatIs(q)) {
1071             case BOOLQUAL : check(l,snd(q),NIL,boolQual,typeBool,0);
1072                             typeComp(l,m,e,qs1);
1073                             break;
1074
1075             case QWHERE   : enterBindings();
1076                             enterSkolVars();
1077                             mapProc(typeBindings,snd(q));
1078                             typeComp(l,m,e,qs1);
1079                             leaveBindings();
1080                             leaveSkolVars(l,typeIs,typeOff,0);
1081                             break;
1082
1083             case FROMQUAL : {   Int beta = newTyvars(1);
1084                                 saveVarsAss();
1085                                 check(l,snd(snd(q)),NIL,genQual,m,beta);
1086                                 enterSkolVars();
1087                                 fst(snd(q))
1088                                     = typeFreshPat(l,patBtyvs(fst(snd(q))));
1089                                 shouldBe(l,fst(snd(q)),NIL,genQual,aVar,beta);
1090                                 typeComp(l,m,e,qs1);
1091                                 restoreVarsAss();
1092                                 doneBtyvs(l);
1093                                 leaveSkolVars(l,typeIs,typeOff,0);
1094                             }
1095                             break;
1096
1097             case DOQUAL   : check(l,snd(q),NIL,genQual,m,newTyvars(1));
1098                             typeComp(l,m,e,qs1);
1099                             break;
1100         }
1101     }
1102 }
1103
1104 static Cell local typeMonadComp(l,e)    /* type check monad comprehension  */
1105 Int  l;
1106 Cell e; {
1107     Int  alpha        = newTyvars(1);
1108     Int  beta         = newTyvars(1);
1109     Cell mon          = ap(mkInt(beta),aVar);
1110     Cell m            = assumeEvid(predMonad,beta);
1111     tyvar(beta)->kind = starToStar;
1112 #if !MONAD_COMPS
1113     bindTv(beta,typeList,0);
1114 #endif
1115
1116     typeComp(l,mon,snd(e),snd(snd(e)));
1117     bindTv(alpha,typeIs,typeOff);
1118     inferType(mon,alpha);
1119     return ap(MONADCOMP,pair(m,snd(e)));
1120 }
1121
1122 static Void local typeDo(l,e)           /* type check do-notation          */
1123 Int  l;
1124 Cell e; {
1125     static String finGen = "final generator";
1126     Int  alpha           = newTyvars(1);
1127     Int  beta            = newTyvars(1);
1128     Cell mon             = ap(mkInt(beta),aVar);
1129     Cell m               = assumeEvid(predMonad,beta);
1130     tyvar(beta)->kind    = starToStar;
1131
1132     typeComp(l,mon,snd(e),snd(snd(e)));
1133     shouldBe(l,fst(snd(e)),NIL,finGen,mon,alpha);
1134     snd(e) = pair(m,snd(e));
1135 }
1136
1137 static Void local typeConFlds(l,e)      /* Type check a construction       */
1138 Int  l;
1139 Cell e; {
1140     static String conExpr = "value construction";
1141     Name c  = fst(snd(e));
1142     List fs = snd(snd(e));
1143     Type tc;
1144     Int  to;
1145     Int  tf;
1146     Int  i;
1147
1148     instantiate(name(c).type);
1149     for (; nonNull(predsAre); predsAre=tl(predsAre))
1150         assumeEvid(hd(predsAre),typeOff);
1151     if (whatIs(typeIs)==RANK2)
1152         typeIs = snd(snd(typeIs));
1153     tc = typeIs;
1154     to = typeOff;
1155     tf = typeFree;
1156
1157     for (; nonNull(fs); fs=tl(fs)) {
1158         Type t = tc;
1159         for (i=sfunPos(fst(hd(fs)),c); --i>0; t=arg(t))
1160             ;
1161         t = dropRank1(arg(fun(t)),to,tf);
1162         if (isPolyType(t))
1163             snd(hd(fs)) = typeExpected(l,conExpr,snd(hd(fs)),t,to,tf,TRUE);
1164         else {
1165             check(l,snd(hd(fs)),e,conExpr,t,to);
1166         }
1167     }
1168     for (i=name(c).arity; i>0; i--)
1169         tc = arg(tc);
1170     inferType(tc,to);
1171 }
1172
1173 static Void local typeUpdFlds(line,e)   /* Type check an update            */
1174 Int  line;                              /* (Written in what might seem a   */
1175 Cell e; {                               /* bizarre manner for the benefit  */
1176     static String update = "update";    /* of as yet unreleased extensions)*/
1177     List cs    = snd3(snd(e));          /* List of constructors            */
1178     List fs    = thd3(snd(e));          /* List of field specifications    */
1179     List ts    = NIL;                   /* List of types for fields        */
1180     Int  n     = length(fs);
1181     Int  alpha = newTyvars(2+n);
1182     Int  i;
1183     List fs1;
1184
1185     /* Calculate type and translation for each expr in the field list      */
1186     for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1187         snd(hd(fs1)) = typeExpr(line,snd(hd(fs1)));
1188         bindTv(i,typeIs,typeOff);
1189     }
1190
1191     clearMarks();
1192     mapProc(markAssumList,defnBounds);
1193     mapProc(markAssumList,varsBounds);
1194     mapProc(markPred,preds);
1195     markBtyvs();
1196
1197     for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1198         resetGenerics();
1199         ts = cons(generalize(NIL,copyTyvar(i)),ts);
1200     }
1201     ts = rev(ts);
1202
1203     /* Type check expression to be updated                                 */
1204     fst3(snd(e)) = typeExpr(line,fst3(snd(e)));
1205     bindTv(alpha,typeIs,typeOff);
1206
1207     for (; nonNull(cs); cs=tl(cs)) {    /* Loop through constrs            */
1208         Name c  = hd(cs);
1209         List ta = replicate(name(c).arity,NIL);
1210         Type td, tr;
1211         Int  od, or;
1212
1213         tcMode = NEW_PATTERN;           /* Domain type                     */
1214         instantiate(name(c).type);
1215         tcMode = EXPRESSION;
1216         td     = typeIs;
1217         od     = typeOff;
1218         for (; nonNull(predsAre); predsAre=tl(predsAre))
1219             assumeEvid(hd(predsAre),typeOff);
1220
1221         if (whatIs(typeIs)==RANK2) {
1222             ERRMSG(line) "Sorry, record update syntax cannot currently be "
1223                          "used for datatypes with polymorphic components"
1224             EEND;
1225         }
1226
1227         instantiate(name(c).type);      /* Range type                      */
1228         tr = typeIs;
1229         or = typeOff;
1230         for (; nonNull(predsAre); predsAre=tl(predsAre))
1231             assumeEvid(hd(predsAre),typeOff);
1232
1233         for (fs1=fs, i=1; nonNull(fs1); fs1=tl(fs1), i++) {
1234             Int n    = sfunPos(fst(hd(fs1)),c);
1235             Cell ta1 = ta;
1236             for (; n>1; n--)
1237                 ta1 = tl(ta1);
1238             hd(ta1) = mkInt(i);
1239         }
1240
1241         for (; nonNull(ta); ta=tl(ta)) {        /* For each cfun arg       */
1242             if (nonNull(hd(ta))) {              /* Field to updated?       */
1243                 Int  n = intOf(hd(ta));
1244                 Cell f = fs;
1245                 Cell t = ts;
1246                 for (; n-- > 1; f=tl(f), t=tl(t))
1247                     ;
1248                 f = hd(f);
1249                 t = hd(t);
1250                 instantiate(t);
1251                 shouldBe(line,snd(f),e,update,arg(fun(tr)),or);
1252             }                                   /* Unmentioned component   */
1253             else if (!unify(arg(fun(td)),od,arg(fun(tr)),or))
1254                 internal("typeUpdFlds");
1255
1256             tr = arg(tr);
1257             td = arg(td);
1258         }
1259
1260         inferType(td,od);                       /* Check domain type       */
1261         shouldBe(line,fst3(snd(e)),e,update,aVar,alpha);
1262         inferType(tr,or);                       /* Check range type        */
1263         shouldBe(line,e,NIL,update,aVar,alpha+1);
1264     }
1265     /* (typeIs,typeOff) still carry the result type when we exit the loop  */
1266 }
1267
1268 static Cell local typeFreshPat(l,p)    /* find type of pattern, assigning  */
1269 Int  l;                                /* fresh type variables to each var */
1270 Cell p; {                              /* bound in the pattern             */
1271     tcMode = NEW_PATTERN;
1272     p      = typeExpr(l,p);
1273     tcMode = EXPRESSION;
1274     return p;
1275 }
1276
1277 /* --------------------------------------------------------------------------
1278  * Type check group of bindings:
1279  * ------------------------------------------------------------------------*/
1280
1281 static Void local typeBindings(bs)      /* type check a binding group      */
1282 List bs; {
1283     Bool usesPatBindings = FALSE;       /* TRUE => pattern binding in bs   */
1284     Bool usesUntypedVar  = FALSE;       /* TRUE => var bind w/o type decl  */
1285     List bs1;
1286
1287     /* The following loop is used to determine whether the monomorphism    */
1288     /* restriction should be applied.  It could be written marginally more */
1289     /* efficiently by using breaks, but clarity is more important here ... */
1290
1291     for (bs1=bs; nonNull(bs1); bs1=tl(bs1)) {  /* Analyse binding group    */
1292         Cell b = hd(bs1);
1293         if (!isVar(fst(b)))
1294             usesPatBindings = TRUE;
1295         else if (isNull(fst(hd(snd(snd(b)))))           /* no arguments    */
1296                  && whatIs(fst(snd(b)))==IMPDEPS)       /* implicitly typed*/
1297             usesUntypedVar  = TRUE;
1298     }
1299
1300     if (usesPatBindings || usesUntypedVar)
1301         monorestrict(bs);
1302     else
1303         unrestricted(bs);
1304
1305     mapProc(removeTypeSigs,bs);                /* Remove binding type info */
1306     hd(varsBounds) = revOnto(hd(defnBounds),   /* transfer completed assmps*/
1307                              hd(varsBounds));  /* out of defnBounds        */
1308     hd(defnBounds) = NIL;
1309     hd(depends)    = NIL;
1310 }
1311
1312 static Void local removeTypeSigs(b)    /* Remove type info from a binding  */
1313 Cell b; {
1314     snd(b) = snd(snd(b));
1315 }
1316
1317 /* --------------------------------------------------------------------------
1318  * Type check a restricted binding group:
1319  * ------------------------------------------------------------------------*/
1320
1321 static Void local monorestrict(bs)      /* Type restricted binding group   */
1322 List bs; {
1323     List savePreds = preds;
1324     Int  line      = isVar(fst(hd(bs))) ? rhsLine(snd(hd(snd(snd(hd(bs))))))
1325                                         : rhsLine(snd(snd(snd(hd(bs)))));
1326     hd(defnBounds) = NIL;
1327     hd(depends)    = NODEPENDS;         /* No need for dependents here     */
1328
1329     preds = NIL;                        /* Type check the bindings         */
1330     mapProc(restrictedBindAss,bs);
1331     mapProc(typeBind,bs);
1332     normPreds(line);
1333     elimTauts();
1334     preds = revOnto(preds,savePreds);
1335
1336     clearMarks();                       /* Mark fixed variables            */
1337     mapProc(markAssumList,tl(defnBounds));
1338     mapProc(markAssumList,tl(varsBounds));
1339     mapProc(markPred,preds);
1340     markBtyvs();
1341
1342     if (isNull(tl(defnBounds))) {       /* Top-level may need defaulting   */
1343         normPreds(line);
1344         if (nonNull(preds) && resolveDefs(genvarAnyAss(hd(defnBounds))))
1345             elimTauts();
1346
1347         clearMarks();
1348         reducePreds();
1349         if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4?     */
1350             elimTauts();
1351
1352         if (nonNull(preds)) {           /* Look for unresolved overloading */
1353             Cell v   = isVar(fst(hd(bs))) ? fst(hd(bs)) : hd(fst(hd(bs)));
1354             Cell ass = findInAssumList(textOf(v),hd(varsBounds));
1355             preds    = scSimplify(preds);
1356
1357             ERRMSG(line) "Unresolved top-level overloading" ETHEN
1358             ERRTEXT     "\n*** Binding             : %s", textToStr(textOf(v))
1359             ETHEN
1360             if (nonNull(ass)) {
1361                 ERRTEXT "\n*** Inferred type       : " ETHEN ERRTYPE(snd(ass));
1362             }
1363             ERRTEXT     "\n*** Outstanding context : " ETHEN
1364                                                 ERRCONTEXT(copyPreds(preds));
1365             ERRTEXT     "\n"
1366             EEND;
1367         }
1368     }
1369
1370     map1Proc(genBind,NIL,bs);           /* Generalize types of def'd vars  */
1371 }
1372
1373 static Void local restrictedBindAss(b)  /* Make assums for vars in binding */
1374 Cell b; {                               /* gp with restricted overloading  */
1375
1376     if (isVar(fst(b))) {                /* function-binding?               */
1377         Cell t = fst(snd(b));
1378         if (whatIs(t)==IMPDEPS)  {      /* Discard implicitly typed deps   */
1379             fst(snd(b)) = t = NIL;      /* in a restricted binding group.  */
1380         }
1381         fst(snd(b)) = localizeBtyvs(t);
1382         restrictedAss(rhsLine(snd(hd(snd(snd(b))))), fst(b), t);
1383     } else {                            /* pattern-binding?                */
1384         List vs   = fst(b);
1385         List ts   = fst(snd(b));
1386         Int  line = rhsLine(snd(snd(snd(b))));
1387
1388         for (; nonNull(vs); vs=tl(vs)) {
1389             if (nonNull(ts)) {
1390                 restrictedAss(line,hd(vs),hd(ts)=localizeBtyvs(hd(ts)));
1391                 ts = tl(ts);
1392             } else {
1393                 restrictedAss(line,hd(vs),NIL);
1394             }
1395         }
1396     }
1397 }
1398
1399 static Void local restrictedAss(l,v,t) /* Assume that type of binding var v*/
1400 Int  l;                                /* is t (if nonNull) in restricted  */
1401 Cell v;                                /* binding group                    */
1402 Type t; {
1403     newDefnBind(v,t);
1404     if (nonNull(predsAre)) {
1405         ERRMSG(l) "Explicit overloaded type for \"%s\"",textToStr(textOf(v))
1406         ETHEN
1407         ERRTEXT   " not permitted in restricted binding"
1408         EEND;
1409     }
1410 }
1411
1412 /* --------------------------------------------------------------------------
1413  * Unrestricted binding group:
1414  * ------------------------------------------------------------------------*/
1415
1416 static Void local unrestricted(bs)      /* Type unrestricted binding group */
1417 List bs; {
1418     List savePreds = preds;
1419     List imps      = NIL;               /* Implicitly typed bindings       */
1420     List exps      = NIL;               /* Explicitly typed bindings       */
1421     List bs1;
1422
1423     /* ----------------------------------------------------------------------
1424      * STEP 1: Separate implicitly typed bindings from explicitly typed 
1425      * bindings and do a dependency analyis, where f depends on g iff f
1426      * is implicitly typed and involves a call to g.
1427      * --------------------------------------------------------------------*/
1428
1429     for (; nonNull(bs); bs=tl(bs)) {
1430         Cell b = hd(bs);
1431         if (whatIs(fst(snd(b)))==IMPDEPS)
1432             imps = cons(b,imps);        /* N.B. New lists are built to     */
1433         else                            /* avoid breaking the original     */
1434             exps = cons(b,exps);        /* list structure for bs.          */
1435     }
1436
1437     for (bs=imps; nonNull(bs); bs=tl(bs)) {
1438         Cell b  = hd(bs);               /* Restrict implicitly typed dep   */
1439         List ds = snd(fst(snd(b)));     /* lists to bindings in imps       */
1440         List cs = NIL;
1441         while (nonNull(ds)) {
1442             bs1 = tl(ds);
1443             if (cellIsMember(hd(ds),imps)) {
1444                 tl(ds) = cs;
1445                 cs     = ds;
1446             }
1447             ds = bs1;
1448         }
1449         fst(snd(b)) = cs;
1450     }
1451     imps = itbscc(imps);                /* Dependency analysis on imps     */
1452     for (bs=imps; nonNull(bs); bs=tl(bs))
1453         for (bs1=hd(bs); nonNull(bs1); bs1=tl(bs1))
1454             fst(snd(hd(bs1))) = NIL;    /* reset imps type fields          */
1455
1456 #ifdef DEBUG_DEPENDS
1457     Printf("Binding group:");
1458     for (bs1=imps; nonNull(bs1); bs1=tl(bs1)) {
1459         Printf(" [imp:");
1460         for (bs=hd(bs1); nonNull(bs); bs=tl(bs))
1461             Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1462         Printf("]");
1463     }
1464     if (nonNull(exps)) {
1465         Printf(" [exp:");
1466         for (bs=exps; nonNull(bs); bs=tl(bs))
1467             Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1468         Printf("]");
1469     }
1470     Printf("\n");
1471 #endif
1472
1473     /* ----------------------------------------------------------------------
1474      * STEP 2: Add type assumptions about any explicitly typed variable.
1475      * --------------------------------------------------------------------*/
1476
1477     for (bs=exps; nonNull(bs); bs=tl(bs)) {
1478         fst(snd(hd(bs))) = localizeBtyvs(fst(snd(hd(bs))));
1479         hd(varsBounds)   = cons(pair(fst(hd(bs)),fst(snd(hd(bs)))),
1480                                 hd(varsBounds));
1481     }
1482
1483     /* ----------------------------------------------------------------------
1484      * STEP 3: Calculate types for each group of implicitly typed bindings.
1485      * --------------------------------------------------------------------*/
1486
1487     for (; nonNull(imps); imps=tl(imps)) {
1488         Cell b   = hd(hd(imps));
1489         Int line = isVar(fst(b)) ? rhsLine(snd(hd(snd(snd(b)))))
1490                                  : rhsLine(snd(snd(snd(b))));
1491         hd(defnBounds) = NIL;
1492         hd(depends)    = NIL;
1493         for (bs1=hd(imps); nonNull(bs1); bs1=tl(bs1))
1494             newDefnBind(fst(hd(bs1)),NIL);
1495
1496         preds = NIL;
1497         mapProc(typeBind,hd(imps));
1498
1499         clearMarks();
1500         mapProc(markAssumList,tl(defnBounds));
1501         mapProc(markAssumList,tl(varsBounds));
1502         mapProc(markPred,savePreds);
1503         markBtyvs();
1504
1505         normPreds(line);
1506         savePreds = elimOuterPreds(savePreds);
1507         if (nonNull(preds) && resolveDefs(genvarAllAss(hd(defnBounds)))) {
1508             savePreds = elimOuterPreds(savePreds);
1509         }
1510
1511         map1Proc(genBind,preds,hd(imps));
1512         if (nonNull(preds)) {
1513             map1Proc(addEvidParams,preds,hd(depends));
1514             map1Proc(qualifyBinding,preds,hd(imps));
1515         }
1516
1517         h98CheckType(line,"inferred type",
1518                         fst(hd(hd(defnBounds))),snd(hd(hd(defnBounds))));
1519         hd(varsBounds) = revOnto(hd(defnBounds),hd(varsBounds));
1520     }
1521
1522     /* ----------------------------------------------------------------------
1523      * STEP 4: Now infer a type for each explicitly typed variable and
1524      * check for compatibility with the declared type.
1525      * --------------------------------------------------------------------*/
1526
1527     for (; nonNull(exps); exps=tl(exps)) {
1528         static String extbind = "explicitly typed binding";
1529         Cell b    = hd(exps);
1530         List alts = snd(snd(b));
1531         Int  line = rhsLine(snd(hd(alts)));
1532         Type t;
1533         Int  o;
1534         Int  m;
1535         List ps;
1536
1537         hd(defnBounds) = NIL;
1538         hd(depends)    = NODEPENDS;
1539         preds          = NIL;
1540
1541         instantiate(fst(snd(b)));
1542         o              = typeOff;
1543         m              = typeFree;
1544         t              = dropRank2(typeIs,o,m);
1545         ps             = makePredAss(predsAre,o);
1546
1547         enterPendingBtyvs();
1548         for (; nonNull(alts); alts=tl(alts))
1549             typeAlt(extbind,fst(b),hd(alts),t,o,m);
1550         leavePendingBtyvs();
1551
1552         if (nonNull(ps))                /* Add dict params, if necessary   */
1553             qualifyBinding(ps,b);
1554
1555         clearMarks();
1556         mapProc(markAssumList,tl(defnBounds));
1557         mapProc(markAssumList,tl(varsBounds));
1558         mapProc(markPred,savePreds);
1559         markBtyvs();
1560
1561         savePreds = elimPredsUsing(ps,savePreds);
1562         if (nonNull(preds)) {
1563             List vs = NIL;
1564             Int  i  = 0;
1565             for (; i<m; ++i)
1566                 vs = cons(mkInt(o+i),vs);
1567             if (resolveDefs(vs))
1568                 savePreds = elimPredsUsing(ps,savePreds);
1569             if (nonNull(preds)) {
1570                 clearMarks();
1571                 reducePreds();
1572                 if (nonNull(preds) && resolveDefs(vs))
1573                     savePreds = elimPredsUsing(ps,savePreds);
1574             }
1575         }
1576
1577         resetGenerics();                /* Make sure we're general enough  */
1578         ps = copyPreds(ps);
1579         t  = generalize(ps,liftRank2(t,o,m));
1580
1581         if (!sameSchemes(t,fst(snd(b))))
1582             tooGeneral(line,fst(b),fst(snd(b)),t);
1583         h98CheckType(line,"inferred type",fst(b),t);
1584
1585         if (nonNull(preds))             /* Check context was strong enough */
1586             cantEstablish(line,extbind,fst(b),t,ps);
1587     }
1588
1589     preds          = savePreds;                 /* Restore predicates      */
1590     hd(defnBounds) = NIL;
1591 }
1592
1593 #define  SCC             itbscc         /* scc for implicitly typed binds  */
1594 #define  LOWLINK         itblowlink
1595 #define  DEPENDS(t)      fst(snd(t))
1596 #define  SETDEPENDS(c,v) fst(snd(c))=v
1597 #include "scc.c"
1598 #undef   SETDEPENDS
1599 #undef   DEPENDS
1600 #undef   LOWLINK
1601 #undef   SCC
1602
1603 static Void local addEvidParams(qs,v)  /* overwrite VARID/OPCELL v with    */
1604 List qs;                               /* application of variable to evid. */
1605 Cell v; {                              /* parameters given by qs           */
1606     if (nonNull(qs)) {
1607         Cell nv;
1608
1609         if (!isVar(v))
1610             internal("addEvidParams");
1611
1612         for (nv=mkVar(textOf(v)); nonNull(tl(qs)); qs=tl(qs))
1613             nv = ap(nv,thd3(hd(qs)));
1614         fst(v) = nv;
1615         snd(v) = thd3(hd(qs));
1616     }
1617 }
1618
1619 /* --------------------------------------------------------------------------
1620  * Type check bodies of class and instance declarations:
1621  * ------------------------------------------------------------------------*/
1622
1623 static Void local typeClassDefn(c)      /* Type check implementations of   */
1624 Class c; {                              /* defaults for class c            */
1625
1626     /* ----------------------------------------------------------------------
1627      * Generate code for default dictionary builder function:
1628      *
1629      *   class.C sc1 ... scn d = let v1 ... = ...
1630      *                               vm ... = ...
1631      *                           in Make.C sc1 ... scn v1 ... vm
1632      *
1633      * where sci are superclass dictionary parameters, vj are implementations
1634      * for member functions, either taken from defaults, or using "error" to
1635      * produce a suitable error message.  (Additional line number values must
1636      * be added at appropriate places but, for clarity, these are not shown
1637      * above.)
1638      * --------------------------------------------------------------------*/
1639
1640     Int  beta   = newKindedVars(cclass(c).kinds);
1641     List params = makePredAss(cclass(c).supers,beta);
1642     Cell body   = cclass(c).dcon;
1643     Cell pat    = body;
1644     List mems   = cclass(c).members;
1645     List defs   = cclass(c).defaults;
1646     List dsels  = cclass(c).dsels;
1647     Cell d      = inventDictVar();
1648     List args   = NIL;
1649     List locs   = NIL;
1650     Cell l      = mkInt(cclass(c).line);
1651     List ps;
1652
1653     for (ps=params; nonNull(ps); ps=tl(ps)) {
1654         Cell v = thd3(hd(ps));
1655         body   = ap(body,v);
1656         pat    = ap(pat,inventVar());
1657         args   = cons(v,args);
1658     }
1659     args   = revOnto(args,singleton(d));
1660     params = appendOnto(params,
1661                         singleton(triple(cclass(c).head,mkInt(beta),d)));
1662
1663     for (; nonNull(mems); mems=tl(mems)) {
1664         Cell v   = inventVar();         /* Pick a name for component       */
1665         Cell imp = NIL;
1666
1667         if (nonNull(defs)) {            /* Look for default implementation */
1668             imp  = hd(defs);
1669             defs = tl(defs);
1670         }
1671
1672         if (isNull(imp)) {              /* Generate undefined member msg   */
1673             static String header = "Undefined member: ";
1674             String name = textToStr(name(hd(mems)).text);
1675             char   msg[FILENAME_MAX+1];
1676             Int    i;
1677             Int    j;
1678
1679             for (i=0; i<FILENAME_MAX && header[i]!='\0'; i++)
1680                 msg[i] = header[i];
1681             for (j=0; (i+j)<FILENAME_MAX && name[j]!='\0'; j++)
1682                 msg[i+j] = name[j];
1683             msg[i+j] = '\0';
1684
1685             imp = pair(v,singleton(pair(NIL,ap(l,ap(nameError,
1686                                                     mkStr(findText(msg)))))));
1687         }
1688         else {                          /* Use default implementation      */
1689             fst(imp) = v;
1690             typeMember("default member binding",
1691                        hd(mems),
1692                        snd(imp),
1693                        params,
1694                        cclass(c).head,
1695                        beta);
1696         }
1697
1698         locs = cons(imp,locs);
1699         body = ap(body,v);
1700         pat  = ap(pat,v);
1701     }
1702     body     = ap(l,body);
1703     if (nonNull(locs))
1704         body = ap(LETREC,pair(singleton(locs),body));
1705     name(cclass(c).dbuild).defn
1706              = singleton(pair(args,body));
1707
1708     name(cclass(c).dbuild).inlineMe = TRUE;
1709     genDefns = cons(cclass(c).dbuild,genDefns);
1710     cclass(c).defaults = NIL;
1711
1712     /* ----------------------------------------------------------------------
1713      * Generate code for superclass and member function selectors:
1714      * --------------------------------------------------------------------*/
1715
1716     args = getArgs(pat);
1717     pat  = singleton(pat);
1718     for (; nonNull(dsels); dsels=tl(dsels)) {
1719         name(hd(dsels)).defn = singleton(pair(pat,ap(l,hd(args))));
1720         name(hd(dsels)).inlineMe = TRUE;
1721         args                 = tl(args);
1722         genDefns             = cons(hd(dsels),genDefns);
1723     }
1724     for (mems=cclass(c).members; nonNull(mems); mems=tl(mems)) {
1725         name(hd(mems)).defn = singleton(pair(pat,ap(mkInt(name(hd(mems)).line),
1726                                                     hd(args))));
1727         args                = tl(args);
1728         genDefns            = cons(hd(mems),genDefns);
1729     }
1730 }
1731
1732 static Void local typeInstDefn(in)      /* Type check implementations of   */
1733 Inst in; {                              /* member functions for instance in*/
1734
1735     /* ----------------------------------------------------------------------
1736      * Generate code for instance specific dictionary builder function:
1737      *
1738      *   inst.maker d1 ... dn = let sc1 = ...
1739      *                                  .
1740      *                                  .
1741      *                                  .
1742      *                              scm = ...
1743      *                              d   = f (class.C sc1 ... scm d)
1744      *           omit if the   /    f (Make.C sc1' ... scm' v1' ... vk')
1745      *          instance decl {         = let vj ... = ...
1746      *           has no imps   \          in Make.C sc1' ... scm' ... vj ...
1747      *                          in d
1748      *
1749      * where sci are superclass dictionaries, d and f are new names, vj
1750      * is a newly generated name corresponding to the implementation of a
1751      * member function.  (Additional line number values must be added at
1752      * appropriate places but, for clarity, these are not shown above.)
1753      * --------------------------------------------------------------------*/
1754
1755     Int  alpha   = newKindedVars(cclass(inst(in).c).kinds);
1756     List supers  = makePredAss(cclass(inst(in).c).supers,alpha);
1757     Int  beta    = newKindedVars(inst(in).kinds);
1758     List params  = makePredAss(inst(in).specifics,beta);
1759     Cell d       = inventDictVar();
1760     List evids   = cons(triple(inst(in).head,mkInt(beta),d),
1761                         appendOnto(dupList(params),supers));
1762
1763     List imps    = inst(in).implements;
1764     Cell l       = mkInt(inst(in).line);
1765     Cell dictDef = cclass(inst(in).c).dbuild;
1766     List args    = NIL;
1767     List locs    = NIL;
1768     List ps;
1769
1770     if (!unifyPred(cclass(inst(in).c).head,alpha,inst(in).head,beta))
1771         internal("typeInstDefn");
1772
1773     for (ps=params; nonNull(ps); ps=tl(ps))     /* Build arglist           */
1774         args = cons(thd3(hd(ps)),args);
1775     args = rev(args);
1776
1777     for (ps=supers; nonNull(ps); ps=tl(ps)) {   /* Superclass dictionaries */
1778         Cell pi = hd(ps);
1779         Cell ev = scEntail(params,fst3(pi),intOf(snd3(pi)),0);
1780         if (isNull(ev))
1781             ev = inEntail(evids,fst3(pi),intOf(snd3(pi)),0);
1782         if (isNull(ev)) {
1783             clearMarks();
1784             ERRMSG(inst(in).line) "Cannot build superclass instance" ETHEN
1785             ERRTEXT "\n*** Instance            : " ETHEN
1786                 ERRPRED(copyPred(inst(in).head,beta));
1787             ERRTEXT "\n*** Context supplied    : " ETHEN
1788                 ERRCONTEXT(copyPreds(params));
1789             ERRTEXT "\n*** Required superclass : " ETHEN
1790                 ERRPRED(copyPred(fst3(pi),intOf(snd3(pi))));
1791             ERRTEXT "\n"
1792             EEND;
1793         }
1794         locs    = cons(pair(thd3(pi),singleton(pair(NIL,ap(l,ev)))),locs);
1795         dictDef = ap(dictDef,thd3(pi));
1796     }
1797     dictDef = ap(dictDef,d);
1798
1799     if (isNull(imps))                           /* No implementations      */
1800         locs = cons(pair(d,singleton(pair(NIL,ap(l,dictDef)))),locs);
1801     else {                                      /* Implementations supplied*/
1802         List mems  = cclass(inst(in).c).members;
1803         Cell f     = inventVar();
1804         Cell pat   = cclass(inst(in).c).dcon;
1805         Cell res   = pat;
1806         List locs1 = NIL;
1807
1808         locs       = cons(pair(d,singleton(pair(NIL,ap(l,ap(f,dictDef))))),
1809                           locs);
1810
1811         for (ps=supers; nonNull(ps); ps=tl(ps)){/* Add param for each sc   */
1812             Cell v = inventVar();
1813             pat    = ap(pat,v);
1814             res    = ap(res,v);
1815         }
1816
1817         for (; nonNull(mems); mems=tl(mems)) {  /* For each member:        */
1818             Cell v   = inventVar();
1819             Cell imp = NIL;
1820
1821             if (nonNull(imps)) {                /* Look for implementation */
1822                 imp  = hd(imps);
1823                 imps = tl(imps);
1824             }
1825
1826             if (isNull(imp)) {                  /* If none, f will copy    */
1827                 pat = ap(pat,v);                /* its argument unchanged  */
1828                 res = ap(res,v);
1829             }
1830             else {                              /* Otherwise, add the impl */
1831                 pat      = ap(pat,WILDCARD);    /* to f as a local defn    */
1832                 res      = ap(res,v);
1833                 typeMember("instance member binding",
1834                            hd(mems),
1835                            snd(imp),
1836                            evids,
1837                            inst(in).head,
1838                            beta);
1839                 locs1    = cons(pair(v,snd(imp)),locs1);
1840             }
1841         }
1842         res = ap(l,res);
1843         if (nonNull(locs1))                     /* Build the body of f     */
1844             res = ap(LETREC,pair(singleton(locs1),res));
1845         pat  = singleton(pat);                  /* And the arglist for f   */
1846         locs = cons(pair(f,singleton(pair(pat,res))),locs);
1847     }
1848     d = ap(l,d);
1849
1850     name(inst(in).builder).defn                 /* Register builder imp    */
1851              = singleton(pair(args,ap(LETREC,pair(singleton(locs),d))));
1852
1853     name(inst(in).builder).inlineMe   = TRUE;
1854     name(inst(in).builder).isDBuilder = TRUE;
1855     genDefns = cons(inst(in).builder,genDefns);
1856 }
1857
1858 static Void local typeMember(wh,mem,alts,evids,head,beta)
1859 String wh;                              /* Type check alternatives alts of */
1860 Name   mem;                             /* member mem for inst type head   */
1861 Cell   alts;                            /* at offset beta using predicate  */
1862 List   evids;                           /* assignment evids                */
1863 Cell   head;
1864 Int    beta; {
1865     Int  line = rhsLine(snd(hd(alts)));
1866     Type t;
1867     Int  o;
1868     Int  m;
1869     List ps;
1870     List qs;
1871     Type rt;
1872
1873 #ifdef DEBUG_TYPES
1874     Printf("\nType check member: ");
1875     printExp(stdout,mem);
1876     Printf(" :: ");
1877     printType(stdout,name(mem).type);
1878     Printf("\n   for the instance: ");
1879     printPred(stdout,head);
1880     Printf("\n");
1881 #endif
1882
1883     instantiate(name(mem).type);        /* Find required type              */
1884     o  = typeOff;
1885     m  = typeFree;
1886     t  = dropRank2(typeIs,o,m);
1887     ps = makePredAss(predsAre,o);
1888     if (!unifyPred(hd(predsAre),typeOff,head,beta))
1889         internal("typeMember1");
1890     clearMarks();
1891     qs = copyPreds(ps);
1892     rt = generalize(qs,liftRank2(t,o,m));
1893
1894 #ifdef DEBUG_TYPES
1895     Printf("Required type is: ");
1896     printType(stdout,rt);
1897     Printf("\n");
1898 #endif
1899
1900     hd(defnBounds) = NIL;               /* Type check each alternative     */
1901     hd(depends)    = NODEPENDS;
1902     enterPendingBtyvs();
1903     for (preds=NIL; nonNull(alts); alts=tl(alts)) {
1904         typeAlt(wh,mem,hd(alts),t,o,m);
1905         qualify(tl(ps),hd(alts));       /* Add any extra dict params       */
1906     }
1907     leavePendingBtyvs();
1908
1909     evids = appendOnto(dupList(tl(ps)), /* Build full complement of dicts  */
1910                        evids);
1911     clearMarks();
1912     qs = elimPredsUsing(evids,NIL);
1913     if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
1914         qs = elimPredsUsing(evids,qs);
1915     if (nonNull(qs)) {
1916         ERRMSG(line)
1917                 "Implementation of %s requires extra context",
1918                  textToStr(name(mem).text) ETHEN
1919         ERRTEXT "\n*** Expected type   : " ETHEN ERRTYPE(rt);
1920         ERRTEXT "\n*** Missing context : " ETHEN ERRCONTEXT(copyPreds(qs));
1921         ERRTEXT "\n"
1922         EEND;
1923     }
1924
1925     resetGenerics();                    /* Make sure we're general enough  */
1926     ps = copyPreds(ps);
1927     t  = generalize(ps,liftRank2(t,o,m));
1928 #ifdef DEBUG_TYPES
1929     Printf("   Inferred type is: ");
1930     printType(stdout,t);
1931     Printf("\n");
1932 #endif
1933     if (!sameSchemes(t,rt))
1934         tooGeneral(line,mem,rt,t);
1935     if (nonNull(preds))
1936         cantEstablish(line,wh,mem,t,ps);
1937 }
1938
1939 /* --------------------------------------------------------------------------
1940  * Type check bodies of bindings:
1941  * ------------------------------------------------------------------------*/
1942
1943 static Void local typeBind(b)          /* Type check binding               */
1944 Cell b; {
1945     if (isVar(fst(b))) {                               /* function binding */
1946         Cell ass = findTopBinding(fst(b));
1947         Int  beta;
1948
1949         if (isNull(ass))
1950             internal("typeBind");
1951
1952         beta = intOf(defType(snd(ass)));
1953         enterPendingBtyvs();
1954         map2Proc(typeDefAlt,beta,fst(b),snd(snd(b)));
1955         leavePendingBtyvs();
1956     }
1957     else {                                             /* pattern binding  */
1958         static String lhsPat = "lhs pattern";
1959         static String rhs    = "right hand side";
1960         Int  beta            = newTyvars(1);
1961         Pair pb              = snd(snd(b));
1962         Int  l               = rhsLine(snd(pb));
1963
1964         tcMode  = OLD_PATTERN;
1965         enterPendingBtyvs();
1966         fst(pb) = patBtyvs(fst(pb));
1967         check(l,fst(pb),NIL,lhsPat,aVar,beta);
1968         tcMode  = EXPRESSION;
1969         snd(pb) = typeRhs(snd(pb));
1970         shouldBe(l,rhsExpr(snd(pb)),NIL,rhs,aVar,beta);
1971         doneBtyvs(l);
1972         leavePendingBtyvs();
1973     }
1974 }
1975
1976 static Void local typeDefAlt(beta,v,a) /* type check alt in func. binding  */
1977 Int  beta;
1978 Cell v;
1979 Pair a; {
1980     static String valDef = "function binding";
1981     typeAlt(valDef,v,a,aVar,beta,0);
1982 }
1983
1984 static Cell local typeRhs(e)           /* check type of rhs of definition  */
1985 Cell e; {
1986     switch (whatIs(e)) {
1987         case GUARDED : {   Int beta = newTyvars(1);
1988                            map1Proc(guardedType,beta,snd(e));
1989                            tyvarType(beta);
1990                        }
1991                        break;
1992
1993         case LETREC  : enterBindings();
1994                        enterSkolVars();
1995                        mapProc(typeBindings,fst(snd(e)));
1996                        snd(snd(e)) = typeRhs(snd(snd(e)));
1997                        leaveBindings();
1998                        leaveSkolVars(rhsLine(snd(snd(e))),typeIs,typeOff,0);
1999                        break;
2000
2001         case RSIGN   : fst(snd(e)) = typeRhs(fst(snd(e)));
2002                        shouldBe(rhsLine(fst(snd(e))),
2003                                 rhsExpr(fst(snd(e))),NIL,
2004                                 "result type",
2005                                 snd(snd(e)),0);
2006                        return fst(snd(e));
2007
2008         default      : snd(e) = typeExpr(intOf(fst(e)),snd(e));
2009                        break;
2010     }
2011     return e;
2012 }
2013
2014 static Void local guardedType(beta,gded)/* check type of guard (li,(gd,ex))*/
2015 Int  beta;                             /* should have gd :: Bool,          */
2016 Cell gded; {                           /*             ex :: (var,beta)     */
2017     static String guarded = "guarded expression";
2018     static String guard   = "guard";
2019     Int line = intOf(fst(gded));
2020
2021     gded     = snd(gded);
2022     check(line,fst(gded),NIL,guard,typeBool,0);
2023     check(line,snd(gded),NIL,guarded,aVar,beta);
2024 }
2025
2026 Cell rhsExpr(rhs)                      /* find first expression on a rhs   */
2027 Cell rhs; {
2028     switch (whatIs(rhs)) {
2029         case GUARDED : return snd(snd(hd(snd(rhs))));
2030         case LETREC  : return rhsExpr(snd(snd(rhs)));
2031         case RSIGN   : return rhsExpr(fst(snd(rhs)));
2032         default      : return snd(rhs);
2033     }
2034 }
2035
2036 Int rhsLine(rhs)                       /* find line number associated with */
2037 Cell rhs; {                            /* a right hand side                */
2038     switch (whatIs(rhs)) {
2039         case GUARDED : return intOf(fst(hd(snd(rhs))));
2040         case LETREC  : return rhsLine(snd(snd(rhs)));
2041         case RSIGN   : return rhsLine(fst(snd(rhs)));
2042         default      : return intOf(fst(rhs));
2043     }
2044 }
2045
2046 /* --------------------------------------------------------------------------
2047  * Calculate generalization of types and compare with declared type schemes:
2048  * ------------------------------------------------------------------------*/
2049
2050 static Void local genBind(ps,b)         /* Generalize the type of each var */
2051 List ps;                                /* defined in binding b, qualifying*/
2052 Cell b; {                               /* each with the predicates in ps. */
2053     Cell v = fst(b);
2054     Cell t = fst(snd(b));
2055
2056     if (isVar(fst(b)))
2057         genAss(rhsLine(snd(hd(snd(snd(b))))),ps,v,t);
2058     else {
2059         Int line = rhsLine(snd(snd(snd(b))));
2060         for (; nonNull(v); v=tl(v)) {
2061             Type ty = NIL;
2062             if (nonNull(t)) {
2063                 ty = hd(t);
2064                 t  = tl(t);
2065             }
2066             genAss(line,ps,hd(v),ty);
2067         }
2068     }
2069 }
2070
2071 static Void local genAss(l,ps,v,dt)     /* Calculate inferred type of v and*/
2072 Int  l;                                 /* compare with declared type, dt, */
2073 List ps;                                /* if given & check for ambiguity. */
2074 Cell v;
2075 Type dt; {
2076     Cell ass = findTopBinding(v);
2077
2078     if (isNull(ass))
2079         internal("genAss");
2080
2081     snd(ass) = genTest(l,v,ps,dt,aVar,intOf(defType(snd(ass))));
2082
2083 #ifdef DEBUG_TYPES
2084     printExp(stdout,v);
2085     Printf(" :: ");
2086     printType(stdout,snd(ass));
2087     Printf("\n");
2088 #endif
2089 }
2090
2091 static Type local genTest(l,v,ps,dt,t,o)/* Generalize and test inferred    */
2092 Int  l;                                 /* type (t,o) with context ps      */
2093 Cell v;                                 /* against declared type dt for v. */
2094 List ps;
2095 Type dt;
2096 Type t;
2097 Int  o; {
2098     Type bt = NIL;                      /* Body of inferred type           */
2099     Type it = NIL;                      /* Full inferred type              */
2100
2101     resetGenerics();                    /* Calculate Haskell typing        */
2102     ps = copyPreds(ps);
2103     bt = copyType(t,o);
2104     it = generalize(ps,bt);
2105
2106     if (nonNull(dt)) {                  /* If a declared type was given,   */
2107         instantiate(dt);                /* check body for match.           */
2108         if (!equalTypes(typeIs,bt))
2109             tooGeneral(l,v,dt,it);
2110     }
2111     else if (nonNull(ps))               /* Otherwise test for ambiguity in */
2112         if (isAmbiguous(it))            /* inferred type.                  */
2113             ambigError(l,"inferred type",v,it);
2114
2115     return it;
2116 }
2117
2118 static Type local generalize(qs,t)      /* calculate generalization of t   */
2119 List qs;                                /* having already marked fixed vars*/
2120 Type t; {                               /* with qualifying preds qs        */
2121     if (nonNull(qs))
2122         t = ap(QUAL,pair(qs,t));
2123     if (nonNull(genericVars)) {
2124         Kind k  = STAR;
2125         List vs = genericVars;
2126         for (; nonNull(vs); vs=tl(vs)) {
2127             Tyvar *tyv = tyvar(intOf(hd(vs)));
2128             Kind   ka  = tyv->kind;
2129             k = ap(ka,k);
2130         }
2131         t = mkPolyType(k,t);
2132 #ifdef DEBUG_KINDS
2133     Printf("Generalized type: ");
2134     printType(stdout,t);
2135     Printf(" ::: ");
2136     printKind(stdout,k);
2137     Printf("\n");
2138 #endif
2139     }
2140     return t;
2141 }
2142
2143 static Bool local equalTypes(t1,t2)    /* Compare simple types for equality*/
2144 Type t1, t2; {
2145
2146 et: if (whatIs(t1)!=whatIs(t2))
2147         return FALSE;
2148
2149     switch (whatIs(t1)) {
2150 #if TREX
2151         case EXT     :
2152 #endif
2153         case TYCON   :
2154         case OFFSET  :
2155         case TUPLE   : return t1==t2;
2156
2157         case INTCELL : return intOf(t1)!=intOf(t2);
2158
2159         case AP      : if (equalTypes(fun(t1),fun(t2))) {
2160                            t1 = arg(t1);
2161                            t2 = arg(t2);
2162                            goto et;
2163                        }
2164                        return FALSE;
2165
2166         default      : internal("equalTypes");
2167     }
2168
2169     return TRUE;/*NOTREACHED*/
2170 }
2171
2172 /* --------------------------------------------------------------------------
2173  * Entry points to type checker:
2174  * ------------------------------------------------------------------------*/
2175
2176 Type typeCheckExp(useDefs)              /* Type check top level expression */
2177 Bool useDefs; {                         /* using defaults if reqd          */
2178     Type type;
2179     List ctxt;
2180     Int  beta;
2181
2182     typeChecker(RESET);
2183     emptySubstitution();
2184     enterBindings();
2185     inputExpr = typeExpr(0,inputExpr);
2186     type      = typeIs;
2187     beta      = typeOff;
2188     clearMarks();
2189     normPreds(0);
2190     elimTauts();
2191     preds     = scSimplify(preds);
2192     if (useDefs && nonNull(preds)) {
2193         clearMarks();
2194         reducePreds();
2195         if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4?     */
2196             elimTauts();
2197     }
2198     resetGenerics();
2199     ctxt      = copyPreds(preds);
2200     type      = generalize(ctxt,copyType(type,beta));
2201     inputExpr = qualifyExpr(0,preds,inputExpr);
2202     h98CheckType(0,"inferred type",inputExpr,type);
2203     typeChecker(RESET);
2204     emptySubstitution();
2205     return type;
2206 }
2207
2208 Void typeCheckDefns() {                /* Type check top level bindings    */
2209     Target t  = length(selDefns)  + length(valDefns) +
2210                 length(instDefns) + length(classDefns);
2211     Target i  = 0;
2212     List   gs;
2213
2214     typeChecker(RESET);
2215     emptySubstitution();
2216     enterSkolVars();
2217     enterBindings();
2218     setGoal("Type checking",t);
2219
2220     for (gs=selDefns; nonNull(gs); gs=tl(gs)) {
2221         mapOver(typeSel,hd(gs));
2222         soFar(i++);
2223     }
2224     for (gs=valDefns; nonNull(gs); gs=tl(gs)) {
2225         typeDefnGroup(hd(gs));
2226         soFar(i++);
2227     }
2228     clearTypeIns();
2229     for (gs=classDefns; nonNull(gs); gs=tl(gs)) {
2230         emptySubstitution();
2231         typeClassDefn(hd(gs));
2232         soFar(i++);
2233     }
2234     for (gs=instDefns; nonNull(gs); gs=tl(gs)) {
2235         emptySubstitution();
2236         typeInstDefn(hd(gs));
2237         soFar(i++);
2238     }
2239
2240     typeChecker(RESET);
2241     emptySubstitution();
2242     done();
2243 }
2244
2245 static Void local typeDefnGroup(bs)     /* type check group of value defns */
2246 List bs; {                              /* (one top level scc)             */
2247     List as;
2248
2249     emptySubstitution();
2250     hd(defnBounds) = NIL;
2251     preds          = NIL;
2252     setTypeIns(bs);
2253     typeBindings(bs);                   /* find types for vars in bindings */
2254
2255     if (nonNull(preds)) {
2256         Cell v = fst(hd(hd(varsBounds)));
2257         Name n = findName(textOf(v));
2258         Int  l = nonNull(n) ? name(n).line : 0;
2259         preds  = scSimplify(preds);
2260         ERRMSG(l) "Instance%s of ", (length(preds)==1 ? "" : "s") ETHEN
2261         ERRCONTEXT(copyPreds(preds));
2262         ERRTEXT   " required for definition of " ETHEN
2263         ERREXPR(nonNull(n)?n:v);
2264         ERRTEXT   "\n"
2265         EEND;
2266     }
2267
2268     if (nonNull(hd(skolVars))) {
2269         Cell b = hd(bs);
2270         Name n = findName(isVar(fst(b)) ? textOf(fst(b)) : textOf(hd(fst(b))));
2271         Int  l = nonNull(n) ? name(n).line : 0;
2272         leaveSkolVars(l,typeUnit,0,0);
2273         enterSkolVars();
2274     }
2275
2276     for (as=hd(varsBounds); nonNull(as); as=tl(as)) {
2277         Cell a = hd(as);                /* add infered types to environment*/
2278         Name n = findName(textOf(fst(a)));
2279         if (isNull(n))
2280             internal("typeDefnGroup");
2281         name(n).type = snd(a);
2282     }
2283     hd(varsBounds) = NIL;
2284 }
2285
2286 static Pair local typeSel(s)            /* Calculate a suitable type for a */
2287 Name s; {                               /* particular selector, s.         */
2288     List cns  = name(s).defn;
2289     Int  line = name(s).line;
2290     Type dom  = NIL;                    /* Inferred domain                 */
2291     Type rng  = NIL;                    /* Inferred range                  */
2292     Cell nv   = inventVar();
2293     List alts = NIL;
2294     Int  o;
2295     Int  m;
2296
2297 #ifdef DEBUG_SELS
2298     Printf("Selector %s, cns=",textToStr(name(s).text));
2299     printExp(stdout,cns);
2300     Putchar('\n');
2301 #endif
2302
2303     emptySubstitution();
2304     preds = NIL;
2305
2306     for (; nonNull(cns); cns=tl(cns)) {
2307         Name c   = fst(hd(cns));
2308         Int  n   = intOf(snd(hd(cns)));
2309         Int  a   = name(c).arity;
2310         Cell pat = c;
2311         Type dom1;
2312         Type rng1;
2313         Int  o1;
2314         Int  m1;
2315
2316         instantiate(name(c).type);      /* Instantiate constructor type    */
2317         o1 = typeOff;
2318         m1 = typeFree;
2319         for (; nonNull(predsAre); predsAre=tl(predsAre))
2320             assumeEvid(hd(predsAre),o1);
2321
2322         if (whatIs(typeIs)==RANK2)      /* Skip rank2 annotation, if any   */
2323             typeIs = snd(snd(typeIs));
2324         for (; --n>0; a--) {            /* Get range                       */
2325             pat    = ap(pat,WILDCARD);
2326             typeIs = arg(typeIs);
2327         }
2328         rng1   = dropRank1(arg(fun(typeIs)),o1,m1);
2329         pat    = ap(pat,nv);
2330         typeIs = arg(typeIs);
2331         while (--a>0) {                 /* And then look for domain        */
2332             pat    = ap(pat,WILDCARD);
2333             typeIs = arg(typeIs);
2334         }
2335         dom1   = typeIs;
2336
2337         if (isNull(dom)) {              /* Save first domain type and then */
2338             dom = dom1;                 /* unify with subsequent domains to*/
2339             o   = o1;                   /* match up preds and range types  */
2340             m   = m1;
2341         }
2342         else if (!unify(dom1,o1,dom,o))
2343             internal("typeSel1");
2344
2345         if (isNull(rng))                /* Compare component types         */
2346             rng = rng1;
2347         else if (!sameSchemes(rng1,rng)) {
2348             clearMarks();
2349             rng  = liftRank1(rng,o,m);
2350             rng1 = liftRank1(rng1,o1,m1);
2351             ERRMSG(name(s).line) "Mismatch in field types for selector \"%s\"",
2352                                  textToStr(name(s).text) ETHEN
2353             ERRTEXT "\n*** Field type     : "            ETHEN ERRTYPE(rng1);
2354             ERRTEXT "\n*** Does not match : "            ETHEN ERRTYPE(rng);
2355             ERRTEXT "\n"
2356             EEND;
2357         }
2358         alts = cons(pair(singleton(pat),pair(mkInt(line),nv)),alts);
2359     }
2360     alts = rev(alts);
2361
2362     if (isNull(dom) || isNull(rng))     /* Should have been initialized by */
2363         internal("typeSel2");           /* now, assuming length cns >= 1.  */
2364
2365     clearMarks();                       /* No fixed variables here         */
2366     preds = scSimplify(preds);          /* Simplify context                */
2367     dom   = copyType(dom,o);            /* Calculate domain type           */
2368     instantiate(rng);
2369     rng   = copyType(typeIs,typeOff);
2370     if (nonNull(predsAre)) {
2371         List ps    = makePredAss(predsAre,typeOff);
2372         List alts1 = alts;
2373         for (; nonNull(alts1); alts1=tl(alts1)) {
2374             Cell body = nv;
2375             List qs   = ps;
2376             for (; nonNull(qs); qs=tl(qs))
2377                 body = ap(body,thd3(hd(qs)));
2378             snd(snd(hd(alts1))) = body;
2379         }
2380         preds = appendOnto(preds,ps);
2381     }
2382     name(s).type  = generalize(copyPreds(preds),fn(dom,rng));
2383     name(s).arity = 1 + length(preds);
2384     map1Proc(qualify,preds,alts);
2385
2386 #ifdef DEBUG_SELS
2387     Printf("Inferred arity = %d, type = ",name(s).arity);
2388     printType(stdout,name(s).type);
2389     Putchar('\n');
2390 #endif
2391
2392     return pair(s,alts);
2393 }
2394
2395
2396 /* --------------------------------------------------------------------------
2397  * Local function prototypes:
2398  * ------------------------------------------------------------------------*/
2399
2400 static Type local basicType Args((Char));
2401
2402
2403 static Type stateVar = NIL;
2404 static Type alphaVar = NIL;
2405 static Type betaVar  = NIL;
2406 static Type gammaVar = NIL;
2407 static Int  nextVar  = 0;
2408
2409 static Void clearTyVars( void )
2410 {
2411     stateVar = NIL;
2412     alphaVar = NIL;
2413     betaVar  = NIL;
2414     gammaVar = NIL;
2415     nextVar  = 0;
2416 }
2417
2418 static Type mkStateVar( void )
2419 {
2420     if (isNull(stateVar)) {
2421         stateVar = mkOffset(nextVar++);
2422     }
2423     return stateVar;
2424 }
2425
2426 static Type mkAlphaVar( void )
2427 {
2428     if (isNull(alphaVar)) {
2429         alphaVar = mkOffset(nextVar++);
2430     }
2431     return alphaVar;
2432 }
2433
2434 static Type mkBetaVar( void )
2435 {
2436     if (isNull(betaVar)) {
2437         betaVar = mkOffset(nextVar++);
2438     }
2439     return betaVar;
2440 }
2441
2442 static Type mkGammaVar( void )
2443 {
2444     if (isNull(gammaVar)) {
2445         gammaVar = mkOffset(nextVar++);
2446     }
2447     return gammaVar;
2448 }
2449
2450 static Type local basicType(k)
2451 Char k; {
2452     switch (k) {
2453     case CHAR_REP:
2454             return typeChar;
2455     case INT_REP:
2456             return typeInt;
2457     case INTEGER_REP:
2458             return typeInteger;
2459     case ADDR_REP:
2460             return typeAddr;
2461     case WORD_REP:
2462             return typeWord;
2463     case FLOAT_REP:
2464             return typeFloat;
2465     case DOUBLE_REP:
2466             return typeDouble;
2467     case ARR_REP:     return ap(typePrimArray,mkAlphaVar());            
2468     case BARR_REP:    return typePrimByteArray;
2469     case REF_REP:     return ap2(typeRef,mkStateVar(),mkAlphaVar());                  
2470     case MUTARR_REP:  return ap2(typePrimMutableArray,mkStateVar(),mkAlphaVar());     
2471     case MUTBARR_REP: return ap(typePrimMutableByteArray,mkStateVar()); 
2472     case STABLE_REP:  return ap(typeStable,mkAlphaVar());
2473 #ifdef PROVIDE_WEAK
2474     case WEAK_REP:
2475             return ap(typeWeak,mkAlphaVar());
2476     case IO_REP:
2477             return ap(typeIO,typeUnit);
2478 #endif
2479 #ifdef PROVIDE_FOREIGN
2480     case FOREIGN_REP:
2481             return typeForeign;
2482 #endif
2483 #ifdef PROVIDE_CONCURRENT
2484     case THREADID_REP:
2485             return typeThreadId;
2486     case MVAR_REP:
2487             return ap(typeMVar,mkAlphaVar());
2488 #endif
2489     case BOOL_REP:
2490             return typeBool;
2491     case HANDLER_REP:
2492             return fn(typeException,mkAlphaVar());
2493     case ERROR_REP:
2494             return typeException;
2495     case ALPHA_REP:
2496             return mkAlphaVar();  /* polymorphic */
2497     case BETA_REP:
2498             return mkBetaVar();   /* polymorphic */
2499     case GAMMA_REP:
2500             return mkGammaVar();  /* polymorphic */
2501     default:
2502             printf("Kind: '%c'\n",k);
2503             internal("basicType");
2504     }
2505     assert(0); return 0; /* NOTREACHED */
2506 }
2507
2508 /* Generate type of primop based on list of arg types and result types:
2509  *
2510  * eg primType "II" "II" = Int -> Int -> (Int,Int)
2511  *
2512  */
2513 Type primType( Int /*AsmMonad*/ monad, String a_kinds, String r_kinds )
2514 {
2515     List rs    = NIL;
2516     List as    = NIL;
2517     List tvars = NIL; /* for polymorphic types */
2518     Type r;
2519
2520     clearTyVars();
2521
2522     /* build result types */
2523     for(; *r_kinds; ++r_kinds) {
2524         rs = cons(basicType(*r_kinds),rs);
2525     }
2526     /* Construct tuple of results */
2527     if (length(rs) == 0) {
2528         r = typeUnit;
2529     } else if (length(rs) == 1) {
2530         r = hd(rs);
2531     } else {
2532         r = mkTuple(length(rs));
2533         for(rs = rev(rs); nonNull(rs); rs=tl(rs)) {
2534             r = ap(r,hd(rs));
2535         }
2536     }
2537     /* Construct list of arguments */
2538     for(; *a_kinds; ++a_kinds) {
2539         as = cons(basicType(*a_kinds),as);
2540     }
2541     /* Apply any monad magic */
2542     if (monad == MONAD_IO) {
2543         r = ap(typeIO,r);
2544     } else if (monad == MONAD_ST) {
2545         r = ap2(typeST,mkStateVar(),r);
2546     }
2547     /* glue it all together */
2548     for(; nonNull(as); as=tl(as)) {
2549         r = fn(hd(as),r);
2550     }
2551     tvars = offsetTyvarsIn(r,NIL);
2552     if (nonNull(tvars)) {
2553         assert(length(tvars) == nextVar);
2554         r = mkPolyType(simpleKind(length(tvars)),r);
2555     }
2556 #if DEBUG_CODE
2557     if (debugCode) {
2558         printType(stdout,r); printf("\n");
2559     }
2560 #endif
2561     return r;
2562 }    
2563
2564 /* forall a1 .. am. TC a1 ... am -> Int */
2565 Type conToTagType(t)
2566 Tycon t; {
2567     Type   ty  = t;
2568     List   tvars = NIL;
2569     Int    i   = 0;
2570     for (i=0; i<tycon(t).arity; ++i) {
2571         Offset tv = mkOffset(i);
2572         ty = ap(ty,tv);
2573         tvars = cons(tv,tvars);
2574     }
2575     ty = fn(ty,typeInt);
2576     if (nonNull(tvars)) {
2577         ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2578     }
2579     return ty;
2580 }
2581
2582 /* forall a1 .. am. Int -> TC a1 ... am */
2583 Type tagToConType(t)
2584 Tycon t; {
2585     Type   ty  = t;
2586     List   tvars = NIL;
2587     Int    i   = 0;
2588     for (i=0; i<tycon(t).arity; ++i) {
2589         Offset tv = mkOffset(i);
2590         ty = ap(ty,tv);
2591         tvars = cons(tv,tvars);
2592     }
2593     ty = fn(typeInt,ty);
2594     if (nonNull(tvars)) {
2595         ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2596     }
2597     return ty;
2598 }
2599
2600 /* --------------------------------------------------------------------------
2601  * Type checker control:
2602  * ------------------------------------------------------------------------*/
2603
2604 Void typeChecker(what)
2605 Int what; {
2606     switch (what) {
2607         case RESET   : tcMode       = EXPRESSION;
2608                        preds        = NIL;
2609                        pendingBtyvs = NIL;
2610                        daSccs       = NIL;
2611                        emptyAssumption();
2612                        break;
2613
2614         case MARK    : mark(daSccs);
2615                        mark(defnBounds);
2616                        mark(varsBounds);
2617                        mark(depends);
2618                        mark(pendingBtyvs);
2619                        mark(skolVars);
2620                        mark(localEvs);
2621                        mark(savedPs);
2622                        mark(dummyVar);
2623                        mark(preds);
2624                        mark(stdDefaults);
2625                        mark(arrow);
2626                        mark(boundPair);
2627                        mark(listof);
2628                        mark(typeVarToVar);
2629                        mark(predNum);
2630                        mark(predFractional);
2631                        mark(predIntegral);
2632                        mark(starToStar);
2633                        mark(predMonad);
2634                        break;
2635
2636         case INSTALL : typeChecker(RESET);
2637                        dummyVar     = inventVar();
2638
2639                        setCurrModule(modulePrelude);
2640
2641                        starToStar   = simpleKind(1);
2642
2643                        typeUnit     = addPrimTycon(findText("()"),
2644                                                    STAR,0,DATATYPE,NIL);
2645                        typeArrow    = addPrimTycon(findText("(->)"),
2646                                                    simpleKind(2),2,
2647                                                    DATATYPE,NIL);
2648                        typeList     = addPrimTycon(findText("[]"),
2649                                                    starToStar,1,
2650                                                    DATATYPE,NIL);
2651
2652                        arrow        = fn(aVar,bVar);
2653                        listof       = ap(typeList,aVar);
2654                        boundPair    = ap(ap(mkTuple(2),aVar),aVar);
2655
2656                        nameUnit     = addPrimCfun(findText("()"),0,0,typeUnit);
2657                        tycon(typeUnit).defn
2658                                     = singleton(nameUnit);
2659
2660                        nameNil      = addPrimCfun(findText("[]"),0,1,
2661                                                    mkPolyType(starToStar,
2662                                                               listof));
2663                        nameCons     = addPrimCfun(findText(":"),2,2,
2664                                                    mkPolyType(starToStar,
2665                                                               fn(aVar,
2666                                                               fn(listof,
2667                                                                  listof))));
2668                        name(nameNil).parent =
2669                        name(nameCons).parent = typeList;
2670
2671                        name(nameCons).syntax
2672                                     = mkSyntax(RIGHT_ASS,5);
2673
2674                        tycon(typeList).defn
2675                                     = cons(nameNil,cons(nameCons,NIL));
2676
2677                        typeVarToVar = fn(aVar,aVar);
2678 #if TREX
2679                        typeNoRow    = addPrimTycon(findText("EmptyRow"),
2680                                                    ROW,0,DATATYPE,NIL);
2681                        typeRec      = addPrimTycon(findText("Rec"),
2682                                                    pair(ROW,STAR),1,
2683                                                    DATATYPE,NIL);
2684                        nameNoRec    = addPrimCfun(findText("EmptyRec"),0,0,
2685                                                         ap(typeRec,typeNoRow));
2686 #else
2687                        /* bogus definitions to avoid changing the prelude */
2688                        addPrimCfun(findText("Rec"),      0,0,typeUnit);
2689                        addPrimCfun(findText("EmptyRow"), 0,0,typeUnit);
2690                        addPrimCfun(findText("EmptyRec"), 0,0,typeUnit);
2691 #endif
2692                        break;
2693     }
2694 }
2695
2696 /*-------------------------------------------------------------------------*/