[project @ 2000-05-17 22:05:44 by lewie]
[ghc-hetmet.git] / ghc / interpreter / static.c
1
2 /* --------------------------------------------------------------------------
3  * Static Analysis for Hugs
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: static.c,v $
12  * $Revision: 1.41 $
13  * $Date: 2000/05/17 22:05:44 $
14  * ------------------------------------------------------------------------*/
15
16 #include "hugsbasictypes.h"
17 #include "storage.h"
18 #include "connect.h"
19 #include "errors.h"
20
21 /* --------------------------------------------------------------------------
22  * local function prototypes:
23  * ------------------------------------------------------------------------*/
24
25 static Void   local kindError           ( Int,Constr,Constr,String,Kind,Int );
26 static Void   local checkQualImport     ( Pair );
27 static Void   local checkUnqualImport   ( Triple );
28
29 static Name   local lookupName          ( Text,List );
30 static List   local checkSubentities    ( List,List,List,String,Text );
31 static List   local checkExportTycon    ( List,Text,Cell,Tycon );
32 static List   local checkExportClass    ( List,Text,Cell,Class );
33 static List   local checkExport         ( List,Text,Cell );
34 static List   local checkImportEntity   ( List,Module,Cell );
35 static List   local resolveImportList   ( Module,Cell );
36 static Void   local checkImportList     ( Pair );
37
38 static Void   local importEntity        ( Module,Cell );
39 static Void   local importName          ( Module,Name );
40 static Void   local importTycon         ( Module,Tycon );
41 static Void   local importClass         ( Module,Class );
42 static List   local checkExports        ( List, Module );
43
44 static Void   local checkTyconDefn      ( Tycon );
45 static Void   local depConstrs          ( Tycon,List,Cell );
46 static List   local addSels             ( Int,Name,List,List );
47 static List   local selectCtxt          ( List,List );
48 static Void   local checkSynonyms       ( List );
49 static List   local visitSyn            ( List,Tycon,List );
50 static Type   local instantiateSyn      ( Type,Type );
51
52 static Void   local checkClassDefn      ( Class );
53 static Cell   local depPredExp          ( Int,List,Cell );
54 static Void   local checkMems           ( Class,List,Cell );
55 static Void   local checkMems2          ( Class,Cell );
56 static Void   local addMembers          ( Class );
57 static Name   local newMember           ( Int,Int,Cell,Type,Class );
58 static Text   local generateText        ( String,Class );
59
60 static List   local classBindings       ( String,Class,List );
61 static Name   local memberName          ( Class,Text );
62 static List   local numInsert           ( Int,Cell,List );
63
64 static List   local maybeAppendVar      ( Cell,List );
65
66 static Type   local checkSigType        ( Int,String,Cell,Type );
67 static Void   local checkOptQuantVars   ( Int,List,List );
68 static Type   local depTopType          ( Int,List,Type );
69 static Type   local depCompType         ( Int,List,Type );
70 static Type   local depTypeExp          ( Int,List,Type );
71 static Type   local depTypeVar          ( Int,List,Text );
72 static List   local checkQuantVars      ( Int,List,List,Cell );
73 static List   local otvars              ( Cell,List );
74 static Bool   local osubset             ( List,List );
75 static Void   local kindConstr          ( Int,Int,Int,Constr );
76 static Kind   local kindAtom            ( Int,Constr );
77 static Void   local kindPred            ( Int,Int,Int,Cell );
78 static Void   local kindType            ( Int,String,Type );
79 static Void   local fixKinds            ( Void );
80
81 static Void   local kindTCGroup         ( List );
82 static Void   local initTCKind          ( Cell );
83 static Void   local kindTC              ( Cell );
84 static Void   local genTC               ( Cell );
85
86 static Void   local checkInstDefn       ( Inst );
87 static Void   local insertInst          ( Inst );
88 static Bool   local instCompare         ( Inst,Inst );
89 static Name   local newInstImp          ( Inst );
90 static Void   local kindInst            ( Inst,Int );
91 static Void   local checkDerive         ( Tycon,List,List,Cell );
92 static Void   local addDerInst          ( Int,Class,List,List,Type,Int );
93 static Void   local deriveContexts      ( List );
94 static Void   local initDerInst         ( Inst );
95 static Void   local calcInstPreds       ( Inst );
96 static Void   local maybeAddPred        ( Cell,Int,Int,List );
97 static List   local calcFunDeps         ( List );
98 static Cell   local copyAdj             ( Cell,Int,Int );
99 static Void   local tidyDerInst         ( Inst );
100 static List   local otvarsZonk          ( Cell,List,Int );
101
102 static Void   local addDerivImp         ( Inst );
103
104 static Void   local checkDefaultDefns   ( Void );
105
106 static Void   local checkForeignImport  ( Name );
107 static Void   local checkForeignExport  ( Name );
108
109 static Cell   local tidyInfix           ( Int,Cell );
110 static Pair   local attachFixity        ( Int,Cell );
111 static Syntax local lookupSyntax        ( Text );
112
113 static Cell   local checkPat            ( Int,Cell );
114 static Cell   local checkMaybeCnkPat    ( Int,Cell );
115 static Cell   local checkApPat          ( Int,Int,Cell );
116 static Void   local addToPatVars        ( Int,Cell );
117 static Name   local conDefined          ( Int,Cell );
118 static Void   local checkIsCfun         ( Int,Name );
119 static Void   local checkCfunArgs       ( Int,Cell,Int );
120 static Cell   local checkPatType        ( Int,String,Cell,Type );
121 static Cell   local applyBtyvs          ( Cell );
122 static Cell   local bindPat             ( Int,Cell );
123 static Void   local bindPats            ( Int,List );
124
125 static List   local extractSigdecls     ( List );
126 static List   local extractFixdecls     ( List );
127 static List   local extractBindings     ( List );
128 static List   local getPatVars          ( Int,Cell,List );
129 static List   local addPatVar           ( Int,Cell,List );
130 static List   local eqnsToBindings      ( List,List,List,List );
131 static Void   local notDefined          ( Int,List,Cell );
132 static Cell   local findBinding         ( Text,List );
133 static Cell   local getAttr             ( List,Cell );
134 static Void   local addSigdecl          ( List,Cell );
135 static Void   local addFixdecl          ( List,List,List,List,Triple );
136 static Void   local dupFixity           ( Int,Text );
137 static Void   local missFixity          ( Int,Text );
138
139 static List   local dependencyAnal      ( List );
140 static List   local topDependAnal       ( List );
141 static Void   local addDepField         ( Cell );
142 static Void   local remDepField         ( List );
143 static Void   local remDepField1        ( Cell );
144 static Void   local clearScope          ( Void );
145 static Void   local withinScope         ( List );
146 static Void   local leaveScope          ( Void );
147 static Void   local saveSyntax          ( Cell,Cell );
148
149 static Void   local depBinding          ( Cell );
150 static Void   local depDefaults         ( Class );
151 static Void   local depInsts            ( Inst );
152 static Void   local depClassBindings    ( List );
153 static Void   local depAlt              ( Cell );
154 static Void   local depRhs              ( Cell );
155 static Void   local depGuard            ( Cell );
156 static Cell   local depExpr             ( Int,Cell );
157 static Void   local depPair             ( Int,Cell );
158 static Void   local depTriple           ( Int,Cell );
159 static Void   local depComp             ( Int,Cell,List );
160 static Void   local depCaseAlt          ( Int,Cell );
161 static Cell   local depVar              ( Int,Cell );
162 static Cell   local depQVar             ( Int,Cell );
163 static Void   local depConFlds          ( Int,Cell,Bool );
164 static Void   local depUpdFlds          ( Int,Cell );
165 static List   local depFields           ( Int,Cell,List,Bool );
166 #if IPARAM
167 static Void   local depWith             ( Int,Cell );
168 static List   local depDwFlds           ( Int,Cell,List );
169 #endif
170 #if TREX
171 static Cell   local depRecord           ( Int,Cell );
172 #endif
173
174 static List   local tcscc               ( List,List );
175 static List   local bscc                ( List );
176
177 static Void   local addRSsigdecls       ( Pair );
178 static Void   local allNoPrevDef        ( Cell );
179 static Void   local noPrevDef           ( Int,Cell );
180 static Bool   local odiff               ( List,List );
181  
182 static Void   local duplicateErrorAux   ( Int,Module,Text,String );
183 #define duplicateError(l,m,t,k) duplicateErrorAux(l,m,t,k)
184 static Void   local checkTypeIn         ( Pair );
185
186 /* --------------------------------------------------------------------------
187  * The code in this file is arranged in roughly the following order:
188  *  - Kind inference preliminaries
189  *  - Module declarations
190  *  - Type declarations (data, type, newtype, type in)
191  *  - Class declarations
192  *  - Type signatures
193  *  - Instance declarations
194  *  - Default declarations
195  *  - Primitive definitions
196  *  - Patterns
197  *  - Infix expressions
198  *  - Value definitions
199  *  - Top-level static analysis and control
200  *  - Haskell 98 compatibility tests
201  * ------------------------------------------------------------------------*/
202
203 /* --------------------------------------------------------------------------
204  * Kind checking preliminaries:
205  * ------------------------------------------------------------------------*/
206
207 Bool kindExpert = FALSE;                /* TRUE => display kind errors in  */
208                                         /*         full detail             */
209
210 static Void local kindError(l,c,in,wh,k,o)
211 Int    l;                               /* line number near constuctor exp */
212 Constr c;                               /* constructor                     */
213 Constr in;                              /* context (if any)                */
214 String wh;                              /* place in which error occurs     */
215 Kind   k;                               /* expected kind (k,o)             */
216 Int    o; {                             /* inferred kind (typeIs,typeOff)  */
217     clearMarks();
218
219     if (!kindExpert) {                  /* for those with a fear of kinds  */
220         ERRMSG(l) "Illegal type" ETHEN
221         if (nonNull(in)) {
222             ERRTEXT " \"" ETHEN ERRTYPE(in);
223             ERRTEXT "\""  ETHEN
224         }
225         ERRTEXT " in %s\n", wh
226         EEND;
227     }
228
229     ERRMSG(l) "Kind error in %s", wh ETHEN
230     if (nonNull(in)) {
231         ERRTEXT "\n*** expression     : " ETHEN ERRTYPE(in);
232     }
233     ERRTEXT "\n*** constructor    : " ETHEN ERRTYPE(c);
234     ERRTEXT "\n*** kind           : " ETHEN ERRKIND(copyType(typeIs,typeOff));
235     ERRTEXT "\n*** does not match : " ETHEN ERRKIND(copyType(k,o));
236     if (unifyFails) {
237         ERRTEXT "\n*** because        : %s", unifyFails ETHEN
238     }
239     ERRTEXT "\n"
240     EEND;
241 }
242
243 #define shouldKind(l,c,in,wh,k,o)       if (!kunify(typeIs,typeOff,k,o)) \
244                                             kindError(l,c,in,wh,k,o)
245 #define checkKind(l,a,m,c,in,wh,k,o)    kindConstr(l,a,m,c); \
246                                         shouldKind(l,c,in,wh,k,o)
247 #define inferKind(k,o)                  typeIs=k; typeOff=o
248
249 static List unkindTypes;                /* types in need of kind annotation*/
250 #if TREX
251 Kind   extKind;                         /* Kind of extension, *->row->row  */
252 #endif
253
254 /* --------------------------------------------------------------------------
255  * Static analysis of modules:
256  * ------------------------------------------------------------------------*/
257
258 Void startModule ( Module m )                    /* switch to a new module */
259 {
260     if (isNull(m)) internal("startModule");
261     setCurrModule(m);
262 }
263
264 Void setExportList(exps)              /* Add export list to current module */
265 List exps; {
266     module(currentModule).exports = exps;
267 }
268
269 Void addQualImport(orig,new)         /* Add to qualified import list       */
270 Cell orig;     /* Original name of module                                  */
271 Cell new;  {   /* Name module is called within this module (or NIL)        */
272     module(currentModule).qualImports = 
273       cons(pair(isNull(new)?orig:new,orig),module(currentModule).qualImports);
274 }
275
276 Void addUnqualImport(mod,entities)     /* Add to unqualified import list   */
277 Cell mod;         /* Name of module                                        */
278 List entities;  { /* List of entity names                                  */
279     unqualImports = cons(pair(mod,entities),unqualImports);
280 }
281
282 static Void local checkQualImport(i)   /* Process qualified import         */
283 Pair i; {
284     Module m = findModid(snd(i));
285     if (isNull(m)) {
286         ERRMSG(0) "Module \"%s\" not previously loaded", 
287                   textToStr(textOf(snd(i)))
288         EEND;
289     }
290     snd(i)=m;
291 }
292
293 static Void local checkUnqualImport(i) /* Process unqualified import       */
294 Pair i; {
295     Module m = findModid(fst(i));
296     if (isNull(m)) {
297         ERRMSG(0) "Module \"%s\" not previously loaded", 
298                   textToStr(textOf(fst(i)))
299         EEND;
300     }
301     fst(i)=m;
302 }
303
304 static Name local lookupName(t,nms)    /* find text t in list of Names     */
305 Text t;
306 List nms; { /* :: [Name] */
307     for(; nonNull(nms); nms=tl(nms)) {
308         if (t == name(hd(nms)).text)
309             return hd(nms);
310     }
311     return NIL;
312 }
313
314 static List local checkSubentities(imports,named,wanted,description,textParent)
315 List   imports;
316 List   named;       /* :: [ Q?(Var|Con)(Id|Op) ]                  */
317 List   wanted;      /* :: [Name]                                  */
318 String description; /* "<constructor>|<member> of <type>|<class>" */
319 Text   textParent; {
320     for(; nonNull(named); named=tl(named)) {
321         Pair x = hd(named);
322         /* ToDo: ignores qualifier; doesn't check that entity is in scope */
323         Text t = isPair(snd(x)) ? qtextOf(x) : textOf(x);
324         Name n = lookupName(t,wanted);
325         if (isNull(n)) {
326             ERRMSG(0) "Entity \"%s\" is not a %s \"%s\"",
327                       textToStr(t),
328                       description,
329                       textToStr(textParent)
330             EEND;
331         }
332         imports = cons(n,imports);
333     }
334     return imports;
335 }
336
337 static List local checkImportEntity(imports,exporter,entity)
338 List   imports; /* Accumulated list of things to import */
339 Module exporter;
340 Cell entity; { /* Entry from import list */
341     List oldImports = imports;
342     Text t  = isIdent(entity) ? textOf(entity) : textOf(fst(entity));
343     List es = NIL;
344     es = module(exporter).exports; 
345
346     for(; nonNull(es); es=tl(es)) {
347         Cell e = hd(es); /* :: Entity
348                              | (Entity, NIL|DOTDOT)
349                              | tycon 
350                              | class
351                           */
352         if (isPair(e)) {
353             Cell f = fst(e);
354             if (isTycon(f)) {
355                 if (tycon(f).text == t) {
356                     imports = cons(f,imports);
357                     if (!isIdent(entity)) {
358                         switch (tycon(f).what) {
359                         case NEWTYPE:
360                         case DATATYPE:
361                             if (DOTDOT == snd(entity)) {
362                                 imports = dupOnto(tycon(f).defn,imports);
363                             } else {
364                                 imports = checkSubentities(
365                                              imports,snd(entity),tycon(f).defn,
366                                              "constructor of type",t);
367                             }
368                             break;
369                         default:;
370                           /* deliberate fall thru */
371                         }
372                     }
373                 }
374             } else if (isClass(f)) {
375                 if (cclass(f).text == t) {
376                     imports = cons(f,imports);
377                     if (!isIdent(entity)) {
378                         if (DOTDOT == snd(entity)) {
379                             return dupOnto(cclass(f).members,imports);
380                         } else {
381                             return checkSubentities(
382                                       imports,snd(entity),cclass(f).members,
383                                       "member of class",t);
384                         }
385                     }
386                 }
387             } else {
388                 internal("checkImportEntity2");
389             }
390         } else if (isName(e)) {
391             if (isIdent(entity) && name(e).text == t) {
392                 imports = cons(e,imports);
393             }
394         } else {
395             internal("checkImportEntity3");
396         }
397     }
398     if (imports == oldImports) {
399         ERRMSG(0) "Unknown entity \"%s\" imported from module \"%s\"",
400                   textToStr(t),
401                   textToStr(module(exporter ).text)
402         EEND;
403     }
404     return imports;
405 }
406
407 static List local resolveImportList(m,impList)
408 Module m;  /* exporting module */
409 Cell impList; {
410     List imports = NIL;
411     if (DOTDOT == impList) {
412         List es = module(m).exports;
413         for(; nonNull(es); es=tl(es)) {
414             Cell e = hd(es);
415             if (isName(e)) {
416                 imports = cons(e,imports);
417             } else {
418                 Cell c = fst(e);
419                 List subentities = NIL;
420                 imports = cons(c,imports);
421                 if (isTycon(c)
422                     && (tycon(c).what == DATATYPE 
423                         || tycon(c).what == NEWTYPE))
424                     subentities = tycon(c).defn;
425                 else if (isClass(c))
426                     subentities = cclass(c).members;
427                 if (DOTDOT == snd(e)) {
428                     imports = dupOnto(subentities,imports);
429                 }
430             }
431         }
432     } else {
433         map1Accum(checkImportEntity,imports,m,impList);
434     }
435     return imports;
436 }
437
438 static Void local checkImportList(importSpec) /*Import a module unqualified*/
439 Pair importSpec; {
440     Module m       = fst(importSpec);
441     Cell   impList = snd(importSpec);
442
443     List   imports = NIL; /* entities we want to import */
444     List   hidden  = NIL; /* entities we want to hide   */
445
446     if (isPair(impList) && HIDDEN == fst(impList)) {
447         /* Somewhat inefficient - but obviously correct:
448          * imports = importsOf("module Foo") `setDifference` hidden;
449          */
450         hidden  = resolveImportList(m, snd(impList));
451         imports = resolveImportList(m, DOTDOT);
452     } else {
453         imports = resolveImportList(m, impList);
454     }
455
456     for(; nonNull(imports); imports=tl(imports)) {
457         Cell e = hd(imports);
458         if (!cellIsMember(e,hidden))
459             importEntity(m,e);
460     }
461     /* ToDo: hang onto the imports list for processing export list entries
462      * of the form "module Foo"
463      */
464 }
465
466 static Void local importEntity(source,e)
467 Module source;
468 Cell e; {
469     switch (whatIs(e)) {
470       case NAME  : importName(source,e); 
471                    break;
472       case TUPLE:
473       case TYCON : importTycon(source,e); 
474                    break;
475       case CLASS : importClass(source,e);
476                    break;
477       default: internal("importEntity");
478     }
479 }
480
481 static Void local importName(source,n)
482 Module source;
483 Name n; {
484     Name clash = addName(n);
485     if (nonNull(clash) && clash!=n) {
486         ERRMSG(0) "Entity \"%s\" imported from module \"%s\""
487                   " already defined in module \"%s\"",
488                   textToStr(name(n).text), 
489                   textToStr(module(source).text),
490                   textToStr(module(name(clash).mod).text)
491         EEND;
492     }
493 }
494
495 static Void local importTycon(source,tc)
496 Module source;
497 Tycon tc; {
498     Tycon clash=addTycon(tc);
499     if (nonNull(clash) && clash!=tc) {
500         ERRMSG(0) "Tycon \"%s\" imported from \"%s\" already defined in module \"%s\"",
501                   textToStr(tycon(tc).text),
502                   textToStr(module(source).text),
503                   textToStr(module(tycon(clash).mod).text)      
504         EEND;
505     }
506     if (nonNull(findClass(tycon(tc).text))) {
507         ERRMSG(0) "Import of type constructor \"%s\" clashes with class in module \"%s\"",
508                   textToStr(tycon(tc).text),
509                   textToStr(module(tycon(tc).mod).text) 
510         EEND;
511     }
512 }
513
514 static Void local importClass(source,c)
515 Module source;
516 Class c; {
517     Class clash=addClass(c);
518     if (nonNull(clash) && clash!=c) {
519         ERRMSG(0) "Class \"%s\" imported from \"%s\" already defined in module \"%s\"",
520                   textToStr(cclass(c).text),
521                   textToStr(module(source).text),
522                   textToStr(module(cclass(clash).mod).text)     
523         EEND;
524     }
525     if (nonNull(findTycon(cclass(c).text))) {
526         ERRMSG(0) "Import of class \"%s\" clashes with type constructor in module \"%s\"",
527                   textToStr(cclass(c).text),
528                   textToStr(module(source).text)        
529         EEND;
530     }
531 }
532
533 static List local checkExportTycon(exports,mt,spec,tc)
534 List  exports;
535 Text  mt;
536 Cell  spec; 
537 Tycon tc; {
538     if (DOTDOT == spec || SYNONYM == tycon(tc).what) {
539         return cons(pair(tc,DOTDOT), exports);
540     } else {
541         return cons(pair(tc,NIL), exports);
542     }
543 }
544
545 static List local checkExportClass(exports,mt,spec,cl)
546 List  exports;
547 Text  mt;
548 Class cl;
549 Cell  spec; {
550     if (DOTDOT == spec) {
551         return cons(pair(cl,DOTDOT), exports);
552     } else {
553         return cons(pair(cl,NIL), exports);
554     }
555 }
556
557 static List local checkExport(exports,mt,e) /* Process entry in export list*/
558 List exports;
559 Text mt; 
560 Cell e; {
561     if (isIdent(e)) {
562         Cell export = NIL;
563         List origExports = exports;
564         if (nonNull(export=findQualName(e))) {
565             exports=cons(export,exports);
566         } 
567         if (isQCon(e) && nonNull(export=findQualTycon(e))) {
568             exports = checkExportTycon(exports,mt,NIL,export);
569         } 
570         if (isQCon(e) && nonNull(export=findQualClass(e))) {
571             /* opaque class export */
572             exports = checkExportClass(exports,mt,NIL,export);
573         }
574         if (exports == origExports) {
575             ERRMSG(0) "Unknown entity \"%s\" exported from module \"%s\"",
576                       identToStr(e),
577                       textToStr(mt)
578             EEND;
579         }
580         return exports;
581     } else if (MODULEENT == fst(e)) {
582         Module m = findModid(snd(e));
583         /* ToDo: shouldn't allow export of module we didn't import */
584         if (isNull(m)) {
585             ERRMSG(0) "Unknown module \"%s\" exported from module \"%s\"",
586                       textToStr(textOf(snd(e))),
587                       textToStr(mt)
588             EEND;
589         }
590         if (m == currentModule) {
591             /* Exporting the current module exports local definitions */
592             List xs;
593             for(xs=module(m).classes; nonNull(xs); xs=tl(xs)) {
594                 if (cclass(hd(xs)).mod==m) 
595                     exports = checkExportClass(exports,mt,DOTDOT,hd(xs));
596             }
597             for(xs=module(m).tycons; nonNull(xs); xs=tl(xs)) {
598                 if (tycon(hd(xs)).mod==m) 
599                     exports = checkExportTycon(exports,mt,DOTDOT,hd(xs));
600             }
601             for(xs=module(m).names; nonNull(xs); xs=tl(xs)) {
602                 if (name(hd(xs)).mod==m) 
603                     exports = cons(hd(xs),exports);
604             }
605         } else {
606             /* Exporting other modules imports all things imported 
607              * unqualified from it.  
608              * ToDo: we reexport everything exported by a module -
609              * whether we imported it or not.  This gives the wrong
610              * result for "module M(module N) where import N(x)"
611              */
612             exports = dupOnto(module(m).exports,exports);
613         }
614         return exports;
615     } else {
616         Cell ident = fst(e); /* class name or type name */
617         Cell parts = snd(e); /* members or constructors */
618         Cell nm;
619         if (isQCon(ident) && nonNull(nm=findQualTycon(ident))) {
620             switch (tycon(nm).what) {
621             case SYNONYM:
622                 if (DOTDOT!=parts) {
623                     ERRMSG(0) "Explicit constructor list given for type synonym"
624                               " \"%s\" in export list of module \"%s\"",
625                               identToStr(ident),
626                               textToStr(mt)
627                     EEND;
628                 }
629                 return cons(pair(nm,DOTDOT),exports);
630             case RESTRICTSYN:   
631                 ERRMSG(0) "Transparent export of restricted type synonym"
632                           " \"%s\" in export list of module \"%s\"",
633                           identToStr(ident),
634                           textToStr(mt)
635                 EEND;
636                 return exports; /* Not reached */
637             case NEWTYPE:
638             case DATATYPE:
639                 if (DOTDOT==parts) {
640                     return cons(pair(nm,DOTDOT),exports);
641                 } else {
642                     exports = checkSubentities(exports,parts,tycon(nm).defn,
643                                                "constructor of type",
644                                                tycon(nm).text);
645                     return cons(pair(nm,DOTDOT), exports);
646                 }
647             default:
648                 internal("checkExport1");
649             }
650         } else if (isQCon(ident) && nonNull(nm=findQualClass(ident))) {
651             if (DOTDOT == parts) {
652                 return cons(pair(nm,DOTDOT),exports);
653             } else {
654                 exports = checkSubentities(exports,parts,cclass(nm).members,
655                                            "member of class",cclass(nm).text);
656                 return cons(pair(nm,DOTDOT), exports);
657             }
658         } else {
659             ERRMSG(0) "Explicit export list given for non-class/datatype \"%s\" in export list of module \"%s\"",
660                       identToStr(ident),
661                       textToStr(mt)
662             EEND;
663         }
664     }
665     return exports; /* NOTUSED */
666 }
667
668 static List local checkExports ( List exports, Module thisModule )
669 {
670     Module m  = thisModule;
671     Text   mt = module(m).text;
672     List   es = NIL;
673
674     map1Accum(checkExport,es,mt,exports);
675
676 #if DEBUG_MODULES
677     for(xs=es; nonNull(xs); xs=tl(xs)) {
678         Printf(" %s", textToStr(textOfEntity(hd(xs))));
679     }
680 #endif
681     return es;
682 }
683
684
685 /* --------------------------------------------------------------------------
686  * Static analysis of type declarations:
687  *
688  * Type declarations come in two forms:
689  * - data declarations - define new constructed data types
690  * - type declarations - define new type synonyms
691  *
692  * A certain amount of work is carried out as the declarations are
693  * read during parsing.  In particular, for each type constructor
694  * definition encountered:
695  * - check that there is no previous definition of constructor
696  * - ensure type constructor not previously used as a class name
697  * - make a new entry in the type constructor table
698  * - record line number of declaration
699  * - Build separate lists of newly defined constructors for later use.
700  * ------------------------------------------------------------------------*/
701
702 Void tyconDefn(line,lhs,rhs,what)       /* process new type definition     */
703 Int  line;                              /* definition line number          */
704 Cell lhs;                               /* left hand side of definition    */
705 Cell rhs;                               /* right hand side of definition   */
706 Cell what; {                            /* SYNONYM/DATATYPE/etc...         */
707     Text t = textOf(getHead(lhs));
708
709     if (nonNull(findTycon(t))) {
710         ERRMSG(line) "Repeated definition of type constructor \"%s\"",
711                      textToStr(t)
712         EEND;
713     }
714     else if (nonNull(findClass(t))) {
715         ERRMSG(line) "\"%s\" used as both class and type constructor",
716                      textToStr(t)
717         EEND;
718     }
719     else {
720         Tycon nw        = newTycon(t);
721         tyconDefns      = cons(nw,tyconDefns);
722         tycon(nw).line  = line;
723         tycon(nw).arity = argCount;
724         tycon(nw).what  = what;
725         if (what==RESTRICTSYN) {
726             h98DoesntSupport(line,"restricted type synonyms");
727             typeInDefns = cons(pair(nw,snd(rhs)),typeInDefns);
728             rhs         = fst(rhs);
729         }
730         tycon(nw).defn  = pair(lhs,rhs);
731     }
732 }
733
734 Void setTypeIns(bs)                     /* set local synonyms for given    */
735 List bs; {                              /* binding group                   */
736     List cvs = typeInDefns;
737     for (; nonNull(cvs); cvs=tl(cvs)) {
738         Tycon c  = fst(hd(cvs));
739         List  vs = snd(hd(cvs));
740         for (tycon(c).what = RESTRICTSYN; nonNull(vs); vs=tl(vs)) {
741             if (nonNull(findBinding(textOf(hd(vs)),bs))) {
742                 tycon(c).what = SYNONYM;
743                 break;
744             }
745         }
746     }
747 }
748
749 Void clearTypeIns() {                   /* clear list of local synonyms    */
750     for (; nonNull(typeInDefns); typeInDefns=tl(typeInDefns))
751         tycon(fst(hd(typeInDefns))).what = RESTRICTSYN;
752 }
753
754 /* --------------------------------------------------------------------------
755  * Further analysis of Type declarations:
756  *
757  * In order to allow the definition of mutually recursive families of
758  * data types, the static analysis of the right hand sides of type
759  * declarations cannot be performed until all of the type declarations
760  * have been read.
761  *
762  * Once parsing is complete, we carry out the following:
763  *
764  * - check format of lhs, extracting list of bound vars and ensuring that
765  *   there are no repeated variables and no Skolem variables.
766  * - run dependency analysis on rhs to check that only bound type vars
767  *   appear in type and that all constructors are defined.
768  *   Replace type variables by offsets, constructors by Tycons.
769  * - use list of dependents to sort into strongly connected components.
770  * - ensure that there is not more than one synonym in each group.
771  * - kind-check each group of type definitions.
772  *
773  * - check that there are no previous definitions for constructor
774  *   functions in data type definitions.
775  * - install synonym expansions and constructor definitions.
776  * ------------------------------------------------------------------------*/
777
778 static List tcDeps = NIL;               /* list of dependent tycons/classes*/
779
780 static Void local checkTyconDefn(d)     /* validate type constructor defn  */
781 Tycon d; {
782     Cell lhs    = fst(tycon(d).defn);
783     Cell rhs    = snd(tycon(d).defn);
784     Int  line   = tycon(d).line;
785     List tyvars = getArgs(lhs);
786     List temp;
787                                         /* check for repeated tyvars on lhs*/
788     for (temp=tyvars; nonNull(temp); temp=tl(temp))
789         if (nonNull(varIsMember(textOf(hd(temp)),tl(temp)))) {
790             ERRMSG(line) "Repeated type variable \"%s\" on left hand side",
791                          textToStr(textOf(hd(temp)))
792             EEND;
793         }
794
795     tcDeps = NIL;                       /* find dependents                 */
796     switch (whatIs(tycon(d).what)) {
797         case RESTRICTSYN :
798         case SYNONYM     : rhs = depTypeExp(line,tyvars,rhs);
799                            if (cellIsMember(d,tcDeps)) {
800                                ERRMSG(line) "Recursive type synonym \"%s\"",
801                                             textToStr(tycon(d).text)
802                                EEND;
803                            }
804                            break;
805
806         case DATATYPE    :
807         case NEWTYPE     : depConstrs(d,tyvars,rhs);
808                            rhs = fst(rhs);
809                            break;
810
811         default          : internal("checkTyconDefn");
812                            break;
813     }
814
815     tycon(d).defn = rhs;
816     tycon(d).kind = tcDeps;
817     tcDeps        = NIL;
818 }
819
820 static Void local depConstrs(t,tyvars,cd)
821 Tycon t;                                /* Define constructor functions and*/
822 List  tyvars;                           /* do dependency analysis for data */
823 Cell  cd; {                             /* definitions (w or w/o deriving) */
824     Int  line      = tycon(t).line;
825     List ctxt      = NIL;
826     Int  conNo     = 1;
827     Type lhs       = t;
828     List cs        = fst(cd);
829     List derivs    = snd(cd);
830     List compTypes = NIL;
831     List sels      = NIL;
832     Int  i;
833
834     for (i=0; i<tycon(t).arity; ++i)    /* build representation for tycon  */
835         lhs = ap(lhs,mkOffset(i));      /* applied to full comp. of args   */
836
837     if (isQualType(cs)) {               /* allow for possible context      */
838         ctxt = fst(snd(cs));
839         cs   = snd(snd(cs));
840         map2Over(depPredExp,line,tyvars,ctxt);
841         h98CheckCtxt(line,"context",TRUE,ctxt,NIL);
842     }
843
844     if (nonNull(cs) && isNull(tl(cs)))  /* Single constructor datatype?    */
845         conNo = 0;
846
847     for (; nonNull(cs); cs=tl(cs)) {    /* For each constructor function:  */
848         Cell con   = hd(cs);
849         List sig   = dupList(tyvars);
850         List evs   = NIL;               /* locally quantified vars         */
851         List lps   = NIL;               /* locally bound predicates        */
852         List ctxt1 = ctxt;              /* constructor function context    */
853         List scs   = NIL;               /* strict components               */
854         List fs    = NONE;              /* selector names                  */
855         Type type  = lhs;               /* constructor function type       */
856         Int  arity = 0;                 /* arity of constructor function   */
857         Int  nr2   = 0;                 /* Number of rank 2 args           */
858         Name n;                         /* name for constructor function   */
859
860         if (whatIs(con)==POLYTYPE) {    /* Locally quantified vars         */
861             evs = fst(snd(con));
862             con = snd(snd(con));
863             sig = checkQuantVars(line,evs,sig,con);
864         }
865
866         if (isQualType(con)) {          /* Local predicates                */
867             List us;
868             lps     = fst(snd(con));
869             for (us = typeVarsIn(lps,NIL,NIL,NIL); nonNull(us); us=tl(us))
870                 if (!varIsMember(textOf(hd(us)),evs)) {
871                     ERRMSG(line)
872                         "Variable \"%s\" in constraint is not locally bound",
873                         textToStr(textOf(hd(us)))
874                     EEND;
875                 }
876             map2Over(depPredExp,line,sig,lps);
877             con     = snd(snd(con));
878             arity   = length(lps);
879         }
880
881         if (whatIs(con)==LABC) {        /* Skeletize constr components     */
882             Cell fls = snd(snd(con));   /* get field specifications        */
883             con      = fst(snd(con));
884             fs       = NIL;
885             for (; nonNull(fls); fls=tl(fls)) { /* for each field spec:    */
886                 List vs     = fst(hd(fls));
887                 Type t      = snd(hd(fls));     /* - scrutinize type       */
888                 Bool banged = whatIs(t)==BANG;
889                 t           = depCompType(line,sig,(banged ? arg(t) : t));
890                 while (nonNull(vs)) {           /* - add named components  */
891                     Cell us = tl(vs);
892                     tl(vs)  = fs;
893                     fs      = vs;
894                     vs      = us;
895                     con     = ap(con,t);
896                     arity++;
897                     if (banged)
898                         scs = cons(mkInt(arity),scs);
899                 }
900             }
901             fs  = rev(fs);
902             scs = rev(scs);             /* put strict comps in ascend ord  */
903         }
904         else {                          /* Non-labelled constructor        */
905             Cell c = con;
906             Int  compNo;
907             for (; isAp(c); c=fun(c))
908                 arity++;
909             for (compNo=arity, c=con; isAp(c); c=fun(c)) {
910                 Type t = arg(c);
911                 if (whatIs(t)==BANG) {
912                     scs = cons(mkInt(compNo),scs);
913                     t   = arg(t);
914                 }
915                 compNo--;
916                 arg(c) = depCompType(line,sig,t);
917             }
918         }
919
920         if (nonNull(ctxt1))             /* Extract relevant part of context*/
921             ctxt1 = selectCtxt(ctxt1,offsetTyvarsIn(con,NIL));
922
923         for (i=arity; isAp(con); i--) { /* Calculate type of constructor   */
924             Type ty  = fun(con);
925             Type cmp = arg(con);
926             fun(con) = typeArrow;
927             if (isPolyOrQualType(cmp)) {
928                 if (nonNull(derivs)) {
929                     ERRMSG(line) "Cannot derive instances for types" ETHEN
930                     ERRTEXT      " with polymorphic or qualified components"
931                     EEND;
932                 }
933                 if (nr2==0)
934                     nr2 = i;
935             }
936             if (nonNull(derivs))        /* and build list of components    */
937                 compTypes = cons(cmp,compTypes);
938             type     = ap(con,type);
939             con      = ty;
940         }
941
942         if (nr2>0) {                    /* Add rank 2 annotation           */
943             type = ap(RANK2,pair(mkInt(nr2-length(lps)),type));
944         }
945
946         if (nonNull(evs)) {             /* Add existential annotation      */
947             if (nonNull(derivs)) {
948                 ERRMSG(line) "Cannot derive instances for types" ETHEN
949                 ERRTEXT      " with existentially typed components"
950                 EEND;
951             }
952             if (fs!=NONE) {
953                 ERRMSG(line)
954                    "Cannot use selectors with existentially typed components"
955                 EEND;
956             }
957             type = ap(EXIST,pair(mkInt(length(evs)),type));
958         }
959
960         if (nonNull(lps)) {             /* Add local preds part to type    */
961             type = ap(CDICTS,pair(lps,type));
962         }
963
964         if (nonNull(ctxt1)) {           /* Add context part to type        */
965             type = ap(QUAL,pair(ctxt1,type));
966         }
967
968         if (nonNull(sig)) {             /* Add quantifiers to type         */
969             List ts1 = sig;
970             for (; nonNull(ts1); ts1=tl(ts1)) {
971                 hd(ts1) = NIL;
972             }
973             type = mkPolyType(sig,type);
974         }
975
976         n = findName(textOf(con));      /* Allocate constructor fun name   */
977         if (isNull(n)) {
978             n = newName(textOf(con),NIL);
979         } else if (name(n).defn!=PREDEFINED) {
980             duplicateError(line,name(n).mod,name(n).text,
981                            "constructor function");
982         }
983         name(n).arity  = arity;         /* Save constructor fun details    */
984         name(n).line   = line;
985         name(n).parent = t;
986         name(n).number = cfunNo(conNo++);
987         name(n).type   = type;
988         if (tycon(t).what==NEWTYPE) {
989             if (nonNull(lps)) {
990                 ERRMSG(line)
991                    "A newtype constructor cannot have class constraints"
992                 EEND;
993             }
994             if (arity!=1) {
995                 ERRMSG(line)
996                    "A newtype constructor must have exactly one argument"
997                 EEND;
998             }
999             if (nonNull(scs)) {
1000                 ERRMSG(line)
1001                    "Illegal strictess annotation for newtype constructor"
1002                 EEND;
1003             }
1004             name(n).defn = nameId;
1005         } else {
1006             implementCfun(n,scs);
1007             name(n).hasStrict = nonNull(scs);
1008         }
1009
1010         hd(cs) = n;
1011         if (fs!=NONE) {
1012             sels = addSels(line,n,fs,sels);
1013         }
1014     }
1015
1016     if (nonNull(sels)) {
1017         sels     = rev(sels);
1018         fst(cd)  = appendOnto(fst(cd),sels);
1019         selDefns = cons(sels,selDefns);
1020     }
1021
1022     if (nonNull(derivs)) {              /* Generate derived instances      */
1023         map3Proc(checkDerive,t,ctxt,compTypes,derivs);
1024     }
1025 }
1026
1027 Int userArity(c)                        /* Find arity for cfun, ignoring   */
1028 Name c; {                               /* CDICTS parameters               */
1029     Int  a = name(c).arity;
1030     Type t = name(c).type;
1031     Int  w;
1032     if (isPolyType(t)) {
1033         t = monotypeOf(t);
1034     }
1035     if ((w=whatIs(t))==QUAL) {
1036         w = whatIs(t=snd(snd(t)));
1037     }
1038     if (w==CDICTS) {
1039         a -= length(fst(snd(t)));
1040     }
1041     return a;
1042 }
1043
1044
1045 static List local addSels(line,c,fs,ss) /* Add fields to selector list     */
1046 Int  line;                              /* line number of constructor      */
1047 Name c;                                 /* corresponding constr function   */
1048 List fs;                                /* list of fields (varids)         */
1049 List ss; {                              /* list of existing selectors      */
1050     Int sn    = 1;
1051     cfunSfuns = cons(pair(c,fs),cfunSfuns);
1052     for (; nonNull(fs); fs=tl(fs), ++sn) {
1053         List ns = ss;
1054         Text t  = textOf(hd(fs));
1055
1056         if (nonNull(varIsMember(t,tl(fs)))) {
1057             ERRMSG(line) "Repeated field name \"%s\" for constructor \"%s\"",
1058                          textToStr(t), textToStr(name(c).text)
1059             EEND;
1060         }
1061
1062         while (nonNull(ns) && t!=name(hd(ns)).text) {
1063             ns = tl(ns);
1064         }
1065
1066         if (nonNull(ns)) {
1067             name(hd(ns)).defn = cons(pair(c,mkInt(sn)),name(hd(ns)).defn);
1068         } else {
1069             Name n = findName(t);
1070             if (nonNull(n)) {
1071                 ERRMSG(line) "Repeated definition for selector \"%s\"",
1072                              textToStr(t)
1073                 EEND;
1074             }
1075             n              = newName(t,c);
1076             name(n).line   = line;
1077             name(n).number = SELNAME;
1078             name(n).defn   = singleton(pair(c,mkInt(sn)));
1079             ss             = cons(n,ss);
1080         }
1081     }
1082     return ss;
1083 }
1084
1085 static List local selectCtxt(ctxt,vs)   /* calculate subset of context     */
1086 List ctxt;
1087 List vs; {
1088     if (isNull(vs)) {
1089         return NIL;
1090     } else {
1091         List ps = NIL;
1092         for (; nonNull(ctxt); ctxt=tl(ctxt)) {
1093             List us = offsetTyvarsIn(hd(ctxt),NIL);
1094             for (; nonNull(us) && cellIsMember(hd(us),vs); us=tl(us)) {
1095             }
1096             if (isNull(us)) {
1097                 ps = cons(hd(ctxt),ps);
1098             }
1099         }
1100         return rev(ps);
1101     }
1102 }
1103
1104 static Void local checkSynonyms(ts)     /* Check for mutually recursive    */
1105 List ts; {                              /* synonyms                        */
1106     List syns = NIL;
1107     for (; nonNull(ts); ts=tl(ts)) {    /* build list of all synonyms      */
1108         Tycon t = hd(ts);
1109         switch (whatIs(tycon(t).what)) {
1110             case SYNONYM     :
1111             case RESTRICTSYN : syns = cons(t,syns);
1112                                break;
1113         }
1114     }
1115     while (nonNull(syns)) {             /* then visit each synonym         */
1116         syns = visitSyn(NIL,hd(syns),syns);
1117     }
1118 }
1119
1120 static List local visitSyn(path,t,syns) /* visit synonym definition to look*/
1121 List  path;                             /* for cycles                      */
1122 Tycon t;
1123 List  syns; {
1124     if (cellIsMember(t,path)) {         /* every elt in path depends on t  */
1125         ERRMSG(tycon(t).line)
1126             "Type synonyms \"%s\" and \"%s\" are mutually recursive",
1127             textToStr(tycon(t).text), textToStr(tycon(hd(path)).text)
1128         EEND;
1129     } else {
1130         List ds    = tycon(t).kind;
1131         List path1 = NIL;
1132         for (; nonNull(ds); ds=tl(ds)) {
1133             if (cellIsMember(hd(ds),syns)) {
1134                 if (isNull(path1)) {
1135                     path1 = cons(t,path);
1136                 }
1137                 syns = visitSyn(path1,hd(ds),syns);
1138             }
1139         }
1140     }
1141     tycon(t).defn = fullExpand(tycon(t).defn);
1142     return removeCell(t,syns);
1143 }
1144
1145 /* --------------------------------------------------------------------------
1146  * Expanding out all type synonyms in a type expression:
1147  * ------------------------------------------------------------------------*/
1148
1149 Type fullExpand(t)                      /* find full expansion of type exp */
1150 Type t; {                               /* assuming that all relevant      */
1151     Cell h = t;                         /* synonym defns of lower rank have*/
1152     Int  n = 0;                         /* already been fully expanded     */
1153     List args;
1154     for (args=NIL; isAp(h); h=fun(h), n++) {
1155         args = cons(fullExpand(arg(h)),args);
1156     }
1157     t = applyToArgs(h,args);
1158     if (isSynonym(h) && n>=tycon(h).arity) {
1159         if (n==tycon(h).arity) {
1160             t = instantiateSyn(tycon(h).defn,t);
1161         } else {
1162             Type p = t;
1163             while (--n > tycon(h).arity) {
1164                 p = fun(p);
1165             }
1166             fun(p) = instantiateSyn(tycon(h).defn,fun(p));
1167         }
1168     }
1169     return t;
1170 }
1171
1172 static Type local instantiateSyn(t,env) /* instantiate type according using*/
1173 Type t;                                 /* env to determine appropriate    */
1174 Type env; {                             /* values for OFFSET type vars     */
1175     switch (whatIs(t)) {
1176         case AP      : return ap(instantiateSyn(fun(t),env),
1177                                  instantiateSyn(arg(t),env));
1178
1179         case OFFSET  : return nthArg(offsetOf(t),env);
1180
1181         default      : return t;
1182     }
1183 }
1184
1185 /* --------------------------------------------------------------------------
1186  * Static analysis of class declarations:
1187  *
1188  * Performed in a similar manner to that used for type declarations.
1189  *
1190  * The first part of the static analysis is performed as the declarations
1191  * are read during parsing.  The parser ensures that:
1192  * - the class header and all superclass predicates are of the form
1193  *   ``Class var''
1194  *
1195  * The classDefn() function:
1196  * - ensures that there is no previous definition for class
1197  * - checks that class name has not previously been used as a type constr.
1198  * - make new entry in class table
1199  * - record line number of declaration
1200  * - build list of classes defined in current script for use in later
1201  *   stages of static analysis.
1202  * ------------------------------------------------------------------------*/
1203
1204 Void classDefn(line,head,ms,fds)       /* process new class definition     */
1205 Int  line;                             /* definition line number           */
1206 Cell head;                             /* class header :: ([Supers],Class) */
1207 List ms;                               /* class definition body            */
1208 List fds; {                            /* functional dependencies          */
1209     Text ct    = textOf(getHead(snd(head)));
1210     Int  arity = argCount;
1211
1212     if (nonNull(findClass(ct))) {
1213         ERRMSG(line) "Repeated definition of class \"%s\"",
1214                      textToStr(ct)
1215         EEND;
1216     } else if (nonNull(findTycon(ct))) {
1217         ERRMSG(line) "\"%s\" used as both class and type constructor",
1218                      textToStr(ct)
1219         EEND;
1220     } else {
1221         Class nw           = newClass(ct);
1222         cclass(nw).line    = line;
1223         cclass(nw).arity   = arity;
1224         cclass(nw).head    = snd(head);
1225         cclass(nw).supers  = fst(head);
1226         cclass(nw).members = ms;
1227         cclass(nw).level   = 0;
1228         cclass(nw).fds     = fds;
1229         cclass(nw).xfds    = NIL;
1230         classDefns         = cons(nw,classDefns);
1231         if (arity!=1)
1232             h98DoesntSupport(line,"multiple parameter classes");
1233     }
1234 }
1235
1236 /* --------------------------------------------------------------------------
1237  * Further analysis of class declarations:
1238  *
1239  * Full static analysis of class definitions must be postponed until the
1240  * complete script has been read and all static analysis on type definitions
1241  * has been completed.
1242  *
1243  * Once this has been achieved, we carry out the following checks on each
1244  * class definition:
1245  * - check that variables in header are distinct
1246  * - replace head by skeleton
1247  * - check superclass declarations, replace by skeletons
1248  * - split body of class into members and declarations
1249  * - make new name entry for each member function
1250  * - record member function number (eventually an offset into dictionary!)
1251  * - no member function has a previous definition ...
1252  * - no member function is mentioned more than once in the list of members
1253  * - each member function type is valid, replace vars by offsets
1254  * - qualify each member function type by class header
1255  * - only bindings for members appear in defaults
1256  * - only function bindings appear in defaults
1257  * - check that extended class hierarchy does not contain any cycles
1258  * ------------------------------------------------------------------------*/
1259
1260 static Void local checkClassDefn(c)    /* validate class definition        */
1261 Class c; {
1262     List tyvars = NIL;
1263     Int  args   = cclass(c).arity - 1;
1264     Cell temp   = cclass(c).head;
1265     List fs     = NIL;
1266     List ss     = NIL;
1267
1268     for (; isAp(temp); temp=fun(temp)) {
1269         if (!isVar(arg(temp))) {
1270             ERRMSG(cclass(c).line) "Type variable required in class head"
1271             EEND;
1272         }
1273         if (nonNull(varIsMember(textOf(arg(temp)),tyvars))) {
1274             ERRMSG(cclass(c).line)
1275                 "Repeated type variable \"%s\" in class head",
1276                 textToStr(textOf(arg(temp)))
1277             EEND;
1278         }
1279         tyvars = cons(arg(temp),tyvars);
1280     }
1281
1282     for (fs=cclass(c).fds; nonNull(fs); fs=tl(fs)) {
1283         Pair fd = hd(fs);
1284         List vs = snd(fd);
1285
1286         /* Check for trivial dependency
1287          */
1288         if (isNull(vs)) {
1289             ERRMSG(cclass(c).line) "Functional dependency is trivial"
1290             EEND;
1291         }
1292
1293         /* Check for duplicated vars on right hand side, and for vars on
1294          * right that also appear on the left:
1295          */
1296         for (vs=snd(fd); nonNull(vs); vs=tl(vs)) {
1297             if (varIsMember(textOf(hd(vs)),fst(fd))) {
1298                 ERRMSG(cclass(c).line)
1299                     "Trivial dependency for variable \"%s\"",
1300                     textToStr(textOf(hd(vs)))
1301                 EEND;
1302             }
1303             if (varIsMember(textOf(hd(vs)),tl(vs))) {
1304                 ERRMSG(cclass(c).line)
1305                     "Repeated variable \"%s\" in functional dependency",
1306                     textToStr(textOf(hd(vs)))
1307                 EEND;
1308             }
1309             hd(vs) = depTypeVar(cclass(c).line,tyvars,textOf(hd(vs)));
1310         }
1311
1312         /* Check for duplicated vars on left hand side:
1313          */
1314         for (vs=fst(fd); nonNull(vs); vs=tl(vs)) {
1315             if (varIsMember(textOf(hd(vs)),tl(vs))) {
1316                 ERRMSG(cclass(c).line)
1317                     "Repeated variable \"%s\" in functional dependency",
1318                     textToStr(textOf(hd(vs)))
1319                 EEND;
1320             }
1321             hd(vs) = depTypeVar(cclass(c).line,tyvars,textOf(hd(vs)));
1322         }
1323     }
1324
1325     if (cclass(c).arity==0) {
1326         cclass(c).head = c;
1327     } else {
1328         Int args = cclass(c).arity - 1;
1329         for (temp=cclass(c).head; args>0; temp=fun(temp), args--) {
1330             arg(temp) = mkOffset(args);
1331         }
1332         arg(temp) = mkOffset(0);
1333         fun(temp) = c;
1334     }
1335
1336     tcDeps              = NIL;          /* find dependents                 */
1337     map2Over(depPredExp,cclass(c).line,tyvars,cclass(c).supers);
1338     h98CheckCtxt(cclass(c).line,"class definition",FALSE,cclass(c).supers,NIL);
1339     cclass(c).numSupers = length(cclass(c).supers);
1340     cclass(c).defaults  = extractBindings(cclass(c).members);   /* defaults*/
1341     ss                  = extractSigdecls(cclass(c).members);
1342     fs                  = extractFixdecls(cclass(c).members);
1343     cclass(c).members   = pair(ss,fs);
1344     map2Proc(checkMems,c,tyvars,ss);
1345
1346     cclass(c).kinds     = tcDeps;
1347     tcDeps              = NIL;
1348 }
1349
1350
1351 /* --------------------------------------------------------------------------
1352  * Functional dependencies are inherited from superclasses.
1353  * For example, if I've got the following classes:
1354  *
1355  * class C a b | a -> b
1356  * class C [b] a => D a b
1357  *
1358  * then C will have the dependency ([a], [b]) as expected, and D will inherit
1359  * the dependency ([b], [a]) from C.
1360  * When doing pairwise improvement, we have to consider not just improving
1361  * when we see a pair of Cs or a pair of Ds in the context, but when we've
1362  * got a C and a D as well.  In this case, we only improve when the
1363  * predicate in question matches the type skeleton in the relevant superclass
1364  * constraint.  E.g., we improve the pair (C [Int] a, D b Int) (unifying
1365  * a and b), but we don't improve the pair (C Int a, D b Int).
1366  * To implement functional dependency inheritance, we calculate
1367  * the closure of all functional dependencies, and store the result
1368  * in an additional field `xfds' (extended functional dependencies).
1369  * The `xfds' field is a list of functional dependency lists, annotated
1370  * with a list of predicate skeletons constraining when improvement can
1371  * happen against this dependency list.  For example, the xfds field
1372  * for C above would be:
1373  *     [([C a b], [([a], [b])])]
1374  * and the xfds field for D would be:
1375  *     [([C [b] a, D a b], [([b], [a])])]
1376  * Self-improvement (of a C with a C, or a D with a D) is treated as a
1377  * special case of an inherited dependency.
1378  * ------------------------------------------------------------------------*/
1379 static List local inheritFundeps ( Class c, Cell pi, Int o )
1380 {
1381     Int alpha = newKindedVars(cclass(c).kinds);
1382     List scs = cclass(c).supers;
1383     List xfds = NIL;
1384     Cell this = NIL;
1385     /* better not fail ;-) */
1386     if (!matchPred(pi,o,cclass(c).head,alpha))
1387         internal("inheritFundeps - predicate failed to match it's own head!");
1388     this = copyPred(pi,o);
1389     for (; nonNull(scs); scs=tl(scs)) {
1390         Class s = getHead(hd(scs));
1391         if (isClass(s)) {
1392             List sfds = inheritFundeps(s,hd(scs),alpha);
1393             for (; nonNull(sfds); sfds=tl(sfds)) {
1394                 Cell h = hd(sfds);
1395                 xfds = cons(pair(cons(this,fst(h)),snd(h)),xfds);
1396             }
1397         }
1398     }
1399     if (nonNull(cclass(c).fds)) {
1400         List fds = NIL, fs = cclass(c).fds;
1401         for (; nonNull(fs); fs=tl(fs)) {
1402             fds = cons(pair(otvars(this,fst(hd(fs))),
1403                             otvars(this,snd(hd(fs)))),fds);
1404         }
1405         xfds = cons(pair(cons(this,NIL),fds),xfds);
1406     }
1407     return xfds;
1408 }
1409
1410 static Void local extendFundeps ( Class c )
1411
1412     Int alpha;
1413     emptySubstitution();
1414     alpha = newKindedVars(cclass(c).kinds);
1415     cclass(c).xfds = inheritFundeps(c,cclass(c).head,alpha);
1416
1417     /* we can now check for ambiguity */
1418     map1Proc(checkMems2,c,fst(cclass(c).members));
1419 }
1420
1421
1422 static Cell local depPredExp(line,tyvars,pred)
1423 Int  line;
1424 List tyvars;
1425 Cell pred; {
1426     Int  args = 0;
1427     Cell prev = NIL;
1428     Cell h    = pred;
1429     for (; isAp(h); args++) {
1430         arg(h) = depTypeExp(line,tyvars,arg(h));
1431         prev   = h;
1432         h      = fun(h);
1433     }
1434
1435     if (args==0) {
1436         h98DoesntSupport(line,"tag classes");
1437     } else if (args!=1) {
1438         h98DoesntSupport(line,"multiple parameter classes");
1439     }
1440
1441     if (isQCon(h)) {                    /* standard class constraint       */
1442         Class c = findQualClass(h);
1443         if (isNull(c)) {
1444             ERRMSG(line) "Undefined class \"%s\"", identToStr(h)
1445             EEND;
1446         }
1447         if (isNull(prev)) {
1448             pred = c;
1449         } else {
1450             fun(prev) = c;
1451         }
1452         if (args!=cclass(c).arity) {
1453             ERRMSG(line) "Wrong number of arguments for class \"%s\"",
1454                         textToStr(cclass(c).text)
1455             EEND;
1456         }
1457         if (cellIsMember(c,classDefns) && !cellIsMember(c,tcDeps)) {
1458             tcDeps = cons(c,tcDeps);
1459         }
1460     }
1461 #if TREX
1462     else if (isExt(h)) {                /* Lacks predicate                 */
1463         if (args!=1) {                  /* parser shouldn't let this happen*/
1464             ERRMSG(line) "Wrong number of arguments for lacks predicate"
1465             EEND;
1466         }
1467     }
1468 #endif
1469     else 
1470 #if IPARAM
1471          if (whatIs(h) != IPCELL)
1472 #endif
1473     {
1474         internal("depPredExp");
1475     }
1476     return pred;
1477 }
1478
1479 static Void local checkMems(c,tyvars,m) /* check member function details   */
1480 Class c;
1481 List  tyvars;
1482 Cell  m; {
1483     Int  line = intOf(fst3(m));
1484     List vs   = snd3(m);
1485     Type t    = thd3(m);
1486     List sig  = NIL;
1487     List tvs  = NIL;
1488     List xtvs = NIL;
1489
1490     if (isPolyType(t)) {
1491         xtvs = fst(snd(t));
1492         t    = monotypeOf(t);
1493     }
1494   
1495
1496     tyvars    = typeVarsIn(t,NIL,xtvs,tyvars);
1497                                         /* Look for extra type vars.       */
1498     checkOptQuantVars(line,xtvs,tyvars);
1499
1500     if (isQualType(t)) {                /* Overloaded member signatures?   */
1501         map2Over(depPredExp,line,tyvars,fst(snd(t)));
1502     } else {
1503         t = ap(QUAL,pair(NIL,t));
1504     }
1505
1506     fst(snd(t)) = cons(cclass(c).head,fst(snd(t)));/* Add main predicate   */
1507     snd(snd(t)) = depTopType(line,tyvars,snd(snd(t)));
1508
1509     for (tvs=tyvars; nonNull(tvs); tvs=tl(tvs)){/* Quantify                */
1510         sig = ap(NIL,sig);
1511     }
1512     if (nonNull(sig)) {
1513         t = mkPolyType(sig,t);
1514     }
1515     thd3(m) = t;                                /* Save type               */
1516     take(cclass(c).arity,tyvars);               /* Delete extra type vars  */
1517
1518     h98CheckType(line,"member type",hd(vs),t);
1519 }
1520
1521 static Void local checkMems2(c,m) /* check member function details   */
1522 Class c;
1523 Cell  m; {
1524     Int  line = intOf(fst3(m));
1525     List vs   = snd3(m);
1526     Type t    = thd3(m);
1527
1528     if (isAmbiguous(t)) {
1529         ambigError(line,"class declaration",hd(vs),t);
1530     }
1531 }
1532
1533 static Void local addMembers(c)         /* Add definitions of member funs  */
1534 Class c; {                              /* and other parts of class struct.*/
1535     List ms  = fst(cclass(c).members);
1536     List fs  = snd(cclass(c).members);
1537     List ns  = NIL;                     /* List of names                   */
1538     Int  mno;                           /* Member function number          */
1539
1540     for (mno=0; mno<cclass(c).numSupers; mno++) {
1541         ns = cons(newDSel(c,mno),ns);
1542     }
1543     cclass(c).dsels = rev(ns);          /* Save dictionary selectors       */
1544
1545     for (mno=1, ns=NIL; nonNull(ms); ms=tl(ms)) {
1546         Int  line = intOf(fst3(hd(ms)));
1547         List vs   = rev(snd3(hd(ms)));
1548         Type t    = thd3(hd(ms));
1549         for (; nonNull(vs); vs=tl(vs)) {
1550             ns = cons(newMember(line,mno++,hd(vs),t,c),ns);
1551         }
1552     }
1553     cclass(c).members    = rev(ns);     /* Save list of members            */
1554     cclass(c).numMembers = length(cclass(c).members);
1555
1556     for (; nonNull(fs); fs=tl(fs)) {    /* fixity declarations             */
1557         Int    line = intOf(fst3(hd(fs)));
1558         List   ops  = snd3(hd(fs));
1559         Syntax s    = intOf(thd3(hd(fs)));
1560         for (; nonNull(ops); ops=tl(ops)) {
1561             Name n = nameIsMember(textOf(hd(ops)),cclass(c).members);
1562             if (isNull(n)) {
1563                 missFixity(line,textOf(hd(ops)));
1564             } else if (name(n).syntax!=NO_SYNTAX) {
1565                 dupFixity(line,textOf(hd(ops)));
1566             }
1567             name(n).syntax = s;
1568         }
1569     }
1570
1571 /*  Not actually needed just yet; for the time being, dictionary code will
1572     not be passed through the type checker.
1573
1574     cclass(c).dtycon    = addPrimTycon(generateText("Dict.%s",c),
1575                                        NIL,
1576                                        cclass(c).arity,
1577                                        DATATYPE,
1578                                        NIL);
1579 */
1580
1581     mno                  = cclass(c).numSupers + cclass(c).numMembers;
1582     /* cclass(c).dcon       = addPrimCfun(generateText("Make.%s",c),mno,0,NIL); */
1583     cclass(c).dcon       = addPrimCfun(generateText(":D%s",c),mno,0,NIL);
1584     /* implementCfun(cclass(c).dcon,NIL);
1585        Don't manufacture a wrapper fn for dictionary constructors.
1586        Applications of dictionary constructors are always saturated,
1587        and translate.c:stgExpr() special-cases saturated constructor apps.
1588     */
1589
1590     if (mno==1) {                       /* Single entry dicts use newtype  */
1591         name(cclass(c).dcon).defn = nameId;
1592         if (nonNull(cclass(c).members)) {
1593             name(hd(cclass(c).members)).number = mfunNo(0);
1594         }
1595     }
1596     cclass(c).defaults   = classBindings("class",c,cclass(c).defaults);
1597 }
1598
1599 static Name local newMember(l,no,v,t,parent)
1600 Int   l;                                /* Make definition for member fn   */
1601 Int   no;
1602 Cell  v;
1603 Type  t; 
1604 Class parent; {
1605     Name m = findName(textOf(v));
1606
1607     if (isNull(m)) {
1608         m = newName(textOf(v),parent);
1609     } else if (name(m).defn!=PREDEFINED) {
1610         ERRMSG(l) "Repeated definition for member function \"%s\"",
1611                   textToStr(name(m).text)
1612         EEND;
1613     }
1614
1615     name(m).line     = l;
1616     name(m).arity    = 1;
1617     name(m).number   = mfunNo(no);
1618     name(m).type     = t;
1619     return m;
1620 }
1621
1622 Name newDSel(c,no)                      /* Make definition for dict selectr*/
1623 Class c;
1624 Int   no; {
1625     Name s;
1626     char buf[16];
1627
1628     /* sprintf(buf,"sc%d.%s",no,"%s"); */
1629     sprintf(buf,"$p%d%s",no+1,"%s");
1630     s                = newName(generateText(buf,c),c);
1631     name(s).line     = cclass(c).line;
1632     name(s).arity    = 1;
1633     name(s).number   = DFUNNAME;
1634     return s;
1635 }
1636
1637 #define MAX_GEN  128
1638
1639 static Text local generateText(sk,c)    /* We need to generate names for   */
1640 String sk;                              /* certain objects corresponding   */
1641 Class  c; {                             /* to each class.                  */
1642     String cname = textToStr(cclass(c).text);
1643     char buffer[MAX_GEN+1];
1644
1645     if ((strlen(sk)+strlen(cname))>=MAX_GEN) {
1646         ERRMSG(0) "Please use a shorter name for class \"%s\"", cname
1647         EEND;
1648     }
1649     sprintf(buffer,sk,cname);
1650     return findText(buffer);
1651 }
1652
1653        Int visitClass(c)                /* visit class defn to check that  */
1654 Class c; {                              /* class hierarchy is acyclic      */
1655 #if TREX
1656     if (isExt(c)) {                     /* special case for lacks preds    */
1657         return 0;
1658     }
1659 #endif
1660     if (cclass(c).level < 0) {          /* already visiting this class?    */
1661         ERRMSG(cclass(c).line) "Class hierarchy for \"%s\" is not acyclic",
1662                                textToStr(cclass(c).text)
1663         EEND;
1664     } else if (cclass(c).level == 0) {  /* visiting class for first time   */
1665         List scs = cclass(c).supers;
1666         Int  lev = 0;
1667         cclass(c).level = (-1);
1668         for (; nonNull(scs); scs=tl(scs)) {
1669             Int l = visitClass(getHead(hd(scs)));
1670             if (l>lev) lev=l;
1671         }
1672         cclass(c).level = 1+lev;        /* level = 1 + max level of supers */
1673     }
1674     return cclass(c).level;
1675 }
1676
1677 /* --------------------------------------------------------------------------
1678  * Process class and instance declaration binding groups:
1679  * ------------------------------------------------------------------------*/
1680
1681 static List local classBindings(where,c,bs)
1682 String where;                           /* Check validity of bindings bs   */
1683 Class  c;                               /* for class c (or an inst of c)   */
1684 List   bs; {                            /* sort into approp. member order  */
1685     List nbs = NIL;
1686
1687     for (; nonNull(bs); bs=tl(bs)) {
1688         Cell b    = hd(bs);
1689         Cell body = snd(snd(b));
1690         Name mnm;
1691
1692         if (!isVar(fst(b))) {           /* Only allow function bindings    */
1693             ERRMSG(rhsLine(snd(body)))
1694                 "Pattern binding illegal in %s declaration", where
1695             EEND;
1696         }
1697
1698         if (isNull(mnm=memberName(c,textOf(fst(b))))) {
1699             ERRMSG(rhsLine(snd(hd(body))))
1700                 "No member \"%s\" in class \"%s\"",
1701                 textToStr(textOf(fst(b))), textToStr(cclass(c).text)
1702             EEND;
1703         }
1704         snd(b) = body;
1705         nbs    = numInsert(mfunOf(mnm)-1,b,nbs);
1706     }
1707     return nbs;
1708 }
1709
1710 static Name local memberName(c,t)       /* return name of member function  */
1711 Class c;                                /* with name t in class c          */
1712 Text  t; {                              /* return NIL if not a member      */
1713     List ms = cclass(c).members;
1714     for (; nonNull(ms); ms=tl(ms)) {
1715         if (t==name(hd(ms)).text) {
1716             return hd(ms);
1717         }
1718     }
1719     return NIL;
1720 }
1721
1722 static List local numInsert(n,x,xs)    /* insert x at nth position in xs,  */
1723 Int  n;                                /* filling gaps with NIL            */
1724 Cell x;
1725 List xs; {
1726     List start = isNull(xs) ? cons(NIL,NIL) : xs;
1727
1728     for (xs=start; 0<n--; xs=tl(xs)) {
1729         if (isNull(tl(xs))) {
1730             tl(xs) = cons(NIL,NIL);
1731         }
1732     }
1733     hd(xs) = x;
1734     return start;
1735 }
1736
1737 /* --------------------------------------------------------------------------
1738  * Calculate set of variables appearing in a given type expression (possibly
1739  * qualified) as a list of distinct values.  The order in which variables
1740  * appear in the list is the same as the order in which those variables
1741  * occur in the type expression when read from left to right.
1742  * ------------------------------------------------------------------------*/
1743
1744 List local typeVarsIn(ty,us,ws,vs)      /*Calculate list of type variables*/
1745 Cell ty;                                /* used in type expression, reading*/
1746 List us;                                /* from left to right ignoring any */
1747 List ws;                                /* listed in us.                   */
1748 List vs; {                              /* ws = explicitly quantified vars */
1749     if (isNull(ty)) return vs;
1750     switch (whatIs(ty)) {
1751         case DICTAP    : return typeVarsIn(snd(snd(ty)),us,ws,vs);
1752         case UNBOXEDTUP: return typeVarsIn(snd(ty),us,ws,vs);
1753
1754         case AP        : return typeVarsIn(snd(ty),us,ws,
1755                                            typeVarsIn(fst(ty),us,ws,vs));
1756
1757         case VARIDCELL :
1758         case VAROPCELL : if ((nonNull(findBtyvs(textOf(ty)))
1759                               && !varIsMember(textOf(ty),ws))
1760                              || varIsMember(textOf(ty),us)) {
1761                              return vs;
1762                          } else {
1763                              return maybeAppendVar(ty,vs);
1764                          }
1765
1766         case POLYTYPE  : return typeVarsIn(monotypeOf(ty),polySigOf(ty),ws,vs);
1767
1768         case QUAL      : {   vs = typeVarsIn(fst(snd(ty)),us,ws,vs);
1769                              return typeVarsIn(snd(snd(ty)),us,ws,vs);
1770                          }
1771
1772         case BANG      : return typeVarsIn(snd(ty),us,ws,vs);
1773
1774         case LABC      : {   List fs = snd(snd(ty));
1775                              for (; nonNull(fs); fs=tl(fs)) {
1776                                 vs = typeVarsIn(snd(hd(fs)),us,ws,vs);
1777                              }
1778                              return vs;
1779                          }
1780         case TUPLE:
1781         case TYCON:
1782         case CONIDCELL:
1783         case QUALIDENT: return vs;
1784
1785         default: fprintf(stderr, " bad tag = %d\n", whatIs(ty));internal("typeVarsIn");
1786     }
1787     assert(0);
1788 }
1789
1790 static List local maybeAppendVar(v,vs) /* append variable to list if not   */
1791 Cell v;                                /* already included                 */
1792 List vs; {
1793     Text t = textOf(v);
1794     List p = NIL;
1795     List c = vs;
1796
1797     while (nonNull(c)) {
1798         if (textOf(hd(c))==t) {
1799             return vs;
1800         }
1801         p = c;
1802         c = tl(c);
1803     }
1804
1805     if (nonNull(p)) {
1806         tl(p) = cons(v,NIL);
1807     } else {
1808         vs    = cons(v,NIL);
1809     }
1810
1811     return vs;
1812 }
1813
1814 /* --------------------------------------------------------------------------
1815  * Static analysis for type expressions is required to:
1816  *   - ensure that each type constructor or class used has been defined.
1817  *   - replace type variables by offsets, constructor names by Tycons.
1818  *   - ensure that the type is well-kinded.
1819  * ------------------------------------------------------------------------*/
1820
1821 static Type local checkSigType(line,where,e,type)
1822 Int    line;                            /* Check validity of type expr in  */
1823 String where;                           /* explicit type signature         */
1824 Cell   e;
1825 Type   type; {
1826     List tvs  = NIL;
1827     List sunk = NIL;
1828     List xtvs = NIL;
1829
1830     if (isPolyType(type)) {
1831         xtvs = fst(snd(type));
1832         type = monotypeOf(type);
1833     }
1834     tvs  = typeVarsIn(type,NIL,xtvs,NIL);
1835     sunk = unkindTypes;
1836     checkOptQuantVars(line,xtvs,tvs);
1837
1838     if (isQualType(type)) {
1839         map2Over(depPredExp,line,tvs,fst(snd(type)));
1840         snd(snd(type)) = depTopType(line,tvs,snd(snd(type)));
1841
1842         if (isAmbiguous(type)) {
1843             ambigError(line,where,e,type);
1844         }
1845     } else {
1846         type = depTopType(line,tvs,type);
1847     }
1848
1849     if (nonNull(tvs)) {
1850         if (length(tvs) >= (OFF_MAX-OFF_MIN+1)) {
1851             ERRMSG(line) "Too many type variables in %s\n", where
1852             EEND;
1853         } else {
1854             List ts = tvs;
1855             for (; nonNull(ts); ts=tl(ts)) {
1856                 hd(ts) = NIL;
1857             }
1858             type    = mkPolyType(tvs,type);
1859         }
1860     }
1861
1862     unkindTypes = NIL;
1863     kindType(line,"type expression",type);
1864     fixKinds();
1865     unkindTypes = sunk;
1866
1867     h98CheckType(line,where,e,type);
1868     return type;
1869 }
1870
1871 static Void local checkOptQuantVars(line,xtvs,tvs)
1872 Int  line;
1873 List xtvs;                              /* Explicitly quantified vars      */
1874 List tvs; {                             /* Implicitly quantified vars      */
1875     if (nonNull(xtvs)) {
1876         List vs = tvs;
1877         for (; nonNull(vs); vs=tl(vs)) {
1878             if (!varIsMember(textOf(hd(vs)),xtvs)) {
1879                 ERRMSG(line) "Quantifier does not mention type variable \"%s\"",
1880                              textToStr(textOf(hd(vs)))
1881                 EEND;
1882             }
1883         }
1884         for (vs=xtvs; nonNull(vs); vs=tl(vs)) {
1885             if (!varIsMember(textOf(hd(vs)),tvs)) {
1886                 ERRMSG(line) "Quantified type variable \"%s\" is not used",
1887                              textToStr(textOf(hd(vs)))
1888                 EEND;
1889             }
1890             if (varIsMember(textOf(hd(vs)),tl(vs))) {
1891                 ERRMSG(line) "Quantified type variable \"%s\" is repeated",
1892                              textToStr(textOf(hd(vs)))
1893                 EEND;
1894             }
1895         }
1896     }
1897 }
1898
1899 static Type local depTopType(l,tvs,t)   /* Check top-level of type sig     */
1900 Int  l;
1901 List tvs;
1902 Type t; {
1903     Type prev = NIL;
1904     Type t1   = t;
1905     Int  nr2  = 0;
1906     Int  i    = 1;
1907     for (; getHead(t1)==typeArrow && argCount==2; ++i) {
1908         arg(fun(t1)) = depCompType(l,tvs,arg(fun(t1)));
1909         if (isPolyOrQualType(arg(fun(t1)))) {
1910             nr2 = i;
1911         }
1912         prev = t1;
1913         t1   = arg(t1);
1914     }
1915     if (nonNull(prev)) {
1916         arg(prev) = depTypeExp(l,tvs,t1);
1917     } else {
1918         t = depTypeExp(l,tvs,t1);
1919     }
1920     if (nr2>0) {
1921         t = ap(RANK2,pair(mkInt(nr2),t));
1922     }
1923     return t;
1924 }
1925
1926 static Type local depCompType(l,tvs,t)  /* Check component type for constr */
1927 Int  l;
1928 List tvs;
1929 Type t; {
1930   Int  ntvs = length(tvs);
1931   List nfr  = NIL;
1932   if (isPolyType(t)) {
1933     List vs  = fst(snd(t));
1934     t        = monotypeOf(t);
1935     tvs      = checkQuantVars(l,vs,tvs,t);
1936     nfr      = replicate(length(vs),NIL);
1937   }
1938   if (isQualType(t)) {
1939     map2Over(depPredExp,l,tvs,fst(snd(t)));
1940     snd(snd(t)) = depTypeExp(l,tvs,snd(snd(t)));
1941     if (isAmbiguous(t)) {
1942       ambigError(l,"type component",NIL,t);
1943     }
1944   } else {
1945     t = depTypeExp(l,tvs,t);
1946   }
1947   if (isNull(nfr)) {
1948     return t;
1949   }
1950   take(ntvs,tvs);
1951   return mkPolyType(nfr,t);
1952 }
1953
1954 static Type local depTypeExp(line,tyvars,type)
1955 Int  line;
1956 List tyvars;
1957 Type type; {
1958     switch (whatIs(type)) {
1959         case AP         : fst(type) = depTypeExp(line,tyvars,fst(type));
1960                           snd(type) = depTypeExp(line,tyvars,snd(type));
1961                           break;
1962
1963         case VARIDCELL  : return depTypeVar(line,tyvars,textOf(type));
1964
1965         case QUALIDENT  : if (isQVar(type)) {
1966                               ERRMSG(line) "Qualified type variables not allowed"
1967                               EEND;
1968                           }
1969                           /* deliberate fall through */
1970         case CONIDCELL  : {   Tycon tc = findQualTycon(type);
1971                               if (isNull(tc)) {
1972                                   ERRMSG(line)
1973                                       "Undefined type constructor \"%s\"",
1974                                       identToStr(type)
1975                                   EEND;
1976                               }
1977                               if (cellIsMember(tc,tyconDefns) &&
1978                                   !cellIsMember(tc,tcDeps)) {
1979                                   tcDeps = cons(tc,tcDeps);
1980                               }
1981                               return tc;
1982                           }
1983
1984 #if TREX
1985         case EXT        : h98DoesntSupport(line,"extensible records");
1986 #endif
1987         case TYCON      :
1988         case TUPLE      : break;
1989
1990         default         : internal("depTypeExp");
1991     }
1992     return type;
1993 }
1994
1995 static Type local depTypeVar(line,tyvars,tv)
1996 Int  line;
1997 List tyvars;
1998 Text tv; {
1999     Int offset = 0;
2000     Int found  = (-1);
2001
2002     for (; nonNull(tyvars); offset++) {
2003         if (tv==textOf(hd(tyvars))) {
2004             found = offset;
2005         }
2006         tyvars = tl(tyvars);
2007     }
2008     if (found<0) {
2009         Cell vt = findBtyvs(tv);
2010         if (nonNull(vt)) {
2011             return fst(vt);
2012         }
2013         ERRMSG(line) "Undefined type variable \"%s\"", textToStr(tv)
2014         EEND;
2015     }
2016     return mkOffset(found);
2017 }
2018
2019 static List local checkQuantVars(line,vs,tvs,body)
2020 Int  line;
2021 List vs;                                /* variables to quantify over      */
2022 List tvs;                               /* variables already in scope      */
2023 Cell body; {                            /* type/constr for scope of vars   */
2024     if (nonNull(vs)) {
2025         List bvs = typeVarsIn(body,NIL,NIL,NIL);
2026         List us  = vs;
2027         for (; nonNull(us); us=tl(us)) {
2028             Text u = textOf(hd(us));
2029             if (varIsMember(u,tl(us))) {
2030                 ERRMSG(line) "Duplicated quantified variable %s",
2031                              textToStr(u)
2032                 EEND;
2033             }
2034 #if 0
2035             if (varIsMember(u,tvs)) {
2036                 ERRMSG(line) "Local quantifier for %s hides an outer use",
2037                              textToStr(u)
2038                 EEND;
2039             }
2040 #endif
2041             if (!varIsMember(u,bvs)) {
2042                 ERRMSG(line) "Locally quantified variable %s is not used",
2043                              textToStr(u)
2044                 EEND;
2045             }
2046         }
2047         tvs = appendOnto(tvs,vs);
2048     }
2049     return tvs;
2050 }
2051
2052 /* --------------------------------------------------------------------------
2053  * Check for ambiguous types:
2054  * A type  Preds => type  is ambiguous if not (TV(P) `subset` TV(type))
2055  * ------------------------------------------------------------------------*/
2056
2057 List offsetTyvarsIn(t,vs)               /* add list of offset tyvars in t  */
2058 Type t;                                 /* to list vs                      */
2059 List vs; {
2060     switch (whatIs(t)) {
2061         case AP       : return offsetTyvarsIn(fun(t),
2062                                 offsetTyvarsIn(arg(t),vs));
2063
2064         case OFFSET   : if (cellIsMember(t,vs))
2065                             return vs;
2066                         else
2067                             return cons(t,vs);
2068
2069         case QUAL     : return offsetTyvarsIn(snd(t),vs);
2070
2071         case POLYTYPE : return offsetTyvarsIn(monotypeOf(t),vs);
2072                         /* slightly inaccurate, but won't matter here      */
2073
2074         case EXIST    :
2075         case RANK2    : return offsetTyvarsIn(snd(snd(t)),vs);
2076
2077         default       : return vs;
2078     }
2079 }
2080
2081 List zonkTyvarsIn(t,vs)
2082 Type t;
2083 List vs; {
2084     switch (whatIs(t)) {
2085         case AP       : return zonkTyvarsIn(fun(t),
2086                                  zonkTyvarsIn(arg(t),vs));
2087
2088         case INTCELL  : if (cellIsMember(t,vs))
2089                             return vs;
2090                         else
2091                             return cons(t,vs);
2092
2093         /* this case will lead to a type error --
2094            much better than reporting an internal error ;-) */
2095         /* case OFFSET   : internal("zonkTyvarsIn"); */
2096
2097         default       : return vs;
2098     }
2099 }
2100
2101 static List local otvars(pi,os)         /* os is a list of offsets that    */
2102 Cell pi;                                /* refer to the arguments of pi;   */
2103 List os; {                              /* find list of offsets in those   */
2104     List us = NIL;                      /* positions                       */
2105     for (; nonNull(os); os=tl(os)) {
2106         us = offsetTyvarsIn(nthArg(offsetOf(hd(os)),pi),us);
2107     }
2108     return us;
2109 }
2110
2111 static List local otvarsZonk(pi,os,o)   /* same as above, but zonks        */
2112 Cell pi;
2113 List os; {
2114     List us = NIL;
2115     for (; nonNull(os); os=tl(os)) {
2116         Type t = zonkType(nthArg(offsetOf(hd(os)),pi),o);
2117         us = zonkTyvarsIn(t,us);
2118     }
2119     return us;
2120 }
2121
2122 static Bool local odiff(us,vs)
2123 List us, vs; {
2124     while (nonNull(us) && cellIsMember(hd(us),vs)) {
2125         us = tl(us);
2126     }
2127     return us;
2128 }
2129
2130 static Bool local osubset(us,vs)        /* Determine whether us is subset  */
2131 List us, vs; {                          /* of vs                           */
2132     while (nonNull(us) && cellIsMember(hd(us),vs)) {
2133         us = tl(us);
2134     }
2135     return isNull(us);
2136 }
2137
2138 List oclose(fds,vs)     /* Compute closure of vs wrt to fds*/
2139 List fds;
2140 List vs; {
2141     Bool changed = TRUE;
2142     while (changed) {
2143         List fds1 = NIL;
2144         changed = FALSE;
2145         while (nonNull(fds)) {
2146             Cell fd   = hd(fds);
2147             List next = tl(fds);
2148             if (osubset(fst(fd),vs)) {  /* Test if fd applies              */
2149                 List os = snd(fd);
2150                 for (; nonNull(os); os=tl(os)) {
2151                     if (!cellIsMember(hd(os),vs)) {
2152                         vs      = cons(hd(os),vs);
2153                         changed = TRUE;
2154                     }
2155                 }
2156             } else {                    /* Didn't apply this time, so keep */
2157                 tl(fds) = fds1;
2158                 fds1    = fds;
2159             }
2160             fds = next;
2161         }
2162         fds = fds1;
2163     }
2164     return vs;
2165 }
2166
2167 Bool isAmbiguous(type)                  /* Determine whether type is       */
2168 Type type; {                            /* ambiguous                       */
2169     if (isPolyType(type)) {
2170         type = monotypeOf(type);
2171     }
2172     if (isQualType(type)) {             /* only qualified types can be     */
2173         List ps   = fst(snd(type));     /* ambiguous                       */
2174         List tvps = offsetTyvarsIn(ps,NIL);
2175         List tvts = offsetTyvarsIn(snd(snd(type)),NIL);
2176         List fds  = calcFunDeps(ps);
2177
2178         tvts = oclose(fds,tvts);        /* Close tvts under fds            */
2179         return !osubset(tvps,tvts);
2180     }
2181     return FALSE;
2182 }
2183
2184 List calcFunDeps(ps)
2185 List ps; {
2186     List fds  = NIL;
2187     for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies        */
2188         Cell pi = hd(ps);
2189         Cell c  = getHead(pi);
2190         if (isClass(c)) {
2191             List xfs = cclass(c).xfds;
2192             for (; nonNull(xfs); xfs=tl(xfs)) {
2193                 List fs = snd(hd(xfs));
2194                 for (; nonNull(fs); fs=tl(fs)) {
2195                     fds = cons(pair(otvars(pi,fst(hd(fs))),
2196                                     otvars(pi,snd(hd(fs)))),fds);
2197                 }
2198             }
2199         }
2200 #if IPARAM
2201         else if (isIP(c)) {
2202             fds = cons(pair(NIL,offsetTyvarsIn(arg(pi),NIL)),fds);
2203         }
2204 #endif
2205     }
2206     return fds;
2207 }
2208
2209 List calcFunDepsPreds(ps)
2210 List ps; {
2211     List fds  = NIL;
2212     for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies        */
2213         Cell pi3 = hd(ps);
2214         Cell pi = fst3(pi3);
2215         Cell c  = getHead(pi);
2216         Int o = intOf(snd3(pi3));
2217         if (isClass(c)) {
2218             List xfs = cclass(c).xfds;
2219             for (; nonNull(xfs); xfs=tl(xfs)) {
2220                 List fs = snd(hd(xfs));
2221                 for (; nonNull(fs); fs=tl(fs)) {
2222                     fds = cons(pair(otvarsZonk(pi,fst(hd(fs)),o),
2223                                     otvarsZonk(pi,snd(hd(fs)),o)),fds);
2224                 }
2225             }
2226         }
2227 #if IPARAM
2228         else if (isIP(c)) {
2229             fds = cons(pair(NIL,zonkTyvarsIn(arg(pi),NIL)),fds);
2230         }
2231 #endif
2232     }
2233     return fds;
2234 }
2235
2236 Void ambigError(line,where,e,type)      /* produce error message for       */
2237 Int    line;                            /* ambiguity                       */
2238 String where;
2239 Cell   e;
2240 Type   type; {
2241     ERRMSG(line) "Ambiguous type signature in %s", where ETHEN
2242     ERRTEXT      "\n*** ambiguous type : " ETHEN ERRTYPE(type);
2243     if (nonNull(e)) {
2244         ERRTEXT  "\n*** assigned to    : " ETHEN ERREXPR(e);
2245     }
2246     ERRTEXT      "\n"
2247     EEND;
2248 }
2249
2250 /* --------------------------------------------------------------------------
2251  * Kind inference for simple types:
2252  * ------------------------------------------------------------------------*/
2253
2254 static Void local kindConstr(line,alpha,m,c)
2255 Int  line;                              /* Determine kind of constructor   */
2256 Int  alpha;
2257 Int  m;
2258 Cell c; {
2259     Cell h = getHead(c);
2260     Int  n = argCount;
2261
2262 #ifdef DEBUG_KINDS
2263     Printf("kindConstr: alpha=%d, m=%d, c=",alpha,m);
2264     printType(stdout,c);
2265     Printf("\n");
2266 #endif
2267
2268     switch (whatIs(h)) {
2269         case POLYTYPE : if (n!=0) {
2270                             internal("kindConstr1");
2271                         } else {
2272                             static String pt = "polymorphic type";
2273                             Type  t  = dropRank1(c,alpha,m);
2274                             Kinds ks = polySigOf(t);
2275                             Int   m1 = 0;
2276                             Int   beta;
2277                             for (; isAp(ks); ks=tl(ks)) {
2278                                 m1++;
2279                             }
2280                             beta        = newKindvars(m1);
2281                             unkindTypes = cons(pair(mkInt(beta),t),unkindTypes);
2282                             checkKind(line,beta,m1,monotypeOf(t),NIL,pt,STAR,0);
2283                         }
2284                         return;
2285
2286         case CDICTS   :
2287         case QUAL     : if (n!=0) {
2288                             internal("kindConstr2");
2289                         }
2290                         map3Proc(kindPred,line,alpha,m,fst(snd(c)));
2291                         kindConstr(line,alpha,m,snd(snd(c)));
2292                         return;
2293
2294         case EXIST    :
2295         case RANK2    : kindConstr(line,alpha,m,snd(snd(c)));
2296                         return;
2297
2298 #if TREX
2299         case EXT      : if (n!=2) {
2300                             ERRMSG(line)
2301                                 "Illegal use of row in " ETHEN ERRTYPE(c);
2302                             ERRTEXT "\n"
2303                             EEND;
2304                         }
2305                         break;
2306 #endif
2307
2308         case TYCON    : if (isSynonym(h) && n<tycon(h).arity) {
2309                             ERRMSG(line)
2310                               "Not enough arguments for type synonym \"%s\"",
2311                               textToStr(tycon(h).text)
2312                             EEND;
2313                         }
2314                         break;
2315     }
2316
2317     if (n==0) {                         /* trivial case, no arguments      */
2318         typeIs = kindAtom(alpha,c);
2319     } else {                            /* non-trivial application         */
2320         static String app = "constructor application";
2321         Cell   a = c;
2322         Int    i;
2323         Kind   k;
2324         Int    beta;
2325
2326         varKind(n);
2327         beta   = typeOff;
2328         k      = typeIs;
2329
2330         typeIs = kindAtom(alpha,h);     /* h  :: v1 -> ... -> vn -> w      */
2331         shouldKind(line,h,c,app,k,beta);
2332
2333         for (i=n; i>0; --i) {           /* ci :: vi for each 1 <- 1..n     */
2334             checkKind(line,alpha,m,arg(a),c,app,aVar,beta+i-1);
2335             a = fun(a);
2336         }
2337         tyvarType(beta+n);              /* inferred kind is w              */
2338     }
2339 }
2340
2341 static Kind local kindAtom(alpha,c)     /* Find kind of atomic constructor */
2342 Int  alpha;
2343 Cell c; {
2344     switch (whatIs(c)) {
2345         case TUPLE     : return simpleKind(tupleOf(c)); /*(,)::* -> * -> * */
2346         case OFFSET    : return mkInt(alpha+offsetOf(c));
2347         case TYCON     : return tycon(c).kind;
2348         case INTCELL   : return c;
2349         case VARIDCELL :
2350         case VAROPCELL : {   Cell vt = findBtyvs(textOf(c));
2351                              if (nonNull(vt)) {
2352                                  return snd(vt);
2353                              }
2354                          }
2355 #if TREX
2356         case EXT       : return extKind;
2357 #endif
2358     }
2359 #if DEBUG_KINDS
2360     Printf("kindAtom(%d,whatIs(%d)) on ",alpha,whatIs(c));
2361     printType(stdout,c);
2362     Printf("\n");
2363 #endif
2364     internal("kindAtom");
2365     return STAR;/* not reached */
2366 }
2367
2368 static Void local kindPred(l,alpha,m,pi)/* Check kinds of arguments in pred*/
2369 Int  l;
2370 Int  alpha;
2371 Int  m;
2372 Cell pi; {
2373 #if TREX
2374     if (isAp(pi) && isExt(fun(pi))) {
2375         static String lackspred = "lacks predicate";
2376         checkKind(l,alpha,m,arg(pi),NIL,lackspred,ROW,0);
2377         return;
2378     }
2379 #endif
2380 #if IPARAM
2381     if (isAp(pi) && whatIs(fun(pi)) == IPCELL) {
2382         static String ippred = "iparam predicate";
2383         checkKind(l,alpha,m,arg(pi),NIL,ippred,STAR,0);
2384         return;
2385     }
2386 #endif
2387     {   static String predicate = "class constraint";
2388         Class c  = getHead(pi);
2389         List  as = getArgs(pi);
2390         Kinds ks = cclass(c).kinds;
2391
2392         while (nonNull(ks)) {
2393             checkKind(l,alpha,m,hd(as),NIL,predicate,hd(ks),0);
2394             ks = tl(ks);
2395             as = tl(as);
2396         }
2397     }
2398 }
2399
2400 static Void local kindType(line,wh,type)/* check that (poss qualified) type*/
2401 Int    line;                            /* is well-kinded                  */
2402 String wh;
2403 Type   type; {
2404     checkKind(line,0,0,type,NIL,wh,STAR,0);
2405 }
2406
2407 static Void local fixKinds() {          /* add kind annotations to types   */
2408     for (; nonNull(unkindTypes); unkindTypes=tl(unkindTypes)) {
2409         Pair pr   = hd(unkindTypes);
2410         Int  beta = intOf(fst(pr));
2411         Cell qts  = polySigOf(snd(pr));
2412         for (;;) {
2413             if (isNull(hd(qts))) {
2414                 hd(qts) = copyKindvar(beta++);
2415             } else {
2416                 internal("fixKinds");
2417             }
2418             if (nonNull(tl(qts))) {
2419                 qts = tl(qts);
2420             } else {
2421                 tl(qts) = STAR;
2422                 break;
2423             }
2424         }
2425 #ifdef DEBUG_KINDS
2426         Printf("Type expression: ");
2427         printType(stdout,snd(pr));
2428         Printf(" :: ");
2429         printKind(stdout,polySigOf(snd(pr)));
2430         Printf("\n");
2431 #endif
2432     }
2433 }
2434
2435 /* --------------------------------------------------------------------------
2436  * Kind checking of groups of type constructors and classes:
2437  * ------------------------------------------------------------------------*/
2438
2439 static Void local kindTCGroup(tcs)      /* find kinds for mutually rec. gp */
2440 List tcs; {                             /* of tycons and classes           */
2441     emptySubstitution();
2442     unkindTypes = NIL;
2443     mapProc(initTCKind,tcs);
2444     mapProc(kindTC,tcs);
2445     mapProc(genTC,tcs);
2446     fixKinds();
2447     emptySubstitution();
2448 }
2449     
2450 static Void local initTCKind(c)         /* build initial kind/arity for c  */
2451 Cell c; {
2452     if (isTycon(c)) {                   /* Initial kind of tycon is:       */
2453         Int beta = newKindvars(1);      /*    v1 -> ... -> vn -> vn+1      */
2454         varKind(tycon(c).arity);        /* where n is the arity of c.      */
2455         bindTv(beta,typeIs,typeOff);    /* For data definitions, vn+1 == * */
2456         switch (whatIs(tycon(c).what)) {
2457             case NEWTYPE  :
2458             case DATATYPE : bindTv(typeOff+tycon(c).arity,STAR,0);
2459         }
2460         tycon(c).kind = mkInt(beta);
2461     } else {
2462         Int n    = cclass(c).arity;
2463         Int beta = newKindvars(n);
2464         cclass(c).kinds = NIL;
2465         while (n>0) {
2466             n--;
2467             cclass(c).kinds = pair(mkInt(beta+n),cclass(c).kinds);
2468         }
2469     }
2470 }
2471
2472 static Void local kindTC(c)             /* check each part of a tycon/class*/
2473 Cell c; {                               /* is well-kinded                  */
2474     if (isTycon(c)) {
2475         static String cfun = "constructor function";
2476         static String tsyn = "synonym definition";
2477         Int line = tycon(c).line;
2478         Int beta = tyvar(intOf(tycon(c).kind))->offs;
2479         Int m    = tycon(c).arity;
2480         switch (whatIs(tycon(c).what)) {
2481             case NEWTYPE     :
2482             case DATATYPE    : {   List cs = tycon(c).defn;
2483                                    if (isQualType(cs)) {
2484                                        map3Proc(kindPred,line,beta,m,
2485                                                                 fst(snd(cs)));
2486                                        tycon(c).defn = cs = snd(snd(cs));
2487                                    }
2488                                    for (; hasCfun(cs); cs=tl(cs)) {
2489                                        kindType(line,cfun,name(hd(cs)).type);
2490                                    }
2491                                    break;
2492                                }
2493
2494             default          : checkKind(line,beta,m,tycon(c).defn,NIL,
2495                                                         tsyn,aVar,beta+m);
2496         }
2497     }
2498     else {                              /* scan type exprs in class defn to*/
2499         List ms   = fst(cclass(c).members);
2500         Int  m    = cclass(c).arity;    /* determine the class signature   */
2501         Int  beta = newKindvars(m);
2502         kindPred(cclass(c).line,beta,m,cclass(c).head);
2503         map3Proc(kindPred,cclass(c).line,beta,m,cclass(c).supers);
2504         for (; nonNull(ms); ms=tl(ms)) {
2505             Int  line = intOf(fst3(hd(ms)));
2506             Type type = thd3(hd(ms));
2507             kindType(line,"member function type signature",type);
2508         }
2509     }
2510 }
2511
2512 static Void local genTC(c)              /* generalise kind inferred for    */
2513 Cell c; {                               /* given tycon/class               */
2514     if (isTycon(c)) {
2515         tycon(c).kind = copyKindvar(intOf(tycon(c).kind));
2516 #ifdef DEBUG_KINDS
2517         Printf("%s :: ",textToStr(tycon(c).text));
2518         printKind(stdout,tycon(c).kind);
2519         Putchar('\n');
2520 #endif
2521     } else {
2522         Kinds ks = cclass(c).kinds;
2523         for (; nonNull(ks); ks=tl(ks)) {
2524             hd(ks) = copyKindvar(intOf(hd(ks)));
2525         }
2526 #ifdef DEBUG_KINDS
2527         Printf("%s :: ",textToStr(cclass(c).text));
2528         printKinds(stdout,cclass(c).kinds);
2529         Putchar('\n');
2530 #endif
2531     }
2532 }
2533
2534 /* --------------------------------------------------------------------------
2535  * Static analysis of instance declarations:
2536  *
2537  * The first part of the static analysis is performed as the declarations
2538  * are read during parsing:
2539  * - make new entry in instance table
2540  * - record line number of declaration
2541  * - build list of instances defined in current script for use in later
2542  *   stages of static analysis.
2543  * ------------------------------------------------------------------------*/
2544
2545 Void instDefn(line,head,ms)            /* process new instance definition  */
2546 Int  line;                             /* definition line number           */
2547 Cell head;                             /* inst header :: (context,Class)   */
2548 List ms; {                             /* instance members                 */
2549     Inst nw             = newInst();
2550     inst(nw).line       = line;
2551     inst(nw).specifics  = fst(head);
2552     inst(nw).head       = snd(head);
2553     inst(nw).implements = ms;
2554     instDefns           = cons(nw,instDefns);
2555 }
2556
2557 /* --------------------------------------------------------------------------
2558  * Further static analysis of instance declarations:
2559  *
2560  * Makes the following checks:
2561  * - Class part of header has form C (T a1 ... an) where C is a known
2562  *   class, and T is a known datatype constructor (or restricted synonym),
2563  *   and there is no previous C-T instance, and (T a1 ... an) has a kind
2564  *   appropriate for the class C.
2565  * - Each element of context is a valid class expression, with type vars
2566  *   drawn from a1, ..., an.
2567  * - All bindings are function bindings
2568  * - All bindings define member functions for class C
2569  * - Arrange bindings into appropriate order for member list
2570  * - No top level type signature declarations
2571  * ------------------------------------------------------------------------*/
2572
2573 Bool allowOverlap = FALSE;              /* TRUE => allow overlapping insts */
2574 Name nameListMonad = NIL;               /* builder function for List Monad */
2575
2576 static Void local checkInstDefn(in)     /* Validate instance declaration   */
2577 Inst in; {
2578     Int  line   = inst(in).line;
2579     List tyvars = typeVarsIn(inst(in).head,NIL,NIL,NIL);
2580     List tvps = NIL, tvts = NIL;
2581     List fds = NIL;
2582
2583     if (haskell98) {                    /* Check for `simple' type         */
2584         List tvs = NIL;
2585         Cell t   = arg(inst(in).head);
2586         for (; isAp(t); t=fun(t)) {
2587             if (!isVar(arg(t))) {
2588                 ERRMSG(line)
2589                    "syntax error in instance head (variable expected)"
2590                 EEND;
2591             }
2592             if (varIsMember(textOf(arg(t)),tvs)) {
2593                 ERRMSG(line) "repeated type variable \"%s\" in instance head",
2594                              textToStr(textOf(arg(t)))
2595                 EEND;
2596             }
2597             tvs = cons(arg(t),tvs);
2598         }
2599         if (isVar(t)) {
2600             ERRMSG(line)
2601                 "syntax error in instance head (constructor expected)"
2602             EEND;
2603         }
2604     }
2605
2606     /* add in the tyvars from the `specifics' so that we don't
2607        prematurely complain about undefined tyvars */
2608     tyvars = typeVarsIn(inst(in).specifics,NIL,NIL,tyvars);
2609     inst(in).head = depPredExp(line,tyvars,inst(in).head);
2610
2611     if (haskell98) {
2612         Type h = getHead(arg(inst(in).head));
2613         if (isSynonym(h)) {
2614             ERRMSG(line) "Cannot use type synonym in instance head"
2615             EEND;
2616         }
2617     }
2618
2619     map2Over(depPredExp,line,tyvars,inst(in).specifics);
2620
2621     /* OK, now we start over, and test for ambiguity */
2622     tvts = offsetTyvarsIn(inst(in).head,NIL);
2623     tvps = offsetTyvarsIn(inst(in).specifics,NIL);
2624     fds  = calcFunDeps(inst(in).specifics);
2625     tvts = oclose(fds,tvts);
2626     tvts = odiff(tvps,tvts);
2627     if (!isNull(tvts)) {
2628         ERRMSG(line) "Undefined type variable \"%s\"",
2629           textToStr(textOf(nth(offsetOf(hd(tvts)),tyvars)))
2630         EEND;
2631     }
2632
2633     h98CheckCtxt(line,"instance definition",FALSE,inst(in).specifics,NIL);
2634     inst(in).numSpecifics = length(inst(in).specifics);
2635     inst(in).c            = getHead(inst(in).head);
2636     if (!isClass(inst(in).c)) {
2637         ERRMSG(line) "Illegal predicate in instance declaration"
2638         EEND;
2639     }
2640
2641     if (nonNull(cclass(inst(in).c).fds)) {
2642         List fds = cclass(inst(in).c).fds;
2643         for (; nonNull(fds); fds=tl(fds)) {
2644             List as = otvars(inst(in).head, fst(hd(fds)));
2645             List bs = otvars(inst(in).head, snd(hd(fds)));
2646             List fs = calcFunDeps(inst(in).specifics);
2647             as = oclose(fs,as);
2648             if (!osubset(bs,as)) {
2649                 ERRMSG(inst(in).line)
2650                    "Instance is more general than a dependency allows"
2651                 ETHEN
2652                 ERRTEXT "\n*** Instance         : "
2653                 ETHEN ERRPRED(inst(in).head);
2654                 ERRTEXT "\n*** For class        : "
2655                 ETHEN ERRPRED(cclass(inst(in).c).head);
2656                 ERRTEXT "\n*** Under dependency : "
2657                 ETHEN ERRFD(hd(fds));
2658                 ERRTEXT "\n"
2659                 EEND;
2660             }
2661         }
2662     }
2663
2664     kindInst(in,length(tyvars));
2665     insertInst(in);
2666
2667     if (nonNull(extractSigdecls(inst(in).implements))) {
2668         ERRMSG(line)
2669           "Type signature declarations not permitted in instance declaration"
2670         EEND;
2671     }
2672     if (nonNull(extractFixdecls(inst(in).implements))) {
2673         ERRMSG(line)
2674           "Fixity declarations not permitted in instance declaration"
2675         EEND;
2676     }
2677     inst(in).implements = classBindings("instance",
2678                                         inst(in).c,
2679                                         extractBindings(inst(in).implements));
2680     inst(in).builder    = newInstImp(in);
2681     if (!preludeLoaded && isNull(nameListMonad) && isAp(inst(in).head)
2682         && fun(inst(in).head)==classMonad && arg(inst(in).head)==typeList) {
2683         nameListMonad = inst(in).builder;
2684     }
2685 }
2686
2687 static Void local insertInst(in)        /* Insert instance into class      */
2688 Inst in; {
2689     Class c    = inst(in).c;
2690     List  ins  = cclass(c).instances;
2691     List  prev = NIL;
2692
2693     if (nonNull(cclass(c).fds)) {       /* Check for conflicts with fds    */
2694         List ins1 = cclass(c).instances;
2695         for (; nonNull(ins1); ins1=tl(ins1)) {
2696             List fds = cclass(c).fds;
2697             substitution(RESET);
2698             for (; nonNull(fds); fds=tl(fds)) {
2699                 Int  alpha = newKindedVars(inst(in).kinds);
2700                 Int  beta  = newKindedVars(inst(hd(ins1)).kinds);
2701                 List as    = fst(hd(fds));
2702                 Bool same  = TRUE;
2703                 for (; same && nonNull(as); as=tl(as)) {
2704                     Int n = offsetOf(hd(as));
2705                     same &= unify(nthArg(n,inst(in).head),alpha,
2706                                   nthArg(n,inst(hd(ins1)).head),beta);
2707                 }
2708                 if (isNull(as) && same) {
2709                     for (as=snd(hd(fds)); same && nonNull(as); as=tl(as)) {
2710                         Int n = offsetOf(hd(as));
2711                         same &= sameType(nthArg(n,inst(in).head),alpha,
2712                                          nthArg(n,inst(hd(ins1)).head),beta);
2713                     }
2714                     if (!same) {
2715                         ERRMSG(inst(in).line)
2716                            "Instances are not consistent with dependencies"
2717                         ETHEN
2718                         ERRTEXT "\n*** This instance    : "
2719                         ETHEN ERRPRED(inst(in).head);
2720                         ERRTEXT "\n*** Conflicts with   : "
2721                         ETHEN ERRPRED(inst(hd(ins)).head);
2722                         ERRTEXT "\n*** For class        : "
2723                         ETHEN ERRPRED(cclass(c).head);
2724                         ERRTEXT "\n*** Under dependency : "
2725                         ETHEN ERRFD(hd(fds));
2726                         ERRTEXT "\n"
2727                         EEND;
2728                     }
2729                 }
2730             }
2731         }
2732     }
2733
2734
2735     substitution(RESET);
2736     while (nonNull(ins)) {              /* Look for overlap w/ other insts */
2737         Int alpha = newKindedVars(inst(in).kinds);
2738         Int beta  = newKindedVars(inst(hd(ins)).kinds);
2739         if (unifyPred(inst(in).head,alpha,inst(hd(ins)).head,beta)) {
2740             Cell pi  = copyPred(inst(in).head,alpha);
2741             if (allowOverlap && !haskell98) {
2742                 Bool bef = instCompare(in,hd(ins));
2743                 Bool aft = instCompare(hd(ins),in);
2744                 if (bef && !aft) {      /* in comes strictly before hd(ins)*/
2745                     break;
2746                 }
2747                 if (aft && !bef) {      /* in comes strictly after hd(ins) */
2748                     prev = ins;
2749                     ins  = tl(ins);
2750                     continue;
2751                 }
2752             }
2753 #if MULTI_INST
2754             if (multiInstRes && nonNull(inst(in).specifics)) {
2755                 break;
2756             } else {
2757 #endif
2758             ERRMSG(inst(in).line) "Overlapping instances for class \"%s\"",
2759                                   textToStr(cclass(c).text)
2760             ETHEN
2761             ERRTEXT "\n*** This instance   : " ETHEN ERRPRED(inst(in).head);
2762             ERRTEXT "\n*** Overlaps with   : " ETHEN
2763                                                ERRPRED(inst(hd(ins)).head);
2764             ERRTEXT "\n*** Common instance : " ETHEN
2765                                                ERRPRED(pi);
2766             ERRTEXT "\n"
2767             EEND;
2768         }
2769 #if MULTI_INST
2770             }
2771 #endif
2772         prev = ins;                     /* No overlap detected, so move on */
2773         ins  = tl(ins);                 /* to next instance                */
2774     }
2775     substitution(RESET);
2776
2777     if (nonNull(prev)) {                /* Insert instance at this point   */
2778         tl(prev) = cons(in,ins);
2779     } else {
2780         cclass(c).instances = cons(in,ins);
2781     }
2782 }
2783
2784 static Bool local instCompare(ia,ib)    /* See if ia is an instance of ib  */
2785 Inst ia, ib;{
2786     Int alpha = newKindedVars(inst(ia).kinds);
2787     Int beta  = newKindedVars(inst(ib).kinds);
2788     return matchPred(inst(ia).head,alpha,inst(ib).head,beta);
2789 }
2790
2791 static Name local newInstImp(in)        /* Make definition for inst builder*/
2792 Inst in; {
2793     Name b         = newName(inventText(),in);
2794     name(b).line   = inst(in).line;
2795     name(b).arity  = inst(in).numSpecifics;
2796     name(b).number = DFUNNAME;
2797     return b;
2798 }
2799
2800 /* --------------------------------------------------------------------------
2801  * Kind checking of instance declaration headers:
2802  * ------------------------------------------------------------------------*/
2803
2804 static Void local kindInst(in,freedom)  /* check predicates in instance    */
2805 Inst in;
2806 Int  freedom; {
2807     Int beta;
2808
2809     emptySubstitution();
2810     beta = newKindvars(freedom);
2811     kindPred(inst(in).line,beta,freedom,inst(in).head);
2812     if (whatIs(inst(in).specifics)!=DERIVE) {
2813         map3Proc(kindPred,inst(in).line,beta,freedom,inst(in).specifics);
2814     }
2815     for (inst(in).kinds = NIL; 0<freedom--; ) {
2816         inst(in).kinds = cons(copyKindvar(beta+freedom),inst(in).kinds);
2817     }
2818 #ifdef DEBUG_KINDS
2819     Printf("instance ");
2820     printPred(stdout,inst(in).head);
2821     Printf(" :: ");
2822     printKinds(stdout,inst(in).kinds);
2823     Putchar('\n');
2824 #endif
2825     emptySubstitution();
2826 }
2827
2828 /* --------------------------------------------------------------------------
2829  * Process derived instance requests:
2830  * ------------------------------------------------------------------------*/
2831
2832 static List derivedInsts;               /* list of derived instances       */
2833
2834 static Void local checkDerive(t,p,ts,ct)/* verify derived instance request */
2835 Tycon t;                                /* for tycon t, with explicit      */
2836 List  p;                                /* context p, component types ts   */
2837 List  ts;                               /* and named class ct              */
2838 Cell  ct; {
2839     Int   line = tycon(t).line;
2840     Class c    = findQualClass(ct);
2841     if (isNull(c)) {
2842         ERRMSG(line) "Unknown class \"%s\" in derived instance",
2843                      identToStr(ct)
2844         EEND;
2845     }
2846     addDerInst(line,c,p,dupList(ts),t,tycon(t).arity);
2847 }
2848
2849 static Void local addDerInst(line,c,p,cts,t,a)  /* Add a derived instance  */
2850 Int   line;
2851 Class c;
2852 List  p, cts;
2853 Type  t;
2854 Int   a; {
2855     Inst in;
2856     Cell head = t;                              /* Build instance head     */
2857     Int  i    = 0;
2858
2859     for (; i<a; i++) {
2860         head = ap(head,mkOffset(i));
2861     }
2862     head = ap(c,head);
2863
2864     in                  = newInst();
2865     inst(in).c          = c;
2866     inst(in).line       = line;
2867     inst(in).head       = head;
2868     inst(in).specifics  = ap(DERIVE,pair(dupList(p),cts));
2869     inst(in).implements = NIL;
2870     inst(in).kinds      = mkInt(a);
2871     derivedInsts        = cons(in,derivedInsts);
2872 }
2873
2874 Void addTupInst(c,n)                    /* Request derived instance of c   */
2875 Class c;                                /* for mkTuple(n) constructor      */
2876 Int   n; {
2877     Int  m   = n;
2878     List cts = NIL;
2879     while (0<m--) {
2880         cts = cons(mkOffset(m),cts);
2881     }
2882     cts = rev(cts);
2883     addDerInst(0,c,NIL,cts,mkTuple(n),n);
2884 }
2885
2886 #if TREX
2887 Inst addRecShowInst(c,e)                /* Generate instance for ShowRecRow*/
2888 Class c;                                /* c *must* be ShowRecRow          */
2889 Ext   e; {
2890     Inst in               = newInst();
2891     inst(in).c            = c;
2892     inst(in).head         = ap(c,ap2(e,aVar,bVar));
2893     inst(in).kinds        = extKind;
2894     inst(in).specifics    = cons(ap(classShow,aVar),
2895                                  cons(ap(e,bVar),
2896                                       cons(ap(c,bVar),NIL)));
2897     inst(in).numSpecifics = 3;
2898     inst(in).builder      = implementRecShw(extText(e),in);
2899     cclass(c).instances   = appendOnto(cclass(c).instances,singleton(in));
2900     return in;
2901 }
2902
2903 Inst addRecEqInst(c,e)                  /* Generate instance for EqRecRow  */
2904 Class c;                                /* c *must* be EqRecRow            */
2905 Ext   e; {
2906     Inst in               = newInst();
2907     inst(in).c            = c;
2908     inst(in).head         = ap(c,ap2(e,aVar,bVar));
2909     inst(in).kinds        = extKind;
2910     inst(in).specifics    = cons(ap(classEq,aVar),
2911                                  cons(ap(e,bVar),
2912                                       cons(ap(c,bVar),NIL)));
2913     inst(in).numSpecifics = 3;
2914     inst(in).builder      = implementRecEq(extText(e),in);
2915     cclass(c).instances   = appendOnto(cclass(c).instances,singleton(in));
2916     return in;
2917 }
2918 #endif
2919
2920 /* --------------------------------------------------------------------------
2921  * Calculation of contexts for derived instances:
2922  *
2923  * Allowing arbitrary types to appear in contexts makes it rather harder
2924  * to decide what the context for a derived instance should be.  For
2925  * example, given:
2926  *
2927  *    data T a = MkT [a] deriving Show,
2928  *
2929  * we could have either of the following:
2930  *
2931  *    instance (Show [a]) => Show (T a) where ...
2932  *    instance (Show a) => Show (T a) where ...
2933  *
2934  * (assuming, of course, that instance (Show a) => Show [a]).  For now, we
2935  * choose to reduce contexts in the hope of detecting errors at an earlier
2936  * stage---in contrast with value definitions, there is no way for a user
2937  * to provide something analogous to a `type signature' by which they might
2938  * be able to control this behaviour themselves.  We eliminate tautological
2939  * predicates, but only allow predicates to appear in the final result if
2940  * they have at least one argument with a variable at its head.
2941  *
2942  * In general, we have to deal with mutually recursive instance declarations.
2943  * We find a solution in the obvious way by iterating to find a fixed point.
2944  * Of course, without restrictions on the form of instance declarations, we
2945  * cannot be sure that this will always terminate!
2946  *
2947  * For each instance we maintain a pair of the form DERIVE (ctxt,ps).
2948  * Ctxt is a list giving the parts of the context that have been produced
2949  * so far in the form of predicate skeletons.  During the calculation of
2950  * derived instances, we attach a dummy NIL value to the end of the list
2951  * which acts as a kind of `variable': other parts of the system maintain
2952  * pointers to this variable, and use it to detect when the context has
2953  * been extended with new elements.  Meanwhile, ps is a list containing
2954  * predicates (pi,o) together with (delayed) substitutions of the form
2955  * (o,xs) where o is an offset and xs is one of the context variables
2956  * described above, which may have been partially instantiated.
2957  * ------------------------------------------------------------------------*/
2958
2959 static Bool instsChanged;
2960
2961 static Void local deriveContexts(is)    /* Calc contexts for derived insts */
2962 List is; {
2963     emptySubstitution();
2964     mapProc(initDerInst,is);            /* Prepare derived instances       */
2965
2966     do {                                /* Main calculation of contexts    */
2967         instsChanged = FALSE;
2968         mapProc(calcInstPreds,is);
2969     } while (instsChanged);
2970
2971     mapProc(tidyDerInst,is);            /* Tidy up results                 */
2972 }
2973
2974 static Void local initDerInst(in)       /* Prepare instance for calculation*/
2975 Inst in; {                              /* of derived instance context     */
2976     Cell spcs = inst(in).specifics;
2977     Int  beta = newKindedVars(inst(in).kinds);
2978     if (whatIs(spcs)!=DERIVE) {
2979         internal("initDerInst");
2980     }
2981     fst(snd(spcs)) = appendOnto(fst(snd(spcs)),singleton(NIL));
2982     for (spcs=snd(snd(spcs)); nonNull(spcs); spcs=tl(spcs)) {
2983         hd(spcs) = ap2(inst(in).c,hd(spcs),mkInt(beta));
2984     }
2985     inst(in).numSpecifics = beta;
2986
2987 #ifdef DEBUG_DERIVING
2988     Printf("initDerInst: ");
2989     printPred(stdout,inst(in).head);
2990     Printf("\n");
2991     printContext(stdout,snd(snd(inst(in).specifics)));
2992     Printf("\n");
2993 #endif
2994 }
2995
2996 static Void local calcInstPreds(in)     /* Calculate next approximation    */
2997 Inst in; {                              /* of the context for a derived    */
2998     List retain = NIL;                  /* instance                        */
2999     List ps     = snd(snd(inst(in).specifics));
3000     List spcs   = fst(snd(inst(in).specifics));
3001     Int  beta   = inst(in).numSpecifics;
3002     Int  its    = 1;
3003     Int  factor = 1+length(ps);
3004
3005 #ifdef DEBUG_DERIVING
3006     Printf("calcInstPreds: ");
3007     printPred(stdout,inst(in).head);
3008     Printf("\n");
3009 #endif
3010
3011     while (nonNull(ps)) {
3012         Cell p = hd(ps);
3013         ps     = tl(ps);
3014         if (its++ >= factor*cutoff) {
3015             Cell bpi = inst(in).head;
3016             ERRMSG(inst(in).line) "\n*** Cannot derive " ETHEN ERRPRED(bpi);
3017             ERRTEXT " after %d iterations.", its-1   ETHEN
3018             ERRTEXT
3019                 "\n*** This may indicate that the problem is undecidable.  However,\n"
3020             ETHEN ERRTEXT
3021                 "*** you may still try to increase the cutoff limit using the -c\n"
3022             ETHEN ERRTEXT
3023                 "*** option and then try again.  (The current setting is -c%d)\n",
3024                 cutoff
3025             EEND;
3026         }
3027         if (isInt(fst(p))) {                    /* Delayed substitution?   */
3028             List qs = snd(p);
3029             for (; nonNull(hd(qs)); qs=tl(qs)) {
3030                 ps = cons(pair(hd(qs),fst(p)),ps);
3031             }
3032             retain = cons(pair(fst(p),qs),retain);
3033         }
3034 #if TREX
3035         else if (isExt(fun(fst(p)))) {          /* Lacks predicate         */
3036             Text   l = extText(fun(fst(p)));
3037             Type   t = arg(fst(p));
3038             Int    o = intOf(snd(p));
3039             Type   h;
3040             Tyvar *tyv;
3041
3042             deRef(tyv,t,o);
3043             h = getDerefHead(t,o);
3044             while (isExt(h) && argCount==2 && l!=extText(h)) {
3045                 t = arg(t);
3046                 deRef(tyv,t,o);
3047                 h = getDerefHead(t,o);
3048             }
3049             if (argCount==0 && isOffset(h)) {
3050                 maybeAddPred(ap(fun(fun(p)),h),o,beta,spcs);
3051             } else if (argCount!=0 || h!=typeNoRow) {
3052                 Cell bpi = inst(in).head;
3053                 Cell pi  = copyPred(fun(p),intOf(snd(p)));
3054                 ERRMSG(inst(in).line) "Cannot derive " ETHEN ERRPRED(bpi);
3055                 ERRTEXT " because predicate " ETHEN ERRPRED(pi);
3056                 ERRTEXT " does not hold\n"
3057                 EEND;
3058             }
3059         }
3060 #endif
3061         else {                                  /* Class predicate         */
3062             Cell pi  = fst(p);
3063             Int  o   = intOf(snd(p));
3064             Inst in1 = findInstFor(pi,o);
3065             if (nonNull(in1)) {
3066                 List qs  = inst(in1).specifics;
3067                 Int  off = mkInt(typeOff);
3068                 if (whatIs(qs)==DERIVE) {       /* Still being derived     */
3069                     for (qs=fst(snd(qs)); nonNull(hd(qs)); qs=tl(qs)) {
3070                         ps = cons(pair(hd(qs),off),ps);
3071                     }
3072                     retain = cons(pair(off,qs),retain);
3073                 } else {                        /* Previously def'd inst   */
3074                     for (; nonNull(qs); qs=tl(qs)) {
3075                         ps = cons(pair(hd(qs),off),ps);
3076                     }
3077                 }
3078             } else {                            /* No matching instance    */
3079                 Cell qi = pi;
3080                 while (isAp(qi) && isOffset(getDerefHead(arg(qi),o))) {
3081                     qi = fun(qi);
3082                 }
3083                 if (isAp(qi)) {
3084                     Cell bpi = inst(in).head;
3085                     pi       = copyPred(pi,o);
3086                     ERRMSG(inst(in).line) "An instance of " ETHEN ERRPRED(pi);
3087                     ERRTEXT " is required to derive "       ETHEN ERRPRED(bpi);
3088                     ERRTEXT "\n"
3089                     EEND;
3090                 } else {
3091                     maybeAddPred(pi,o,beta,spcs);
3092                 }
3093             }
3094         }
3095     }
3096     snd(snd(inst(in).specifics)) = retain;
3097 }
3098
3099 static Void local maybeAddPred(pi,o,beta,ps)
3100 Cell pi;                                /* Add predicate pi to the list ps,*/
3101 Int  o;                                 /* setting the instsChanged flag if*/
3102 Int  beta;                              /* pi is not already a member and  */
3103 List ps; {                              /* using beta to adjust vars       */
3104     Cell c = getHead(pi);
3105     for (; nonNull(ps); ps=tl(ps)) {
3106         if (isNull(hd(ps))) {           /* reached the `dummy' end of list?*/
3107             hd(ps)       = copyAdj(pi,o,beta);
3108             tl(ps)       = pair(NIL,NIL);
3109             instsChanged = TRUE;
3110             return;
3111         } else if (c==getHead(hd(ps)) && samePred(pi,o,hd(ps),beta)) {
3112             return;
3113         }
3114     }
3115 }
3116
3117 static Cell local copyAdj(c,o,beta)     /* Copy (c,o), replacing vars with */
3118 Cell c;                                 /* offsets relative to beta.       */
3119 Int  o;
3120 Int  beta; {
3121     switch (whatIs(c)) {
3122         case AP     : {   Cell l = copyAdj(fst(c),o,beta);
3123                           Cell r = copyAdj(snd(c),o,beta);
3124                           return ap(l,r);
3125                       }
3126
3127         case OFFSET : {   Int   vn   = o+offsetOf(c);
3128                           Tyvar *tyv = tyvar(vn);
3129                           if (isBound(tyv)) {
3130                               return copyAdj(tyv->bound,tyv->offs,beta);
3131                           }
3132                           vn -= beta;
3133                           if (vn<0 || vn>=(OFF_MAX-OFF_MIN+1)) {
3134                               internal("copyAdj");
3135                           }
3136                           return mkOffset(vn);
3137                       }
3138     }
3139     return c;
3140 }
3141
3142 static Void local tidyDerInst(in)       /* Tidy up results of derived inst */
3143 Inst in; {                              /* calculations                    */
3144     Int  o  = inst(in).numSpecifics;
3145     List ps = tl(rev(fst(snd(inst(in).specifics))));
3146     clearMarks();
3147     copyPred(inst(in).head,o);
3148     inst(in).specifics    = simpleContext(ps,o);
3149     h98CheckCtxt(inst(in).line,"derived instance",FALSE,inst(in).specifics,in);
3150     inst(in).numSpecifics = length(inst(in).specifics);
3151
3152 #ifdef DEBUG_DERIVING
3153     Printf("Derived instance: ");
3154     printContext(stdout,inst(in).specifics);
3155     Printf(" ||- ");
3156     printPred(stdout,inst(in).head);
3157     Printf("\n");
3158 #endif
3159 }
3160
3161 /* --------------------------------------------------------------------------
3162  * Generate code for derived instances:
3163  * ------------------------------------------------------------------------*/
3164
3165 static Void local addDerivImp(in)
3166 Inst in; {
3167     List  imp = NIL;
3168     Type  t   = getHead(arg(inst(in).head));
3169     Class c   = inst(in).c;
3170     if (c==classEq) {
3171         imp = deriveEq(t);
3172     } else if (c==classOrd) {
3173         imp = deriveOrd(t);
3174     } else if (c==classEnum) {
3175         imp = deriveEnum(t);
3176     } else if (c==classIx) {
3177         imp = deriveIx(t);
3178     } else if (c==classShow) {
3179         imp = deriveShow(t);
3180     } else if (c==classRead) {
3181         imp = deriveRead(t);
3182     } else if (c==classBounded) {
3183         imp = deriveBounded(t);
3184     } else {
3185         ERRMSG(inst(in).line) "Cannot derive instances of class \"%s\"",
3186                               textToStr(cclass(inst(in).c).text)
3187         EEND;
3188     }
3189
3190     kindInst(in,intOf(inst(in).kinds));
3191     insertInst(in);
3192     inst(in).builder    = newInstImp(in);
3193     inst(in).implements = classBindings("derived instance",
3194                                         inst(in).c,
3195                                         imp);
3196 }
3197
3198
3199 /* --------------------------------------------------------------------------
3200  * Default definitions; only one default definition is permitted in a
3201  * given script file.  If no default is supplied, then a standard system
3202  * default will be used where necessary.
3203  * ------------------------------------------------------------------------*/
3204
3205 Void defaultDefn(line,defs)             /* Handle default types definition */
3206 Int  line;
3207 List defs; {
3208     if (defaultLine!=0) {
3209         ERRMSG(line) "Multiple default declarations are not permitted in" ETHEN
3210         ERRTEXT     "a single script file.\n"
3211         EEND;
3212     }
3213     defaultDefns = defs;
3214     defaultLine  = line;
3215 }
3216
3217 static Void local checkDefaultDefns() { /* check that default types are    */
3218     List ds = NIL;                      /* well-kinded instances of Num    */
3219
3220     if (defaultLine!=0) {
3221         map2Over(depTypeExp,defaultLine,NIL,defaultDefns);
3222         emptySubstitution();
3223         unkindTypes = NIL;
3224         map2Proc(kindType,defaultLine,"default type",defaultDefns);
3225         fixKinds();
3226         emptySubstitution();
3227         mapOver(fullExpand,defaultDefns);
3228     } else {
3229         defaultDefns = stdDefaults;
3230     }
3231
3232     if (isNull(classNum)) {
3233         classNum = findClass(findText("Num"));
3234     }
3235
3236     for (ds=defaultDefns; nonNull(ds); ds=tl(ds)) {
3237         if (isNull(provePred(NIL,NIL,ap(classNum,hd(ds))))) {
3238             ERRMSG(defaultLine)
3239                 "Default types must be instances of the Num class"
3240             EEND;
3241         }
3242     }
3243 }
3244
3245
3246 /* --------------------------------------------------------------------------
3247  * Foreign import declarations are Hugs' equivalent of GHC's ccall mechanism.
3248  * They are used to "import" C functions into a module.
3249  * They are usually not written by hand but, rather, generated automatically
3250  * by GreenCard, IDL compilers or whatever.  We support foreign import 
3251  * (static) and foreign import dynamic.  In the latter case, extName==NIL.
3252  *
3253  * Foreign export declarations generate C wrappers for Hugs functions.
3254  * Hugs only provides "foreign export dynamic" because it's not obvious
3255  * what "foreign export static" would mean in an interactive setting.
3256  * ------------------------------------------------------------------------*/
3257
3258 Void foreignImport(line,callconv,extName,intName,type) 
3259                                               /* Handle foreign imports    */
3260 Cell line;
3261 Text callconv;
3262 Pair extName;
3263 Cell intName;
3264 Cell type; {
3265     Text t = textOf(intName);
3266     Name n = findName(t);
3267
3268     if (isNull(n)) {
3269         n = newName(t,NIL);
3270     } else if (name(n).defn!=PREDEFINED) {
3271         ERRMSG(line) "Redeclaration of foreign \"%s\"", textToStr(t)
3272         EEND;
3273     }
3274     name(n).line     = line;
3275     name(n).defn     = extName;
3276     name(n).type     = type;
3277     name(n).callconv = callconv;
3278     foreignImports   = cons(n,foreignImports);
3279 }
3280
3281 static Void local checkForeignImport(p)   /* Check foreign import          */
3282 Name p; {
3283     emptySubstitution();
3284     name(p).type = checkSigType(name(p).line,
3285                                 "foreign import declaration",
3286                                 p,
3287                                 name(p).type);
3288     /* We don't expand synonyms here because we don't want the IO
3289      * part to be expanded.
3290      * name(p).type = fullExpand(name(p).type);
3291      */
3292     implementForeignImport(p);
3293 }
3294
3295 Void foreignExport(line,callconv,extName,intName,type)
3296                                               /* Handle foreign exports    */
3297 Cell line;
3298 Text callconv;
3299 Cell extName;
3300 Cell intName;
3301 Cell type; {
3302     Text t = textOf(intName);
3303     Name n = findName(t);
3304
3305     if (isNull(n)) {
3306         n = newName(t,NIL);
3307     } else if (name(n).defn!=PREDEFINED) {
3308         ERRMSG(line) "Redeclaration of foreign \"%s\"", textToStr(t)
3309         EEND;
3310     }
3311     name(n).line     = line;
3312     name(n).defn     = NIL;  /* nothing to say */
3313     name(n).type     = type;
3314     name(n).callconv = callconv;
3315     foreignExports   = cons(n,foreignExports);
3316 }
3317
3318 static Void local checkForeignExport(p)       /* Check foreign export      */
3319 Name p; {
3320     emptySubstitution();
3321     name(p).type = checkSigType(name(p).line,
3322                                 "foreign export declaration",
3323                                 p,
3324                                 name(p).type);
3325     implementForeignExport(p);
3326 }
3327
3328
3329
3330 /* --------------------------------------------------------------------------
3331  * Static analysis of patterns:
3332  *
3333  * Patterns are parsed as ordinary (atomic) expressions.  Static analysis
3334  * makes the following checks:
3335  *  - Patterns are well formed (according to pattern syntax), including the
3336  *    special case of (n+k) patterns.
3337  *  - All constructor functions have been defined and are used with the
3338  *    correct number of arguments.
3339  *  - No variable name is used more than once in a pattern.
3340  *
3341  * The list of pattern variables occuring in each pattern is accumulated in
3342  * a global list `patVars', which must be initialised to NIL at appropriate
3343  * points before using these routines to check for valid patterns.  This
3344  * mechanism enables the pattern checking routine to be mapped over a list
3345  * of patterns, ensuring that no variable occurs more than once in the
3346  * complete pattern list (as is required on the lhs of a function defn).
3347  * ------------------------------------------------------------------------*/
3348
3349 static List patVars;                   /* List of vars bound in pattern    */
3350
3351 static Cell local checkPat(line,p)     /* Check valid pattern syntax       */
3352 Int  line;
3353 Cell p; {
3354     switch (whatIs(p)) {
3355         case VARIDCELL :
3356         case VAROPCELL : addToPatVars(line,p);
3357                          break;
3358
3359         case INFIX     : return checkPat(line,tidyInfix(line,snd(p)));
3360
3361         case AP        : return checkMaybeCnkPat(line,p);
3362
3363         case NAME      :
3364         case QUALIDENT : 
3365         case CONIDCELL : 
3366         case CONOPCELL : return checkApPat(line,0,p);
3367
3368         case WILDCARD  :
3369         case STRCELL   :
3370         case CHARCELL  :
3371         case FLOATCELL : break;
3372         case INTCELL   : break;
3373
3374         case ASPAT     : addToPatVars(line,fst(snd(p)));
3375                          snd(snd(p)) = checkPat(line,snd(snd(p)));
3376                          break;
3377
3378         case LAZYPAT   : snd(p) = checkPat(line,snd(p));
3379                          break;
3380
3381         case FINLIST   : map1Over(checkPat,line,snd(p));
3382                          break;
3383
3384         case CONFLDS   : depConFlds(line,p,TRUE);
3385                          break;
3386
3387         case ESIGN     : snd(snd(p)) = checkPatType(line,
3388                                                     "pattern",
3389                                                     fst(snd(p)),
3390                                                     snd(snd(p)));
3391                          fst(snd(p)) = checkPat(line,fst(snd(p)));
3392                          break;
3393
3394         default        : ERRMSG(line) "Illegal pattern syntax"
3395                          EEND;
3396     }
3397     return p;
3398 }
3399
3400 static Cell local checkMaybeCnkPat(l,p)/* Check applicative pattern with   */
3401 Int  l;                                /* the possibility of n+k pattern   */
3402 Cell p; {
3403     Cell h = getHead(p);
3404
3405     if (argCount==2 && isVar(h) && textOf(h)==textPlus) {       /* n+k     */
3406         Cell v = arg(fun(p));
3407         if (!isInt(arg(p))) {
3408             ERRMSG(l) "Second argument in (n+k) pattern must be an integer"
3409             EEND;
3410         }
3411         if (intOf(arg(p))<=0) {
3412             ERRMSG(l) "Integer k in (n+k) pattern must be > 0"
3413             EEND;
3414         }
3415         fst(fun(p))      = ADDPAT;
3416         intValOf(fun(p)) = intOf(arg(p));
3417         arg(p)           = checkPat(l,v);
3418         return p;
3419     }
3420     return checkApPat(l,0,p);
3421 }
3422
3423 static Cell local checkApPat(line,args,p)
3424 Int  line;                             /* check validity of application    */
3425 Int  args;                             /* of constructor to arguments      */
3426 Cell p; {
3427     switch (whatIs(p)) {
3428         case AP        : fun(p) = checkApPat(line,args+1,fun(p));
3429                          arg(p) = checkPat(line,arg(p));
3430                          break;
3431
3432         case TUPLE     : if (tupleOf(p)!=args) {
3433                              ERRMSG(line) "Illegal tuple pattern"
3434                              EEND;
3435                          }
3436                          break;
3437
3438 #if TREX
3439         case EXT       : h98DoesntSupport(line,"extensible records");
3440                          if (args!=2) {
3441                              ERRMSG(line) "Illegal record pattern"
3442                              EEND;
3443                          }
3444                          break;
3445 #endif
3446
3447         case QUALIDENT : if (!isQCon(p)) {
3448                             ERRMSG(line)
3449                                 "Illegal use of qualified variable in pattern"
3450                             EEND;
3451                          }
3452                          /* deliberate fall through */
3453         case CONIDCELL :
3454         case CONOPCELL : p = conDefined(line,p);
3455                          checkCfunArgs(line,p,args);
3456                          break;
3457
3458         case NAME      : checkIsCfun(line,p);
3459                          checkCfunArgs(line,p,args);
3460                          break;
3461
3462         default        : ERRMSG(line) "Illegal pattern syntax"
3463                          EEND;
3464     }
3465     return p;
3466 }
3467
3468 static Void local addToPatVars(line,v)  /* Add variable v to list of vars  */
3469 Int  line;                              /* in current pattern, checking    */
3470 Cell v; {                               /* for repeated variables.         */
3471     Text t = textOf(v);
3472     List p = NIL;
3473     List n = patVars;
3474
3475     for (; nonNull(n); p=n, n=tl(n)) {
3476         if (textOf(hd(n))==t) {
3477             ERRMSG(line) "Repeated variable \"%s\" in pattern",
3478                          textToStr(t)
3479             EEND;
3480         }
3481     }
3482
3483     if (isNull(p)) {
3484          patVars = cons(v,NIL);
3485     } else {
3486          tl(p)   = cons(v,NIL);
3487     }
3488 }
3489
3490 static Name local conDefined(line,nm)  /* check that nm is the name of a   */
3491 Int  line;                             /* previously defined constructor   */
3492 Cell nm; {                             /* function.                        */
3493     Name n = findQualName(nm);
3494     if (isNull(n)) {
3495         ERRMSG(line) "Undefined constructor function \"%s\"", identToStr(nm)
3496         EEND;
3497     }
3498     checkIsCfun(line,n);
3499     return n;
3500 }
3501
3502 static Void local checkIsCfun(line,c)  /* Check that c is a constructor fn */
3503 Int  line;
3504 Name c; {
3505     if (!isCfun(c)) {
3506         ERRMSG(line) "\"%s\" is not a constructor function",
3507                      textToStr(name(c).text)
3508         EEND;
3509     }
3510 }
3511
3512 static Void local checkCfunArgs(line,c,args)
3513 Int  line;                             /* Check constructor applied with   */
3514 Cell c;                                /* correct number of arguments      */
3515 Int  args; {
3516     Int a = userArity(c);
3517     if (a!=args) {
3518         ERRMSG(line)
3519           "Constructor \"%s\" must have exactly %d argument%s in pattern",
3520           textToStr(name(c).text), a, ((a==1)?"":"s")
3521         EEND;
3522     }
3523 }
3524
3525 static Cell local checkPatType(l,wh,e,t)/* Check type appearing in pattern */
3526 Int    l;
3527 String wh;
3528 Cell   e;
3529 Type   t; {
3530     List tvs = typeVarsIn(t,NIL,NIL,NIL);
3531     h98DoesntSupport(l,"pattern type annotations");
3532     for (; nonNull(tvs); tvs=tl(tvs)) {
3533         Int beta    = newKindvars(1);
3534         hd(btyvars) = cons(pair(hd(tvs),mkInt(beta)), hd(btyvars));
3535     }
3536     t = checkSigType(l,"pattern type",e,t);
3537     if (isPolyOrQualType(t) || whatIs(t)==RANK2) {
3538         ERRMSG(l) "Illegal syntax in %s type annotation", wh
3539         EEND;
3540     }
3541     return t;
3542 }
3543
3544 static Cell local applyBtyvs(pat)       /* Record bound type vars in pat   */
3545 Cell pat; {
3546     List bts = hd(btyvars);
3547     leaveBtyvs();
3548     if (nonNull(bts)) {
3549         pat = ap(BIGLAM,pair(bts,pat));
3550         for (; nonNull(bts); bts=tl(bts)) {
3551             snd(hd(bts)) = copyKindvar(intOf(snd(hd(bts))));
3552         }
3553     }
3554     return pat;
3555 }
3556
3557 /* --------------------------------------------------------------------------
3558  * Maintaining lists of bound variables and local definitions, for
3559  * dependency and scope analysis.
3560  * ------------------------------------------------------------------------*/
3561
3562 static List bounds;                    /* list of lists of bound vars      */
3563 static List bindings;                  /* list of lists of binds in scope  */
3564 static List depends;                   /* list of lists of dependents      */
3565
3566 /* bounds   :: [[Var]]        -- var equality used on Vars     */
3567 /* bindings :: [[([Var],?)]]  -- var equality used on Vars     */
3568 /* depends  :: [[Var]]        -- pointer equality used on Vars */
3569
3570 #define saveBvars()      hd(bounds)    /* list of bvars in current scope   */
3571 #define restoreBvars(bs) hd(bounds)=bs /* restore list of bound variables  */
3572
3573 static Cell local bindPat(line,p)      /* add new bound vars for pattern   */
3574 Int  line;
3575 Cell p; {
3576     patVars    = NIL;
3577     p          = checkPat(line,p);
3578     hd(bounds) = revOnto(patVars,hd(bounds));
3579     return p;
3580 }
3581
3582 static Void local bindPats(line,ps)    /* add new bound vars for patterns  */
3583 Int  line;
3584 List ps; {
3585     patVars    = NIL;
3586     map1Over(checkPat,line,ps);
3587     hd(bounds) = revOnto(patVars,hd(bounds));
3588 }
3589
3590 /* --------------------------------------------------------------------------
3591  * Before processing value and type signature declarations, all data and
3592  * type definitions have been processed so that:
3593  * - all valid type constructors (with their arities) are known.
3594  * - all valid constructor functions (with their arities and types) are
3595  *   known.
3596  *
3597  * The result of parsing a list of value declarations is a list of Eqns:
3598  *       Eqn ::= (SIGDECL,(Line,[Var],type))
3599  *            |  (FIXDECL,(Line,[Op],SyntaxInt))
3600  *            |  (Expr,Rhs)
3601  * The ordering of the equations in this list is the reverse of the original
3602  * ordering in the script parsed.  This is a consequence of the structure of
3603  * the parser ... but also turns out to be most convenient for the static
3604  * analysis.
3605  *
3606  * As the first stage of the static analysis of value declarations, each
3607  * list of Eqns is converted to a list of Bindings.  As part of this
3608  * process:
3609  * - The ordering of the list of Bindings produced is the same as in the
3610  *   original script.
3611  * - When a variable (function) is defined over a number of lines, all
3612  *   of the definitions should appear together and each should give the
3613  *   same arity to the variable being defined.
3614  * - No variable can have more than one definition.
3615  * - For pattern bindings:
3616  *   - Each lhs is a valid pattern/function lhs, all constructor functions
3617  *     have been defined and are used with the correct number of arguments.
3618  *   - Each lhs contains no repeated pattern variables.
3619  *   - Each equation defines at least one variable (e.g. True = False is
3620  *     not allowed).
3621  * - Types appearing in type signatures are well formed:
3622  *    - Type constructors used are defined and used with correct number
3623  *      of arguments.
3624  *    - type variables are replaced by offsets, type constructor names
3625  *      by Tycons.
3626  * - Every variable named in a type signature declaration is defined by
3627  *   one or more equations elsewhere in the script.
3628  * - No variable has more than one type declaration.
3629  * - Similar properties for fixity declarations.
3630  *
3631  * ------------------------------------------------------------------------*/
3632
3633 #define bindingAttr(b) fst(snd(b))     /* type(s)/fixity(ies) for binding  */
3634 #define fbindAlts(b)   snd(snd(b))     /* alternatives for function binding*/
3635
3636 static List local extractSigdecls(es)  /* Extract the SIGDECLS from list   */
3637 List es; {                             /* of equations                     */
3638     List sigdecls = NIL;               /* :: [(Line,[Var],Type)]           */
3639
3640     for(; nonNull(es); es=tl(es)) {
3641         if (fst(hd(es))==SIGDECL) {                  /* type-declaration?  */
3642             Pair sig  = snd(hd(es));
3643             Int  line = intOf(fst3(sig));
3644             List vs   = snd3(sig);
3645             for(; nonNull(vs); vs=tl(vs)) {
3646                 if (isQualIdent(hd(vs))) {
3647                     ERRMSG(line) "Type signature for qualified variable \"%s\" is not allowed",
3648                                  identToStr(hd(vs))
3649                     EEND;
3650                 }
3651             }
3652             sigdecls = cons(sig,sigdecls);           /* discard SIGDECL tag*/
3653         }
3654     }
3655     return sigdecls;
3656 }
3657
3658 static List local extractFixdecls(es)   /* Extract the FIXDECLS from list  */
3659 List es; {                              /* of equations                    */
3660     List fixdecls = NIL;                /* :: [(Line,SyntaxInt,[Op])]      */
3661
3662     for(; nonNull(es); es=tl(es)) {
3663         if (fst(hd(es))==FIXDECL) {                  /* fixity declaration?*/
3664             fixdecls = cons(snd(hd(es)),fixdecls);   /* discard FIXDECL tag*/
3665         }
3666     }
3667     return fixdecls;
3668 }
3669
3670 static List local extractBindings(ds)   /* extract untyped bindings from   */
3671 List ds; {                              /* given list of equations         */
3672     Cell lastVar   = NIL;               /* = var def'd in last eqn (if any)*/
3673     Int  lastArity = 0;                 /* = number of args in last defn   */
3674     List bs        = NIL;               /* :: [Binding]                    */
3675
3676     for(; nonNull(ds); ds=tl(ds)) {
3677         Cell d = hd(ds);
3678         if (fst(d)==FUNBIND) {          /* Function bindings               */
3679             Cell rhs    = snd(snd(d));
3680             Int  line   = rhsLine(rhs);
3681             Cell lhs    = fst(snd(d));
3682             Cell v      = getHead(lhs);
3683             Cell newAlt = pair(getArgs(lhs),rhs);
3684             if (!isVar(v)) {
3685                 internal("FUNBIND");
3686             }
3687             if (nonNull(lastVar) && textOf(v)==textOf(lastVar)) {
3688                 if (argCount!=lastArity) {
3689                     ERRMSG(line) "Equations give different arities for \"%s\"",
3690                                  textToStr(textOf(v))
3691                     EEND;
3692                 }
3693                 fbindAlts(hd(bs)) = cons(newAlt,fbindAlts(hd(bs)));
3694             }
3695             else {
3696                 lastVar   = v;
3697                 lastArity = argCount;
3698                 notDefined(line,bs,v);
3699                 bs        = cons(pair(v,pair(NIL,singleton(newAlt))),bs);
3700             }
3701
3702         } else if (fst(d)==PATBIND) {   /* Pattern bindings                */
3703             Cell rhs  = snd(snd(d));
3704             Int  line = rhsLine(rhs);
3705             Cell pat  = fst(snd(d));
3706             while (whatIs(pat)==ESIGN) {/* Move type annotations to rhs   */
3707                 Cell p        = fst(snd(pat));
3708                 fst(snd(pat)) = rhs;
3709                 snd(snd(d))   = rhs = pat;
3710                 fst(snd(d))   = pat = p;
3711                 fst(rhs)      = RSIGN;
3712             }
3713             if (isVar(pat)) {           /* Convert simple pattern bind to */
3714                 notDefined(line,bs,pat);/* a function binding             */
3715                 bs = cons(pair(pat,pair(NIL,singleton(pair(NIL,rhs)))),bs);
3716             } else {
3717                 List vs = getPatVars(line,pat,NIL);
3718                 if (isNull(vs)) {
3719                     ERRMSG(line) "No variables defined in lhs pattern"
3720                     EEND;
3721                 }
3722                 map2Proc(notDefined,line,bs,vs);
3723                 bs          = cons(pair(vs,pair(NIL,snd(d))),bs);
3724             }
3725             lastVar = NIL;
3726         }
3727     }
3728     return bs;
3729 }
3730
3731 static List local getPatVars(line,p,vs) /* Find list of variables bound in */
3732 Int  line;                              /* pattern p                       */
3733 Cell p;
3734 List vs; {
3735     switch (whatIs(p)) {
3736         case AP         : do {
3737                               vs = getPatVars(line,arg(p),vs);
3738                               p  = fun(p);
3739                           } while (isAp(p));
3740                           return vs;    /* Ignore head of application      */
3741
3742         case CONFLDS    : {   List pfs = snd(snd(p));
3743                               for (; nonNull(pfs); pfs=tl(pfs)) {
3744                                   if (isVar(hd(pfs))) {
3745                                       vs = addPatVar(line,hd(pfs),vs);
3746                                   } else {
3747                                       vs = getPatVars(line,snd(hd(pfs)),vs);
3748                                   }
3749                               }
3750                           }
3751                           return vs;
3752
3753         case FINLIST    : {   List ps = snd(p);
3754                               for (; nonNull(ps); ps=tl(ps)) {
3755                                   vs = getPatVars(line,hd(ps),vs);
3756                               }
3757                           }
3758                           return vs;
3759
3760         case ESIGN      : return getPatVars(line,fst(snd(p)),vs);
3761
3762         case LAZYPAT    :
3763         case NEG        :
3764         case ONLY       :
3765         case INFIX      : return getPatVars(line,snd(p),vs);
3766
3767         case ASPAT      : return addPatVar(line,fst(snd(p)),
3768                                              getPatVars(line,snd(snd(p)),vs));
3769
3770         case VARIDCELL  :
3771         case VAROPCELL  : return addPatVar(line,p,vs);
3772
3773         case CONIDCELL  :
3774         case CONOPCELL  :
3775         case QUALIDENT  :
3776         case INTCELL    :
3777         case FLOATCELL  :
3778         case CHARCELL   :
3779         case STRCELL    :
3780         case NAME       :
3781         case WILDCARD   : return vs;
3782
3783         default         : internal("getPatVars");
3784     }
3785     return vs;
3786 }
3787
3788 static List local addPatVar(line,v,vs)  /* Add var to list of previously   */
3789 Int  line;                              /* encountered variables           */
3790 Cell v;
3791 List vs; {
3792     if (varIsMember(textOf(v),vs)) {
3793         ERRMSG(line) "Repeated use of variable \"%s\" in pattern binding",
3794                      textToStr(textOf(v))
3795         EEND;
3796     }
3797     return cons(v,vs);
3798 }
3799
3800 static List local eqnsToBindings(es,ts,cs,ps)
3801 List es;                                /* Convert list of equations to    */
3802 List ts;                                /* list of typed bindings          */
3803 List cs;
3804 List ps; {
3805     List bs = extractBindings(es);
3806     map1Proc(addSigdecl,bs,extractSigdecls(es));
3807     map4Proc(addFixdecl,bs,ts,cs,ps,extractFixdecls(es));
3808     return bs;
3809 }
3810
3811 static Void local notDefined(line,bs,v)/* check if name already defined in */
3812 Int  line;                             /* list of bindings                 */
3813 List bs;
3814 Cell v; {
3815     if (nonNull(findBinding(textOf(v),bs))) {
3816         ERRMSG(line) "\"%s\" multiply defined", textToStr(textOf(v))
3817         EEND;
3818     }
3819 }
3820
3821 static Cell local findBinding(t,bs)    /* look for binding for variable t  */
3822 Text t;                                /* in list of bindings bs           */
3823 List bs; {
3824     for (; nonNull(bs); bs=tl(bs)) {
3825         if (isVar(fst(hd(bs)))) {                     /* function-binding? */
3826             if (textOf(fst(hd(bs)))==t) {
3827                 return hd(bs);
3828             }
3829         } else if (nonNull(varIsMember(t,fst(hd(bs))))){/* pattern-binding?*/
3830             return hd(bs);
3831         }
3832     }
3833     return NIL;
3834 }
3835
3836 static Cell local getAttr(bs,v)         /* Locate type/fixity attribute    */
3837 List bs;                                /* for variable v in bindings bs   */
3838 Cell v; {
3839     Text t = textOf(v);
3840     Cell b = findBinding(t,bs);
3841
3842     if (isNull(b)) {                                    /* No binding      */
3843         return NIL;
3844     } else if (isVar(fst(b))) {                         /* func binding?   */
3845         if (isNull(bindingAttr(b))) {
3846             bindingAttr(b) = pair(NIL,NIL);
3847         }
3848         return bindingAttr(b);
3849     } else {                                            /* pat binding?    */
3850         List vs = fst(b);
3851         List as = bindingAttr(b);
3852
3853         if (isNull(as)) {
3854             bindingAttr(b) = as = replicate(length(vs),NIL);
3855         }
3856
3857         while (nonNull(vs) && t!=textOf(hd(vs))) {
3858             vs = tl(vs);
3859             as = tl(as);
3860         }
3861
3862         if (isNull(vs)) {
3863             internal("getAttr");
3864         } else if (isNull(hd(as))) {
3865             hd(as) = pair(NIL,NIL);
3866         }
3867         return hd(as);
3868     }
3869 }
3870
3871 static Void local addSigdecl(bs,sigdecl)/* add type information to bindings*/
3872 List bs;                               /* :: [Binding]                     */
3873 Cell sigdecl; {                        /* :: (Line,[Var],Type)             */
3874     Int  l    = intOf(fst3(sigdecl));
3875     List vs   = snd3(sigdecl);
3876     Type type = checkSigType(l,"type declaration",hd(vs),thd3(sigdecl));
3877
3878     for (; nonNull(vs); vs=tl(vs)) {
3879         Cell v    = hd(vs);
3880         Pair attr = getAttr(bs,v);
3881         if (isNull(attr)) {
3882             ERRMSG(l) "Missing binding for variable \"%s\" in type signature",
3883                       textToStr(textOf(v))
3884             EEND;
3885         } else if (nonNull(fst(attr))) {
3886             ERRMSG(l) "Repeated type signature for \"%s\"",
3887                       textToStr(textOf(v))
3888             EEND;
3889         }
3890         fst(attr) = type;
3891     }
3892 }
3893
3894 static Void local addFixdecl(bs,ts,cs,ps,fixdecl)
3895 List   bs;
3896 List   ts;
3897 List   cs;
3898 List   ps;
3899 Triple fixdecl; {
3900     Int  line = intOf(fst3(fixdecl));
3901     List ops  = snd3(fixdecl);
3902     Cell sy   = thd3(fixdecl);
3903
3904     for (; nonNull(ops); ops=tl(ops)) {
3905         Cell op   = hd(ops);
3906         Text t    = textOf(op);
3907         Cell attr = getAttr(bs,op);
3908         if (nonNull(attr)) {            /* Found name in binding?          */
3909             if (nonNull(snd(attr))) {
3910                 dupFixity(line,t);
3911             }
3912             snd(attr) = sy;
3913         } else {                        /* Look in tycons, classes, prims  */
3914             Name n   = NIL;
3915             List ts1 = ts;
3916             List cs1 = cs;
3917             List ps1 = ps;
3918             for (; isNull(n) && nonNull(ts1); ts1=tl(ts1)) {    /* tycons  */
3919                 Tycon tc = hd(ts1);
3920                 if (tycon(tc).what==DATATYPE || tycon(tc).what==NEWTYPE) {
3921                     n = nameIsMember(t,tycon(tc).defn);
3922                 }
3923             }
3924             for (; isNull(n) && nonNull(cs1); cs1=tl(cs1)) {    /* classes */
3925                 n = nameIsMember(t,cclass(hd(cs1)).members);
3926             }
3927             for (; isNull(n) && nonNull(ps1); ps1=tl(ps1)) {    /* prims   */
3928                 n = nameIsMember(t,hd(ps1));
3929             }
3930
3931             if (isNull(n)) {
3932                 missFixity(line,t);
3933             } else if (name(n).syntax!=NO_SYNTAX) {
3934                 dupFixity(line,t);
3935             }
3936             name(n).syntax = intOf(sy);
3937         }
3938     }
3939 }
3940
3941 static Void local dupFixity(line,t)     /* Report repeated fixity decl     */
3942 Int  line;
3943 Text t; {
3944     ERRMSG(line)
3945         "Repeated fixity declaration for operator \"%s\"", textToStr(t)
3946     EEND;
3947 }
3948
3949 static Void local missFixity(line,t)    /* Report missing op for fixity    */
3950 Int  line;
3951 Text t; {
3952     ERRMSG(line)
3953         "Cannot find binding for operator \"%s\" in fixity declaration",
3954         textToStr(t)
3955     EEND;
3956 }
3957
3958 /* --------------------------------------------------------------------------
3959  * Dealing with infix operators:
3960  *
3961  * Expressions involving infix operators or unary minus are parsed as
3962  * elements of the following type:
3963  *
3964  *     data InfixExp = Only Exp | Neg InfixExp | Infix InfixExp Op Exp
3965  *
3966  * (The algorithms here do not assume that negation can be applied only once,
3967  * i.e., that - - x is a syntax error, as required by the Haskell report.
3968  * Instead, that restriction is captured by the grammar itself, given above.)
3969  *
3970  * There are rules of precedence and grouping, expressed by two functions:
3971  *
3972  *     prec :: Op -> Int;   assoc :: Op -> Assoc    (Assoc = {L, N, R})
3973  *
3974  * InfixExp values are rearranged accordingly when a complete expression
3975  * has been read using a simple shift-reduce parser whose result may be taken
3976  * to be a value of the following type:
3977  *
3978  *     data Exp = Atom Int | Negate Exp | Apply Op Exp Exp | Error String
3979  *
3980  * The machine on which this parser is based can be defined as follows:
3981  *
3982  *     tidy                         :: InfixExp -> [(Op,Exp)] -> Exp
3983  *     tidy (Only a)      []         = a
3984  *     tidy (Only a)      ((o,b):ss) = tidy (Only (Apply o a b)) ss
3985  *     tidy (Infix a o b) []         = tidy a [(o,b)]
3986  *     tidy (Infix a o b) ((p,c):ss)
3987  *                      | shift  o p = tidy a ((o,b):(p,c):ss)
3988  *                      | red    o p = tidy (Infix a o (Apply p b c)) ss
3989  *                      | ambig  o p = Error "ambiguous use of operators"
3990  *     tidy (Neg e)       []         = tidy (tidyNeg e) []
3991  *     tidy (Neg e)       ((o,b):ss)
3992  *                      | nshift o   = tidy (Neg (underNeg o b e)) ss
3993  *                      | nred   o   = tidy (tidyNeg e) ((o,b):ss)
3994  *                      | nambig o   = Error "illegal use of negation"
3995  *
3996  * At each stage, the parser can either shift, reduce, accept, or error.
3997  * The transitions when dealing with juxtaposed operators o and p are
3998  * determined by the following rules:
3999  *
4000  *     shift o p  = (prec o > prec p)
4001  *               || (prec o == prec p && assoc o == L && assoc p == L)
4002  *
4003  *     red o p    = (prec o < prec p)
4004  *               || (prec o == prec p && assoc o == R && assoc p == R)
4005  *
4006  *     ambig o p  = (prec o == prec p)
4007  *               && (assoc o == N || assoc p == N || assoc o /= assoc p)
4008  *
4009  * The transitions when dealing with juxtaposed unary minus and infix
4010  * operators are as follows.  The precedence of unary minus (infixl 6) is
4011  * hardwired in to these definitions, as it is to the definitions of the
4012  * Haskell grammar in the official report.
4013  *
4014  *     nshift o   = (prec o > 6)
4015  *     nred   o   = (prec o < 6) || (prec o == 6 && assoc o == L)
4016  *     nambig o   = prec o == 6 && (assoc o == R || assoc o == N)
4017  *
4018  * An InfixExp of the form (Neg e) means negate the last thing in
4019  * the InfixExp e; we can force this negation using:
4020  *
4021  *     tidyNeg              :: OpExp -> OpExp
4022  *     tidyNeg (Only e)      = Only (Negate e)
4023  *     tidyNeg (Infix a o b) = Infix a o (Negate b)
4024  *     tidyNeg (Neg e)       = tidyNeg (tidyNeg e)
4025  * 
4026  * On the other hand, if we want to sneak application of an infix operator
4027  * under a negation, then we use:
4028  *
4029  *     underNeg                  :: Op -> Exp -> OpExp -> OpExp
4030  *     underNeg o b (Only e)      = Only (Apply o e b)
4031  *     underNeg o b (Neg e)       = Neg (underNeg o b e)
4032  *     underNeg o b (Infix e p f) = Infix e p (Apply o f b)
4033  *
4034  * As a concession to efficiency, we lower the number of calls to syntaxOf
4035  * by keeping track of the values of sye, sys throughout the process.  The
4036  * value APPLIC is used to indicate that the syntax value is unknown.
4037  * ------------------------------------------------------------------------*/
4038
4039 static Cell local tidyInfix(line,e)     /* Convert infixExp to Exp         */
4040 Int  line;
4041 Cell e; {                               /* :: OpExp                        */
4042     Cell   s   = NIL;                   /* :: [(Op,Exp)]                   */
4043     Syntax sye = APPLIC;                /* Syntax of op in e (init unknown)*/
4044     Syntax sys = APPLIC;                /* Syntax of op in s (init unknown)*/
4045     Cell   d   = e;
4046
4047     while (fst(d)!=ONLY) {              /* Attach fixities to operators    */
4048         if (fst(d)==NEG) {
4049             d = snd(d);
4050         } else {
4051             fun(fun(d)) = attachFixity(line,fun(fun(d)));
4052             d           = arg(fun(d));
4053         }
4054     }
4055
4056     for (;;)
4057         switch (whatIs(e)) {
4058             case ONLY : e = snd(e);
4059                         while (nonNull(s)) {
4060                             Cell next   = arg(fun(s));
4061                             arg(fun(s)) = e;
4062                             fun(fun(s)) = snd(fun(fun(s)));
4063                             e           = s;
4064                             s           = next;
4065                         }
4066                         return e;
4067
4068             case NEG  : if (nonNull(s)) {
4069                             if (sys==APPLIC) {  /* calculate sys           */
4070                                 sys = intOf(fst(fun(fun(s))));
4071                             }
4072
4073                             if (precOf(sys)==UMINUS_PREC &&     /* nambig  */
4074                                 assocOf(sys)!=UMINUS_ASSOC) {
4075                                 ERRMSG(line)
4076                                  "Ambiguous use of unary minus with \""
4077                                 ETHEN ERREXPR(snd(fun(fun(s))));
4078                                 ERRTEXT "\""
4079                                 EEND;
4080                             }
4081
4082                             if (precOf(sys)>UMINUS_PREC) {      /* nshift  */
4083                                 Cell e1    = snd(e);
4084                                 Cell t     = s;
4085                                 s          = arg(fun(s));
4086                                 while (whatIs(e1)==NEG)
4087                                     e1 = snd(e1);
4088                                 arg(fun(t)) = arg(e1);
4089                                 fun(fun(t)) = snd(fun(fun(t)));
4090                                 arg(e1)     = t;
4091                                 sys         = APPLIC;
4092                                 continue;
4093                             }
4094                         }
4095
4096                         /* Intentional fall-thru for nreduce and isNull(s) */
4097
4098                         {   Cell prev = e;              /* e := tidyNeg e  */
4099                             Cell temp = arg(prev);
4100                             Int  nneg = 1;
4101                             for (; whatIs(temp)==NEG; nneg++) {
4102                                 fun(prev) = nameNegate;
4103                                 prev      = temp;
4104                                 temp      = arg(prev);
4105                             }
4106                             if (isInt(arg(temp))) {     /* special cases   */
4107                                 if (nneg&1)             /* for literals    */
4108                                     arg(temp) = mkInt(-intOf(arg(temp)));
4109                             }
4110                             else if (isFloat(arg(temp))) {
4111                                 if (nneg&1)
4112                                     arg(temp) = floatNegate(arg(temp));
4113                                                 //mkFloat(-floatOf(arg(temp)));
4114                             }
4115                             else {
4116                                 fun(prev) = nameNegate;
4117                                 arg(prev) = arg(temp);
4118                                 arg(temp) = e;
4119                             }
4120                             e = temp;
4121                         }
4122                         continue;
4123
4124             default   : if (isNull(s)) {/* Move operation onto empty stack */
4125                             Cell next   = arg(fun(e));
4126                             s           = e;
4127                             arg(fun(s)) = NIL;
4128                             e           = next;
4129                             sys         = sye;
4130                             sye         = APPLIC;
4131                         }
4132                         else {          /* deal with pair of operators     */
4133
4134                             if (sye==APPLIC) {  /* calculate sys and sye   */
4135                                 sye = intOf(fst(fun(fun(e))));
4136                             }
4137                             if (sys==APPLIC) {
4138                                 sys = intOf(fst(fun(fun(s))));
4139                             }
4140
4141                             if (precOf(sye)==precOf(sys) &&     /* ambig   */
4142                                 (assocOf(sye)!=assocOf(sys) ||
4143                                  assocOf(sye)==NON_ASS)) {
4144                                 ERRMSG(line) "Ambiguous use of operator \""
4145                                 ETHEN ERREXPR(snd(fun(fun(e))));
4146                                 ERRTEXT "\" with \""
4147                                 ETHEN ERREXPR(snd(fun(fun(s))));
4148                                 ERRTEXT "\""
4149                                 EEND;
4150                             }
4151
4152                             if (precOf(sye)>precOf(sys) ||      /* shift   */
4153                                 (precOf(sye)==precOf(sys) &&
4154                                  assocOf(sye)==LEFT_ASS &&
4155                                  assocOf(sys)==LEFT_ASS)) {
4156                                 Cell next   = arg(fun(e));
4157                                 arg(fun(e)) = s;
4158                                 s           = e;
4159                                 e           = next;
4160                                 sys         = sye;
4161                                 sye         = APPLIC;
4162                             }
4163                             else {                              /* reduce  */
4164                                 Cell next   = arg(fun(s));
4165                                 arg(fun(s)) = arg(e);
4166                                 fun(fun(s)) = snd(fun(fun(s)));
4167                                 arg(e)      = s;
4168                                 s           = next;
4169                                 sys         = APPLIC;
4170                                 /* sye unchanged */
4171                             }
4172                         }
4173                         continue;
4174         }
4175 }
4176
4177 static Pair local attachFixity(line,op) /* Attach fixity to operator in an */
4178 Int  line;                              /* infix expression                */
4179 Cell op; {
4180     Syntax sy = DEF_OPSYNTAX;
4181
4182     switch (whatIs(op)) {
4183         case VAROPCELL :
4184         case VARIDCELL : if ((sy=lookupSyntax(textOf(op)))==NO_SYNTAX) {
4185                              Name n = findName(textOf(op));
4186                              if (isNull(n)) {
4187                                 ERRMSG(line) "Undefined variable \"%s\"",
4188                                              textToStr(textOf(op))
4189                                 EEND;
4190                              }
4191                              sy = syntaxOf(n);
4192                              op = n;
4193                          }
4194                          break;
4195
4196         case CONOPCELL :
4197         case CONIDCELL : sy = syntaxOf(op = conDefined(line,op));
4198                          break;
4199
4200         case QUALIDENT : {   Name n = findQualName(op);
4201                              if (nonNull(n)) {
4202                                  op = n;
4203                                  sy = syntaxOf(n);
4204                              } else {
4205                                  ERRMSG(line)
4206                                    "Undefined qualified variable \"%s\"",
4207                                    identToStr(op)
4208                                  EEND;
4209                              }
4210                          }
4211                          break;
4212     }
4213     if (sy==APPLIC) {
4214         sy = DEF_OPSYNTAX;
4215     }
4216     return pair(mkInt(sy),op);          /* Pair fixity with (possibly)     */
4217                                         /* translated operator             */
4218 }
4219
4220 static Syntax local lookupSyntax(t)     /* Try to find fixity for var in   */
4221 Text t; {                               /* enclosing bindings              */
4222     List bounds1   = bounds;
4223     List bindings1 = bindings;
4224
4225     while (nonNull(bindings1)) {
4226         if (nonNull(varIsMember(t,hd(bounds1)))) {
4227             return DEF_OPSYNTAX;
4228         } else {
4229             Cell b = findBinding(t,hd(bindings1));
4230             if (nonNull(b)) {
4231                 Cell a = fst(snd(b));
4232                 if (isVar(fst(b))) {    /* Function binding                */
4233                     if (nonNull(a) && nonNull(snd(a))) {
4234                         return intOf(snd(a));
4235                     }
4236                 } else {                /* Pattern binding                 */
4237                     List vs = fst(b);
4238                     while (nonNull(vs) && nonNull(a)) {
4239                         if (t==textOf(hd(vs))) {
4240                             if (nonNull(hd(a)) && isInt(snd(hd(a)))) {
4241                                 return intOf(snd(hd(a)));
4242                             }
4243                             break;
4244                         }
4245                         vs = tl(vs);
4246                         a  = tl(a);
4247                     }
4248                 }
4249                 return DEF_OPSYNTAX;
4250             }
4251         }
4252         bounds1   = tl(bounds1);
4253         bindings1 = tl(bindings1);
4254     }
4255     return NO_SYNTAX;
4256 }
4257
4258 /* --------------------------------------------------------------------------
4259  * To facilitate dependency analysis, lists of bindings are temporarily
4260  * augmented with an additional field, which is used in two ways:
4261  * - to build the `adjacency lists' for the dependency graph. Represented by
4262  *   a list of pointers to other bindings in the same list of bindings.
4263  * - to hold strictly positive integer values (depth first search numbers) of
4264  *   elements `on the stack' during the strongly connected components search
4265  *   algorithm, or a special value mkInt(0), once the binding has been added
4266  *   to a particular strongly connected component.
4267  *
4268  * Using this extra field, the type of each list of declarations during
4269  * dependency analysis is [Binding'] where:
4270  *
4271  *    Binding' ::= (Var, (Attr, (Dep, [Alt])))         -- function binding
4272  *              |  ([Var], ([Attr], (Dep, (Pat,Rhs)))) -- pattern binding
4273  *
4274  * ------------------------------------------------------------------------*/
4275
4276 #define depVal(d) (fst(snd(snd(d))))    /* Access to dependency information*/
4277
4278 static List local dependencyAnal(bs)    /* Separate lists of bindings into */
4279 List bs; {                              /* mutually recursive groups in    */
4280                                         /* order of dependency             */
4281     mapProc(addDepField,bs);            /* add extra field for dependents  */
4282     mapProc(depBinding,bs);             /* find dependents of each binding */
4283     bs = bscc(bs);                      /* sort to strongly connected comps*/
4284     mapProc(remDepField,bs);            /* remove dependency info field    */
4285     return bs;
4286 }
4287
4288 static List local topDependAnal(bs)     /* Like dependencyAnal(), but at   */
4289 List bs; {                              /* top level, reporting on progress*/
4290     List xs;
4291     Int  i = 0;
4292
4293     setGoal("Dependency analysis",(Target)(length(bs)));
4294
4295     mapProc(addDepField,bs);           /* add extra field for dependents   */
4296     for (xs=bs; nonNull(xs); xs=tl(xs)) {
4297         emptySubstitution();
4298         depBinding(hd(xs));
4299         soFar((Target)(i++));
4300     }
4301     bs = bscc(bs);                     /* sort to strongly connected comps */
4302     mapProc(remDepField,bs);           /* remove dependency info field     */
4303     done();
4304     return bs;
4305 }
4306
4307 static Void local addDepField(b)       /* add extra field to binding to    */
4308 Cell b; {                              /* hold list of dependents          */
4309     snd(snd(b)) = pair(NIL,snd(snd(b)));
4310 }
4311
4312 static Void local remDepField(bs)      /* remove dependency field from     */
4313 List bs; {                             /* list of bindings                 */
4314     mapProc(remDepField1,bs);
4315 }
4316
4317 static Void local remDepField1(b)      /* remove dependency field from     */
4318 Cell b; {                              /* single binding                   */
4319     snd(snd(b)) = snd(snd(snd(b)));
4320 }
4321
4322 static Void local clearScope() {       /* initialise dependency scoping    */
4323     bounds   = NIL;
4324     bindings = NIL;
4325     depends  = NIL;
4326 }
4327
4328 static Void local withinScope(bs)       /* Enter scope of bindings bs      */
4329 List bs; {
4330     bounds   = cons(NIL,bounds);
4331     bindings = cons(bs,bindings);
4332     depends  = cons(NIL,depends);
4333 }
4334
4335 static Void local leaveScope() {        /* Leave scope of last withinScope */
4336     List bs       = hd(bindings);       /* Remove fixity info from binds   */
4337     Bool toplevel = isNull(tl(bindings));
4338     for (; nonNull(bs); bs=tl(bs)) {
4339         Cell b = hd(bs);
4340         if (isVar(fst(b))) {            /* Variable binding                */
4341             Cell a = fst(snd(b));
4342             if (isPair(a)) {
4343                 if (toplevel) {
4344                     saveSyntax(fst(b),snd(a));
4345                 }
4346                 fst(snd(b)) = fst(a);
4347             }
4348         } else {                        /* Pattern binding                 */
4349             List vs = fst(b);
4350             List as = fst(snd(b));
4351             while (nonNull(vs) && nonNull(as)) {
4352                 if (isPair(hd(as))) {
4353                     if (toplevel) {
4354                         saveSyntax(hd(vs),snd(hd(as)));
4355                     }
4356                     hd(as) = fst(hd(as));
4357                 }
4358                 vs = tl(vs);
4359                 as = tl(as);
4360             }
4361         }
4362     }
4363     bounds   = tl(bounds);
4364     bindings = tl(bindings);
4365     depends  = tl(depends);
4366 }
4367
4368 static Void local saveSyntax(v,sy)      /* Save syntax of top-level var    */
4369 Cell v;                                 /* in corresponding Name           */
4370 Cell sy; {
4371     Name n = findName(textOf(v));
4372     if (isNull(n) || name(n).syntax!=NO_SYNTAX) {
4373         internal("saveSyntax");
4374     }
4375     if (nonNull(sy)) {
4376         name(n).syntax = intOf(sy);
4377     }
4378 }
4379
4380 /* --------------------------------------------------------------------------
4381  * As a side effect of the dependency analysis we also make the following
4382  * checks:
4383  * - Each lhs is a valid pattern/function lhs, all constructor functions
4384  *   have been defined and are used with the correct number of arguments.
4385  * - No lhs contains repeated pattern variables.
4386  * - Expressions used on the rhs of an eqn should be well formed.  This
4387  *   includes:
4388  *   - Checking for valid patterns (including repeated vars) in lambda,
4389  *     case, and list comprehension expressions.
4390  *   - Recursively checking local lists of equations.
4391  * - No free (i.e. unbound) variables are used in the declaration list.
4392  * ------------------------------------------------------------------------*/
4393
4394 static Void local depBinding(b)        /* find dependents of binding       */
4395 Cell b; {
4396     Cell defpart = snd(snd(snd(b)));   /* definition part of binding       */
4397
4398     hd(depends) = NIL;
4399
4400     if (isVar(fst(b))) {               /* function-binding?                */
4401         mapProc(depAlt,defpart);
4402         if (isNull(fst(snd(b)))) {      /* Save dep info if no type sig    */
4403             fst(snd(b)) = pair(ap(IMPDEPS,hd(depends)),NIL);
4404         } else if (isNull(fst(fst(snd(b))))) {
4405             fst(fst(snd(b))) = ap(IMPDEPS,hd(depends));
4406         }
4407     } else {                           /* pattern-binding?                 */
4408         Int line = rhsLine(snd(defpart));
4409         enterBtyvs();
4410         patVars = NIL;
4411         fst(defpart) = checkPat(line,fst(defpart));
4412         depRhs(snd(defpart));
4413 #if 0
4414         if (nonNull(hd(btyvars))) {
4415             ERRMSG(line)
4416               "Sorry, no type variables are allowed in pattern binding type annotations"
4417             EEND;
4418         }
4419 #endif
4420         fst(defpart) = applyBtyvs(fst(defpart));
4421     }
4422     depVal(b) = hd(depends);
4423 }
4424
4425 static Void local depDefaults(c)       /* dependency analysis on defaults  */
4426 Class c; {                             /* from class definition            */
4427     depClassBindings(cclass(c).defaults);
4428 }
4429
4430 static Void local depInsts(in)         /* dependency analysis on instance  */
4431 Inst in; {                             /* bindings                         */
4432     depClassBindings(inst(in).implements);
4433 }
4434
4435 static Void local depClassBindings(bs) /* dependency analysis on list of   */
4436 List bs; {                             /* bindings, possibly containing    */
4437     for (; nonNull(bs); bs=tl(bs)) {   /* NIL bindings ...                 */
4438         if (nonNull(hd(bs))) {         /* No need to add extra field for   */
4439            mapProc(depAlt,snd(hd(bs)));/* dependency information...        */
4440         }
4441     }
4442 }
4443
4444 static Void local depAlt(a)             /* Find dependents of alternative  */
4445 Cell a; {
4446     List obvs = saveBvars();            /* Save list of bound variables    */
4447     enterBtyvs();
4448     bindPats(rhsLine(snd(a)),fst(a));   /* add new bound vars for patterns */
4449     depRhs(snd(a));                     /* find dependents of rhs          */
4450     fst(a)    = applyBtyvs(fst(a));
4451     restoreBvars(obvs);                 /* restore original list of bvars  */
4452 }
4453
4454 static Void local depRhs(r)             /* Find dependents of rhs          */
4455 Cell r; {
4456     switch (whatIs(r)) {
4457         case GUARDED : mapProc(depGuard,snd(r));
4458                        break;
4459
4460         case LETREC  : fst(snd(r)) = eqnsToBindings(fst(snd(r)),NIL,NIL,NIL);
4461                        withinScope(fst(snd(r)));
4462                        fst(snd(r)) = dependencyAnal(fst(snd(r)));
4463                        hd(depends) = fst(snd(r));
4464                        depRhs(snd(snd(r)));
4465                        leaveScope();
4466                        break;
4467
4468         case RSIGN   : snd(snd(r)) = checkPatType(rhsLine(fst(snd(r))),
4469                                                   "result",
4470                                                   rhsExpr(fst(snd(r))),
4471                                                   snd(snd(r)));
4472                        depRhs(fst(snd(r)));
4473                        break;
4474
4475         default      : snd(r) = depExpr(intOf(fst(r)),snd(r));
4476                        break;
4477     }
4478 }
4479
4480 static Void local depGuard(g)          /* find dependents of single guarded*/
4481 Cell g; {                              /* expression                       */
4482     depPair(intOf(fst(g)),snd(g));
4483 }
4484
4485 static Cell local depExpr(line,e)      /* find dependents of expression    */
4486 Int  line;
4487 Cell e; {
4488   //Printf( "\n\n"); print(e,100); Printf("\n");
4489   //printExp(stdout,e);
4490     switch (whatIs(e)) {
4491
4492         case VARIDCELL  :
4493         case VAROPCELL  : return depVar(line,e);
4494
4495         case CONIDCELL  :
4496         case CONOPCELL  : return conDefined(line,e);
4497
4498         case QUALIDENT  : if (isQVar(e)) {
4499                               return depQVar(line,e);
4500                           } else { /* QConOrConOp */
4501                               return conDefined(line,e);
4502                           }
4503
4504         case INFIX     : return depExpr(line,tidyInfix(line,snd(e)));
4505
4506 #if TREX
4507         case RECSEL     : break;
4508
4509         case AP         : if (isAp(e) && isAp(fun(e)) && isExt(fun(fun(e)))) {
4510                               return depRecord(line,e);
4511                           } else {
4512                               Cell nx = e;
4513                               Cell a;
4514                               do {
4515                                   a      = nx;
4516                                   arg(a) = depExpr(line,arg(a));
4517                                   nx     = fun(a);
4518                               } while (isAp(nx));
4519                               fun(a) = depExpr(line,fun(a));
4520                           }
4521                           break;
4522 #else
4523         case AP         : depPair(line,e);
4524                           break;
4525 #endif
4526
4527 #if IPARAM
4528         case IPVAR      :
4529 #endif
4530
4531         case NAME       :
4532         case TUPLE      :
4533         case STRCELL    :
4534         case CHARCELL   :
4535         case FLOATCELL  :
4536         case BIGCELL    :
4537         case INTCELL    : break;
4538
4539         case COND       : depTriple(line,snd(e));
4540                           break;
4541
4542         case FINLIST    : map1Over(depExpr,line,snd(e));
4543                           break;
4544
4545         case LETREC     : fst(snd(e)) = eqnsToBindings(fst(snd(e)),NIL,NIL,NIL);
4546                           withinScope(fst(snd(e)));
4547                           fst(snd(e)) = dependencyAnal(fst(snd(e)));
4548                           hd(depends) = fst(snd(e));
4549                           snd(snd(e)) = depExpr(line,snd(snd(e)));
4550                           leaveScope();
4551                           break;
4552
4553         case LAMBDA     : depAlt(snd(e));
4554                           break;
4555
4556         case DOCOMP     : /* fall-thru */
4557         case COMP       : depComp(line,snd(e),snd(snd(e)));
4558                           break;
4559
4560         case ESIGN      : fst(snd(e)) = depExpr(line,fst(snd(e)));
4561                           snd(snd(e)) = checkSigType(line,
4562                                                      "expression",
4563                                                      fst(snd(e)),
4564                                                      snd(snd(e)));
4565                           break;
4566
4567         case CASE       : fst(snd(e)) = depExpr(line,fst(snd(e)));
4568                           map1Proc(depCaseAlt,line,snd(snd(e)));
4569                           break;
4570
4571         case CONFLDS    : depConFlds(line,e,FALSE);
4572                           break;
4573
4574         case UPDFLDS    : depUpdFlds(line,e);
4575                           break;
4576
4577 #if IPARAM
4578         case WITHEXP    : depWith(line,e);
4579                           break;
4580 #endif
4581
4582         case ASPAT      : ERRMSG(line) "Illegal `@' in expression"
4583                           EEND;
4584
4585         case LAZYPAT    : ERRMSG(line) "Illegal `~' in expression"
4586                           EEND;
4587
4588         case WILDCARD   : ERRMSG(line) "Illegal `_' in expression"
4589                           EEND;
4590
4591 #if TREX
4592         case EXT        : ERRMSG(line) "Illegal application of record"
4593                           EEND;
4594 #endif
4595
4596         default         : internal("depExpr");
4597    }
4598    return e;
4599 }
4600
4601 static Void local depPair(line,e)       /* find dependents of pair of exprs*/
4602 Int  line;
4603 Cell e; {
4604     fst(e) = depExpr(line,fst(e));
4605     snd(e) = depExpr(line,snd(e));
4606 }
4607
4608 static Void local depTriple(line,e)     /* find dependents of triple exprs */
4609 Int  line;
4610 Cell e; {
4611     fst3(e) = depExpr(line,fst3(e));
4612     snd3(e) = depExpr(line,snd3(e));
4613     thd3(e) = depExpr(line,thd3(e));
4614 }
4615
4616 static Void local depComp(l,e,qs)       /* find dependents of comprehension*/
4617 Int  l;
4618 Cell e;
4619 List qs; {
4620     if (isNull(qs)) {
4621         fst(e) = depExpr(l,fst(e));
4622     } else {
4623         Cell q   = hd(qs);
4624         List qs1 = tl(qs);
4625         switch (whatIs(q)) {
4626             case FROMQUAL : {   List obvs   = saveBvars();
4627                                 snd(snd(q)) = depExpr(l,snd(snd(q)));
4628                                 enterBtyvs();
4629                                 fst(snd(q)) = bindPat(l,fst(snd(q)));
4630                                 depComp(l,e,qs1);
4631                                 fst(snd(q)) = applyBtyvs(fst(snd(q)));
4632                                 restoreBvars(obvs);
4633                             }
4634                             break;
4635
4636             case QWHERE   : snd(q)      = eqnsToBindings(snd(q),NIL,NIL,NIL);
4637                             withinScope(snd(q));
4638                             snd(q)      = dependencyAnal(snd(q));
4639                             hd(depends) = snd(q);
4640                             depComp(l,e,qs1);
4641                             leaveScope();
4642                             break;
4643
4644             case DOQUAL   : /* fall-thru */
4645             case BOOLQUAL : snd(q) = depExpr(l,snd(q));
4646                             depComp(l,e,qs1);
4647                             break;
4648         }
4649     }
4650 }
4651
4652 static Void local depCaseAlt(line,a)    /* Find dependents of case altern. */
4653 Int  line;
4654 Cell a; {
4655     List obvs = saveBvars();            /* Save list of bound variables    */
4656     enterBtyvs();
4657     fst(a)    = bindPat(line,fst(a));   /* Add new bound vars for pats     */
4658     depRhs(snd(a));                     /* Find dependents of rhs          */
4659     fst(a)    = applyBtyvs(fst(a));
4660     restoreBvars(obvs);                 /* Restore original list of bvars  */
4661 }
4662
4663 static Cell local depVar(line,e)        /* Register occurrence of variable */
4664 Int line;
4665 Cell e; {
4666     List bounds1   = bounds;
4667     List bindings1 = bindings;
4668     List depends1  = depends;
4669     Text t         = textOf(e);
4670     Cell n;
4671
4672     while (nonNull(bindings1)) {
4673         n = varIsMember(t,hd(bounds1));   /* look for t in bound variables */
4674         if (nonNull(n)) {
4675             return n;
4676         }
4677         n = findBinding(t,hd(bindings1)); /* look for t in var bindings    */
4678         if (nonNull(n)) {
4679             if (!cellIsMember(n,hd(depends1))) {
4680                 hd(depends1) = cons(n,hd(depends1));
4681             }
4682            return (isVar(fst(n)) ? fst(n) : e);
4683         }
4684
4685         bounds1   = tl(bounds1);
4686         bindings1 = tl(bindings1);
4687         depends1  = tl(depends1);
4688     }
4689
4690     if (isNull(n=findName(t))) {               /* check global definitions */
4691         ERRMSG(line) "Undefined variable \"%s\"", textToStr(t)
4692         EEND;
4693     }
4694
4695     /* Later phases of the system cannot cope if we resolve references
4696      * to unprocessed objects too early.  This is the main reason that
4697      * we cannot cope with recursive modules at the moment.
4698      */
4699     return e;
4700 }
4701
4702 static Cell local depQVar(line,e)/* register occurrence of qualified variable */
4703 Int line;
4704 Cell e; {
4705     Name n = findQualName(e);
4706     if (isNull(n)) {                            /* check global definitions */
4707         ERRMSG(line) "Undefined qualified variable \"%s\"", identToStr(e)
4708         EEND;
4709     }
4710     if (name(n).mod != currentModule) {
4711         return n;
4712     }
4713     if (fst(e) == VARIDCELL) {
4714         e = mkVar(qtextOf(e));
4715     } else {
4716         e = mkVarop(qtextOf(e));
4717     }
4718     return depVar(line,e);
4719 }
4720
4721 static Void local depConFlds(line,e,isP)/* check construction using fields */
4722 Int  line;
4723 Cell e;
4724 Bool isP; {
4725     Name c = conDefined(line,fst(snd(e)));
4726     if (isNull(snd(snd(e))) ||
4727         nonNull(cellIsMember(c,depFields(line,e,snd(snd(e)),isP)))) {
4728         fst(snd(e)) = c;
4729     } else {
4730         ERRMSG(line) "Constructor \"%s\" does not have selected fields in ",
4731                      textToStr(name(c).text)
4732         ETHEN ERREXPR(e);
4733         ERRTEXT "\n"
4734         EEND;
4735     }
4736     if (!isP && isPair(name(c).defn)) { /* Check that banged fields defined*/
4737         List scs = fst(name(c).defn);   /* List of strict components       */
4738         Type t   = name(c).type;
4739         Int  a   = userArity(c);
4740         List fs  = snd(snd(e));
4741         List ss;
4742         if (isPolyType(t)) {            /* Find tycon that c belongs to    */
4743             t = monotypeOf(t);
4744         }
4745         if (isQualType(t)) {
4746             t = snd(snd(t));
4747         }
4748         if (whatIs(t)==CDICTS) {
4749             t = snd(snd(t));
4750         }
4751         while (0<a--) {
4752             t = arg(t);
4753         }
4754         while (isAp(t)) {
4755             t = fun(t);
4756         }
4757         for (ss=tycon(t).defn; hasCfun(ss); ss=tl(ss)) {
4758         }
4759         /* Now we know the tycon t that c belongs to, and the corresponding
4760          * list of selectors for that type, ss.  Now we have to check that
4761          * each of the fields identified by scs appears in fs, using ss to
4762          * cross reference, and convert integers to selector names.
4763          */
4764         for (; nonNull(scs); scs=tl(scs)) {
4765             Int  i   = intOf(hd(scs));
4766             List ss1 = ss;
4767             for (; nonNull(ss1); ss1=tl(ss1)) {
4768                 List cns = name(hd(ss1)).defn;
4769                 for (; nonNull(cns); cns=tl(cns)) {
4770                     if (fst(hd(cns))==c) {
4771                         break;
4772                     }
4773                 }
4774                 if (nonNull(cns) && intOf(snd(hd(cns)))==i) {
4775                     break;
4776                 }
4777             }
4778             if (isNull(ss1)) {
4779                 internal("depConFlds");
4780             } else {
4781                 Name s   = hd(ss1);
4782                 List fs1 = fs;
4783                 for (; nonNull(fs1) && s!=fst(hd(fs1)); fs1=tl(fs1)) {
4784                 }
4785                 if (isNull(fs1)) {
4786                     ERRMSG(line) "Construction does not define strict field"
4787                     ETHEN
4788                     ERRTEXT      "\nExpression : " ETHEN ERREXPR(e);
4789                     ERRTEXT      "\nField      : " ETHEN ERREXPR(s);
4790                     ERRTEXT      "\n"
4791                     EEND;
4792                 }
4793             }
4794         }
4795     }
4796 }
4797
4798 static Void local depUpdFlds(line,e)    /* check update using fields       */
4799 Int  line;
4800 Cell e; {
4801     if (isNull(thd3(snd(e)))) {
4802         ERRMSG(line) "Empty field list in update"
4803         EEND;
4804     }
4805     fst3(snd(e)) = depExpr(line,fst3(snd(e)));
4806     snd3(snd(e)) = depFields(line,e,thd3(snd(e)),FALSE);
4807 }
4808
4809 static List local depFields(l,e,fs,isP) /* check field binding list        */
4810 Int  l;
4811 Cell e;
4812 List fs;
4813 Bool isP; {
4814     List cs = NIL;
4815     List ss = NIL;
4816
4817     for (; nonNull(fs); fs=tl(fs)) {    /* for each field binding          */
4818         Cell fb = hd(fs);
4819         Name s;
4820
4821         if (isVar(fb)) {                /* expand  var  to  var = var      */
4822             h98DoesntSupport(l,"missing field bindings");
4823             fb = hd(fs) = pair(fb,fb);
4824         }
4825
4826         s = findQualName(fst(fb));      /* check for selector              */
4827         if (nonNull(s) && isSfun(s)) {
4828             fst(fb) = s;
4829         } else {
4830             ERRMSG(l) "\"%s\" is not a selector function/field name",
4831                       textToStr(textOf(fst(fb)))
4832             EEND;
4833         }
4834
4835         if (isNull(ss)) {               /* for first named selector        */
4836             List scs = name(s).defn;    /* calculate list of constructors  */
4837             for (; nonNull(scs); scs=tl(scs)) {
4838                 cs = cons(fst(hd(scs)),cs);
4839             }
4840             ss = singleton(s);          /* initialize selector list        */
4841         } else {                        /* for subsequent selectors        */
4842             List ds = cs;               /* intersect constructor lists     */
4843             for (cs=NIL; nonNull(ds); ) {
4844                 List scs = name(s).defn;
4845                 while (nonNull(scs) && fst(hd(scs))!=hd(ds)) {
4846                     scs = tl(scs);
4847                 }
4848                 if (isNull(scs)) {
4849                     ds = tl(ds);
4850                 } else {
4851                     List next = tl(ds);
4852                     tl(ds)    = cs;
4853                     cs        = ds;
4854                     ds        = next;
4855                 }
4856             }
4857
4858             if (cellIsMember(s,ss)) {   /* check for repeated uses         */
4859                 ERRMSG(l) "Repeated field name \"%s\" in field list",
4860                           textToStr(name(s).text)
4861                 EEND;
4862             }
4863             ss = cons(s,ss);
4864         }
4865
4866         if (isNull(cs)) {               /* Are there any matching constrs? */
4867             ERRMSG(l) "No constructor has all of the fields specified in "
4868             ETHEN ERREXPR(e);
4869             ERRTEXT "\n"
4870             EEND;
4871         }
4872
4873         snd(fb) = (isP ? checkPat(l,snd(fb)) : depExpr(l,snd(fb)));
4874     }
4875     return cs;
4876 }
4877
4878 #if IPARAM
4879 static Void local depWith(line,e)       /* check with using fields         */
4880 Int  line;
4881 Cell e; {
4882     fst(snd(e)) = depExpr(line,fst(snd(e)));
4883     snd(snd(e)) = depDwFlds(line,e,snd(snd(e)));
4884 }
4885
4886 static List local depDwFlds(l,e,fs)/* check field binding list     */
4887 Int  l;
4888 Cell e;
4889 List fs;
4890 {
4891     Cell c = fs;
4892     for (; nonNull(c); c=tl(c)) {       /* for each field binding          */
4893         snd(hd(c)) = depExpr(l,snd(hd(c)));
4894     }
4895     return fs;
4896 }
4897 #endif
4898
4899 #if TREX
4900 static Cell local depRecord(line,e)     /* find dependents of record and   */
4901 Int  line;                              /* sort fields into approp. order  */
4902 Cell e; {                               /* to make construction and update */
4903     List exts = NIL;                    /* more efficient.                 */
4904     Cell r    = e;
4905
4906     h98DoesntSupport(line,"extensible records");
4907     do {                                /* build up list of extensions     */
4908         Text   t    = extText(fun(fun(r)));
4909         String s    = textToStr(t);
4910         List   prev = NIL;
4911         List   nx   = exts;
4912         while (nonNull(nx) && strcmp(textToStr(extText(fun(fun(nx)))),s)>0) {
4913             prev = nx;
4914             nx   = extRow(nx);
4915         }
4916         if (nonNull(nx) && t==extText(fun(fun(nx)))) {
4917             ERRMSG(line) "Repeated label \"%s\" in record ", s
4918             ETHEN ERREXPR(e);
4919             ERRTEXT "\n"
4920             EEND;
4921         }
4922         if (isNull(prev)) {
4923             exts = cons(fun(r),exts);
4924         } else {
4925             tl(prev) = cons(fun(r),nx);
4926         }
4927         extField(r) = depExpr(line,extField(r));
4928         r           = extRow(r);
4929     } while (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r))));
4930     r = depExpr(line,r);
4931     return revOnto(exts,r);
4932 }
4933 #endif
4934
4935
4936 /* --------------------------------------------------------------------------
4937  * Several parts of this program require an algorithm for sorting a list
4938  * of values (with some added dependency information) into a list of strongly
4939  * connected components in which each value appears before its dependents.
4940  *
4941  * Each of these algorithms is obtained by parameterising a standard
4942  * algorithm in "scc.c" as shown below.
4943  * ------------------------------------------------------------------------*/
4944
4945 #define  SCC2            tcscc          /* make scc algorithm for Tycons   */
4946 #define  LOWLINK         tclowlink
4947 #define  DEPENDS(c)      (isTycon(c) ? tycon(c).kind : cclass(c).kinds)
4948 #define  SETDEPENDS(c,v) if(isTycon(c)) tycon(c).kind=v; else cclass(c).kinds=v
4949 #include "scc.c"
4950 #undef   SETDEPENDS
4951 #undef   DEPENDS
4952 #undef   LOWLINK
4953 #undef   SCC2
4954
4955 #define  SCC             bscc           /* make scc algorithm for Bindings */
4956 #define  LOWLINK         blowlink
4957 #define  DEPENDS(t)      depVal(t)
4958 #define  SETDEPENDS(c,v) depVal(c)=v
4959 #include "scc.c"
4960 #undef   SETDEPENDS
4961 #undef   DEPENDS
4962 #undef   LOWLINK
4963 #undef   SCC
4964
4965 /* --------------------------------------------------------------------------
4966  * Main static analysis:
4967  * ------------------------------------------------------------------------*/
4968
4969 Void checkExp() {                       /* Top level static check on Expr  */
4970     staticAnalysis(RESET);
4971     clearScope();                       /* Analyse expression in the scope */
4972     withinScope(NIL);                   /* of no local bindings            */
4973     inputExpr = depExpr(0,inputExpr);
4974     leaveScope();
4975     staticAnalysis(RESET);
4976 }
4977
4978 #if EXPLAIN_INSTANCE_RESOLUTION
4979 Void checkContext(void) {               /* Top level static check on Expr  */
4980     List vs, qs;
4981
4982     staticAnalysis(RESET);
4983     clearScope();                       /* Analyse expression in the scope */
4984     withinScope(NIL);                   /* of no local bindings            */
4985     qs = inputContext;
4986     for (vs = NIL; nonNull(qs); qs=tl(qs)) {
4987         vs = typeVarsIn(hd(qs),NIL,NIL,vs);
4988     }
4989     map2Proc(depPredExp,0,vs,inputContext);
4990     leaveScope();
4991     staticAnalysis(RESET);
4992 }
4993 #endif
4994
4995 Void checkDefns ( Module thisModule ) { /* Top level static analysis       */
4996     Text modName = module(thisModule).text;
4997
4998     staticAnalysis(RESET);
4999
5000     setCurrModule(thisModule);
5001
5002     /* Resolve module references */
5003     mapProc(checkQualImport,  module(thisModule).qualImports);
5004     mapProc(checkUnqualImport,unqualImports);
5005     /* Add "import Prelude" if there`s no explicit import */
5006     if (modName == textPrelPrim || modName == textPrelude) {
5007       /* Nothing. */
5008     } else if (isNull(cellAssoc(modulePrelude,unqualImports))
5009                && isNull(cellRevAssoc(modulePrelude,module(thisModule).qualImports))) {
5010       unqualImports = cons(pair(modulePrelude,DOTDOT),unqualImports);
5011     } else {
5012       /* Every module implicitly contains "import qualified Prelude" 
5013        */
5014       module(thisModule).qualImports
5015         =cons(pair(mkCon(textPrelude),modulePrelude),
5016               module(thisModule).qualImports);
5017     }
5018     mapProc(checkImportList, unqualImports);
5019
5020     /* Note: there's a lot of side-effecting going on here, so
5021        don't monkey about with the order of operations here unless
5022        you know what you are doing */
5023     if (!combined) linkPreludeTC();     /* Get prelude tycons and classes  */
5024
5025     mapProc(checkTyconDefn,tyconDefns); /* validate tycon definitions      */
5026     checkSynonyms(tyconDefns);          /* check synonym definitions       */
5027     mapProc(checkClassDefn,classDefns); /* process class definitions       */
5028     mapProc(kindTCGroup,tcscc(tyconDefns,classDefns)); /* attach kinds     */
5029     mapProc(visitClass,classDefns);     /* check class hierarchy           */
5030     mapProc(extendFundeps,classDefns);  /* finish class definitions        */
5031                                         /* (convenient if we do this after */
5032                                         /* calling `visitClass' so that we */
5033                                         /* know the class hierarchy is     */
5034                                         /* acyclic)                        */
5035
5036     mapProc(addMembers,classDefns);     /* add definitions for member funs */
5037
5038     if (!combined) linkPreludeCM();     /* Get prelude cfuns and mfuns     */
5039     
5040     instDefns = rev(instDefns);         /* process instance definitions    */
5041     mapProc(checkInstDefn,instDefns);
5042
5043     setCurrModule(thisModule);
5044     mapProc(addRSsigdecls,typeInDefns); /* add sigdecls for RESTRICTSYN    */
5045     valDefns   = eqnsToBindings(valDefns,tyconDefns,classDefns,/*primDefns*/NIL);
5046     mapProc(allNoPrevDef,valDefns);     /* check against previous defns    */
5047     mapProc(addDerivImp,derivedInsts);  /* Add impls for derived instances */
5048     deriveContexts(derivedInsts);       /* Calculate derived inst contexts */
5049     instDefns  = appendOnto(instDefns,derivedInsts);
5050     checkDefaultDefns();                /* validate default definitions    */
5051
5052     mapProc(allNoPrevDef,valDefns);     /* check against previous defns    */
5053
5054     if (!combined) linkPrimNames();     /* link primitive names           */
5055
5056     mapProc(checkForeignImport,foreignImports); /* check foreign imports   */
5057     mapProc(checkForeignExport,foreignExports); /* check foreign exports   */
5058     foreignImports = NIL;
5059     foreignExports = NIL;
5060
5061     /* Every top-level name has now been created - so we can build the     */
5062     /* export list.  Note that this has to happen before dependency        */
5063     /* analysis so that references to Prelude.foo will be resolved         */
5064     /* when compiling the prelude.                                         */
5065     module(thisModule).exports 
5066        = checkExports ( module(thisModule).exports, thisModule );
5067
5068     mapProc(checkTypeIn,typeInDefns);   /* check restricted synonym defns  */
5069
5070     clearScope();
5071     withinScope(valDefns);
5072     valDefns = topDependAnal(valDefns); /* top level dependency ordering   */
5073     mapProc(depDefaults,classDefns);    /* dep. analysis on class defaults */
5074     mapProc(depInsts,instDefns);        /* dep. analysis on inst defns     */
5075     leaveScope();
5076
5077     /* ToDo: evalDefaults should match current evaluation module */
5078     evalDefaults = defaultDefns;        /* Set defaults for evaluator      */
5079
5080     staticAnalysis(RESET);
5081 }
5082
5083
5084
5085
5086 static Void local addRSsigdecls(pr)     /* add sigdecls from TYPE ... IN ..*/
5087 Pair pr; {
5088     List vs = snd(pr);                  /* get list of variables           */
5089     for (; nonNull(vs); vs=tl(vs)) {
5090         if (fst(hd(vs))==SIGDECL) {     /* find a sigdecl                  */
5091             valDefns = cons(hd(vs),valDefns);   /* add to valDefns         */
5092             hd(vs)   = hd(snd3(snd(hd(vs))));   /* and replace with var    */
5093         }
5094     }
5095 }
5096
5097 static Void local allNoPrevDef(b)        /* ensure no previous bindings for*/
5098 Cell b; {                                /* variables in new binding       */
5099     if (isVar(fst(b))) {
5100         noPrevDef(rhsLine(snd(hd(snd(snd(b))))),fst(b));
5101     } else {
5102         Int line = rhsLine(snd(snd(snd(b))));
5103         map1Proc(noPrevDef,line,fst(b));
5104     }
5105 }
5106
5107 static Void local noPrevDef(line,v)      /* ensure no previous binding for */
5108 Int  line;                               /* new variable                   */
5109 Cell v; {
5110     Name n = findName(textOf(v));
5111
5112     if (isNull(n)) {
5113         n            = newName(textOf(v),NIL);
5114         name(n).defn = PREDEFINED;
5115     } else if (name(n).defn!=PREDEFINED) {
5116         duplicateError(line,name(n).mod,name(n).text,"variable");
5117     }
5118     name(n).line = line;
5119 }
5120
5121 static Void local duplicateErrorAux(line,mod,t,kind)/* report duplicate defn */
5122 Int    line;
5123 Module mod;
5124 Text   t;
5125 String kind; {
5126     if (mod == currentModule) {
5127         ERRMSG(line) "Repeated definition for %s \"%s\"", kind, 
5128                      textToStr(t)
5129         EEND;
5130     } else {
5131         ERRMSG(line) "Definition of %s \"%s\" clashes with import", kind,
5132                      textToStr(t)
5133         EEND;
5134     }
5135 }
5136
5137 static Void local checkTypeIn(cvs)      /* Check that vars in restricted   */
5138 Pair cvs; {                             /* synonym are defined             */
5139     Tycon c  = fst(cvs);
5140     List  vs = snd(cvs);
5141
5142     for (; nonNull(vs); vs=tl(vs)) {
5143         if (isNull(findName(textOf(hd(vs))))) {
5144             ERRMSG(tycon(c).line)
5145                 "No top level binding of \"%s\" for restricted synonym \"%s\"",
5146                 textToStr(textOf(hd(vs))), textToStr(tycon(c).text)
5147             EEND;
5148         }
5149     }
5150 }
5151
5152 /* --------------------------------------------------------------------------
5153  * Haskell 98 compatibility tests:
5154  * ------------------------------------------------------------------------*/
5155
5156 Bool h98Pred(allowArgs,pi)              /* Check syntax of Hask98 predicate*/
5157 Bool allowArgs;
5158 Cell pi; {
5159     return isClass(getHead(pi)) && argCount==1 &&
5160            isOffset(getHead(arg(pi))) && (argCount==0 || allowArgs);
5161 }
5162
5163 Cell h98Context(allowArgs,ps)           /* Check syntax of Hask98 context  */
5164 Bool allowArgs;
5165 List ps; {
5166     for (; nonNull(ps); ps=tl(ps)) {
5167         if (!h98Pred(allowArgs,hd(ps))) {
5168             return hd(ps);
5169         }
5170     }
5171     return NIL;
5172 }
5173
5174 Void h98CheckCtxt(line,wh,allowArgs,ps,in)
5175 Int    line;                            /* Report illegal context/predicate*/
5176 String wh;
5177 Bool   allowArgs;
5178 List   ps;
5179 Inst   in; {
5180     if (haskell98) {
5181         Cell pi = h98Context(allowArgs,ps);
5182         if (nonNull(pi)) {
5183             ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh ETHEN
5184             if (nonNull(in)) {
5185                 ERRTEXT  "\n*** Instance   : " ETHEN ERRPRED(inst(in).head);
5186             }
5187             ERRTEXT      "\n*** Constraint : " ETHEN ERRPRED(pi);
5188             if (nonNull(ps) && nonNull(tl(ps))) {
5189                 ERRTEXT  "\n*** Context    : " ETHEN ERRCONTEXT(ps);
5190             }
5191             ERRTEXT      "\n"
5192             EEND;
5193         }
5194     }
5195 }
5196
5197 Void h98CheckType(line,wh,e,t)          /* Check for Haskell 98 type       */
5198 Int    line;
5199 String wh;
5200 Cell   e;
5201 Type   t; {
5202     if (haskell98) {
5203         Type ty = t;
5204         if (isPolyType(t))
5205             t = monotypeOf(t);
5206         if (isQualType(t)) {
5207             Cell pi = h98Context(TRUE,fst(snd(t)));
5208             if (nonNull(pi)) {
5209                 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh
5210                 ETHEN
5211                 ERRTEXT  "\n*** Expression : " ETHEN ERREXPR(e);
5212                 ERRTEXT  "\n*** Type       : " ETHEN ERRTYPE(ty);
5213                 ERRTEXT  "\n"
5214                 EEND;
5215             }
5216         }
5217     }
5218 }
5219
5220 Void h98DoesntSupport(line,wh)          /* Report feature missing in H98   */
5221 Int    line;
5222 String wh; {
5223     if (haskell98) {
5224         ERRMSG(line) "Haskell 98 does not support %s", wh
5225         EEND;
5226     }
5227 }
5228
5229 /* --------------------------------------------------------------------------
5230  * Static Analysis control:
5231  * ------------------------------------------------------------------------*/
5232
5233 Void staticAnalysis(what)
5234 Int what; {
5235     switch (what) {
5236         case RESET   : cfunSfuns    = NIL;
5237                        daSccs       = NIL;
5238                        patVars      = NIL;
5239                        bounds       = NIL;
5240                        bindings     = NIL;
5241                        depends      = NIL;
5242                        tcDeps       = NIL;
5243                        derivedInsts = NIL;
5244                        diVars       = NIL;
5245                        diNum        = 0;
5246                        unkindTypes  = NIL;
5247                        break;
5248
5249         case MARK    : mark(daSccs);
5250                        mark(patVars);
5251                        mark(bounds);
5252                        mark(bindings);
5253                        mark(depends);
5254                        mark(tcDeps);
5255                        mark(derivedInsts);
5256                        mark(diVars);
5257                        mark(cfunSfuns);
5258                        mark(unkindTypes);
5259 #if TREX
5260                        mark(extKind);
5261 #endif
5262                        break;
5263
5264         case POSTPREL: break;
5265
5266         case PREPREL : staticAnalysis(RESET);
5267 #if TREX
5268                        extKind = pair(STAR,pair(ROW,ROW));
5269 #endif
5270     }
5271 }
5272
5273 /*-------------------------------------------------------------------------*/