[project @ 1999-04-27 10:06:47 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.6 $
12  * $Date: 1999/04/27 10:07:09 $
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     //print(h,1000);
728     //printf("\n");
729
730     switch (whatIs(h)) {
731         case NAME      : typeIs = name(h).type;
732                          break;
733
734         case VAROPCELL :
735         case VARIDCELL : if (tcMode==NEW_PATTERN) {
736                              inferType(aVar,newVarsBind(e));
737                          }
738                          else {
739                              Cell v = findAssum(textOf(h));
740                              if (nonNull(v)) {
741                                  h      = v;
742                                  typeIs = (tcMode==OLD_PATTERN)
743                                                 ? defType(typeIs)
744                                                 : useType(typeIs);
745                              }
746                              else {
747                                  h = findName(textOf(h));
748                                  if (isNull(h))
749                                      internal("typeAp0");
750                                  typeIs = name(h).type;
751                              }
752                          }
753                          break;
754
755         default        : h = typeExpr(l,h);
756                          break;
757     }
758
759     if (isNull(typeIs)) {
760         //printf("\n NAME " );
761         //print(h,1000);
762         //printf(" TYPE " ); print(typeIs,1000);
763         internal("typeAp1");
764     }
765
766     instantiate(typeIs);                /* Deal with polymorphism ...      */
767     if (nonNull(predsAre)) {            /* ... and with qualified types.   */
768         List evs = NIL;
769         for (; nonNull(predsAre); predsAre=tl(predsAre)) {
770             evs = cons(assumeEvid(hd(predsAre),typeOff),evs);
771         }
772         if (!isName(h) || !isCfun(h)) {
773             h = applyToArgs(h,rev(evs));
774         }
775     }
776
777     if (whatIs(typeIs)==CDICTS) {       /* Deal with local dictionaries    */
778         List evs = makePredAss(fst(snd(typeIs)),typeOff);
779         List ps  = evs;
780         typeIs   = snd(snd(typeIs));
781         for (; nonNull(ps); ps=tl(ps)) {
782             h = ap(h,thd3(hd(ps)));
783         }
784         if (tcMode==EXPRESSION) {
785             preds = revOnto(evs,preds);
786         } else {
787             hd(localEvs) = revOnto(evs,hd(localEvs));
788         }
789     }
790
791     if (whatIs(typeIs)==EXIST) {        /* Deal with existential arguments */
792         Int n  = intOf(fst(snd(typeIs)));
793         typeIs = snd(snd(typeIs));
794         if (!isCfun(getHead(h)) || n>typeFree) {
795             internal("typeAp2");
796         } else if (tcMode!=EXPRESSION) {
797             Int alpha = typeOff + typeFree;
798             for (; n>0; n--) {
799                 bindTv(alpha-n,SKOLEM,0);
800                 hd(skolVars) = cons(pair(mkInt(alpha-n),e),hd(skolVars));
801             }
802         }
803     }
804
805     if (whatIs(typeIs)==RANK2) {        /* Deal with rank 2 arguments      */
806         Int  alpha = typeOff;
807         Int  m     = typeFree;
808         Int  nr2   = intOf(fst(snd(typeIs)));
809         Type body  = snd(snd(typeIs));
810         List as    = e;
811         Bool added = FALSE;
812
813         if (n<nr2) {                    /* Must have enough arguments      */
814             ERRMSG(l)   "Use of " ETHEN ERREXPR(h);
815             if (n>1) {
816                 ERRTEXT " in "    ETHEN ERREXPR(e);
817             }
818             ERRTEXT     " requires at least %d argument%s\n",
819                         nr2, (nr2==1 ? "" : "s")
820             EEND;
821         }
822
823         for (i=nr2; i<n; ++i)           /* Find rank two arguments         */
824             as = fun(as);
825
826         for (as=getArgs(as); nonNull(as); as=tl(as), body=arg(body)) {
827             Type expect = dropRank1(arg(fun(body)),alpha,m);
828             if (isPolyType(expect)) {
829                 if (tcMode==EXPRESSION)         /* poly/qual type in expr  */
830                     hd(as) = typeExpected(l,app,hd(as),expect,alpha,m,TRUE);
831                 else if (hd(as)!=WILDCARD) {    /* Pattern binding/match   */
832                     if (!isVar(hd(as))) {
833                         ERRMSG(l) "Argument "    ETHEN ERREXPR(arg(as));
834                         ERRTEXT   " in pattern " ETHEN ERREXPR(e);
835                         ERRTEXT   " where a variable is required\n"
836                         EEND;
837                     }
838                     if (tcMode==NEW_PATTERN) {  /* Pattern match           */
839                         if (m>0 && !added) {
840                             for (i=0; i<m; i++)
841                                 addVarAssump(dummyVar,mkInt(alpha+i));
842                             added = TRUE;
843                         }
844                         addVarAssump(hd(as),expect);
845                     }
846                     else {                      /* Pattern binding         */
847                         Text t = textOf(hd(as));
848                         Cell a = findInAssumList(t,hd(defnBounds));
849                         if (isNull(a))
850                             internal("typeAp3");
851                         instantiate(expect);
852                         if (nonNull(predsAre)) {
853                             ERRMSG(l) "Cannot use pattern binding for " ETHEN
854                             ERREXPR(hd(as));
855                             ERRTEXT   " as a component with a qualified type\n"
856                             EEND;
857                         }
858                         shouldBe(l,hd(as),e,app,aVar,intOf(defType(snd(a))));
859                     }
860                 }
861             }
862             else {                              /* Not a poly/qual type    */
863                 check(l,hd(as),e,app,expect,alpha);
864             }
865             h = ap(h,hd(as));                   /* Save checked argument   */
866         }
867         inferType(body,alpha);
868         n -= nr2;
869     }
870
871     if (n>0) {                          /* Deal with remaining args        */
872         Int beta = funcType(n);         /* check h::t1->t2->...->tn->rn+1  */
873         shouldBe(l,h,e,app,aVar,beta);
874         for (i=n; i>0; --i) {           /* check e_i::t_i for each i       */
875             check(l,arg(a),e,app,aVar,beta+2*i-1);
876             p = a;
877             a = fun(a);
878         }
879         tyvarType(beta+2*n);            /* Inferred type is r_n+1          */
880     }
881
882     if (isNull(p))                      /* Replace head with translation   */
883         e = h;
884     else
885         fun(p) = h;
886
887     return e;
888 }
889
890 static Cell local typeExpected(l,wh,e,reqd,alpha,n,addEvid)
891 Int    l;                               /* Type check expression e in wh   */
892 String wh;                              /* at line l, expecting type reqd, */
893 Cell   e;                               /* and treating vars alpha through */
894 Type   reqd;                            /* (alpha+n-1) as fixed.           */
895 Int    alpha;
896 Int    n;
897 Bool   addEvid; {                       /* TRUE => add \ev -> ...          */
898     List savePreds = preds;
899     Type t;
900     Int  o;
901     Int  m;
902     List ps;
903     Int  i;
904
905     instantiate(reqd);
906     t     = typeIs;
907     o     = typeOff;
908     m     = typeFree;
909     ps    = makePredAss(predsAre,o);
910
911     preds = NIL;
912     check(l,e,NIL,wh,t,o);
913
914     clearMarks();
915     mapProc(markAssumList,defnBounds);
916     mapProc(markAssumList,varsBounds);
917     mapProc(markPred,savePreds);
918     markBtyvs();
919
920     for (i=0; i<n; i++)
921         markTyvar(alpha+i);
922
923     savePreds = elimPredsUsing(ps,savePreds);
924     if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
925         savePreds = elimPredsUsing(ps,savePreds);
926     if (nonNull(preds)) {
927         Type ty = copyType(t,o);
928         List qs = copyPreds(ps);
929         cantEstablish(l,wh,e,ty,qs);
930     }
931
932     resetGenerics();
933     for (i=0; i<m; i++)
934         if (copyTyvar(o+i)!=mkOffset(i)) {
935             List qs = copyPreds(ps);
936             Type it = copyType(t,o);
937             tooGeneral(l,e,reqd,generalize(qs,it));
938         }
939
940     if (addEvid) {
941         e     = qualifyExpr(l,ps,e);
942         preds = savePreds;
943     }
944     else
945         preds = revOnto(ps,savePreds);
946
947     inferType(t,o);
948     return e;
949 }
950
951 static Void local typeAlt(wh,e,a,t,o,m) /* Type check abstraction (Alt)    */
952 String wh;                              /* a = ( [p1, ..., pn], rhs )      */
953 Cell   e;
954 Cell   a;
955 Type   t;
956 Int    o;
957 Int    m; {
958     Type origt = t;
959     List ps    = fst(a) = patBtyvs(fst(a));
960     Int  n     = length(ps);
961     Int  l     = rhsLine(snd(a));
962     Int  nr2   = 0;
963     List as    = NIL;
964     Bool added = FALSE;
965
966     saveVarsAss();
967     enterSkolVars();
968     if (whatIs(t)==RANK2) {
969         if (n<(nr2=intOf(fst(snd(t))))) {
970             ERRMSG(l) "Definition requires at least %d parameters on lhs",
971                       intOf(fst(snd(t)))
972             EEND;
973         }
974         t = snd(snd(t));
975     }
976
977     while (getHead(t)==typeArrow && argCount==2 && nonNull(ps)) {
978         Type ta = arg(fun(t));
979         if (isPolyType(ta)) {
980             if (hd(ps)!=WILDCARD) {
981                 if (!isVar(hd(ps))) {
982                    ERRMSG(l) "Argument " ETHEN ERREXPR(hd(ps));
983                    ERRTEXT   " used where a variable or wildcard is required\n"
984                    EEND;
985                 }
986                 if (m>0 && !added) {
987                     Int i = 0;
988                     for (; i<m; i++)
989                         addVarAssump(dummyVar,mkInt(o+i));
990                     added = TRUE;
991                 }
992                 addVarAssump(hd(ps),ta);
993             }
994         }
995         else {
996             hd(ps) = typeFreshPat(l,hd(ps));
997             shouldBe(l,hd(ps),NIL,wh,ta,o);
998         }
999         t  = arg(t);
1000         ps = tl(ps);
1001         as = fn(ta,as);
1002         n--;
1003     }
1004
1005     if (n==0)
1006         snd(a) = typeRhs(snd(a));
1007     else {
1008         Int beta = funcType(n);
1009         Int i    = 0;
1010         for (; i<n; ++i) {
1011             hd(ps) = typeFreshPat(l,hd(ps));
1012             bindTv(beta+2*i+1,typeIs,typeOff);
1013             ps = tl(ps);
1014         }
1015         snd(a) = typeRhs(snd(a));
1016         bindTv(beta+2*n,typeIs,typeOff);
1017         tyvarType(beta);
1018     }
1019
1020     if (!unify(typeIs,typeOff,t,o)) {
1021         Type req, got;
1022         clearMarks();
1023         req = liftRank2(origt,o,m);
1024         liftRank2Args(as,o,m);
1025         got = ap(RANK2,pair(mkInt(nr2),revOnto(as,copyType(typeIs,typeOff))));
1026         reportTypeError(l,e,NIL,wh,got,req);
1027     }
1028
1029     restoreVarsAss();
1030     doneBtyvs(l);
1031     leaveSkolVars(l,origt,o,m);
1032 }
1033
1034 static Int local funcType(n)            /*return skeleton for function type*/
1035 Int n; {                                /*with n arguments, taking the form*/
1036     Int beta = newTyvars(2*n+1);        /*    r1 t1 r2 t2 ... rn tn rn+1   */
1037     Int i;                              /* with r_i := t_i -> r_i+1        */
1038     for (i=0; i<n; ++i)
1039         bindTv(beta+2*i,arrow,beta+2*i+1);
1040     return beta;
1041 }
1042
1043 static Void local typeCase(l,beta,c)   /* type check case: pat -> rhs      */
1044 Int  l;                                /* (case given by c == (pat,rhs))   */
1045 Int  beta;                             /* need:  pat :: (var,beta)         */
1046 Cell c; {                              /*        rhs :: (var,beta+1)       */
1047     static String casePat  = "case pattern";
1048     static String caseExpr = "case expression";
1049
1050     saveVarsAss();
1051     enterSkolVars();
1052     fst(c) = typeFreshPat(l,patBtyvs(fst(c)));
1053     shouldBe(l,fst(c),NIL,casePat,aVar,beta);
1054     snd(c) = typeRhs(snd(c));
1055     shouldBe(l,rhsExpr(snd(c)),NIL,caseExpr,aVar,beta+1);
1056
1057     restoreVarsAss();
1058     doneBtyvs(l);
1059     leaveSkolVars(l,typeIs,typeOff,0);
1060 }
1061
1062 static Void local typeComp(l,m,e,qs)    /* type check comprehension        */
1063 Int  l;
1064 Type m;                                 /* monad (mkOffset(0))             */
1065 Cell e;
1066 List qs; {
1067     static String boolQual = "boolean qualifier";
1068     static String genQual  = "generator";
1069
1070     if (isNull(qs))                     /* no qualifiers left              */
1071         fst(e) = typeExpr(l,fst(e));
1072     else {
1073         Cell q   = hd(qs);
1074         List qs1 = tl(qs);
1075         switch (whatIs(q)) {
1076             case BOOLQUAL : check(l,snd(q),NIL,boolQual,typeBool,0);
1077                             typeComp(l,m,e,qs1);
1078                             break;
1079
1080             case QWHERE   : enterBindings();
1081                             enterSkolVars();
1082                             mapProc(typeBindings,snd(q));
1083                             typeComp(l,m,e,qs1);
1084                             leaveBindings();
1085                             leaveSkolVars(l,typeIs,typeOff,0);
1086                             break;
1087
1088             case FROMQUAL : {   Int beta = newTyvars(1);
1089                                 saveVarsAss();
1090                                 check(l,snd(snd(q)),NIL,genQual,m,beta);
1091                                 enterSkolVars();
1092                                 fst(snd(q))
1093                                     = typeFreshPat(l,patBtyvs(fst(snd(q))));
1094                                 shouldBe(l,fst(snd(q)),NIL,genQual,aVar,beta);
1095                                 typeComp(l,m,e,qs1);
1096                                 restoreVarsAss();
1097                                 doneBtyvs(l);
1098                                 leaveSkolVars(l,typeIs,typeOff,0);
1099                             }
1100                             break;
1101
1102             case DOQUAL   : check(l,snd(q),NIL,genQual,m,newTyvars(1));
1103                             typeComp(l,m,e,qs1);
1104                             break;
1105         }
1106     }
1107 }
1108
1109 static Cell local typeMonadComp(l,e)    /* type check monad comprehension  */
1110 Int  l;
1111 Cell e; {
1112     Int  alpha        = newTyvars(1);
1113     Int  beta         = newTyvars(1);
1114     Cell mon          = ap(mkInt(beta),aVar);
1115     Cell m            = assumeEvid(predMonad,beta);
1116     tyvar(beta)->kind = starToStar;
1117 #if !MONAD_COMPS
1118     bindTv(beta,typeList,0);
1119 #endif
1120
1121     typeComp(l,mon,snd(e),snd(snd(e)));
1122     bindTv(alpha,typeIs,typeOff);
1123     inferType(mon,alpha);
1124     return ap(MONADCOMP,pair(m,snd(e)));
1125 }
1126
1127 static Void local typeDo(l,e)           /* type check do-notation          */
1128 Int  l;
1129 Cell e; {
1130     static String finGen = "final generator";
1131     Int  alpha           = newTyvars(1);
1132     Int  beta            = newTyvars(1);
1133     Cell mon             = ap(mkInt(beta),aVar);
1134     Cell m               = assumeEvid(predMonad,beta);
1135     tyvar(beta)->kind    = starToStar;
1136
1137     typeComp(l,mon,snd(e),snd(snd(e)));
1138     shouldBe(l,fst(snd(e)),NIL,finGen,mon,alpha);
1139     snd(e) = pair(m,snd(e));
1140 }
1141
1142 static Void local typeConFlds(l,e)      /* Type check a construction       */
1143 Int  l;
1144 Cell e; {
1145     static String conExpr = "value construction";
1146     Name c  = fst(snd(e));
1147     List fs = snd(snd(e));
1148     Type tc;
1149     Int  to;
1150     Int  tf;
1151     Int  i;
1152
1153     instantiate(name(c).type);
1154     for (; nonNull(predsAre); predsAre=tl(predsAre))
1155         assumeEvid(hd(predsAre),typeOff);
1156     if (whatIs(typeIs)==RANK2)
1157         typeIs = snd(snd(typeIs));
1158     tc = typeIs;
1159     to = typeOff;
1160     tf = typeFree;
1161
1162     for (; nonNull(fs); fs=tl(fs)) {
1163         Type t = tc;
1164         for (i=sfunPos(fst(hd(fs)),c); --i>0; t=arg(t))
1165             ;
1166         t = dropRank1(arg(fun(t)),to,tf);
1167         if (isPolyType(t))
1168             snd(hd(fs)) = typeExpected(l,conExpr,snd(hd(fs)),t,to,tf,TRUE);
1169         else {
1170             check(l,snd(hd(fs)),e,conExpr,t,to);
1171         }
1172     }
1173     for (i=name(c).arity; i>0; i--)
1174         tc = arg(tc);
1175     inferType(tc,to);
1176 }
1177
1178 static Void local typeUpdFlds(line,e)   /* Type check an update            */
1179 Int  line;                              /* (Written in what might seem a   */
1180 Cell e; {                               /* bizarre manner for the benefit  */
1181     static String update = "update";    /* of as yet unreleased extensions)*/
1182     List cs    = snd3(snd(e));          /* List of constructors            */
1183     List fs    = thd3(snd(e));          /* List of field specifications    */
1184     List ts    = NIL;                   /* List of types for fields        */
1185     Int  n     = length(fs);
1186     Int  alpha = newTyvars(2+n);
1187     Int  i;
1188     List fs1;
1189
1190     /* Calculate type and translation for each expr in the field list      */
1191     for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1192         snd(hd(fs1)) = typeExpr(line,snd(hd(fs1)));
1193         bindTv(i,typeIs,typeOff);
1194     }
1195
1196     clearMarks();
1197     mapProc(markAssumList,defnBounds);
1198     mapProc(markAssumList,varsBounds);
1199     mapProc(markPred,preds);
1200     markBtyvs();
1201
1202     for (fs1=fs, i=alpha+2; nonNull(fs1); fs1=tl(fs1), i++) {
1203         resetGenerics();
1204         ts = cons(generalize(NIL,copyTyvar(i)),ts);
1205     }
1206     ts = rev(ts);
1207
1208     /* Type check expression to be updated                                 */
1209     fst3(snd(e)) = typeExpr(line,fst3(snd(e)));
1210     bindTv(alpha,typeIs,typeOff);
1211
1212     for (; nonNull(cs); cs=tl(cs)) {    /* Loop through constrs            */
1213         Name c  = hd(cs);
1214         List ta = replicate(name(c).arity,NIL);
1215         Type td, tr;
1216         Int  od, or;
1217
1218         tcMode = NEW_PATTERN;           /* Domain type                     */
1219         instantiate(name(c).type);
1220         tcMode = EXPRESSION;
1221         td     = typeIs;
1222         od     = typeOff;
1223         for (; nonNull(predsAre); predsAre=tl(predsAre))
1224             assumeEvid(hd(predsAre),typeOff);
1225
1226         if (whatIs(typeIs)==RANK2) {
1227             ERRMSG(line) "Sorry, record update syntax cannot currently be "
1228                          "used for datatypes with polymorphic components"
1229             EEND;
1230         }
1231
1232         instantiate(name(c).type);      /* Range type                      */
1233         tr = typeIs;
1234         or = typeOff;
1235         for (; nonNull(predsAre); predsAre=tl(predsAre))
1236             assumeEvid(hd(predsAre),typeOff);
1237
1238         for (fs1=fs, i=1; nonNull(fs1); fs1=tl(fs1), i++) {
1239             Int n    = sfunPos(fst(hd(fs1)),c);
1240             Cell ta1 = ta;
1241             for (; n>1; n--)
1242                 ta1 = tl(ta1);
1243             hd(ta1) = mkInt(i);
1244         }
1245
1246         for (; nonNull(ta); ta=tl(ta)) {        /* For each cfun arg       */
1247             if (nonNull(hd(ta))) {              /* Field to updated?       */
1248                 Int  n = intOf(hd(ta));
1249                 Cell f = fs;
1250                 Cell t = ts;
1251                 for (; n-- > 1; f=tl(f), t=tl(t))
1252                     ;
1253                 f = hd(f);
1254                 t = hd(t);
1255                 instantiate(t);
1256                 shouldBe(line,snd(f),e,update,arg(fun(tr)),or);
1257             }                                   /* Unmentioned component   */
1258             else if (!unify(arg(fun(td)),od,arg(fun(tr)),or))
1259                 internal("typeUpdFlds");
1260
1261             tr = arg(tr);
1262             td = arg(td);
1263         }
1264
1265         inferType(td,od);                       /* Check domain type       */
1266         shouldBe(line,fst3(snd(e)),e,update,aVar,alpha);
1267         inferType(tr,or);                       /* Check range type        */
1268         shouldBe(line,e,NIL,update,aVar,alpha+1);
1269     }
1270     /* (typeIs,typeOff) still carry the result type when we exit the loop  */
1271 }
1272
1273 static Cell local typeFreshPat(l,p)    /* find type of pattern, assigning  */
1274 Int  l;                                /* fresh type variables to each var */
1275 Cell p; {                              /* bound in the pattern             */
1276     tcMode = NEW_PATTERN;
1277     p      = typeExpr(l,p);
1278     tcMode = EXPRESSION;
1279     return p;
1280 }
1281
1282 /* --------------------------------------------------------------------------
1283  * Type check group of bindings:
1284  * ------------------------------------------------------------------------*/
1285
1286 static Void local typeBindings(bs)      /* type check a binding group      */
1287 List bs; {
1288     Bool usesPatBindings = FALSE;       /* TRUE => pattern binding in bs   */
1289     Bool usesUntypedVar  = FALSE;       /* TRUE => var bind w/o type decl  */
1290     List bs1;
1291
1292     /* The following loop is used to determine whether the monomorphism    */
1293     /* restriction should be applied.  It could be written marginally more */
1294     /* efficiently by using breaks, but clarity is more important here ... */
1295
1296     for (bs1=bs; nonNull(bs1); bs1=tl(bs1)) {  /* Analyse binding group    */
1297         Cell b = hd(bs1);
1298         if (!isVar(fst(b)))
1299             usesPatBindings = TRUE;
1300         else if (isNull(fst(hd(snd(snd(b)))))           /* no arguments    */
1301                  && whatIs(fst(snd(b)))==IMPDEPS)       /* implicitly typed*/
1302             usesUntypedVar  = TRUE;
1303     }
1304
1305     if (usesPatBindings || usesUntypedVar)
1306         monorestrict(bs);
1307     else
1308         unrestricted(bs);
1309
1310     mapProc(removeTypeSigs,bs);                /* Remove binding type info */
1311     hd(varsBounds) = revOnto(hd(defnBounds),   /* transfer completed assmps*/
1312                              hd(varsBounds));  /* out of defnBounds        */
1313     hd(defnBounds) = NIL;
1314     hd(depends)    = NIL;
1315 }
1316
1317 static Void local removeTypeSigs(b)    /* Remove type info from a binding  */
1318 Cell b; {
1319     snd(b) = snd(snd(b));
1320 }
1321
1322 /* --------------------------------------------------------------------------
1323  * Type check a restricted binding group:
1324  * ------------------------------------------------------------------------*/
1325
1326 static Void local monorestrict(bs)      /* Type restricted binding group   */
1327 List bs; {
1328     List savePreds = preds;
1329     Int  line      = isVar(fst(hd(bs))) ? rhsLine(snd(hd(snd(snd(hd(bs))))))
1330                                         : rhsLine(snd(snd(snd(hd(bs)))));
1331     hd(defnBounds) = NIL;
1332     hd(depends)    = NODEPENDS;         /* No need for dependents here     */
1333
1334     preds = NIL;                        /* Type check the bindings         */
1335     mapProc(restrictedBindAss,bs);
1336     mapProc(typeBind,bs);
1337     normPreds(line);
1338     elimTauts();
1339     preds = revOnto(preds,savePreds);
1340
1341     clearMarks();                       /* Mark fixed variables            */
1342     mapProc(markAssumList,tl(defnBounds));
1343     mapProc(markAssumList,tl(varsBounds));
1344     mapProc(markPred,preds);
1345     markBtyvs();
1346
1347     if (isNull(tl(defnBounds))) {       /* Top-level may need defaulting   */
1348         normPreds(line);
1349         if (nonNull(preds) && resolveDefs(genvarAnyAss(hd(defnBounds))))
1350             elimTauts();
1351
1352         clearMarks();
1353         reducePreds();
1354         if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4?     */
1355             elimTauts();
1356
1357         if (nonNull(preds)) {           /* Look for unresolved overloading */
1358             Cell v   = isVar(fst(hd(bs))) ? fst(hd(bs)) : hd(fst(hd(bs)));
1359             Cell ass = findInAssumList(textOf(v),hd(varsBounds));
1360             preds    = scSimplify(preds);
1361
1362             ERRMSG(line) "Unresolved top-level overloading" ETHEN
1363             ERRTEXT     "\n*** Binding             : %s", textToStr(textOf(v))
1364             ETHEN
1365             if (nonNull(ass)) {
1366                 ERRTEXT "\n*** Inferred type       : " ETHEN ERRTYPE(snd(ass));
1367             }
1368             ERRTEXT     "\n*** Outstanding context : " ETHEN
1369                                                 ERRCONTEXT(copyPreds(preds));
1370             ERRTEXT     "\n"
1371             EEND;
1372         }
1373     }
1374
1375     map1Proc(genBind,NIL,bs);           /* Generalize types of def'd vars  */
1376 }
1377
1378 static Void local restrictedBindAss(b)  /* Make assums for vars in binding */
1379 Cell b; {                               /* gp with restricted overloading  */
1380
1381     if (isVar(fst(b))) {                /* function-binding?               */
1382         Cell t = fst(snd(b));
1383         if (whatIs(t)==IMPDEPS)  {      /* Discard implicitly typed deps   */
1384             fst(snd(b)) = t = NIL;      /* in a restricted binding group.  */
1385         }
1386         fst(snd(b)) = localizeBtyvs(t);
1387         restrictedAss(rhsLine(snd(hd(snd(snd(b))))), fst(b), t);
1388     } else {                            /* pattern-binding?                */
1389         List vs   = fst(b);
1390         List ts   = fst(snd(b));
1391         Int  line = rhsLine(snd(snd(snd(b))));
1392
1393         for (; nonNull(vs); vs=tl(vs)) {
1394             if (nonNull(ts)) {
1395                 restrictedAss(line,hd(vs),hd(ts)=localizeBtyvs(hd(ts)));
1396                 ts = tl(ts);
1397             } else {
1398                 restrictedAss(line,hd(vs),NIL);
1399             }
1400         }
1401     }
1402 }
1403
1404 static Void local restrictedAss(l,v,t) /* Assume that type of binding var v*/
1405 Int  l;                                /* is t (if nonNull) in restricted  */
1406 Cell v;                                /* binding group                    */
1407 Type t; {
1408     newDefnBind(v,t);
1409     if (nonNull(predsAre)) {
1410         ERRMSG(l) "Explicit overloaded type for \"%s\"",textToStr(textOf(v))
1411         ETHEN
1412         ERRTEXT   " not permitted in restricted binding"
1413         EEND;
1414     }
1415 }
1416
1417 /* --------------------------------------------------------------------------
1418  * Unrestricted binding group:
1419  * ------------------------------------------------------------------------*/
1420
1421 static Void local unrestricted(bs)      /* Type unrestricted binding group */
1422 List bs; {
1423     List savePreds = preds;
1424     List imps      = NIL;               /* Implicitly typed bindings       */
1425     List exps      = NIL;               /* Explicitly typed bindings       */
1426     List bs1;
1427
1428     /* ----------------------------------------------------------------------
1429      * STEP 1: Separate implicitly typed bindings from explicitly typed 
1430      * bindings and do a dependency analyis, where f depends on g iff f
1431      * is implicitly typed and involves a call to g.
1432      * --------------------------------------------------------------------*/
1433
1434     for (; nonNull(bs); bs=tl(bs)) {
1435         Cell b = hd(bs);
1436         if (whatIs(fst(snd(b)))==IMPDEPS)
1437             imps = cons(b,imps);        /* N.B. New lists are built to     */
1438         else                            /* avoid breaking the original     */
1439             exps = cons(b,exps);        /* list structure for bs.          */
1440     }
1441
1442     for (bs=imps; nonNull(bs); bs=tl(bs)) {
1443         Cell b  = hd(bs);               /* Restrict implicitly typed dep   */
1444         List ds = snd(fst(snd(b)));     /* lists to bindings in imps       */
1445         List cs = NIL;
1446         while (nonNull(ds)) {
1447             bs1 = tl(ds);
1448             if (cellIsMember(hd(ds),imps)) {
1449                 tl(ds) = cs;
1450                 cs     = ds;
1451             }
1452             ds = bs1;
1453         }
1454         fst(snd(b)) = cs;
1455     }
1456     imps = itbscc(imps);                /* Dependency analysis on imps     */
1457     for (bs=imps; nonNull(bs); bs=tl(bs))
1458         for (bs1=hd(bs); nonNull(bs1); bs1=tl(bs1))
1459             fst(snd(hd(bs1))) = NIL;    /* reset imps type fields          */
1460
1461 #ifdef DEBUG_DEPENDS
1462     Printf("Binding group:");
1463     for (bs1=imps; nonNull(bs1); bs1=tl(bs1)) {
1464         Printf(" [imp:");
1465         for (bs=hd(bs1); nonNull(bs); bs=tl(bs))
1466             Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1467         Printf("]");
1468     }
1469     if (nonNull(exps)) {
1470         Printf(" [exp:");
1471         for (bs=exps; nonNull(bs); bs=tl(bs))
1472             Printf(" %s",textToStr(textOf(fst(hd(bs)))));
1473         Printf("]");
1474     }
1475     Printf("\n");
1476 #endif
1477
1478     /* ----------------------------------------------------------------------
1479      * STEP 2: Add type assumptions about any explicitly typed variable.
1480      * --------------------------------------------------------------------*/
1481
1482     for (bs=exps; nonNull(bs); bs=tl(bs)) {
1483         fst(snd(hd(bs))) = localizeBtyvs(fst(snd(hd(bs))));
1484         hd(varsBounds)   = cons(pair(fst(hd(bs)),fst(snd(hd(bs)))),
1485                                 hd(varsBounds));
1486     }
1487
1488     /* ----------------------------------------------------------------------
1489      * STEP 3: Calculate types for each group of implicitly typed bindings.
1490      * --------------------------------------------------------------------*/
1491
1492     for (; nonNull(imps); imps=tl(imps)) {
1493         Cell b   = hd(hd(imps));
1494         Int line = isVar(fst(b)) ? rhsLine(snd(hd(snd(snd(b)))))
1495                                  : rhsLine(snd(snd(snd(b))));
1496         hd(defnBounds) = NIL;
1497         hd(depends)    = NIL;
1498         for (bs1=hd(imps); nonNull(bs1); bs1=tl(bs1))
1499             newDefnBind(fst(hd(bs1)),NIL);
1500
1501         preds = NIL;
1502         mapProc(typeBind,hd(imps));
1503
1504         clearMarks();
1505         mapProc(markAssumList,tl(defnBounds));
1506         mapProc(markAssumList,tl(varsBounds));
1507         mapProc(markPred,savePreds);
1508         markBtyvs();
1509
1510         normPreds(line);
1511         savePreds = elimOuterPreds(savePreds);
1512         if (nonNull(preds) && resolveDefs(genvarAllAss(hd(defnBounds)))) {
1513             savePreds = elimOuterPreds(savePreds);
1514         }
1515
1516         map1Proc(genBind,preds,hd(imps));
1517         if (nonNull(preds)) {
1518             map1Proc(addEvidParams,preds,hd(depends));
1519             map1Proc(qualifyBinding,preds,hd(imps));
1520         }
1521
1522         h98CheckType(line,"inferred type",
1523                         fst(hd(hd(defnBounds))),snd(hd(hd(defnBounds))));
1524         hd(varsBounds) = revOnto(hd(defnBounds),hd(varsBounds));
1525     }
1526
1527     /* ----------------------------------------------------------------------
1528      * STEP 4: Now infer a type for each explicitly typed variable and
1529      * check for compatibility with the declared type.
1530      * --------------------------------------------------------------------*/
1531
1532     for (; nonNull(exps); exps=tl(exps)) {
1533         static String extbind = "explicitly typed binding";
1534         Cell b    = hd(exps);
1535         List alts = snd(snd(b));
1536         Int  line = rhsLine(snd(hd(alts)));
1537         Type t;
1538         Int  o;
1539         Int  m;
1540         List ps;
1541
1542         hd(defnBounds) = NIL;
1543         hd(depends)    = NODEPENDS;
1544         preds          = NIL;
1545
1546         instantiate(fst(snd(b)));
1547         o              = typeOff;
1548         m              = typeFree;
1549         t              = dropRank2(typeIs,o,m);
1550         ps             = makePredAss(predsAre,o);
1551
1552         enterPendingBtyvs();
1553         for (; nonNull(alts); alts=tl(alts))
1554             typeAlt(extbind,fst(b),hd(alts),t,o,m);
1555         leavePendingBtyvs();
1556
1557         if (nonNull(ps))                /* Add dict params, if necessary   */
1558             qualifyBinding(ps,b);
1559
1560         clearMarks();
1561         mapProc(markAssumList,tl(defnBounds));
1562         mapProc(markAssumList,tl(varsBounds));
1563         mapProc(markPred,savePreds);
1564         markBtyvs();
1565
1566         savePreds = elimPredsUsing(ps,savePreds);
1567         if (nonNull(preds)) {
1568             List vs = NIL;
1569             Int  i  = 0;
1570             for (; i<m; ++i)
1571                 vs = cons(mkInt(o+i),vs);
1572             if (resolveDefs(vs))
1573                 savePreds = elimPredsUsing(ps,savePreds);
1574             if (nonNull(preds)) {
1575                 clearMarks();
1576                 reducePreds();
1577                 if (nonNull(preds) && resolveDefs(vs))
1578                     savePreds = elimPredsUsing(ps,savePreds);
1579             }
1580         }
1581
1582         resetGenerics();                /* Make sure we're general enough  */
1583         ps = copyPreds(ps);
1584         t  = generalize(ps,liftRank2(t,o,m));
1585
1586         if (!sameSchemes(t,fst(snd(b))))
1587             tooGeneral(line,fst(b),fst(snd(b)),t);
1588         h98CheckType(line,"inferred type",fst(b),t);
1589
1590         if (nonNull(preds))             /* Check context was strong enough */
1591             cantEstablish(line,extbind,fst(b),t,ps);
1592     }
1593
1594     preds          = savePreds;                 /* Restore predicates      */
1595     hd(defnBounds) = NIL;
1596 }
1597
1598 #define  SCC             itbscc         /* scc for implicitly typed binds  */
1599 #define  LOWLINK         itblowlink
1600 #define  DEPENDS(t)      fst(snd(t))
1601 #define  SETDEPENDS(c,v) fst(snd(c))=v
1602 #include "scc.c"
1603 #undef   SETDEPENDS
1604 #undef   DEPENDS
1605 #undef   LOWLINK
1606 #undef   SCC
1607
1608 static Void local addEvidParams(qs,v)  /* overwrite VARID/OPCELL v with    */
1609 List qs;                               /* application of variable to evid. */
1610 Cell v; {                              /* parameters given by qs           */
1611     if (nonNull(qs)) {
1612         Cell nv;
1613
1614         if (!isVar(v))
1615             internal("addEvidParams");
1616
1617         for (nv=mkVar(textOf(v)); nonNull(tl(qs)); qs=tl(qs))
1618             nv = ap(nv,thd3(hd(qs)));
1619         fst(v) = nv;
1620         snd(v) = thd3(hd(qs));
1621     }
1622 }
1623
1624 /* --------------------------------------------------------------------------
1625  * Type check bodies of class and instance declarations:
1626  * ------------------------------------------------------------------------*/
1627
1628 static Void local typeClassDefn(c)      /* Type check implementations of   */
1629 Class c; {                              /* defaults for class c            */
1630
1631     /* ----------------------------------------------------------------------
1632      * Generate code for default dictionary builder function:
1633      *
1634      *   class.C sc1 ... scn d = let v1 ... = ...
1635      *                               vm ... = ...
1636      *                           in Make.C sc1 ... scn v1 ... vm
1637      *
1638      * where sci are superclass dictionary parameters, vj are implementations
1639      * for member functions, either taken from defaults, or using "error" to
1640      * produce a suitable error message.  (Additional line number values must
1641      * be added at appropriate places but, for clarity, these are not shown
1642      * above.)
1643      * --------------------------------------------------------------------*/
1644
1645     Int  beta   = newKindedVars(cclass(c).kinds);
1646     List params = makePredAss(cclass(c).supers,beta);
1647     Cell body   = cclass(c).dcon;
1648     Cell pat    = body;
1649     List mems   = cclass(c).members;
1650     List defs   = cclass(c).defaults;
1651     List dsels  = cclass(c).dsels;
1652     Cell d      = inventDictVar();
1653     List args   = NIL;
1654     List locs   = NIL;
1655     Cell l      = mkInt(cclass(c).line);
1656     List ps;
1657
1658     for (ps=params; nonNull(ps); ps=tl(ps)) {
1659         Cell v = thd3(hd(ps));
1660         body   = ap(body,v);
1661         pat    = ap(pat,inventVar());
1662         args   = cons(v,args);
1663     }
1664     args   = revOnto(args,singleton(d));
1665     params = appendOnto(params,
1666                         singleton(triple(cclass(c).head,mkInt(beta),d)));
1667
1668     for (; nonNull(mems); mems=tl(mems)) {
1669         Cell v   = inventVar();         /* Pick a name for component       */
1670         Cell imp = NIL;
1671
1672         if (nonNull(defs)) {            /* Look for default implementation */
1673             imp  = hd(defs);
1674             defs = tl(defs);
1675         }
1676
1677         if (isNull(imp)) {              /* Generate undefined member msg   */
1678             static String header = "Undefined member: ";
1679             String name = textToStr(name(hd(mems)).text);
1680             char   msg[FILENAME_MAX+1];
1681             Int    i;
1682             Int    j;
1683
1684             for (i=0; i<FILENAME_MAX && header[i]!='\0'; i++)
1685                 msg[i] = header[i];
1686             for (j=0; (i+j)<FILENAME_MAX && name[j]!='\0'; j++)
1687                 msg[i+j] = name[j];
1688             msg[i+j] = '\0';
1689
1690             imp = pair(v,singleton(pair(NIL,ap(l,ap(nameError,
1691                                                     mkStr(findText(msg)))))));
1692         }
1693         else {                          /* Use default implementation      */
1694             fst(imp) = v;
1695             typeMember("default member binding",
1696                        hd(mems),
1697                        snd(imp),
1698                        params,
1699                        cclass(c).head,
1700                        beta);
1701         }
1702
1703         locs = cons(imp,locs);
1704         body = ap(body,v);
1705         pat  = ap(pat,v);
1706     }
1707     body     = ap(l,body);
1708     if (nonNull(locs))
1709         body = ap(LETREC,pair(singleton(locs),body));
1710     name(cclass(c).dbuild).defn
1711              = singleton(pair(args,body));
1712     //--------- Default
1713     name(cclass(c).dbuild).inlineMe = TRUE;
1714     genDefns = cons(cclass(c).dbuild,genDefns);
1715     cclass(c).defaults = NIL;
1716
1717     /* ----------------------------------------------------------------------
1718      * Generate code for superclass and member function selectors:
1719      * --------------------------------------------------------------------*/
1720
1721     args = getArgs(pat);
1722     pat  = singleton(pat);
1723     for (; nonNull(dsels); dsels=tl(dsels)) {
1724         name(hd(dsels)).defn = singleton(pair(pat,ap(l,hd(args))));
1725         name(hd(dsels)).inlineMe = TRUE;
1726         args                 = tl(args);
1727         genDefns             = cons(hd(dsels),genDefns);
1728     }
1729     for (mems=cclass(c).members; nonNull(mems); mems=tl(mems)) {
1730         name(hd(mems)).defn = singleton(pair(pat,ap(mkInt(name(hd(mems)).line),
1731                                                     hd(args))));
1732         args                = tl(args);
1733         genDefns            = cons(hd(mems),genDefns);
1734     }
1735 }
1736
1737 static Void local typeInstDefn(in)      /* Type check implementations of   */
1738 Inst in; {                              /* member functions for instance in*/
1739
1740     /* ----------------------------------------------------------------------
1741      * Generate code for instance specific dictionary builder function:
1742      *
1743      *   inst.maker d1 ... dn = let sc1 = ...
1744      *                                  .
1745      *                                  .
1746      *                                  .
1747      *                              scm = ...
1748      *                              d   = f (class.C sc1 ... scm d)
1749      *           omit if the   /    f (Make.C sc1' ... scm' v1' ... vk')
1750      *          instance decl {         = let vj ... = ...
1751      *           has no imps   \          in Make.C sc1' ... scm' ... vj ...
1752      *                          in d
1753      *
1754      * where sci are superclass dictionaries, d and f are new names, vj
1755      * is a newly generated name corresponding to the implementation of a
1756      * member function.  (Additional line number values must be added at
1757      * appropriate places but, for clarity, these are not shown above.)
1758      * --------------------------------------------------------------------*/
1759
1760     Int  alpha   = newKindedVars(cclass(inst(in).c).kinds);
1761     List supers  = makePredAss(cclass(inst(in).c).supers,alpha);
1762     Int  beta    = newKindedVars(inst(in).kinds);
1763     List params  = makePredAss(inst(in).specifics,beta);
1764     Cell d       = inventDictVar();
1765     List evids   = cons(triple(inst(in).head,mkInt(beta),d),
1766                         appendOnto(dupList(params),supers));
1767
1768     List imps    = inst(in).implements;
1769     Cell l       = mkInt(inst(in).line);
1770     Cell dictDef = cclass(inst(in).c).dbuild;
1771     List args    = NIL;
1772     List locs    = NIL;
1773     List ps;
1774
1775     if (!unifyPred(cclass(inst(in).c).head,alpha,inst(in).head,beta))
1776         internal("typeInstDefn");
1777
1778     for (ps=params; nonNull(ps); ps=tl(ps))     /* Build arglist           */
1779         args = cons(thd3(hd(ps)),args);
1780     args = rev(args);
1781
1782     for (ps=supers; nonNull(ps); ps=tl(ps)) {   /* Superclass dictionaries */
1783         Cell pi = hd(ps);
1784         Cell ev = scEntail(params,fst3(pi),intOf(snd3(pi)),0);
1785         if (isNull(ev))
1786             ev = inEntail(evids,fst3(pi),intOf(snd3(pi)),0);
1787         if (isNull(ev)) {
1788             clearMarks();
1789             ERRMSG(inst(in).line) "Cannot build superclass instance" ETHEN
1790             ERRTEXT "\n*** Instance            : " ETHEN
1791                 ERRPRED(copyPred(inst(in).head,beta));
1792             ERRTEXT "\n*** Context supplied    : " ETHEN
1793                 ERRCONTEXT(copyPreds(params));
1794             ERRTEXT "\n*** Required superclass : " ETHEN
1795                 ERRPRED(copyPred(fst3(pi),intOf(snd3(pi))));
1796             ERRTEXT "\n"
1797             EEND;
1798         }
1799         locs    = cons(pair(thd3(pi),singleton(pair(NIL,ap(l,ev)))),locs);
1800         dictDef = ap(dictDef,thd3(pi));
1801     }
1802     dictDef = ap(dictDef,d);
1803
1804     if (isNull(imps))                           /* No implementations      */
1805         locs = cons(pair(d,singleton(pair(NIL,ap(l,dictDef)))),locs);
1806     else {                                      /* Implementations supplied*/
1807         List mems  = cclass(inst(in).c).members;
1808         Cell f     = inventVar();
1809         Cell pat   = cclass(inst(in).c).dcon;
1810         Cell res   = pat;
1811         List locs1 = NIL;
1812
1813         locs       = cons(pair(d,singleton(pair(NIL,ap(l,ap(f,dictDef))))),
1814                           locs);
1815
1816         for (ps=supers; nonNull(ps); ps=tl(ps)){/* Add param for each sc   */
1817             Cell v = inventVar();
1818             pat    = ap(pat,v);
1819             res    = ap(res,v);
1820         }
1821
1822         for (; nonNull(mems); mems=tl(mems)) {  /* For each member:        */
1823             Cell v   = inventVar();
1824             Cell imp = NIL;
1825
1826             if (nonNull(imps)) {                /* Look for implementation */
1827                 imp  = hd(imps);
1828                 imps = tl(imps);
1829             }
1830
1831             if (isNull(imp)) {                  /* If none, f will copy    */
1832                 pat = ap(pat,v);                /* its argument unchanged  */
1833                 res = ap(res,v);
1834             }
1835             else {                              /* Otherwise, add the impl */
1836                 pat      = ap(pat,WILDCARD);    /* to f as a local defn    */
1837                 res      = ap(res,v);
1838                 typeMember("instance member binding",
1839                            hd(mems),
1840                            snd(imp),
1841                            evids,
1842                            inst(in).head,
1843                            beta);
1844                 locs1    = cons(pair(v,snd(imp)),locs1);
1845             }
1846         }
1847         res = ap(l,res);
1848         if (nonNull(locs1))                     /* Build the body of f     */
1849             res = ap(LETREC,pair(singleton(locs1),res));
1850         pat  = singleton(pat);                  /* And the arglist for f   */
1851         locs = cons(pair(f,singleton(pair(pat,res))),locs);
1852     }
1853     d = ap(l,d);
1854
1855     name(inst(in).builder).defn                 /* Register builder imp    */
1856              = singleton(pair(args,ap(LETREC,pair(singleton(locs),d))));
1857     //--------- Actual
1858     name(inst(in).builder).inlineMe   = TRUE;
1859     name(inst(in).builder).isDBuilder = TRUE;
1860     genDefns = cons(inst(in).builder,genDefns);
1861 }
1862
1863 static Void local typeMember(wh,mem,alts,evids,head,beta)
1864 String wh;                              /* Type check alternatives alts of */
1865 Name   mem;                             /* member mem for inst type head   */
1866 Cell   alts;                            /* at offset beta using predicate  */
1867 List   evids;                           /* assignment evids                */
1868 Cell   head;
1869 Int    beta; {
1870     Int  line = rhsLine(snd(hd(alts)));
1871     Type t;
1872     Int  o;
1873     Int  m;
1874     List ps;
1875     List qs;
1876     Type rt;
1877
1878 #ifdef DEBUG_TYPES
1879     Printf("\nType check member: ");
1880     printExp(stdout,mem);
1881     Printf(" :: ");
1882     printType(stdout,name(mem).type);
1883     Printf("\n   for the instance: ");
1884     printPred(stdout,head);
1885     Printf("\n");
1886 #endif
1887
1888     instantiate(name(mem).type);        /* Find required type              */
1889     o  = typeOff;
1890     m  = typeFree;
1891     t  = dropRank2(typeIs,o,m);
1892     ps = makePredAss(predsAre,o);
1893     if (!unifyPred(hd(predsAre),typeOff,head,beta))
1894         internal("typeMember1");
1895     clearMarks();
1896     qs = copyPreds(ps);
1897     rt = generalize(qs,liftRank2(t,o,m));
1898
1899 #ifdef DEBUG_TYPES
1900     Printf("Required type is: ");
1901     printType(stdout,rt);
1902     Printf("\n");
1903 #endif
1904
1905     hd(defnBounds) = NIL;               /* Type check each alternative     */
1906     hd(depends)    = NODEPENDS;
1907     enterPendingBtyvs();
1908     for (preds=NIL; nonNull(alts); alts=tl(alts)) {
1909         typeAlt(wh,mem,hd(alts),t,o,m);
1910         qualify(tl(ps),hd(alts));       /* Add any extra dict params       */
1911     }
1912     leavePendingBtyvs();
1913
1914     evids = appendOnto(dupList(tl(ps)), /* Build full complement of dicts  */
1915                        evids);
1916     clearMarks();
1917     qs = elimPredsUsing(evids,NIL);
1918     if (nonNull(preds) && resolveDefs(genvarType(t,o,NIL)))
1919         qs = elimPredsUsing(evids,qs);
1920     if (nonNull(qs)) {
1921         ERRMSG(line)
1922                 "Implementation of %s requires extra context",
1923                  textToStr(name(mem).text) ETHEN
1924         ERRTEXT "\n*** Expected type   : " ETHEN ERRTYPE(rt);
1925         ERRTEXT "\n*** Missing context : " ETHEN ERRCONTEXT(copyPreds(qs));
1926         ERRTEXT "\n"
1927         EEND;
1928     }
1929
1930     resetGenerics();                    /* Make sure we're general enough  */
1931     ps = copyPreds(ps);
1932     t  = generalize(ps,liftRank2(t,o,m));
1933 #ifdef DEBUG_TYPES
1934     Printf("   Inferred type is: ");
1935     printType(stdout,t);
1936     Printf("\n");
1937 #endif
1938     if (!sameSchemes(t,rt))
1939         tooGeneral(line,mem,rt,t);
1940     if (nonNull(preds))
1941         cantEstablish(line,wh,mem,t,ps);
1942 }
1943
1944 /* --------------------------------------------------------------------------
1945  * Type check bodies of bindings:
1946  * ------------------------------------------------------------------------*/
1947
1948 static Void local typeBind(b)          /* Type check binding               */
1949 Cell b; {
1950     if (isVar(fst(b))) {                               /* function binding */
1951         Cell ass = findTopBinding(fst(b));
1952         Int  beta;
1953
1954         if (isNull(ass))
1955             internal("typeBind");
1956
1957         beta = intOf(defType(snd(ass)));
1958         enterPendingBtyvs();
1959         map2Proc(typeDefAlt,beta,fst(b),snd(snd(b)));
1960         leavePendingBtyvs();
1961     }
1962     else {                                             /* pattern binding  */
1963         static String lhsPat = "lhs pattern";
1964         static String rhs    = "right hand side";
1965         Int  beta            = newTyvars(1);
1966         Pair pb              = snd(snd(b));
1967         Int  l               = rhsLine(snd(pb));
1968
1969         tcMode  = OLD_PATTERN;
1970         enterPendingBtyvs();
1971         fst(pb) = patBtyvs(fst(pb));
1972         check(l,fst(pb),NIL,lhsPat,aVar,beta);
1973         tcMode  = EXPRESSION;
1974         snd(pb) = typeRhs(snd(pb));
1975         shouldBe(l,rhsExpr(snd(pb)),NIL,rhs,aVar,beta);
1976         doneBtyvs(l);
1977         leavePendingBtyvs();
1978     }
1979 }
1980
1981 static Void local typeDefAlt(beta,v,a) /* type check alt in func. binding  */
1982 Int  beta;
1983 Cell v;
1984 Pair a; {
1985     static String valDef = "function binding";
1986     typeAlt(valDef,v,a,aVar,beta,0);
1987 }
1988
1989 static Cell local typeRhs(e)           /* check type of rhs of definition  */
1990 Cell e; {
1991     switch (whatIs(e)) {
1992         case GUARDED : {   Int beta = newTyvars(1);
1993                            map1Proc(guardedType,beta,snd(e));
1994                            tyvarType(beta);
1995                        }
1996                        break;
1997
1998         case LETREC  : enterBindings();
1999                        enterSkolVars();
2000                        mapProc(typeBindings,fst(snd(e)));
2001                        snd(snd(e)) = typeRhs(snd(snd(e)));
2002                        leaveBindings();
2003                        leaveSkolVars(rhsLine(snd(snd(e))),typeIs,typeOff,0);
2004                        break;
2005
2006         case RSIGN   : fst(snd(e)) = typeRhs(fst(snd(e)));
2007                        shouldBe(rhsLine(fst(snd(e))),
2008                                 rhsExpr(fst(snd(e))),NIL,
2009                                 "result type",
2010                                 snd(snd(e)),0);
2011                        return fst(snd(e));
2012
2013         default      : snd(e) = typeExpr(intOf(fst(e)),snd(e));
2014                        break;
2015     }
2016     return e;
2017 }
2018
2019 static Void local guardedType(beta,gded)/* check type of guard (li,(gd,ex))*/
2020 Int  beta;                             /* should have gd :: Bool,          */
2021 Cell gded; {                           /*             ex :: (var,beta)     */
2022     static String guarded = "guarded expression";
2023     static String guard   = "guard";
2024     Int line = intOf(fst(gded));
2025
2026     gded     = snd(gded);
2027     check(line,fst(gded),NIL,guard,typeBool,0);
2028     check(line,snd(gded),NIL,guarded,aVar,beta);
2029 }
2030
2031 Cell rhsExpr(rhs)                      /* find first expression on a rhs   */
2032 Cell rhs; {
2033     switch (whatIs(rhs)) {
2034         case GUARDED : return snd(snd(hd(snd(rhs))));
2035         case LETREC  : return rhsExpr(snd(snd(rhs)));
2036         case RSIGN   : return rhsExpr(fst(snd(rhs)));
2037         default      : return snd(rhs);
2038     }
2039 }
2040
2041 Int rhsLine(rhs)                       /* find line number associated with */
2042 Cell rhs; {                            /* a right hand side                */
2043     switch (whatIs(rhs)) {
2044         case GUARDED : return intOf(fst(hd(snd(rhs))));
2045         case LETREC  : return rhsLine(snd(snd(rhs)));
2046         case RSIGN   : return rhsLine(fst(snd(rhs)));
2047         default      : return intOf(fst(rhs));
2048     }
2049 }
2050
2051 /* --------------------------------------------------------------------------
2052  * Calculate generalization of types and compare with declared type schemes:
2053  * ------------------------------------------------------------------------*/
2054
2055 static Void local genBind(ps,b)         /* Generalize the type of each var */
2056 List ps;                                /* defined in binding b, qualifying*/
2057 Cell b; {                               /* each with the predicates in ps. */
2058     Cell v = fst(b);
2059     Cell t = fst(snd(b));
2060
2061     if (isVar(fst(b)))
2062         genAss(rhsLine(snd(hd(snd(snd(b))))),ps,v,t);
2063     else {
2064         Int line = rhsLine(snd(snd(snd(b))));
2065         for (; nonNull(v); v=tl(v)) {
2066             Type ty = NIL;
2067             if (nonNull(t)) {
2068                 ty = hd(t);
2069                 t  = tl(t);
2070             }
2071             genAss(line,ps,hd(v),ty);
2072         }
2073     }
2074 }
2075
2076 static Void local genAss(l,ps,v,dt)     /* Calculate inferred type of v and*/
2077 Int  l;                                 /* compare with declared type, dt, */
2078 List ps;                                /* if given & check for ambiguity. */
2079 Cell v;
2080 Type dt; {
2081     Cell ass = findTopBinding(v);
2082
2083     if (isNull(ass))
2084         internal("genAss");
2085
2086     snd(ass) = genTest(l,v,ps,dt,aVar,intOf(defType(snd(ass))));
2087
2088 #ifdef DEBUG_TYPES
2089     printExp(stdout,v);
2090     Printf(" :: ");
2091     printType(stdout,snd(ass));
2092     Printf("\n");
2093 #endif
2094 }
2095
2096 static Type local genTest(l,v,ps,dt,t,o)/* Generalize and test inferred    */
2097 Int  l;                                 /* type (t,o) with context ps      */
2098 Cell v;                                 /* against declared type dt for v. */
2099 List ps;
2100 Type dt;
2101 Type t;
2102 Int  o; {
2103     Type bt = NIL;                      /* Body of inferred type           */
2104     Type it = NIL;                      /* Full inferred type              */
2105
2106     resetGenerics();                    /* Calculate Haskell typing        */
2107     ps = copyPreds(ps);
2108     bt = copyType(t,o);
2109     it = generalize(ps,bt);
2110
2111     if (nonNull(dt)) {                  /* If a declared type was given,   */
2112         instantiate(dt);                /* check body for match.           */
2113         if (!equalTypes(typeIs,bt))
2114             tooGeneral(l,v,dt,it);
2115     }
2116     else if (nonNull(ps))               /* Otherwise test for ambiguity in */
2117         if (isAmbiguous(it))            /* inferred type.                  */
2118             ambigError(l,"inferred type",v,it);
2119
2120     return it;
2121 }
2122
2123 static Type local generalize(qs,t)      /* calculate generalization of t   */
2124 List qs;                                /* having already marked fixed vars*/
2125 Type t; {                               /* with qualifying preds qs        */
2126     if (nonNull(qs))
2127         t = ap(QUAL,pair(qs,t));
2128     if (nonNull(genericVars)) {
2129         Kind k  = STAR;
2130         List vs = genericVars;
2131         for (; nonNull(vs); vs=tl(vs)) {
2132             Tyvar *tyv = tyvar(intOf(hd(vs)));
2133             Kind   ka  = tyv->kind;
2134             k = ap(ka,k);
2135         }
2136         t = mkPolyType(k,t);
2137 #ifdef DEBUG_KINDS
2138     Printf("Generalized type: ");
2139     printType(stdout,t);
2140     Printf(" ::: ");
2141     printKind(stdout,k);
2142     Printf("\n");
2143 #endif
2144     }
2145     return t;
2146 }
2147
2148 static Bool local equalTypes(t1,t2)    /* Compare simple types for equality*/
2149 Type t1, t2; {
2150
2151 et: if (whatIs(t1)!=whatIs(t2))
2152         return FALSE;
2153
2154     switch (whatIs(t1)) {
2155 #if TREX
2156         case EXT     :
2157 #endif
2158         case TYCON   :
2159         case OFFSET  :
2160         case TUPLE   : return t1==t2;
2161
2162         case INTCELL : return intOf(t1)!=intOf(t2);
2163
2164         case AP      : if (equalTypes(fun(t1),fun(t2))) {
2165                            t1 = arg(t1);
2166                            t2 = arg(t2);
2167                            goto et;
2168                        }
2169                        return FALSE;
2170
2171         default      : internal("equalTypes");
2172     }
2173
2174     return TRUE;/*NOTREACHED*/
2175 }
2176
2177 /* --------------------------------------------------------------------------
2178  * Entry points to type checker:
2179  * ------------------------------------------------------------------------*/
2180
2181 Type typeCheckExp(useDefs)              /* Type check top level expression */
2182 Bool useDefs; {                         /* using defaults if reqd          */
2183     Type type;
2184     List ctxt;
2185     Int  beta;
2186
2187     typeChecker(RESET);
2188     emptySubstitution();
2189     enterBindings();
2190     inputExpr = typeExpr(0,inputExpr);
2191     type      = typeIs;
2192     beta      = typeOff;
2193     clearMarks();
2194     normPreds(0);
2195     elimTauts();
2196     preds     = scSimplify(preds);
2197     if (useDefs && nonNull(preds)) {
2198         clearMarks();
2199         reducePreds();
2200         if (nonNull(preds) && resolveDefs(NIL)) /* Nearly Haskell 1.4?     */
2201             elimTauts();
2202     }
2203     resetGenerics();
2204     ctxt      = copyPreds(preds);
2205     type      = generalize(ctxt,copyType(type,beta));
2206     inputExpr = qualifyExpr(0,preds,inputExpr);
2207     h98CheckType(0,"inferred type",inputExpr,type);
2208     typeChecker(RESET);
2209     emptySubstitution();
2210     return type;
2211 }
2212
2213 Void typeCheckDefns() {                /* Type check top level bindings    */
2214     Target t  = length(selDefns)  + length(valDefns) +
2215                 length(instDefns) + length(classDefns);
2216     Target i  = 0;
2217     List   gs;
2218
2219     typeChecker(RESET);
2220     emptySubstitution();
2221     enterSkolVars();
2222     enterBindings();
2223     setGoal("Type checking",t);
2224
2225     for (gs=selDefns; nonNull(gs); gs=tl(gs)) {
2226         mapOver(typeSel,hd(gs));
2227         soFar(i++);
2228     }
2229     for (gs=valDefns; nonNull(gs); gs=tl(gs)) {
2230         typeDefnGroup(hd(gs));
2231         soFar(i++);
2232     }
2233     clearTypeIns();
2234     for (gs=classDefns; nonNull(gs); gs=tl(gs)) {
2235         emptySubstitution();
2236         typeClassDefn(hd(gs));
2237         soFar(i++);
2238     }
2239     for (gs=instDefns; nonNull(gs); gs=tl(gs)) {
2240         emptySubstitution();
2241         typeInstDefn(hd(gs));
2242         soFar(i++);
2243     }
2244
2245     typeChecker(RESET);
2246     emptySubstitution();
2247     done();
2248 }
2249
2250 static Void local typeDefnGroup(bs)     /* type check group of value defns */
2251 List bs; {                              /* (one top level scc)             */
2252     List as;
2253     // printf("\n\n+++ DefnGroup ++++++++++++++++++++++++++++\n");
2254     //{ List qq; for (qq=bs;nonNull(qq);qq=tl(qq)){
2255     //   print(hd(qq),4);
2256     //   printf("\n");
2257     //}}
2258
2259     emptySubstitution();
2260     hd(defnBounds) = NIL;
2261     preds          = NIL;
2262     setTypeIns(bs);
2263     typeBindings(bs);                   /* find types for vars in bindings */
2264
2265     if (nonNull(preds)) {
2266         Cell v = fst(hd(hd(varsBounds)));
2267         Name n = findName(textOf(v));
2268         Int  l = nonNull(n) ? name(n).line : 0;
2269         preds  = scSimplify(preds);
2270         ERRMSG(l) "Instance%s of ", (length(preds)==1 ? "" : "s") ETHEN
2271         ERRCONTEXT(copyPreds(preds));
2272         ERRTEXT   " required for definition of " ETHEN
2273         ERREXPR(nonNull(n)?n:v);
2274         ERRTEXT   "\n"
2275         EEND;
2276     }
2277
2278     if (nonNull(hd(skolVars))) {
2279         Cell b = hd(bs);
2280         Name n = findName(isVar(fst(b)) ? textOf(fst(b)) : textOf(hd(fst(b))));
2281         Int  l = nonNull(n) ? name(n).line : 0;
2282         leaveSkolVars(l,typeUnit,0,0);
2283         enterSkolVars();
2284     }
2285
2286     for (as=hd(varsBounds); nonNull(as); as=tl(as)) {
2287         Cell a = hd(as);                /* add infered types to environment*/
2288         Name n = findName(textOf(fst(a)));
2289         if (isNull(n))
2290             internal("typeDefnGroup");
2291         name(n).type = snd(a);
2292     }
2293     hd(varsBounds) = NIL;
2294 }
2295
2296 static Pair local typeSel(s)            /* Calculate a suitable type for a */
2297 Name s; {                               /* particular selector, s.         */
2298     List cns  = name(s).defn;
2299     Int  line = name(s).line;
2300     Type dom  = NIL;                    /* Inferred domain                 */
2301     Type rng  = NIL;                    /* Inferred range                  */
2302     Cell nv   = inventVar();
2303     List alts = NIL;
2304     Int  o;
2305     Int  m;
2306
2307 #ifdef DEBUG_SELS
2308     Printf("Selector %s, cns=",textToStr(name(s).text));
2309     printExp(stdout,cns);
2310     Putchar('\n');
2311 #endif
2312
2313     emptySubstitution();
2314     preds = NIL;
2315
2316     for (; nonNull(cns); cns=tl(cns)) {
2317         Name c   = fst(hd(cns));
2318         Int  n   = intOf(snd(hd(cns)));
2319         Int  a   = name(c).arity;
2320         Cell pat = c;
2321         Type dom1;
2322         Type rng1;
2323         Int  o1;
2324         Int  m1;
2325
2326         instantiate(name(c).type);      /* Instantiate constructor type    */
2327         o1 = typeOff;
2328         m1 = typeFree;
2329         for (; nonNull(predsAre); predsAre=tl(predsAre))
2330             assumeEvid(hd(predsAre),o1);
2331
2332         if (whatIs(typeIs)==RANK2)      /* Skip rank2 annotation, if any   */
2333             typeIs = snd(snd(typeIs));
2334         for (; --n>0; a--) {            /* Get range                       */
2335             pat    = ap(pat,WILDCARD);
2336             typeIs = arg(typeIs);
2337         }
2338         rng1   = dropRank1(arg(fun(typeIs)),o1,m1);
2339         pat    = ap(pat,nv);
2340         typeIs = arg(typeIs);
2341         while (--a>0) {                 /* And then look for domain        */
2342             pat    = ap(pat,WILDCARD);
2343             typeIs = arg(typeIs);
2344         }
2345         dom1   = typeIs;
2346
2347         if (isNull(dom)) {              /* Save first domain type and then */
2348             dom = dom1;                 /* unify with subsequent domains to*/
2349             o   = o1;                   /* match up preds and range types  */
2350             m   = m1;
2351         }
2352         else if (!unify(dom1,o1,dom,o))
2353             internal("typeSel1");
2354
2355         if (isNull(rng))                /* Compare component types         */
2356             rng = rng1;
2357         else if (!sameSchemes(rng1,rng)) {
2358             clearMarks();
2359             rng  = liftRank1(rng,o,m);
2360             rng1 = liftRank1(rng1,o1,m1);
2361             ERRMSG(name(s).line) "Mismatch in field types for selector \"%s\"",
2362                                  textToStr(name(s).text) ETHEN
2363             ERRTEXT "\n*** Field type     : "            ETHEN ERRTYPE(rng1);
2364             ERRTEXT "\n*** Does not match : "            ETHEN ERRTYPE(rng);
2365             ERRTEXT "\n"
2366             EEND;
2367         }
2368         alts = cons(pair(singleton(pat),pair(mkInt(line),nv)),alts);
2369     }
2370     alts = rev(alts);
2371
2372     if (isNull(dom) || isNull(rng))     /* Should have been initialized by */
2373         internal("typeSel2");           /* now, assuming length cns >= 1.  */
2374
2375     clearMarks();                       /* No fixed variables here         */
2376     preds = scSimplify(preds);          /* Simplify context                */
2377     dom   = copyType(dom,o);            /* Calculate domain type           */
2378     instantiate(rng);
2379     rng   = copyType(typeIs,typeOff);
2380     if (nonNull(predsAre)) {
2381         List ps    = makePredAss(predsAre,typeOff);
2382         List alts1 = alts;
2383         for (; nonNull(alts1); alts1=tl(alts1)) {
2384             Cell body = nv;
2385             List qs   = ps;
2386             for (; nonNull(qs); qs=tl(qs))
2387                 body = ap(body,thd3(hd(qs)));
2388             snd(snd(hd(alts1))) = body;
2389         }
2390         preds = appendOnto(preds,ps);
2391     }
2392     name(s).type  = generalize(copyPreds(preds),fn(dom,rng));
2393     name(s).arity = 1 + length(preds);
2394     map1Proc(qualify,preds,alts);
2395
2396 #ifdef DEBUG_SELS
2397     Printf("Inferred arity = %d, type = ",name(s).arity);
2398     printType(stdout,name(s).type);
2399     Putchar('\n');
2400 #endif
2401
2402     return pair(s,alts);
2403 }
2404
2405
2406 /* --------------------------------------------------------------------------
2407  * Local function prototypes:
2408  * ------------------------------------------------------------------------*/
2409
2410 static Type local basicType Args((Char));
2411
2412
2413 static Type stateVar = NIL;
2414 static Type alphaVar = NIL;
2415 static Type betaVar  = NIL;
2416 static Type gammaVar = NIL;
2417 static Int  nextVar  = 0;
2418
2419 static Void clearTyVars( void )
2420 {
2421     stateVar = NIL;
2422     alphaVar = NIL;
2423     betaVar  = NIL;
2424     gammaVar = NIL;
2425     nextVar  = 0;
2426 }
2427
2428 static Type mkStateVar( void )
2429 {
2430     if (isNull(stateVar)) {
2431         stateVar = mkOffset(nextVar++);
2432     }
2433     return stateVar;
2434 }
2435
2436 static Type mkAlphaVar( void )
2437 {
2438     if (isNull(alphaVar)) {
2439         alphaVar = mkOffset(nextVar++);
2440     }
2441     return alphaVar;
2442 }
2443
2444 static Type mkBetaVar( void )
2445 {
2446     if (isNull(betaVar)) {
2447         betaVar = mkOffset(nextVar++);
2448     }
2449     return betaVar;
2450 }
2451
2452 static Type mkGammaVar( void )
2453 {
2454     if (isNull(gammaVar)) {
2455         gammaVar = mkOffset(nextVar++);
2456     }
2457     return gammaVar;
2458 }
2459
2460 static Type local basicType(k)
2461 Char k; {
2462     switch (k) {
2463     case CHAR_REP:
2464             return typeChar;
2465     case INT_REP:
2466             return typeInt;
2467     case INTEGER_REP:
2468             return typeInteger;
2469     case ADDR_REP:
2470             return typeAddr;
2471     case WORD_REP:
2472             return typeWord;
2473     case FLOAT_REP:
2474             return typeFloat;
2475     case DOUBLE_REP:
2476             return typeDouble;
2477     case ARR_REP:     return ap(typePrimArray,mkAlphaVar());            
2478     case BARR_REP:    return typePrimByteArray;
2479     case REF_REP:     return ap2(typeRef,mkStateVar(),mkAlphaVar());                  
2480     case MUTARR_REP:  return ap2(typePrimMutableArray,mkStateVar(),mkAlphaVar());     
2481     case MUTBARR_REP: return ap(typePrimMutableByteArray,mkStateVar()); 
2482 #ifdef PROVIDE_STABLE
2483     case STABLE_REP:
2484             return ap(typeStable,mkAlphaVar());
2485 #endif
2486 #ifdef PROVIDE_WEAK
2487     case WEAK_REP:
2488             return ap(typeWeak,mkAlphaVar());
2489     case IO_REP:
2490             return ap(typeIO,typeUnit);
2491 #endif
2492 #ifdef PROVIDE_FOREIGN
2493     case FOREIGN_REP:
2494             return typeForeign;
2495 #endif
2496 #ifdef PROVIDE_CONCURRENT
2497     case THREADID_REP:
2498             return typeThreadId;
2499     case MVAR_REP:
2500             return ap(typeMVar,mkAlphaVar());
2501 #endif
2502     case BOOL_REP:
2503             return typeBool;
2504     case HANDLER_REP:
2505             return fn(typeException,mkAlphaVar());
2506     case ERROR_REP:
2507             return typeException;
2508     case ALPHA_REP:
2509             return mkAlphaVar();  /* polymorphic */
2510     case BETA_REP:
2511             return mkBetaVar();   /* polymorphic */
2512     case GAMMA_REP:
2513             return mkGammaVar();  /* polymorphic */
2514     default:
2515             printf("Kind: '%c'\n",k);
2516             internal("basicType");
2517     }
2518     assert(0); return 0; /* NOTREACHED */
2519 }
2520
2521 /* Generate type of primop based on list of arg types and result types:
2522  *
2523  * eg primType "II" "II" = Int -> Int -> (Int,Int)
2524  *
2525  */
2526 Type primType( Int /*AsmMonad*/ monad, String a_kinds, String r_kinds )
2527 {
2528     List rs    = NIL;
2529     List as    = NIL;
2530     List tvars = NIL; /* for polymorphic types */
2531     Type r;
2532
2533     clearTyVars();
2534
2535     /* build result types */
2536     for(; *r_kinds; ++r_kinds) {
2537         rs = cons(basicType(*r_kinds),rs);
2538     }
2539     /* Construct tuple of results */
2540     if (length(rs) == 0) {
2541         r = typeUnit;
2542     } else if (length(rs) == 1) {
2543         r = hd(rs);
2544     } else {
2545         r = mkTuple(length(rs));
2546         for(rs = rev(rs); nonNull(rs); rs=tl(rs)) {
2547             r = ap(r,hd(rs));
2548         }
2549     }
2550     /* Construct list of arguments */
2551     for(; *a_kinds; ++a_kinds) {
2552         as = cons(basicType(*a_kinds),as);
2553     }
2554     /* Apply any monad magic */
2555     if (monad == MONAD_IO) {
2556         r = ap(typeIO,r);
2557     } else if (monad == MONAD_ST) {
2558         r = ap2(typeST,mkStateVar(),r);
2559     }
2560     /* glue it all together */
2561     for(; nonNull(as); as=tl(as)) {
2562         r = fn(hd(as),r);
2563     }
2564     tvars = offsetTyvarsIn(r,NIL);
2565     if (nonNull(tvars)) {
2566         assert(length(tvars) == nextVar);
2567         r = mkPolyType(simpleKind(length(tvars)),r);
2568     }
2569 #if DEBUG_CODE
2570     if (debugCode) {
2571         printType(stdout,r); printf("\n");
2572     }
2573 #endif
2574     return r;
2575 }    
2576
2577 /* forall a1 .. am. TC a1 ... am -> Int */
2578 Type conToTagType(t)
2579 Tycon t; {
2580     Type   ty  = t;
2581     List   tvars = NIL;
2582     Int    i   = 0;
2583     for (i=0; i<tycon(t).arity; ++i) {
2584         Offset tv = mkOffset(i);
2585         ty = ap(ty,tv);
2586         tvars = cons(tv,tvars);
2587     }
2588     ty = fn(ty,typeInt);
2589     if (nonNull(tvars)) {
2590         ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2591     }
2592     return ty;
2593 }
2594
2595 /* forall a1 .. am. Int -> TC a1 ... am */
2596 Type tagToConType(t)
2597 Tycon t; {
2598     Type   ty  = t;
2599     List   tvars = NIL;
2600     Int    i   = 0;
2601     for (i=0; i<tycon(t).arity; ++i) {
2602         Offset tv = mkOffset(i);
2603         ty = ap(ty,tv);
2604         tvars = cons(tv,tvars);
2605     }
2606     ty = fn(typeInt,ty);
2607     if (nonNull(tvars)) {
2608         ty = mkPolyType(simpleKind(tycon(t).arity),ty);
2609     }
2610     return ty;
2611 }
2612
2613 /* --------------------------------------------------------------------------
2614  * Type checker control:
2615  * ------------------------------------------------------------------------*/
2616
2617 Void typeChecker(what)
2618 Int what; {
2619     switch (what) {
2620         case RESET   : tcMode       = EXPRESSION;
2621                        preds        = NIL;
2622                        pendingBtyvs = NIL;
2623                        daSccs       = NIL;
2624                        emptyAssumption();
2625                        break;
2626
2627         case MARK    : mark(daSccs);
2628                        mark(defnBounds);
2629                        mark(varsBounds);
2630                        mark(depends);
2631                        mark(pendingBtyvs);
2632                        mark(skolVars);
2633                        mark(localEvs);
2634                        mark(savedPs);
2635                        mark(dummyVar);
2636                        mark(preds);
2637                        mark(stdDefaults);
2638                        mark(arrow);
2639                        mark(boundPair);
2640                        mark(listof);
2641                        mark(typeVarToVar);
2642                        mark(predNum);
2643                        mark(predFractional);
2644                        mark(predIntegral);
2645                        mark(starToStar);
2646                        mark(predMonad);
2647                        break;
2648
2649         case INSTALL : typeChecker(RESET);
2650                        dummyVar     = inventVar();
2651
2652                        setCurrModule(modulePrelude);
2653
2654                        starToStar   = simpleKind(1);
2655
2656                        typeUnit     = addPrimTycon(findText("()"),
2657                                                    STAR,0,DATATYPE,NIL);
2658                        typeArrow    = addPrimTycon(findText("(->)"),
2659                                                    simpleKind(2),2,
2660                                                    DATATYPE,NIL);
2661                        typeList     = addPrimTycon(findText("[]"),
2662                                                    starToStar,1,
2663                                                    DATATYPE,NIL);
2664
2665                        arrow        = fn(aVar,bVar);
2666                        listof       = ap(typeList,aVar);
2667                        boundPair    = ap(ap(mkTuple(2),aVar),aVar);
2668
2669                        nameUnit     = addPrimCfun(findText("()"),0,0,typeUnit);
2670                        tycon(typeUnit).defn
2671                                     = singleton(nameUnit);
2672
2673                        nameNil      = addPrimCfun(findText("[]"),0,1,
2674                                                    mkPolyType(starToStar,
2675                                                               listof));
2676                        nameCons     = addPrimCfun(findText(":"),2,2,
2677                                                    mkPolyType(starToStar,
2678                                                               fn(aVar,
2679                                                               fn(listof,
2680                                                                  listof))));
2681                        name(nameNil).parent =
2682                        name(nameCons).parent = typeList;
2683
2684                        name(nameCons).syntax
2685                                     = mkSyntax(RIGHT_ASS,5);
2686
2687                        tycon(typeList).defn
2688                                     = cons(nameNil,cons(nameCons,NIL));
2689
2690                        typeVarToVar = fn(aVar,aVar);
2691 #if TREX
2692                        typeNoRow    = addPrimTycon(findText("EmptyRow"),
2693                                                    ROW,0,DATATYPE,NIL);
2694                        typeRec      = addPrimTycon(findText("Rec"),
2695                                                    pair(ROW,STAR),1,
2696                                                    DATATYPE,NIL);
2697                        nameNoRec    = addPrimCfun(findText("EmptyRec"),0,0,
2698                                                         ap(typeRec,typeNoRow));
2699 #else
2700                        /* bogus definitions to avoid changing the prelude */
2701                        addPrimCfun(findText("Rec"),      0,0,typeUnit);
2702                        addPrimCfun(findText("EmptyRow"), 0,0,typeUnit);
2703                        addPrimCfun(findText("EmptyRec"), 0,0,typeUnit);
2704 #endif
2705                        break;
2706     }
2707 }
2708
2709 /*-------------------------------------------------------------------------*/