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