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