ead1c975502703c97e5a146d60e024e55df1bed1
[ghc-hetmet.git] / ghc / interpreter / subst.c
1
2 /* --------------------------------------------------------------------------
3  * Provides an implementation for the `current substitution' used during
4  * type and kind inference in both static analysis and type checking.
5  *
6  * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
7  * Yale Haskell Group, and the Oregon Graduate Institute of Science and
8  * Technology, 1994-1999, All rights reserved.  It is distributed as
9  * free software under the license in the file "License", which is
10  * included in the distribution.
11  *
12  * $RCSfile: subst.c,v $
13  * $Revision: 1.7 $
14  * $Date: 1999/10/16 02:17:27 $
15  * ------------------------------------------------------------------------*/
16
17 #include "prelude.h"
18 #include "storage.h"
19 #include "connect.h"
20 #include "errors.h"
21 #include "link.h"
22 #include "subst.h"
23
24 /*#define DEBUG_TYPES*/
25
26 static Int numTyvars;                   /* no. type vars currently in use  */
27 static Int maxTyvars = 0;
28 static Int nextGeneric;                 /* number of generics found so far */
29
30 #if    FIXED_SUBST
31 Tyvar  tyvars[NUM_TYVARS];              /* storage for type variables      */
32 #else
33 Tyvar  *tyvars = 0;                     /* storage for type variables      */
34 #endif
35 Int    typeOff;                         /* offset of result type           */
36 Type   typeIs;                          /* skeleton of result type         */
37 Int    typeFree;                        /* freedom in instantiated type    */
38 List   predsAre;                        /* list of predicates in type      */
39 List   genericVars;                     /* list of generic vars            */
40 List   btyvars = NIL;                   /* explicitly scoped type vars     */
41
42 /* --------------------------------------------------------------------------
43  * local function prototypes:
44  * ------------------------------------------------------------------------*/
45
46 static Void local expandSubst           Args((Int));
47 static Int  local findBtyvsInt          Args((Text));
48 static Type local makeTupleType         Args((Int));
49 static Kind local makeSimpleKind        Args((Int));
50 static Kind local makeVarKind           Args((Int));
51 static Void local expandSyn1            Args((Tycon, Type *, Int *));
52 static List local listTyvar             Args((Int,List));
53 static List local listTyvars            Args((Type,Int,List));
54 static Cell local dupTyvar              Args((Int,List));
55 static Cell local dupTyvars             Args((Cell,Int,List));
56 static Pair local copyNoMark            Args((Cell,Int));
57 static Type local dropRank1Body         Args((Type,Int,Int));
58 static Type local liftRank1Body         Args((Type,Int));
59
60 static Bool local varToVarBind          Args((Tyvar *,Tyvar *));
61 static Bool local varToTypeBind         Args((Tyvar *,Type,Int));
62 #if TREX
63 static Bool local inserter              Args((Type,Int,Type,Int));
64 static Int  local remover               Args((Text,Type,Int));
65 static Int  local tailVar               Args((Type,Int));
66 #endif
67
68 static Bool local pairImprove           Args((Int,Class,Cell,Int,Cell,Int));
69 static Bool local instImprove           Args((Int,Cell,Int));
70 static Bool local improveAgainst        Args((Int,List,Cell,Int));
71 #if IPARAM
72 static Bool local ipImprove             Args((Int,Cell,Int,Cell,Int));
73 #endif
74
75 static Bool local kvarToVarBind         Args((Tyvar *,Tyvar *));
76 static Bool local kvarToTypeBind        Args((Tyvar *,Type,Int));
77
78 /* --------------------------------------------------------------------------
79  * The substitution, types, and kinds:
80  *
81  * In early versions of Gofer, the `substitution' data structure was only
82  * used by the type checker, so it made sense to include support for it in
83  * type.c.  This changed when kinds and kind inference where introduced,
84  * which required access to the substitution during static analysis.  The
85  * links between type.c and static.c that were intially used to accomplish
86  * this have now been avoided by making the substitution visible as an
87  * independent data structure in storage.c.
88  *
89  * In the same way that values have types, type constructors (and more
90  * generally, expressions built from such constructors) have kinds.
91  * The syntax of kinds in the current implementation is very simple:
92  *
93  *        kind ::= STAR         -- the kind of types
94  *              |  kind => kind -- constructors
95  *              |  variables    -- either INTCELL or OFFSET
96  *
97  * For various reasons, this implementation uses structure sharing, instead
98  * of a copying approach.  In principal, this is fast and avoids the need to
99  * build new type expressions.  Unfortunately, this implementation will not
100  * be able to handle *very* large expressions.
101  *
102  * The substitution is represented by an array of type variables each of
103  * which is a triple:
104  *      bound   a (skeletal) type expression, or NIL if the variable
105  *              is not bound, or SKOLEM for a Skolem constant (i.e., an
106  *              uninstantiable variable).
107  *      offs    offset of skeleton in bound.  If isNull(bound), then offs is
108  *              used to indicate whether that variable is generic (i.e. free
109  *              in the current assumption set) or fixed (i.e. bound in the
110  *              current assumption set).  Generic variables are assigned
111  *              offset numbers whilst copying type expressions (t,o) to
112  *              obtain their most general form.
113  *      kind    kind of value bound to type variable (`type variable' is
114  *              rather inaccurate -- `constructor variable' would be better).
115  * ------------------------------------------------------------------------*/
116
117 Void emptySubstitution() {              /* clear current substitution      */
118     numTyvars   = 0;
119 #if !FIXED_SUBST
120     if (maxTyvars!=NUM_TYVARS) {
121         maxTyvars = 0;
122         if (tyvars) {
123             free(tyvars);
124             tyvars = 0;
125         }
126     }
127 #endif
128     nextGeneric = 0;
129     genericVars = NIL;
130     typeIs      = NIL;
131     predsAre    = NIL;
132     btyvars     = NIL;
133 }
134
135 static Void local expandSubst(n)        /* add further n type variables to */
136 Int n; {                                /* current substituion             */
137 #if FIXED_SUBST
138     if (numTyvars+n>NUM_TYVARS) {
139         ERRMSG(0) "Too many type variables in type checker"
140         EEND;
141     }
142 #else
143     if (numTyvars+n>maxTyvars) {        /* need to expand substitution     */
144         Int   newMax = maxTyvars+NUM_TYVARS;
145         Tyvar *newTvs;
146         Int   i;
147
148         if (numTyvars+n>newMax) {       /* safety precaution               */
149             ERRMSG(0) "Substitution expanding too quickly"
150             EEND;
151         }
152
153         /* It would be better to realloc() here, but that isn't portable
154          * enough for calloc()ed arrays.  The following code could cause
155          * a space leak if an interrupt occurs while we're copying the
156          * array ... we won't worry about this for the time being because
157          * we don't expect to have to go through this process much (if at
158          * all) in normal use of the type checker.
159          */
160
161         newTvs = (Tyvar *)calloc(newMax,sizeof(Tyvar));
162         if (!newTvs) {
163             ERRMSG(0) "Too many variables (%d) in type checker", newMax
164             EEND;
165         }
166         for (i=0; i<numTyvars;++i) {            /* copy substitution       */
167             newTvs[i].offs  = tyvars[i].offs;
168             newTvs[i].bound = tyvars[i].bound;
169             newTvs[i].kind  = tyvars[i].kind;
170         }
171         maxTyvars = 0;                          /* protection from SIGINT? */
172         if (tyvars) free(tyvars);
173         tyvars    = newTvs;
174         maxTyvars = newMax;
175     }
176 #endif
177 }
178
179 Int newTyvars(n)                        /* allocate new type variables     */
180 Int n; {                                /* all of kind STAR                */
181     Int beta = numTyvars;
182
183     expandSubst(n);
184     for (numTyvars+=n; n>0; n--) {
185         tyvars[numTyvars-n].offs  = UNUSED_GENERIC;
186         tyvars[numTyvars-n].bound = NIL;
187         tyvars[numTyvars-n].kind  = STAR;
188 #ifdef DEBUG_TYPES
189         Printf("new type variable: _%d ::: ",numTyvars-n);
190         printKind(stdout,tyvars[numTyvars-n].kind);
191         Putchar('\n');
192 #endif
193     }
194     return beta;
195 }
196
197 Int newKindedVars(k)                    /* allocate new variables with     */
198 Kind k; {                               /* specified kinds                 */
199     Int beta = numTyvars;               /* if k = k0 -> k1 -> ... -> kn    */
200     for (; isPair(k); k=snd(k)) {       /* then allocate n vars with kinds */
201         expandSubst(1);                 /* k0, k1, ..., k(n-1)             */
202         tyvars[numTyvars].offs  = UNUSED_GENERIC;
203         tyvars[numTyvars].bound = NIL;
204         tyvars[numTyvars].kind  = fst(k);
205 #ifdef DEBUG_TYPES
206         Printf("new type variable: _%d ::: ",numTyvars);
207         printKind(stdout,tyvars[numTyvars].kind);
208         Putchar('\n');
209 #endif
210         numTyvars++;
211     }
212     return beta;
213 }
214
215 Void instantiate(type)                  /* instantiate type, if nonNull    */
216 Type type; {
217     predsAre = NIL;
218     typeIs   = type;
219     typeFree = 0;
220
221     if (nonNull(typeIs)) {             /* instantiate type expression ?    */
222
223         if (isPolyType(typeIs)) {      /* Polymorphic type scheme ?        */
224             Kinds ks = polySigOf(typeIs);
225             typeOff  = newKindedVars(ks);
226             typeIs   = monotypeOf(typeIs);
227             for (; isAp(ks); ks=arg(ks))
228                 typeFree++;
229         }
230
231         if (isQualType(typeIs)) {    /* Qualified type?                    */
232             predsAre = fst(snd(typeIs));
233             typeIs   = snd(snd(typeIs));
234         }
235     }
236 }
237
238 /* --------------------------------------------------------------------------
239  * Bound type variables:
240  * ------------------------------------------------------------------------*/
241
242 Pair findBtyvs(t)                       /* Look for bound tyvar            */
243 Text t; {
244     List bts = btyvars;
245     for (; nonNull(bts); bts=tl(bts)) {
246         List bts1 = hd(bts);
247         for (; nonNull(bts1); bts1=tl(bts1))
248             if (t==textOf(fst(hd(bts1))))
249                 return hd(bts1);
250     }
251     return NIL;
252 }
253
254 static Int local findBtyvsInt(t)        /* Look for bound type variable    */
255 Text t; {                               /* expecting to find an integer    */
256     Pair p = findBtyvs(t);
257     if (isNull(p))
258         internal("findBtyvsInt");
259     return intOf(snd(p));
260 }
261
262 Void markBtyvs() {                      /* Mark explicitly scoped vars     */
263     List bts = btyvars;
264     for (; nonNull(bts); bts=tl(bts)) {
265         List bts1 = hd(bts);
266         for (; nonNull(bts1); bts1=tl(bts1))
267             markTyvar(intOf(snd(hd(bts1))));
268     }
269 }
270
271 Type localizeBtyvs(t)                   /* Localize type to eliminate refs */
272 Type t; {                               /* to explicitly scoped vars       */
273     switch (whatIs(t)) {
274         case RANK2    :
275         case POLYTYPE : snd(snd(t)) = localizeBtyvs(snd(snd(t)));
276                         break;
277
278         case QUAL     : fst(snd(t)) = localizeBtyvs(fst(snd(t)));
279                         snd(snd(t)) = localizeBtyvs(snd(snd(t)));
280                         break;
281
282         case AP       : fst(t) = localizeBtyvs(fst(t));
283                         snd(t) = localizeBtyvs(snd(t));
284                         break;
285
286         case VARIDCELL:
287         case VAROPCELL: return mkInt(findBtyvsInt(textOf(t)));
288     }
289     return t;
290 }
291
292 /* --------------------------------------------------------------------------
293  * Dereference or bind types in subsitution:
294  * ------------------------------------------------------------------------*/
295
296 Tyvar *getTypeVar(t,o)                  /* get number of type variable     */
297 Type t;                                 /* represented by (t,o) [if any].  */
298 Int  o; {
299     switch (whatIs(t)) {
300         case INTCELL   : return tyvar(intOf(t));
301         case OFFSET    : return tyvar(o+offsetOf(t));
302         case VARIDCELL :
303         case VAROPCELL : return tyvar(findBtyvsInt(textOf(t)));
304     }
305     return ((Tyvar *)0);
306 }
307
308 Void tyvarType(vn)                      /* load type held in type variable */
309 Int vn; {                               /* vn into (typeIs,typeOff)        */
310     Tyvar *tyv;
311
312     while ((tyv=tyvar(vn)), isBound(tyv))
313         switch(whatIs(tyv->bound)) {
314             case INTCELL   : vn = intOf(tyv->bound);
315                              break;
316
317             case OFFSET    : vn = offsetOf(tyv->bound)+(tyv->offs);
318                              break;
319
320             case VARIDCELL :
321             case VAROPCELL : vn = findBtyvsInt(textOf(tyv->bound));
322                              break;
323
324             default        : typeIs  = tyv->bound;
325                              typeOff = tyv->offs;
326                              return;
327         }
328     typeIs  = aVar;
329     typeOff = vn;
330 }
331
332 Void bindTv(vn,t,o)                     /* set type variable vn to (t,o)   */
333 Int  vn;
334 Type t;
335 Int  o; {
336     Tyvar *tyv = tyvar(vn);
337     tyv->bound = t;
338     tyv->offs  = o;
339 #ifdef DEBUG_TYPES
340     Printf("binding type variable: _%d to ",vn);
341     printType(stdout,debugType(t,o));
342     Putchar('\n');
343 #endif
344 }
345
346 Cell getDerefHead(t,o)                  /* get value at head of type exp.  */
347 Type t;
348 Int  o; {
349     Tyvar *tyv;
350     argCount = 0;
351     for (;;) {
352         while (isAp(t)) {
353             argCount++;
354             t = fun(t);
355         }
356         if ((tyv=getTypeVar(t,o)) && isBound(tyv)) {
357             t = tyv->bound;
358             o = tyv->offs;
359         }
360         else
361             break;
362     }
363     return t;
364 }
365
366 /* --------------------------------------------------------------------------
367  * Expand type synonyms:
368  * ------------------------------------------------------------------------*/
369
370 Void expandSyn(h,ar,at,ao)              /* Expand type synonym with:       */
371 Tycon h;                                /* head h                          */
372 Int   ar;                               /* ar args (NB. ar>=tycon(h).arity)*/
373 Type  *at;                              /* original expression (*at,*ao)   */
374 Int   *ao; {                            /* expansion returned in (*at,*ao) */
375     ar -= tycon(h).arity;               /* calculate surplus arguments     */
376     if (ar==0)
377         expandSyn1(h,at,ao);
378     else {                              /* if there are more args than the */
379         Type t    = *at;                /* arity, we have to do a little   */
380         Int  o    = *ao;                /* bit of work to isolate args that*/
381         Type args = NIL;                /* will not be changed by expansion*/
382         Int  i;
383         while (ar-- > 0) {              /* find part to expand, and the    */
384             Tyvar *tyv;                 /* unused arguments                */
385             args = cons(arg(t),args);
386             t    = fun(t);
387             deRef(tyv,t,o);
388         }
389         expandSyn1(h,&t,&o);            /* do the expansion                */
390         bindTv((i=newTyvars(1)),t,o);   /* and embed the results back in   */
391         tyvar(i)->kind = getKind(t,o);  /* (*at, *ao) as required          */
392         *at = applyToArgs(mkInt(i),args);
393     }
394 }
395
396 static Void local expandSyn1(h,at,ao)   /* Expand type synonym with:       */
397 Tycon h;                                /* head h, tycon(h).arity args,    */
398 Type  *at;                              /* original expression (*at,*ao)   */
399 Int   *ao; {                            /* expansion returned in (*at,*ao) */
400     Int   n = tycon(h).arity;
401     Type  t = *at;
402     Int   o = *ao;
403     Tyvar *tyv;
404
405     *at = tycon(h).defn;
406     *ao = newKindedVars(tycon(h).kind);
407     for (; 0<n--; t=fun(t)) {
408         deRef(tyv,t,o);
409         if (tyv || !isAp(t))
410             internal("expandSyn1");
411         bindTv(*ao+n,arg(t),o);
412     }
413 }
414
415 /* --------------------------------------------------------------------------
416  * Marking fixed variables in type expressions:
417  * ------------------------------------------------------------------------*/
418
419 Void clearMarks() {                     /* Set all unbound type vars to    */
420     Int i;                              /* unused generic variables        */
421     for (i=0; i<numTyvars; ++i)
422         if (!isBound(tyvar(i)))
423             tyvar(i)->offs = UNUSED_GENERIC;
424     genericVars = NIL;
425     nextGeneric = 0;
426 }
427
428 Void markAllVars() {                    /* Set all unbound type vars to    */
429     Int i;                              /* be fixed vars                   */
430     for (i=0; i<numTyvars; ++i)
431         if (!isBound(tyvar(i)))
432             tyvar(i)->offs = FIXED_TYVAR;
433     genericVars = NIL;
434     nextGeneric = 0;
435 }
436
437 Void resetGenerics() {                  /* Reset all generic vars to unused*/
438     Int i;
439     for (i=0; i<numTyvars; ++i)
440         if (!isBound(tyvar(i)) && tyvar(i)->offs>=GENERIC)
441             tyvar(i)->offs = UNUSED_GENERIC;
442     genericVars = NIL;
443     nextGeneric = 0;
444 }
445
446 Void markTyvar(vn)                      /* mark fixed vars in type bound to*/
447 Int vn; {                               /* given type variable             */
448     Tyvar *tyv = tyvar(vn);
449
450     if (isBound(tyv))
451         markType(tyv->bound, tyv->offs);
452     else
453         (tyv->offs) = FIXED_TYVAR;
454 }
455
456 Void markType(t,o)                      /* mark fixed vars in type (t,o)   */
457 Type t;
458 Int  o; {
459     STACK_CHECK
460     switch (whatIs(t)) {
461         case POLYTYPE  :
462         case QUAL      :
463 #if TREX
464         case EXT       :
465 #endif
466         case TYCON     :
467         case TUPLE     : return;
468
469         case AP        : markType(fst(t),o);
470                          markType(snd(t),o);
471                          return;
472
473         case OFFSET    : markTyvar(o+offsetOf(t));
474                          return;
475
476         case INTCELL   : markTyvar(intOf(t));
477                          return;
478
479         case VARIDCELL :
480         case VAROPCELL : markTyvar(findBtyvsInt(textOf(t)));
481                          return;
482
483         case RANK2     : markType(snd(snd(t)),o);
484                          return;
485
486         default        : internal("markType");
487     }
488 }
489
490 Void markPred(pi)                       /* Marked fixed type vars in pi    */
491 Cell pi; {
492     Cell cl = fst3(pi);
493     Int  o  = intOf(snd3(pi));
494
495     for (; isAp(cl); cl=fun(cl))
496         markType(arg(cl),o);
497 }
498
499 /* --------------------------------------------------------------------------
500  * Copy type expression from substitution to make a single type expression:
501  * ------------------------------------------------------------------------*/
502
503 Type copyTyvar(vn)                      /* calculate most general form of  */
504 Int vn; {                               /* type bound to given type var    */
505     Tyvar *tyv = tyvar(vn);
506
507     if ((tyv->bound)==SKOLEM) {
508         return mkInt(vn);
509     } else if (tyv->bound) {
510         return copyType(tyv->bound,tyv->offs);
511     }
512
513     switch (tyv->offs) {
514         case FIXED_TYVAR    : return mkInt(vn);
515
516         case UNUSED_GENERIC : (tyv->offs) = GENERIC + nextGeneric++;
517                               if (nextGeneric>=NUM_OFFSETS) {
518                                   ERRMSG(0)
519                                       "Too many quantified type variables"
520                                   EEND;
521                               }
522                               genericVars = cons(mkInt(vn),genericVars);
523
524         default             : return mkOffset(tyv->offs - GENERIC);
525     }
526 }
527
528 Type copyType(t,o)                      /* calculate most general form of  */
529 Type t;                                 /* type expression (t,o)           */
530 Int  o; {
531     STACK_CHECK
532     switch (whatIs(t)) {
533         case AP        : {   Type l = copyType(fst(t),o);/* ensure correct */
534                              Type r = copyType(snd(t),o);/* eval. order    */
535                              return ap(l,r);
536                          }
537         case OFFSET    : return copyTyvar(o+offsetOf(t));
538         case INTCELL   : return copyTyvar(intOf(t));
539         case VARIDCELL :
540         case VAROPCELL : return copyTyvar(findBtyvsInt(textOf(t)));
541     }
542
543     return t;
544 }
545
546 Cell copyPred(pi,o)                     /* Copy single predicate (or part  */
547 Cell pi;                                /* thereof) ...                    */
548 Int  o; {
549     if (isAp(pi)) {
550         Cell temp = copyPred(fun(pi),o);/* to ensure correct order of eval.*/
551         return ap(temp,copyType(arg(pi),o));
552     }
553     else
554         return pi;
555 }
556
557 Type zonkTyvar(vn)      /* flatten type by chasing all references          */
558 Int vn; {               /* and collapsing OFFSETS to absolute indexes      */
559     Tyvar *tyv = tyvar(vn);
560
561     if (tyv->bound)
562         return zonkType(tyv->bound,tyv->offs);
563     else
564         return mkInt(vn);
565 }
566
567 Type zonkType(t,o)      /* flatten type by chasing all references          */
568 Type t;                 /* and collapsing OFFSETS to absolute indexes      */
569 Int  o; {
570     STACK_CHECK
571     switch (whatIs(t)) {
572         case AP        : {   Type l = zonkType(fst(t),o);/* ensure correct */
573                              Type r = zonkType(snd(t),o);/* eval. order    */
574                              return ap(l,r);
575                          }
576         case OFFSET    : return zonkTyvar(o+offsetOf(t));
577         case INTCELL   : return zonkTyvar(intOf(t));
578     }
579
580     return t;
581 }
582
583 #ifdef DEBUG_TYPES
584 Type debugTyvar(vn)                     /* expand type structure in full   */
585 Int vn; {                               /* detail                          */
586     Tyvar *tyv = tyvar(vn);
587
588     if (isBound(tyv))
589         return debugType(tyv->bound,tyv->offs);
590     return mkInt(vn);
591 }
592
593 Type debugType(t,o)
594 Type t;
595 Int  o; {
596     STACK_CHECK
597     switch (whatIs(t)) {
598         case AP        : {   Type l = debugType(fst(t),o);
599                              Type r = debugType(snd(t),o);
600                              return ap(l,r);
601                          }
602         case OFFSET    : return debugTyvar(o+offsetOf(t));
603         case INTCELL   : return debugTyvar(intOf(t));
604         case VARIDCELL :
605         case VAROPCELL : return debugTyvar(findBtyvsInt(textOf(t)));
606     }
607
608     return t;
609 }
610 List debugContext(ps)
611 List ps; {
612     Cell p;
613     List qs = NIL;
614     for (; nonNull(ps); ps=tl(ps)) {
615         p = debugPred(fst3(hd(ps)),intOf(snd3(hd(ps))));
616         qs = cons(p,qs);
617     }
618     return rev(qs);
619 }
620
621 Cell debugPred(pi,o)
622 Cell pi;
623 Int  o; {
624     if (isAp(pi)) {
625         return pair(debugPred(fun(pi),o),debugType(arg(pi),o));
626     }
627     return pi;
628 }
629 #endif /*DEBUG_TYPES*/
630
631 Kind copyKindvar(vn)                    /* build kind attatched to variable*/
632 Int vn; {
633     Tyvar *tyv = tyvar(vn);
634     if (tyv->bound)
635         return copyKind(tyv->bound,tyv->offs);
636     return STAR;                        /* any unbound variable defaults to*/
637 }                                       /* the kind of all types           */
638
639 Kind copyKind(k,o)                      /* build kind expression from      */
640 Kind k;                                 /* given skeleton                  */
641 Int  o; {
642     switch (whatIs(k)) {
643         case AP      : {   Kind l = copyKind(fst(k),o);  /* ensure correct */
644                            Kind r = copyKind(snd(k),o);  /* eval. order    */
645                            return ap(l,r);
646                        }
647         case OFFSET  : return copyKindvar(o+offsetOf(k));
648         case INTCELL : return copyKindvar(intOf(k));
649     }
650     return k;
651 }
652
653 /* --------------------------------------------------------------------------
654  * Copy type expression from substitution without marking:
655  * ------------------------------------------------------------------------*/
656
657 static List local listTyvar(vn,ns)
658 Int  vn;
659 List ns; {
660     Tyvar *tyv = tyvar(vn);
661
662     if (isBound(tyv)) {
663         return listTyvars(tyv->bound,tyv->offs,ns);
664     } else if (!intIsMember(vn,ns)) {
665         ns = cons(mkInt(vn),ns);
666     }
667     return ns;
668 }
669
670 static List local listTyvars(t,o,ns)
671 Cell t;
672 Int  o;
673 List ns; {
674     switch (whatIs(t)) {
675         case AP        : return listTyvars(fst(t),o,
676                                  listTyvars(snd(t),o,
677                                   ns));
678         case OFFSET    : return listTyvar(o+offsetOf(t),ns);
679         case INTCELL   : return listTyvar(intOf(t),ns);
680         default        : break;
681     }
682     return ns;
683 }
684
685 static Cell local dupTyvar(vn,ns)
686 Int  vn;
687 List ns; {
688     Tyvar *tyv = tyvar(vn);
689
690     if (isBound(tyv)) {
691         return dupTyvars(tyv->bound,tyv->offs,ns);
692     } else {
693         Int i = 0;
694         for (; nonNull(ns) && vn!=intOf(hd(ns)); ns=tl(ns)) {
695             i++;
696         }
697         return mkOffset(i);
698     }
699 }
700
701 static Cell local dupTyvars(t,o,ns)
702 Cell t;
703 Int  o;
704 List ns; {
705     switch (whatIs(t)) {
706         case AP        : {   Type l = dupTyvars(fst(t),o,ns);
707                              Type r = dupTyvars(snd(t),o,ns);
708                              return ap(l,r);
709                          }
710         case OFFSET    : return dupTyvar(o+offsetOf(t),ns);
711         case INTCELL   : return dupTyvar(intOf(t),ns);
712     }
713     return t;
714 }
715
716 static Cell local copyNoMark(t,o)       /* Copy a type or predicate without*/
717 Cell t;                                 /* changing marks                  */
718 Int  o; {
719     List ns     = listTyvars(t,o,NIL);
720     Cell result = pair(ns,dupTyvars(t,o,ns));
721     for (; nonNull(ns); ns=tl(ns)) {
722         hd(ns) = tyvar(intOf(hd(ns)))->kind;
723     }
724     return result;
725 }
726
727 /* --------------------------------------------------------------------------
728  * Droping and lifting of type schemes that appear in rank 2 position:
729  * ------------------------------------------------------------------------*/
730
731 Type dropRank2(t,alpha,n)               /* Drop a (potentially) rank2 type */
732 Type t;
733 Int  alpha;
734 Int  n; {
735     if (whatIs(t)==RANK2) {
736         Cell r  = fst(snd(t));
737         Int  i  = intOf(r);
738         Type as = NIL;
739         for (t=snd(snd(t)); i>0; i--) {
740             Type a = arg(fun(t));
741             if (isPolyType(a))
742                 a = dropRank1(a,alpha,n);
743             as = fn(a,as);
744             t  = arg(t);
745         }
746         t = ap(RANK2,pair(r,revOnto(as,t)));
747     }
748     return t;
749 }
750
751 Type dropRank1(t,alpha,n)               /* Copy rank1 argument type t to   */
752 Type t;                                 /* make a rank1 type scheme        */
753 Int  alpha;
754 Int  n; {
755     if (n>0 && isPolyType(t))
756         t = mkPolyType(polySigOf(t),dropRank1Body(monotypeOf(t),alpha,n));
757     return t;
758 }
759
760 static Type local dropRank1Body(t,alpha,n)
761 Type t;
762 Int  alpha;
763 Int  n; {
764     switch (whatIs(t)) {
765         case OFFSET   : {   Int m = offsetOf(t);
766                             return (m>=n) ? mkOffset(m-n) : mkInt(alpha+m);
767                         }
768
769         case POLYTYPE : return mkPolyType(polySigOf(t),
770                                           dropRank1Body(monotypeOf(t),alpha,n));
771
772         case QUAL     : return ap(QUAL,dropRank1Body(snd(t),alpha,n));
773
774         case RANK2    : return ap(RANK2,pair(fst(snd(t)),
775                                              dropRank1Body(snd(snd(t)),
776                                                            alpha,
777                                                            n)));
778
779         case AP       : return ap(dropRank1Body(fun(t),alpha,n),
780                                   dropRank1Body(arg(t),alpha,n));
781
782         default       : return t;
783     }
784 }
785
786 Void liftRank2Args(as,alpha,m)
787 List as;
788 Int  alpha;
789 Int  m; {
790     Int i = 0;
791     for (; i<m; i++)
792         copyTyvar(alpha+i);
793     for (m=nextGeneric; nonNull(as); as=tl(as)) {
794         Type ta = arg(fun(as));
795         ta      = isPolyType(ta) ? liftRank1Body(ta,m) : copyType(ta,alpha);
796         arg(fun(as))
797                 = ta;
798     }
799 }
800
801 Type liftRank2(t,alpha,m)
802 Type t;
803 Int  alpha;
804 Int  m; {
805     if (whatIs(t)==RANK2) {
806         Cell r  = fst(snd(t));
807         Int  i  = 0;
808         Type as = NIL;
809         for (; i<m; i++)
810             copyTyvar(alpha+i);
811         m = nextGeneric;
812         t = snd(snd(t));
813         for (i=intOf(r); i>0; i--) {
814             Type a = arg(fun(t));
815             a      = isPolyType(a) ? liftRank1Body(a,m) : copyType(a,alpha);
816             as     = fn(a,as);
817             t      = arg(t);
818         }
819         t = ap(RANK2,pair(r,revOnto(as,copyType(t,alpha))));
820     }
821     else
822         t = copyType(t,alpha);
823     return t;
824 }
825
826 Type liftRank1(t,alpha,m)
827 Type t;
828 Int  alpha;
829 Int  m; {
830     if (m>0 && isPolyType(t)) {
831         Int i = 0;
832         resetGenerics();
833         for (; i<m; i++)
834             copyTyvar(alpha+i);
835         t = liftRank1Body(t,nextGeneric);
836     }
837     return t;
838 }
839
840 static Type local liftRank1Body(t,n)
841 Type t;
842 Int  n; {
843     switch (whatIs(t)) {
844         case OFFSET    : return mkOffset(n+offsetOf(t));
845
846         case INTCELL   : return copyTyvar(intOf(t));
847
848         case VARIDCELL :
849         case VAROPCELL : return copyTyvar(findBtyvsInt(textOf(t)));
850
851         case POLYTYPE  : return mkPolyType(polySigOf(t),
852                                            liftRank1Body(monotypeOf(t),n));
853
854         case QUAL      : return ap(QUAL,liftRank1Body(snd(t),n));
855
856         case RANK2     : return ap(RANK2,pair(fst(snd(t)),
857                                               liftRank1Body(snd(snd(t)),n)));
858
859         case AP        : return ap(liftRank1Body(fun(t),n),
860                                    liftRank1Body(arg(t),n));
861
862         default        : return t;
863     }
864 }
865
866 /* --------------------------------------------------------------------------
867  * Support for `kind preserving substitutions' from unification:
868  * ------------------------------------------------------------------------*/
869
870 Bool eqKind(k1,k2)                      /* check that two (mono)kinds are  */
871 Kind k1, k2; {                          /* equal                           */
872     return k1==k2
873            || (isPair(k1) && isPair(k2)
874               && eqKind(fst(k1),fst(k2))
875               && eqKind(snd(k1),snd(k2)));
876 }
877
878 Kind getKind(c,o)                       /* Find kind of constr during type */
879 Cell c;                                 /* checking process                */
880 Int  o; {
881     if (isAp(c))                                        /* application     */
882         return snd(getKind(fst(c),o));
883     switch (whatIs(c)) {
884         case TUPLE     : return simpleKind(tupleOf(c)); /*(,)::* -> * -> * */
885         case OFFSET    : return tyvar(o+offsetOf(c))->kind;
886         case INTCELL   : return tyvar(intOf(c))->kind;
887         case VARIDCELL :
888         case VAROPCELL : return tyvar(findBtyvsInt(textOf(c)))->kind;
889         case TYCON     : return tycon(c).kind;
890 #if TREX
891         case EXT    : return extKind;
892 #endif
893     }
894 #ifdef DEBUG_KINDS
895     Printf("getKind c = %d, whatIs=%d\n",c,whatIs(c));
896 #endif
897     internal("getKind");
898     return STAR;/* not reached */
899 }
900
901 /* --------------------------------------------------------------------------
902  * Find generic variables in a type:
903  * ------------------------------------------------------------------------*/
904
905 Type genvarTyvar(vn,vs)                 /* calculate list of generic vars  */
906 Int  vn;                                /* thru variable vn, prepended to  */
907 List vs; {                              /* list vs                         */
908     Tyvar *tyv = tyvar(vn);
909
910     if (isBound(tyv))
911         return genvarType(tyv->bound,tyv->offs,vs);
912     else if (tyv->offs == UNUSED_GENERIC) {
913         tyv->offs += GENERIC + nextGeneric++;
914         return cons(mkInt(vn),vs);
915     }
916     else if (tyv->offs>=GENERIC && !intIsMember(vn,vs))
917         return cons(mkInt(vn),vs);
918     else
919         return vs;
920 }
921
922 List genvarType(t,o,vs)                 /* calculate list of generic vars  */
923 Type t;                                 /* in type expression (t,o)        */
924 Int  o;                                 /* results are prepended to vs     */
925 List vs; {
926     switch (whatIs(t)) {
927         case AP        : return genvarType(snd(t),o,genvarType(fst(t),o,vs));
928         case OFFSET    : return genvarTyvar(o+offsetOf(t),vs);
929         case INTCELL   : return genvarTyvar(intOf(t),vs);
930         case VARIDCELL :
931         case VAROPCELL : return genvarTyvar(findBtyvsInt(textOf(t)),vs);
932     }
933     return vs;
934 }
935
936 /* --------------------------------------------------------------------------
937  * Occurs check:
938  * ------------------------------------------------------------------------*/
939
940 Bool doesntOccurIn(lookFor,t,o)         /* Return TRUE if var lookFor      */
941 Tyvar *lookFor;                         /* isn't referenced in (t,o)       */
942 Type  t;
943 Int   o; {
944     Tyvar *tyv;
945
946     STACK_CHECK
947     for (;;) {
948         deRef(tyv,t,o);
949         if (tyv)                        /* type variable                   */
950             return tyv!=lookFor;
951         else if (isAp(t)) {             /* application                     */
952             if (doesntOccurIn(lookFor,snd(t),o))
953                 t = fst(t);
954             else
955                 return FALSE;
956         }
957         else                            /* no variable found               */
958             break;
959     }
960     return TRUE;
961 }
962
963 /* --------------------------------------------------------------------------
964  * Unification algorithm:
965  * ------------------------------------------------------------------------*/
966
967 char   *unifyFails   = 0;               /* Unification error message       */
968 static Int bindAbove = 0;               /* Used to restrict var binding    */
969
970 #define bindOnlyAbove(beta)     bindAbove=beta
971 #define noBind()                bindAbove=MAXPOSINT
972 #define unrestrictBind()        bindAbove=0
973
974 static Bool local varToVarBind(tyv1,tyv2)/* Make binding tyv1 := tyv2      */
975 Tyvar *tyv1, *tyv2; {
976     if (tyv1!=tyv2) {                   /* If vars are same, nothing to do!*/
977
978         /* Check that either tyv1 or tyv2 is in allowed range for binding  */
979         /* and is not a Skolem constant, and swap vars if nec. so we can   */
980         /* bind to tyv1.                                                   */
981
982         if (tyvNum(tyv1)<bindAbove || tyv1->bound==SKOLEM) {
983             if (tyvNum(tyv2)<bindAbove || tyv2->bound==SKOLEM) {
984                 unifyFails = "types do not match";
985                 return FALSE;
986             }
987             else {
988                 Tyvar *tyv = tyv1;
989                 tyv1       = tyv2;
990                 tyv2       = tyv;
991             }
992         }
993         if (!eqKind(tyv1->kind,tyv2->kind)) {
994             unifyFails = "constructor variable kinds do not match";
995             return FALSE;
996         }
997         tyv1->bound = aVar;
998         tyv1->offs  = tyvNum(tyv2);
999 #ifdef DEBUG_TYPES
1000         Printf("vv binding tyvar: _%d to _%d\n",tyvNum(tyv1),tyvNum(tyv2));
1001 #endif
1002     }
1003     return TRUE;
1004 }
1005
1006 static Bool local varToTypeBind(tyv,t,o)/* Make binding tyv := (t,o)       */
1007 Tyvar *tyv;
1008 Type  t;                                /* guaranteed not to be a v'ble or */
1009 Int   o; {                              /* have synonym as outermost constr*/
1010     if (tyvNum(tyv)<bindAbove) {        /* Check that tyv is in range      */
1011         unifyFails = "types do not match";
1012         return FALSE;
1013     }
1014     else if (tyv->bound == SKOLEM) {    /* Check that it is not Skolemized */
1015         unifyFails = "cannot instantiate Skolem constant";
1016         return FALSE;
1017     }
1018     else if (!doesntOccurIn(tyv,t,o))   /* Carry out occurs check          */
1019         unifyFails = "unification would give infinite type";
1020     else if (!eqKind(tyv->kind,getKind(t,o)))
1021         unifyFails = "kinds do not match";
1022     else {
1023         tyv->bound = t;
1024         tyv->offs  = o;
1025 #ifdef DEBUG_TYPES
1026         Printf("vt binding type variable: _%d to ",tyvNum(tyv));
1027         printType(stdout,debugType(t,o));
1028         Putchar('\n');
1029 #endif
1030         return TRUE;
1031     }
1032     return FALSE;
1033 }
1034
1035 Bool unify(t1,o1,t2,o2)                 /* Main unification routine        */
1036 Type t1,t2;                             /* unify (t1,o1) with (t2,o2)      */
1037 Int  o1,o2; {
1038     Tyvar *tyv1, *tyv2;
1039
1040     STACK_CHECK
1041     deRef(tyv1,t1,o1);
1042     deRef(tyv2,t2,o2);
1043
1044 un: if (tyv1) {
1045         if (tyv2)
1046             return varToVarBind(tyv1,tyv2);         /* t1, t2 variables    */
1047         else {
1048             Cell h2 = getDerefHead(t2,o2);          /* t1 variable, t2 not */
1049             if (isSynonym(h2) && argCount>=tycon(h2).arity) {
1050                 expandSyn(h2,argCount,&t2,&o2);
1051                 deRef(tyv2,t2,o2);
1052                 goto un;
1053             }
1054             return varToTypeBind(tyv1,t2,o2);
1055         }
1056     }
1057     else
1058         if (tyv2) {
1059             Cell h1 = getDerefHead(t1,o1);          /* t2 variable, t1 not */
1060             if (isSynonym(h1) && argCount>=tycon(h1).arity) {
1061                 expandSyn(h1,argCount,&t1,&o1);
1062                 deRef(tyv1,t1,o1);
1063                 goto un;
1064             }
1065             return varToTypeBind(tyv2,t1,o1);
1066         }
1067         else {                                      /* t1, t2 not vars     */
1068             Type h1 = getDerefHead(t1,o1);
1069             Int  a1 = argCount;
1070             Type h2 = getDerefHead(t2,o2);
1071             Int  a2 = argCount;
1072
1073 #ifdef DEBUG_TYPES
1074             Printf("tt unifying types: ");
1075             printType(stdout,debugType(t1,o1));
1076             Printf(" with ");
1077             printType(stdout,debugType(t2,o2));
1078             Putchar('\n');
1079 #endif
1080             if (isOffset(h1) || isInt(h1)) h1=NIL;  /* represent var by NIL*/
1081             if (isOffset(h2) || isInt(h2)) h2=NIL;
1082
1083 #if TREX
1084             if (isExt(h1) || isExt(h2)) {
1085                 if (a1==2 && isExt(h1) && a2==2 && isExt(h2)) {
1086                     if (extText(h1)==extText(h2)) {
1087                         return unify(arg(fun(t1)),o1,arg(fun(t2)),o2) &&
1088                                 unify(arg(t1),o1,arg(t2),o2);
1089                     } else {
1090                         return inserter(t1,o1,t2,o2) &&
1091                                   unify(arg(t1),o1,aVar,
1092                                      remover(extText(h1),t2,o2));
1093                     }
1094                 } else {
1095                     unifyFails = "rows are not compatible";
1096                     return FALSE;
1097                 }
1098             }
1099 #endif
1100             if (nonNull(h1) && h1==h2) {/* Assuming well-formed types, both*/
1101                 if (a1!=a2) {           /* t1, t2 must have same no of args*/
1102                     unifyFails = "incompatible constructors";
1103                     return FALSE;
1104                 }
1105                 while (isAp(t1)) {
1106                     if (!unify(arg(t1),o1,arg(t2),o2))
1107                         return FALSE;
1108                     t1 = fun(t1);
1109                     deRef(tyv1,t1,o1);
1110                     t2 = fun(t2);
1111                     deRef(tyv2,t2,o2);
1112                 }
1113                 unifyFails = 0;
1114                 return TRUE;
1115             }
1116
1117             /* Types do not match -- look for type synonyms to expand */
1118
1119             if (isSynonym(h1) && a1>=tycon(h1).arity) {
1120                 expandSyn(h1,a1,&t1,&o1);
1121                 deRef(tyv1,t1,o1);
1122                 goto un;
1123             }
1124             if (isSynonym(h2) && a2>=tycon(h2).arity) {
1125                 expandSyn(h2,a2,&t2,&o2);
1126                 deRef(tyv2,t2,o2);
1127                 goto un;
1128             }
1129
1130             if ((isNull(h1) && a1<=a2) ||       /* last attempt -- maybe   */
1131                 (isNull(h2) && a2<=a1)) {       /* one head is a variable? */
1132                 for (;;) {
1133                     deRef(tyv1,t1,o1);
1134                     deRef(tyv2,t2,o2);
1135
1136                     if (tyv1) {                         /* unify heads!    */
1137                         if (tyv2)
1138                             return varToVarBind(tyv1,tyv2);
1139                         else
1140                             return varToTypeBind(tyv1,t2,o2);
1141                     }
1142                     else if (tyv2)
1143                         return varToTypeBind(tyv2,t1,o1);
1144
1145                     /* at this point, neither t1 nor t2 is a variable. In  */
1146                     /* addition, they must both be APs unless one of the   */
1147                     /* head variables has been bound during unification of */
1148                     /* the arguments.                                      */
1149
1150                     if (!isAp(t1) || !isAp(t2)) {       /* might not be APs*/
1151                         unifyFails = 0;
1152                         return t1==t2;
1153                     }
1154                     if (!unify(arg(t1),o1,arg(t2),o2))  /* o/w must be APs */
1155                         return FALSE;
1156                     t1 = fun(t1);
1157                     t2 = fun(t2);
1158                 }
1159             }
1160         }
1161     unifyFails = 0;
1162     return FALSE;
1163 }
1164
1165 #if TREX
1166 static Bool local inserter(r1,o1,r,o)   /* Insert first field in (r1,o1)   */
1167 Type r1;                                /* into row (r,o), both of which   */
1168 Int  o1;                                /* are known to begin with an EXT  */
1169 Type r;
1170 Int  o; {
1171     Text labt = extText(fun(fun(r1)));  /* Find the text of the label      */
1172 #ifdef DEBUG_TYPES
1173     Printf("inserting ");
1174     printType(stdout,debugType(r1,o1));
1175     Printf(" into ");
1176     printType(stdout,debugType(r,o));
1177     Putchar('\n');
1178 #endif
1179     for (;;) {
1180         Tyvar *tyv;
1181         deRef(tyv,r,o);
1182         if (tyv) {
1183             Int beta;                   /* Test for common tail            */
1184             if (tailVar(arg(r1),o1)==tyvNum(tyv)) {
1185                 unifyFails = "distinct rows have common tail";
1186                 return FALSE;
1187             }
1188             beta = newTyvars(1);        /* Extend row with new field       */
1189             tyvar(beta)->kind = ROW;
1190             return varToTypeBind(tyv,ap(fun(r1),mkInt(beta)),o1);
1191         }
1192         else if (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r)))) {
1193             if (labt==extText(fun(fun(r))))/* Compare existing fields      */
1194                 return unify(arg(fun(r1)),o1,extField(r),o);
1195             r = extRow(r);              /* Or skip to next field           */
1196         }
1197         else {                          /* Nothing else will match         */
1198             unifyFails = "field mismatch";
1199             return FALSE;
1200         }
1201     }
1202 }
1203
1204 static Int local remover(l,r,o)         /* Make a new row by copying (r,o) */
1205 Text l;                                 /* but removing the l field (which */
1206 Type r;                                 /* MUST exist)                     */
1207 Int  o; {
1208     Tyvar *tyv;
1209     Int    beta       = newTyvars(1);
1210     tyvar(beta)->kind = ROW;
1211 #ifdef DEBUG_TYPES
1212     Printf("removing %s from",textToStr(l));
1213     printType(stdout,debugType(r,o));
1214     Putchar('\n');
1215 #endif
1216     deRef(tyv,r,o);
1217     if (tyv || !isAp(r) || !isAp(fun(r)) || !isExt(fun(fun(r))))
1218         internal("remover");
1219     if (l==extText(fun(fun(r))))
1220         r = extRow(r);
1221     else
1222         r = ap(fun(r),mkInt(remover(l,extRow(r),o)));
1223     bindTv(beta,r,o);
1224     return beta;
1225 }
1226
1227
1228 static Int local tailVar(r,o)           /* Find var at tail end of a row   */
1229 Type r;
1230 Int  o; {
1231     for (;;) {
1232         Tyvar *tyv;
1233         deRef(tyv,r,o);
1234         if (tyv) {
1235             return tyvNum(tyv);
1236         }
1237         else if (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r)))) {
1238             r = extRow(r);
1239         }
1240         else {
1241             return (-1);
1242         }
1243     }
1244 }
1245 #endif
1246
1247
1248 Bool typeMatches(type,mt)               /* test if type matches monotype mt*/
1249     Type type, mt; {                    /* imported from STG Hugs          */
1250     Bool result;
1251      if (isPolyOrQualType(type))
1252         return FALSE;
1253     emptySubstitution();
1254     noBind();
1255     result = unify(mt,0,type,0);
1256     unrestrictBind();
1257     emptySubstitution();
1258     return result;
1259 }
1260
1261
1262
1263 /* --------------------------------------------------------------------------
1264  * Matching predicates:
1265  *
1266  * There are (at least) four situations where we need to match up pairs
1267  * of predicates:
1268  *
1269  *   1) Testing to see if two predicates are the same (ignoring differences
1270  *      caused by the use of type synonyms, for example).
1271  *
1272  *   2) Matching a predicate with the head of its class so that we can
1273  *      find the corresponding superclass predicates.  If the predicates
1274  *      have already been kind-checked, and the classes are known to be
1275  *      the same, then this should never fail.
1276  *
1277  *   3) Matching a predicate against the head of an instance to see if
1278  *      that instance is applicable.
1279  *
1280  *   4) Matching two instance heads to see if there is an overlap.
1281  *
1282  * For (1), we need a matching process that does not bind any variables.
1283  * For (2) and (3), we need to use one-way matching, only allowing
1284  * variables in the class or instance head to be instantiated.  For
1285  * (4), we need two-way unification.
1286  *
1287  * Another situation in which both one-way and two-way unification might
1288  * be used is in an implementation of improvement.  Here, a one-way match
1289  * would be used to determine applicability of a rule for improvement
1290  * that would then be followed by unification with another predicate.
1291  * One possible syntax for this might be:
1292  *
1293  *     instance P => pi [improves pi'] where ...
1294  *
1295  * The intention here is that any predicate matching pi' can be unified
1296  * with pi to get more accurate types.  A simple example of this is:
1297  *
1298  *   instance Collection [a] a improves Collection [a] b where ...
1299  *
1300  * As soon as we know what the collection type is (in this case, a list),
1301  * we will also know what the element type is.  To ensure that the rule
1302  * for improvement is valid, the compilation system will also need to use
1303  * a one-way matching process to ensure that pi is a (substitution) instance
1304  * of pi'.  Another extension would be to allow more than one predicate pi'
1305  * in an improving rule.  Read the paper on simplification and improvement
1306  * for technical background.  Watch this space for implementation news!
1307  * ------------------------------------------------------------------------*/
1308
1309 Bool samePred(pi1,o1,pi,o)              /* Test to see if predicates are   */
1310 Cell pi1;                               /* the same, with no binding of    */
1311 Int  o1;                                /* the variables in either one.    */
1312 Cell pi;                                /* Assumes preds are kind correct  */
1313 Int  o; {                               /* with the same class.            */
1314     Bool result;
1315     noBind();
1316     result = unifyPred(pi1,o1,pi,o);
1317     unrestrictBind();
1318     return result;
1319 }
1320
1321 Bool matchPred(pi1,o1,pi,o)             /* One way match predicate (pi1,o1)*/
1322 Cell pi1;                               /* against (pi,o), allowing only   */
1323 Int  o1;                                /* vars in 2nd pred to be bound.   */
1324 Cell pi;                                /* Assumes preds are kind correct  */
1325 Int  o; {                               /* with the same class and that no */
1326     Bool result;                        /* vars have been alloc'd since o. */
1327     bindOnlyAbove(o);
1328     result = unifyPred(pi1,o1,pi,o);
1329     unrestrictBind();
1330     return result;
1331 }
1332
1333 Bool unifyPred(pi1,o1,pi,o)             /* Unify two predicates            */
1334 Cell pi1;                               /* Assumes preds are kind correct  */
1335 Int  o1;                                /* with the same class.            */
1336 Cell pi;
1337 Int  o; {
1338     for (; isAp(pi1); pi1=fun(pi1), pi=fun(pi))
1339         if (!unify(arg(pi1),o1,arg(pi),o))
1340             return FALSE;
1341 #if IPARAM
1342     if (isIP(pi1) && isIP(pi))
1343         return textOf(pi1)==textOf(pi);
1344     else
1345 #endif
1346     return pi1==pi;
1347 }
1348
1349 #if TREX
1350 static Cell trexShow = NIL;             /* Used to test for show on records*/
1351 static Cell trexEq   = NIL;             /* Used to test for eq on records  */
1352 #endif
1353
1354 Inst findInstFor(pi,o)                  /* Find matching instance for pred */
1355 Cell  pi;                               /* (pi,o), or otherwise NIL.  If a */
1356 Int   o; {                              /* match is found, then tyvars from*/
1357     Class c = getHead(pi);              /* typeOff have been initialized to*/
1358     List  ins;                          /* allow direct use of specifics.  */
1359     Cell  kspi = NIL;
1360
1361     if (!isClass(c))
1362         return NIL;
1363
1364     for (ins=cclass(c).instances; nonNull(ins); ins=tl(ins)) {
1365         Inst in   = hd(ins);
1366         Int  beta = newKindedVars(inst(in).kinds);
1367         if (matchPred(pi,o,inst(in).head,beta)) {
1368             typeOff = beta;
1369             return in;
1370         }
1371         else {
1372             numTyvars = beta;
1373             if (allowOverlap) {
1374                 Int alpha = newKindedVars(inst(in).kinds);
1375                 if (isNull(kspi)) {
1376                     kspi = copyNoMark(pi,o);
1377                 }
1378                 beta = newKindedVars(fst(kspi));
1379                 if (matchPred(inst(in).head,alpha,snd(kspi),beta)) {
1380                     numTyvars = alpha;
1381                     return NIL;
1382                 }
1383                 numTyvars = alpha;
1384             }
1385         }
1386     }
1387     unrestrictBind();
1388
1389 #if TREX
1390     {   Bool wantShow   = (c==findQualClass(trexShow));
1391         Bool wantEither = wantShow || (c==findQualClass(trexEq));
1392
1393         if (wantEither) {                       /* Generate instances of   */
1394             Type  t = arg(pi);                  /* ShowRecRow and EqRecRow */
1395             Tyvar *tyv;                         /* on the fly              */
1396             Cell  e;
1397             deRef(tyv,t,o);
1398             e = getHead(t);
1399             if (isExt(e)) {
1400                 Inst in = NIL;
1401                 for (ins=cclass(c).instances; nonNull(ins); ins=tl(ins))
1402                     if (getHead(arg(inst(hd(ins)).head))==e) {
1403                         in = hd(ins);
1404                         break;
1405                     }
1406                 if (isNull(in))
1407                     in = (wantShow ? addRecShowInst(c,e) : addRecEqInst(c,e));
1408                 typeOff = newKindedVars(extKind);
1409                 bindTv(typeOff,arg(fun(t)),o);
1410                 bindTv(typeOff+1,arg(t),o);
1411                 return in;
1412             }
1413         }
1414     }
1415 #endif
1416
1417     return NIL;
1418 }
1419
1420 #if MULTI_INST
1421 Cell findInstsFor(pi,o)                 /* Find matching instance for pred */
1422 Cell  pi;                               /* (pi,o), or otherwise NIL.  If a */
1423 Int   o; {                              /* match is found, then tyvars from*/
1424     Class c = getHead(pi);              /* typeOff have been initialized to*/
1425     List  ins;                          /* allow direct use of specifics.  */
1426     List  res = NIL;
1427
1428     if (!isClass(c))
1429         return NIL;
1430
1431     for (ins=cclass(c).instances; nonNull(ins); ins=tl(ins)) {
1432         Inst in   = hd(ins);
1433         Int  beta = newKindedVars(inst(in).kinds);
1434         if (matchPred(pi,o,inst(in).head,beta)) {
1435             res = cons (pair (beta, in), res);
1436             continue;
1437         }
1438         else
1439             numTyvars = beta;
1440     }
1441     if (res == NIL) {
1442         unrestrictBind();
1443     }
1444
1445     return rev(res);
1446 }
1447 #endif
1448
1449 /* --------------------------------------------------------------------------
1450  * Improvement:
1451  * ------------------------------------------------------------------------*/
1452
1453 Void improve(line,sps,ps)               /* Improve a list of predicates    */
1454 Int  line;
1455 List sps;
1456 List ps; {
1457     Bool improved;
1458     List ps1;
1459     do {
1460         improved = FALSE;
1461         for (ps1=ps; nonNull(ps1); ps1=tl(ps1)) {
1462             Cell pi = fst3(hd(ps1));
1463             Int  o  = intOf(snd3(hd(ps1)));
1464             Cell c  = getHead(pi);
1465             if ((isClass(c) && nonNull(cclass(c).fds)) || isIP(c)) {
1466                 improved |= improveAgainst(line,sps,pi,o);
1467                 if (!isIP(c))
1468                     improved |= instImprove(line,pi,o);
1469                 improved |= improveAgainst(line,tl(ps1),pi,o);
1470             }
1471         }
1472     } while (improved);
1473 }
1474
1475 Bool improveAgainst(line,ps,pi,o)
1476 Int line;
1477 List ps;
1478 Cell pi;
1479 Int o; {
1480     Bool improved = FALSE;
1481     Cell h = getHead(pi);
1482     for (; nonNull(ps); ps=tl(ps)) {
1483         Cell pr = hd(ps);
1484         Cell pi1 = fst3(pr);
1485         Int o1 = intOf(snd3(pr));
1486         Cell h1 = getHead(pi1);
1487         if (isClass(h1) && h==h1)
1488             improved |= pairImprove(line,h,pi,o,pi1,o1);
1489 #if IPARAM
1490         else if (isIP(h1) && textOf(h1) == textOf(h))
1491             improved |= ipImprove(line,pi,o,pi1,o1);
1492 #endif
1493     }
1494     return improved;
1495 }
1496
1497 #if IPARAM
1498 Bool ipImprove(line,pi,o,pi1,o1)
1499 Int line;
1500 Cell pi;
1501 Int o;
1502 Cell pi1;
1503 Int o1; {
1504     Type t  = arg(pi);
1505     Type t1 = arg(pi1);
1506     if (!sameType(t,o,t1,o1)) {
1507         if (!unify(t,o,t1,o1)) {
1508             ERRMSG(line) "Mismatching uses of implicit parameter\n"
1509             ETHEN
1510             ERRTEXT "\n***  "
1511             ETHEN ERRPRED(copyPred(pi1,o1));
1512             ERRTEXT "\n***  "
1513             ETHEN ERRPRED(copyPred(pi,o));
1514             ERRTEXT "\n"
1515             EEND;
1516         }
1517         return TRUE;
1518     }
1519     return FALSE;
1520 }
1521 #endif
1522
1523 Bool pairImprove(line,c,pi1,o1,pi,o)    /* Look for improvement of (pi1,o1)*/
1524 Int   line;                             /* against (pi,o), assuming that   */
1525 Class c;                                /* both pi and pi1 are for class c */
1526 Cell  pi1;
1527 Int   o1;
1528 Cell  pi;
1529 Int   o; {
1530     Bool improved = FALSE;
1531     List fds      = cclass(c).fds;
1532     for (; nonNull(fds); fds=tl(fds)) {
1533         List as   = fst(hd(fds));
1534         Bool same = TRUE;
1535         for (; same && nonNull(as); as=tl(as)) {
1536             Int n = offsetOf(hd(as));
1537             same &= sameType(nthArg(n,pi1),o1,nthArg(n,pi),o);
1538         }
1539         if (isNull(as) && same) {
1540             for (as=snd(hd(fds)); same && nonNull(as); as=tl(as)) {
1541                 Int  n  = offsetOf(hd(as));
1542                 Type t1 = nthArg(n,pi1);
1543                 Type t  = nthArg(n,pi);
1544                 if (!sameType(t1,o1,t,o)) {
1545                     same &= unify(t1,o1,t,o);
1546                     improved = TRUE;
1547                 }
1548             }
1549             if (!same) {
1550                 ERRMSG(line)
1551                   "Constraints are not consistent with functional dependency"
1552                 ETHEN
1553                 ERRTEXT "\n*** Constraint       : "
1554                 ETHEN ERRPRED(copyPred(pi1,o1));
1555                 ERRTEXT "\n*** And constraint   : "
1556                 ETHEN ERRPRED(copyPred(pi,o));
1557                 ERRTEXT "\n*** For class        : "
1558                 ETHEN ERRPRED(cclass(c).head);
1559                 ERRTEXT "\n*** Break dependency : "
1560                 ETHEN ERRFD(hd(fds));
1561                 ERRTEXT "\n"
1562                 EEND;
1563             }
1564         }
1565     }
1566     return improved;
1567 }
1568
1569 Bool instImprove(line,pi,o)             /* Look for improvement of (pi,o)  */
1570 Int  line;                              /* returning TRUE if an improvement*/
1571 Cell pi;                                /* was made, and FALSE otherwise   */
1572 Int  o; {
1573     Bool improved = FALSE;
1574     Cell c        = getHead(pi);
1575     if (isClass(c) && nonNull(cclass(c).fds)) {
1576         List ins = cclass(c).instances;
1577         for (; nonNull(ins); ins=tl(ins)) {
1578             Cell in   = hd(ins);
1579             List fds  = cclass(c).fds;
1580             for (; nonNull(fds); fds=tl(fds)) {
1581                 Int  beta = newKindedVars(inst(in).kinds);
1582                 Bool same = TRUE;
1583                 List as   = fst(hd(fds));
1584                 for (; same && nonNull(as); as=tl(as)) {
1585                     Int n = offsetOf(hd(as));
1586                     same &= matchType(nthArg(n,pi),o,
1587                                       nthArg(n,inst(in).head),beta);
1588                 }
1589                 if (isNull(as) && same) {
1590                     for (as=snd(hd(fds)); same && nonNull(as); as=tl(as)) {
1591                         Int  n  = offsetOf(hd(as));
1592                         Type tp = nthArg(n,pi);
1593                         Type ti = nthArg(n,inst(in).head);
1594                         if (!matchType(tp,o,ti,beta)) {
1595                             same &= unify(tp,o,ti,beta);
1596                             improved = TRUE;
1597                         }
1598                     }
1599                     if (!same) {
1600                         ERRMSG(line)
1601                           "Constraint is not consistent with declared instance"
1602                         ETHEN
1603                         ERRTEXT "\n*** Constraint       : "
1604                         ETHEN ERRPRED(copyPred(pi,o));
1605                         ERRTEXT "\n*** Instance         : "
1606                         ETHEN ERRPRED(inst(in).head);
1607                         ERRTEXT "\n*** For class        : "
1608                         ETHEN ERRPRED(cclass(c).head);
1609                         ERRTEXT "\n*** Under dependency : "
1610                         ETHEN ERRFD(hd(fds));
1611                         ERRTEXT "\n"
1612                         EEND;
1613                     }
1614                 } else {
1615                     numTyvars = beta;
1616                 }
1617             }
1618         }
1619     }
1620     return improved;
1621 }
1622
1623 /* --------------------------------------------------------------------------
1624  * Compare type schemes:
1625  * ------------------------------------------------------------------------*/
1626
1627 Bool sameSchemes(s,s1)                  /* Test to see whether two type    */
1628 Type s;                                 /* schemes are the same            */
1629 Type s1; {
1630     Int  o   = 0;
1631     Int  m   = 0;
1632     Int  nr2 = 0;
1633     Bool b   = isPolyType(s);           /* Check quantifiers are the same  */
1634     Bool b1  = isPolyType(s1);
1635     if (b || b1) {
1636         if (b && b1 && eqKind(polySigOf(s),polySigOf(s1))) {
1637             Kind k = polySigOf(s);
1638             s      = monotypeOf(s);
1639             s1     = monotypeOf(s1);
1640             o      = newKindedVars(k);
1641             for (; isAp(k); k=arg(k))
1642                 m++;
1643         }
1644         else
1645             return FALSE;
1646     }
1647
1648     b  = (whatIs(s)==QUAL);             /* Check that contexts are the same*/
1649     b1 = (whatIs(s1)==QUAL);
1650     if (b || b1) {
1651         if (b && b1) {
1652             List ps  = fst(snd(s));
1653             List ps1 = fst(snd(s1));
1654             noBind();
1655             while (nonNull(ps) && nonNull(ps1)) {
1656                 Cell pi  = hd(ps);
1657                 Cell pi1 = hd(ps1);
1658                 if (getHead(pi)!=getHead(pi1)
1659                         || !unifyPred(pi,o,pi1,o))
1660                     break;
1661                 ps  = tl(ps);
1662                 ps1 = tl(ps1);
1663             }
1664             unrestrictBind();
1665             if (nonNull(ps) || nonNull(ps1))
1666                 return FALSE;
1667             s  = snd(snd(s));
1668             s1 = snd(snd(s1));
1669         }
1670         else
1671             return FALSE;
1672     }
1673
1674     b  = (whatIs(s)==RANK2);            /* Check any rank 2 annotations    */
1675     b1 = (whatIs(s1)==RANK2);
1676     if (b || b1) {
1677         if (b && b1 && intOf(fst(snd(s)))==intOf(fst(snd(s1)))) {
1678             nr2 = intOf(fst(snd(s)));
1679             s   = snd(snd(s));
1680             s1  = snd(snd(s1));
1681         }
1682         else
1683             return FALSE;
1684     }
1685
1686     for (; nr2>0; nr2--) {              /* Deal with rank 2 arguments      */
1687         Type t  = arg(fun(s));
1688         Type t1 = arg(fun(s1));
1689         b       = isPolyOrQualType(t);
1690         b1      = isPolyOrQualType(t1);
1691         if (b || b1) {
1692             if (b && b1) {
1693                 t  = dropRank1(t,o,m);
1694                 t1 = dropRank1(t1,o,m);
1695                 if (!sameSchemes(t,t1))
1696                     return FALSE;
1697             }
1698             else
1699                 return FALSE;
1700         }
1701         else {
1702             if (!sameType(t,o,t1,o)) {
1703                 return FALSE;
1704             }
1705         }
1706
1707         s  = arg(s);
1708         s1 = arg(s1);
1709     }
1710
1711     return sameType(s,o,s1,o);          /* Ensure body types are the same  */
1712 }
1713
1714 Bool sameType(t1,o1,t,o)                /* Test to see if types are        */
1715 Type t1;                                /* the same, with no binding of    */
1716 Int  o1;                                /* the variables in either one.    */
1717 Cell t;                                 /* Assumes types are kind correct  */
1718 Int  o; {                               /* with the same kind.             */
1719     Bool result;
1720     noBind();
1721     result = unify(t1,o1,t,o);
1722     unrestrictBind();
1723     return result;
1724 }
1725
1726 Bool matchType(t1,o1,t,o)               /* One way match type (t1,o1)      */
1727 Type t1;                                /* against (t,o), allowing only    */
1728 Int  o1;                                /* vars in 2nd type to be bound.   */
1729 Type t;                                 /* Assumes types are kind correct  */
1730 Int  o; {                               /* and that no vars have been      */
1731     Bool result;                        /* alloc'd since o.                */
1732     bindOnlyAbove(o);
1733     result = unify(t1,o1,t,o);
1734     unrestrictBind();
1735     return result;
1736 }
1737
1738 /* --------------------------------------------------------------------------
1739  * Unify kind expressions:
1740  * ------------------------------------------------------------------------*/
1741
1742 static Bool local kvarToVarBind(tyv1,tyv2)/* Make binding tyv1 := tyv2     */
1743 Tyvar *tyv1, *tyv2; {                     /* for kind variable bindings    */
1744     if (tyv1!=tyv2) {
1745         tyv1->bound = aVar;
1746         tyv1->offs  = tyvNum(tyv2);
1747 #ifdef DEBUG_KINDS
1748         Printf("vv binding kvar: _%d to _%d\n",tyvNum(tyv1),tyvNum(tyv2));
1749 #endif
1750     }
1751     return TRUE;
1752 }
1753
1754 static Bool local kvarToTypeBind(tyv,t,o)/* Make binding tyv := (t,o)      */
1755 Tyvar *tyv;                             /* for kind variable bindings      */
1756 Type  t;                                /* guaranteed not to be a v'ble or */
1757 Int   o; {                              /* have synonym as outermost constr*/
1758     if (doesntOccurIn(tyv,t,o)) {
1759         tyv->bound = t;
1760         tyv->offs  = o;
1761 #ifdef DEBUG_KINDS
1762         Printf("vt binding kind variable: _%d to ",tyvNum(tyv));
1763         printType(stdout,debugType(t,o));
1764         Putchar('\n');
1765 #endif
1766         return TRUE;
1767     }
1768     unifyFails = "unification would give infinite kind";
1769     return FALSE;
1770 }
1771
1772 Bool kunify(k1,o1,k2,o2)                /* Unify kind expr (k1,o1) with    */
1773 Kind k1,k2;                             /* (k2,o2)                         */
1774 Int  o1,o2; {
1775     Tyvar *kyv1, *kyv2;
1776
1777     deRef(kyv1,k1,o1);
1778     deRef(kyv2,k2,o2);
1779
1780     if (kyv1) {
1781         if (kyv2)
1782             return kvarToVarBind(kyv1,kyv2);        /* k1, k2 variables    */
1783         else
1784             return kvarToTypeBind(kyv1,k2,o2);      /* k1 variable, k2 not */
1785     }
1786     else
1787         if (kyv2)
1788             return kvarToTypeBind(kyv2,k1,o1);      /* k2 variable, k1 not */
1789         else {
1790 #ifdef DEBUG_KINDS
1791             Printf("unifying kinds: ");
1792             printType(stdout,debugType(k1,o1));
1793             Printf(" with ");
1794             printType(stdout,debugType(k2,o2));
1795             Putchar('\n');
1796 #endif
1797             if (k1==STAR && k2==STAR)               /* k1, k2 not vars     */
1798                 return TRUE;
1799 #if TREX
1800             else if (k1==ROW && k2==ROW)
1801                 return TRUE;
1802 #endif
1803             else if (isAp(k1) && isAp(k2))
1804                 return kunify(fst(k1),o1,fst(k2),o2) &&
1805                        kunify(snd(k1),o1,snd(k2),o2);
1806         }
1807     unifyFails = 0;
1808     return FALSE;
1809 }
1810
1811 /* --------------------------------------------------------------------------
1812  * Tuple type constructors: are generated as necessary.  The most common
1813  * n-tuple constructors (n<MAXTUPCON) are held in a cache to avoid
1814  * repeated generation of the constructor types.
1815  * ------------------------------------------------------------------------*/
1816
1817 #define MAXTUPCON 10
1818 static Type tupleConTypes[MAXTUPCON];
1819
1820 Void typeTuple(e)                      /* find type for tuple constr, using*/
1821 Cell e; {                              /* tupleConTypes to cache previously*/
1822     Int n   = tupleOf(e);              /* calculated tuple constr. types.  */
1823     typeOff = newTyvars(n);
1824     if (n>=MAXTUPCON)
1825          typeIs = makeTupleType(n);
1826     else if (tupleConTypes[n])
1827          typeIs = tupleConTypes[n];
1828     else
1829          typeIs = tupleConTypes[n] = makeTupleType(n);
1830 }
1831
1832 static Type local makeTupleType(n)     /* construct type for tuple constr. */
1833 Int n; {                               /* t1 -> ... -> tn -> (t1,...,tn)   */
1834     Type h = mkTuple(n);
1835     Int  i;
1836
1837     for (i=0; i<n; ++i)
1838         h = ap(h,mkOffset(i));
1839     while (0<n--)
1840         h = fn(mkOffset(n),h);
1841     return h;
1842 }
1843
1844 /* --------------------------------------------------------------------------
1845  * Two forms of kind expression are used quite frequently:
1846  *      *  -> *  -> ... -> *  -> *      for kinds of ->, [], ->, (,) etc...
1847  *      v1 -> v2 -> ... -> vn -> vn+1   skeletons for constructor kinds
1848  * Expressions of these forms are produced by the following functions which
1849  * use a cache to avoid repeated construction of commonly used values.
1850  * A similar approach is used to store the types of tuple constructors in the
1851  * main type checker.
1852  * ------------------------------------------------------------------------*/
1853
1854 #define MAXKINDFUN 10
1855 static  Kind simpleKindCache[MAXKINDFUN];
1856 static  Kind varKindCache[MAXKINDFUN];
1857
1858 static Kind local makeSimpleKind(n)     /* construct * -> ... -> * (n args)*/
1859 Int n; {
1860     Kind k = STAR;
1861     while (n-- > 0)
1862         k = ap(STAR,k);
1863     return k;
1864 }
1865
1866 Kind simpleKind(n)                      /* return (possibly cached) simple */
1867 Int n; {                                /* function kind                   */
1868     if (n>=MAXKINDFUN)
1869         return makeSimpleKind(n);
1870     else if (nonNull(simpleKindCache[n]))
1871         return simpleKindCache[n];
1872     else if (n==0)
1873         return simpleKindCache[0] = STAR;
1874     else
1875         return simpleKindCache[n] = ap(STAR,simpleKind(n-1));
1876 }
1877
1878 static Kind local makeVarKind(n)        /* construct v0 -> .. -> vn        */
1879 Int n; {
1880     Kind k = mkOffset(n);
1881     while (n-- > 0)
1882         k = ap(mkOffset(n),k);
1883     return k;
1884 }
1885
1886 Void varKind(n)                         /* return (possibly cached) var    */
1887 Int n; {                                /* function kind                   */
1888     typeOff = newKindvars(n+1);
1889     if (n>=MAXKINDFUN)
1890         typeIs = makeVarKind(n);
1891     else if (nonNull(varKindCache[n]))
1892         typeIs = varKindCache[n];
1893     else
1894         typeIs = varKindCache[n] = makeVarKind(n);
1895 }
1896
1897 /* --------------------------------------------------------------------------
1898  * Substitutution control:
1899  * ------------------------------------------------------------------------*/
1900
1901 Void substitution(what)
1902 Int what; {
1903     Int  i;
1904
1905     switch (what) {
1906         case RESET   : emptySubstitution();
1907                        unrestrictBind();
1908                        btyvars = NIL;
1909                        break;
1910
1911         case MARK    : for (i=0; i<MAXTUPCON; ++i)
1912                            mark(tupleConTypes[i]);
1913                        for (i=0; i<MAXKINDFUN; ++i) {
1914                            mark(simpleKindCache[i]);
1915                            mark(varKindCache[i]);
1916                        }
1917                        for (i=0; i<numTyvars; ++i)
1918                            mark(tyvars[i].bound);
1919                        mark(btyvars);
1920                        mark(typeIs);
1921                        mark(predsAre);
1922                        mark(genericVars);
1923 #if TREX
1924                        mark(trexShow);
1925                        mark(trexEq);
1926 #endif
1927                        break;
1928
1929         case INSTALL : substitution(RESET);
1930                        for (i=0; i<MAXTUPCON; ++i)
1931                            tupleConTypes[i] = NIL;
1932                        for (i=0; i<MAXKINDFUN; ++i) {
1933                            simpleKindCache[i] = NIL;
1934                            varKindCache[i]    = NIL;
1935                        }
1936 #if TREX
1937                        trexShow = mkQCon(findText("Trex"),
1938                                          findText("ShowRecRow"));
1939                        trexEq   = mkQCon(findText("Trex"),
1940                                          findText("EqRecRow"));
1941 #endif
1942                        break;
1943     }
1944 }
1945
1946 /*-------------------------------------------------------------------------*/