[project @ 2000-04-17 11:39:23 by sewardj]
[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.40 $
13  * $Date: 2000/04/07 10:00:28 $
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     if (isAmbiguous(t)) {
1519         ambigError(line,"class declaration",hd(vs),t);
1520     }
1521     h98CheckType(line,"member type",hd(vs),t);
1522 }
1523
1524 static Void local checkMems2(c,m) /* check member function details   */
1525 Class c;
1526 Cell  m; {
1527     Int  line = intOf(fst3(m));
1528     List vs   = snd3(m);
1529     Type t    = thd3(m);
1530 }
1531
1532 static Void local addMembers(c)         /* Add definitions of member funs  */
1533 Class c; {                              /* and other parts of class struct.*/
1534     List ms  = fst(cclass(c).members);
1535     List fs  = snd(cclass(c).members);
1536     List ns  = NIL;                     /* List of names                   */
1537     Int  mno;                           /* Member function number          */
1538
1539     for (mno=0; mno<cclass(c).numSupers; mno++) {
1540         ns = cons(newDSel(c,mno),ns);
1541     }
1542     cclass(c).dsels = rev(ns);          /* Save dictionary selectors       */
1543
1544     for (mno=1, ns=NIL; nonNull(ms); ms=tl(ms)) {
1545         Int  line = intOf(fst3(hd(ms)));
1546         List vs   = rev(snd3(hd(ms)));
1547         Type t    = thd3(hd(ms));
1548         for (; nonNull(vs); vs=tl(vs)) {
1549             ns = cons(newMember(line,mno++,hd(vs),t,c),ns);
1550         }
1551     }
1552     cclass(c).members    = rev(ns);     /* Save list of members            */
1553     cclass(c).numMembers = length(cclass(c).members);
1554
1555     for (; nonNull(fs); fs=tl(fs)) {    /* fixity declarations             */
1556         Int    line = intOf(fst3(hd(fs)));
1557         List   ops  = snd3(hd(fs));
1558         Syntax s    = intOf(thd3(hd(fs)));
1559         for (; nonNull(ops); ops=tl(ops)) {
1560             Name n = nameIsMember(textOf(hd(ops)),cclass(c).members);
1561             if (isNull(n)) {
1562                 missFixity(line,textOf(hd(ops)));
1563             } else if (name(n).syntax!=NO_SYNTAX) {
1564                 dupFixity(line,textOf(hd(ops)));
1565             }
1566             name(n).syntax = s;
1567         }
1568     }
1569
1570 /*  Not actually needed just yet; for the time being, dictionary code will
1571     not be passed through the type checker.
1572
1573     cclass(c).dtycon    = addPrimTycon(generateText("Dict.%s",c),
1574                                        NIL,
1575                                        cclass(c).arity,
1576                                        DATATYPE,
1577                                        NIL);
1578 */
1579
1580     mno                  = cclass(c).numSupers + cclass(c).numMembers;
1581     /* cclass(c).dcon       = addPrimCfun(generateText("Make.%s",c),mno,0,NIL); */
1582     cclass(c).dcon       = addPrimCfun(generateText(":D%s",c),mno,0,NIL);
1583     /* implementCfun(cclass(c).dcon,NIL);
1584        Don't manufacture a wrapper fn for dictionary constructors.
1585        Applications of dictionary constructors are always saturated,
1586        and translate.c:stgExpr() special-cases saturated constructor apps.
1587     */
1588
1589     if (mno==1) {                       /* Single entry dicts use newtype  */
1590         name(cclass(c).dcon).defn = nameId;
1591         if (nonNull(cclass(c).members)) {
1592             name(hd(cclass(c).members)).number = mfunNo(0);
1593         }
1594     }
1595     cclass(c).defaults   = classBindings("class",c,cclass(c).defaults);
1596 }
1597
1598 static Name local newMember(l,no,v,t,parent)
1599 Int   l;                                /* Make definition for member fn   */
1600 Int   no;
1601 Cell  v;
1602 Type  t; 
1603 Class parent; {
1604     Name m = findName(textOf(v));
1605
1606     if (isNull(m)) {
1607         m = newName(textOf(v),parent);
1608     } else if (name(m).defn!=PREDEFINED) {
1609         ERRMSG(l) "Repeated definition for member function \"%s\"",
1610                   textToStr(name(m).text)
1611         EEND;
1612     }
1613
1614     name(m).line     = l;
1615     name(m).arity    = 1;
1616     name(m).number   = mfunNo(no);
1617     name(m).type     = t;
1618     return m;
1619 }
1620
1621 Name newDSel(c,no)                      /* Make definition for dict selectr*/
1622 Class c;
1623 Int   no; {
1624     Name s;
1625     char buf[16];
1626
1627     /* sprintf(buf,"sc%d.%s",no,"%s"); */
1628     sprintf(buf,"$p%d%s",no+1,"%s");
1629     s                = newName(generateText(buf,c),c);
1630     name(s).line     = cclass(c).line;
1631     name(s).arity    = 1;
1632     name(s).number   = DFUNNAME;
1633     return s;
1634 }
1635
1636 #define MAX_GEN  128
1637
1638 static Text local generateText(sk,c)    /* We need to generate names for   */
1639 String sk;                              /* certain objects corresponding   */
1640 Class  c; {                             /* to each class.                  */
1641     String cname = textToStr(cclass(c).text);
1642     char buffer[MAX_GEN+1];
1643
1644     if ((strlen(sk)+strlen(cname))>=MAX_GEN) {
1645         ERRMSG(0) "Please use a shorter name for class \"%s\"", cname
1646         EEND;
1647     }
1648     sprintf(buffer,sk,cname);
1649     return findText(buffer);
1650 }
1651
1652        Int visitClass(c)                /* visit class defn to check that  */
1653 Class c; {                              /* class hierarchy is acyclic      */
1654 #if TREX
1655     if (isExt(c)) {                     /* special case for lacks preds    */
1656         return 0;
1657     }
1658 #endif
1659     if (cclass(c).level < 0) {          /* already visiting this class?    */
1660         ERRMSG(cclass(c).line) "Class hierarchy for \"%s\" is not acyclic",
1661                                textToStr(cclass(c).text)
1662         EEND;
1663     } else if (cclass(c).level == 0) {  /* visiting class for first time   */
1664         List scs = cclass(c).supers;
1665         Int  lev = 0;
1666         cclass(c).level = (-1);
1667         for (; nonNull(scs); scs=tl(scs)) {
1668             Int l = visitClass(getHead(hd(scs)));
1669             if (l>lev) lev=l;
1670         }
1671         cclass(c).level = 1+lev;        /* level = 1 + max level of supers */
1672     }
1673     return cclass(c).level;
1674 }
1675
1676 /* --------------------------------------------------------------------------
1677  * Process class and instance declaration binding groups:
1678  * ------------------------------------------------------------------------*/
1679
1680 static List local classBindings(where,c,bs)
1681 String where;                           /* Check validity of bindings bs   */
1682 Class  c;                               /* for class c (or an inst of c)   */
1683 List   bs; {                            /* sort into approp. member order  */
1684     List nbs = NIL;
1685
1686     for (; nonNull(bs); bs=tl(bs)) {
1687         Cell b    = hd(bs);
1688         Cell body = snd(snd(b));
1689         Name mnm;
1690
1691         if (!isVar(fst(b))) {           /* Only allow function bindings    */
1692             ERRMSG(rhsLine(snd(body)))
1693                 "Pattern binding illegal in %s declaration", where
1694             EEND;
1695         }
1696
1697         if (isNull(mnm=memberName(c,textOf(fst(b))))) {
1698             ERRMSG(rhsLine(snd(hd(body))))
1699                 "No member \"%s\" in class \"%s\"",
1700                 textToStr(textOf(fst(b))), textToStr(cclass(c).text)
1701             EEND;
1702         }
1703         snd(b) = body;
1704         nbs    = numInsert(mfunOf(mnm)-1,b,nbs);
1705     }
1706     return nbs;
1707 }
1708
1709 static Name local memberName(c,t)       /* return name of member function  */
1710 Class c;                                /* with name t in class c          */
1711 Text  t; {                              /* return NIL if not a member      */
1712     List ms = cclass(c).members;
1713     for (; nonNull(ms); ms=tl(ms)) {
1714         if (t==name(hd(ms)).text) {
1715             return hd(ms);
1716         }
1717     }
1718     return NIL;
1719 }
1720
1721 static List local numInsert(n,x,xs)    /* insert x at nth position in xs,  */
1722 Int  n;                                /* filling gaps with NIL            */
1723 Cell x;
1724 List xs; {
1725     List start = isNull(xs) ? cons(NIL,NIL) : xs;
1726
1727     for (xs=start; 0<n--; xs=tl(xs)) {
1728         if (isNull(tl(xs))) {
1729             tl(xs) = cons(NIL,NIL);
1730         }
1731     }
1732     hd(xs) = x;
1733     return start;
1734 }
1735
1736 /* --------------------------------------------------------------------------
1737  * Calculate set of variables appearing in a given type expression (possibly
1738  * qualified) as a list of distinct values.  The order in which variables
1739  * appear in the list is the same as the order in which those variables
1740  * occur in the type expression when read from left to right.
1741  * ------------------------------------------------------------------------*/
1742
1743 List local typeVarsIn(ty,us,ws,vs)      /*Calculate list of type variables*/
1744 Cell ty;                                /* used in type expression, reading*/
1745 List us;                                /* from left to right ignoring any */
1746 List ws;                                /* listed in us.                   */
1747 List vs; {                              /* ws = explicitly quantified vars */
1748     if (isNull(ty)) return vs;
1749     switch (whatIs(ty)) {
1750         case DICTAP    : return typeVarsIn(snd(snd(ty)),us,ws,vs);
1751         case UNBOXEDTUP: return typeVarsIn(snd(ty),us,ws,vs);
1752
1753         case AP        : return typeVarsIn(snd(ty),us,ws,
1754                                            typeVarsIn(fst(ty),us,ws,vs));
1755
1756         case VARIDCELL :
1757         case VAROPCELL : if ((nonNull(findBtyvs(textOf(ty)))
1758                               && !varIsMember(textOf(ty),ws))
1759                              || varIsMember(textOf(ty),us)) {
1760                              return vs;
1761                          } else {
1762                              return maybeAppendVar(ty,vs);
1763                          }
1764
1765         case POLYTYPE  : return typeVarsIn(monotypeOf(ty),polySigOf(ty),ws,vs);
1766
1767         case QUAL      : {   vs = typeVarsIn(fst(snd(ty)),us,ws,vs);
1768                              return typeVarsIn(snd(snd(ty)),us,ws,vs);
1769                          }
1770
1771         case BANG      : return typeVarsIn(snd(ty),us,ws,vs);
1772
1773         case LABC      : {   List fs = snd(snd(ty));
1774                              for (; nonNull(fs); fs=tl(fs)) {
1775                                 vs = typeVarsIn(snd(hd(fs)),us,ws,vs);
1776                              }
1777                              return vs;
1778                          }
1779         case TUPLE:
1780         case TYCON:
1781         case CONIDCELL:
1782         case QUALIDENT: return vs;
1783
1784         default: fprintf(stderr, " bad tag = %d\n", whatIs(ty));internal("typeVarsIn");
1785     }
1786     assert(0);
1787 }
1788
1789 static List local maybeAppendVar(v,vs) /* append variable to list if not   */
1790 Cell v;                                /* already included                 */
1791 List vs; {
1792     Text t = textOf(v);
1793     List p = NIL;
1794     List c = vs;
1795
1796     while (nonNull(c)) {
1797         if (textOf(hd(c))==t) {
1798             return vs;
1799         }
1800         p = c;
1801         c = tl(c);
1802     }
1803
1804     if (nonNull(p)) {
1805         tl(p) = cons(v,NIL);
1806     } else {
1807         vs    = cons(v,NIL);
1808     }
1809
1810     return vs;
1811 }
1812
1813 /* --------------------------------------------------------------------------
1814  * Static analysis for type expressions is required to:
1815  *   - ensure that each type constructor or class used has been defined.
1816  *   - replace type variables by offsets, constructor names by Tycons.
1817  *   - ensure that the type is well-kinded.
1818  * ------------------------------------------------------------------------*/
1819
1820 static Type local checkSigType(line,where,e,type)
1821 Int    line;                            /* Check validity of type expr in  */
1822 String where;                           /* explicit type signature         */
1823 Cell   e;
1824 Type   type; {
1825     List tvs  = NIL;
1826     List sunk = NIL;
1827     List xtvs = NIL;
1828
1829     if (isPolyType(type)) {
1830         xtvs = fst(snd(type));
1831         type = monotypeOf(type);
1832     }
1833     tvs  = typeVarsIn(type,NIL,xtvs,NIL);
1834     sunk = unkindTypes;
1835     checkOptQuantVars(line,xtvs,tvs);
1836
1837     if (isQualType(type)) {
1838         map2Over(depPredExp,line,tvs,fst(snd(type)));
1839         snd(snd(type)) = depTopType(line,tvs,snd(snd(type)));
1840
1841         if (isAmbiguous(type)) {
1842             ambigError(line,where,e,type);
1843         }
1844     } else {
1845         type = depTopType(line,tvs,type);
1846     }
1847
1848     if (nonNull(tvs)) {
1849         if (length(tvs) >= (OFF_MAX-OFF_MIN+1)) {
1850             ERRMSG(line) "Too many type variables in %s\n", where
1851             EEND;
1852         } else {
1853             List ts = tvs;
1854             for (; nonNull(ts); ts=tl(ts)) {
1855                 hd(ts) = NIL;
1856             }
1857             type    = mkPolyType(tvs,type);
1858         }
1859     }
1860
1861     unkindTypes = NIL;
1862     kindType(line,"type expression",type);
1863     fixKinds();
1864     unkindTypes = sunk;
1865
1866     h98CheckType(line,where,e,type);
1867     return type;
1868 }
1869
1870 static Void local checkOptQuantVars(line,xtvs,tvs)
1871 Int  line;
1872 List xtvs;                              /* Explicitly quantified vars      */
1873 List tvs; {                             /* Implicitly quantified vars      */
1874     if (nonNull(xtvs)) {
1875         List vs = tvs;
1876         for (; nonNull(vs); vs=tl(vs)) {
1877             if (!varIsMember(textOf(hd(vs)),xtvs)) {
1878                 ERRMSG(line) "Quantifier does not mention type variable \"%s\"",
1879                              textToStr(textOf(hd(vs)))
1880                 EEND;
1881             }
1882         }
1883         for (vs=xtvs; nonNull(vs); vs=tl(vs)) {
1884             if (!varIsMember(textOf(hd(vs)),tvs)) {
1885                 ERRMSG(line) "Quantified type variable \"%s\" is not used",
1886                              textToStr(textOf(hd(vs)))
1887                 EEND;
1888             }
1889             if (varIsMember(textOf(hd(vs)),tl(vs))) {
1890                 ERRMSG(line) "Quantified type variable \"%s\" is repeated",
1891                              textToStr(textOf(hd(vs)))
1892                 EEND;
1893             }
1894         }
1895     }
1896 }
1897
1898 static Type local depTopType(l,tvs,t)   /* Check top-level of type sig     */
1899 Int  l;
1900 List tvs;
1901 Type t; {
1902     Type prev = NIL;
1903     Type t1   = t;
1904     Int  nr2  = 0;
1905     Int  i    = 1;
1906     for (; getHead(t1)==typeArrow && argCount==2; ++i) {
1907         arg(fun(t1)) = depCompType(l,tvs,arg(fun(t1)));
1908         if (isPolyOrQualType(arg(fun(t1)))) {
1909             nr2 = i;
1910         }
1911         prev = t1;
1912         t1   = arg(t1);
1913     }
1914     if (nonNull(prev)) {
1915         arg(prev) = depTypeExp(l,tvs,t1);
1916     } else {
1917         t = depTypeExp(l,tvs,t1);
1918     }
1919     if (nr2>0) {
1920         t = ap(RANK2,pair(mkInt(nr2),t));
1921     }
1922     return t;
1923 }
1924
1925 static Type local depCompType(l,tvs,t)  /* Check component type for constr */
1926 Int  l;
1927 List tvs;
1928 Type t; {
1929   Int  ntvs = length(tvs);
1930   List nfr  = NIL;
1931   if (isPolyType(t)) {
1932     List vs  = fst(snd(t));
1933     t        = monotypeOf(t);
1934     tvs      = checkQuantVars(l,vs,tvs,t);
1935     nfr      = replicate(length(vs),NIL);
1936   }
1937   if (isQualType(t)) {
1938     map2Over(depPredExp,l,tvs,fst(snd(t)));
1939     snd(snd(t)) = depTypeExp(l,tvs,snd(snd(t)));
1940     if (isAmbiguous(t)) {
1941       ambigError(l,"type component",NIL,t);
1942     }
1943   } else {
1944     t = depTypeExp(l,tvs,t);
1945   }
1946   if (isNull(nfr)) {
1947     return t;
1948   }
1949   take(ntvs,tvs);
1950   return mkPolyType(nfr,t);
1951 }
1952
1953 static Type local depTypeExp(line,tyvars,type)
1954 Int  line;
1955 List tyvars;
1956 Type type; {
1957     switch (whatIs(type)) {
1958         case AP         : fst(type) = depTypeExp(line,tyvars,fst(type));
1959                           snd(type) = depTypeExp(line,tyvars,snd(type));
1960                           break;
1961
1962         case VARIDCELL  : return depTypeVar(line,tyvars,textOf(type));
1963
1964         case QUALIDENT  : if (isQVar(type)) {
1965                               ERRMSG(line) "Qualified type variables not allowed"
1966                               EEND;
1967                           }
1968                           /* deliberate fall through */
1969         case CONIDCELL  : {   Tycon tc = findQualTycon(type);
1970                               if (isNull(tc)) {
1971                                   ERRMSG(line)
1972                                       "Undefined type constructor \"%s\"",
1973                                       identToStr(type)
1974                                   EEND;
1975                               }
1976                               if (cellIsMember(tc,tyconDefns) &&
1977                                   !cellIsMember(tc,tcDeps)) {
1978                                   tcDeps = cons(tc,tcDeps);
1979                               }
1980                               return tc;
1981                           }
1982
1983 #if TREX
1984         case EXT        : h98DoesntSupport(line,"extensible records");
1985 #endif
1986         case TYCON      :
1987         case TUPLE      : break;
1988
1989         default         : internal("depTypeExp");
1990     }
1991     return type;
1992 }
1993
1994 static Type local depTypeVar(line,tyvars,tv)
1995 Int  line;
1996 List tyvars;
1997 Text tv; {
1998     Int offset = 0;
1999     Int found  = (-1);
2000
2001     for (; nonNull(tyvars); offset++) {
2002         if (tv==textOf(hd(tyvars))) {
2003             found = offset;
2004         }
2005         tyvars = tl(tyvars);
2006     }
2007     if (found<0) {
2008         Cell vt = findBtyvs(tv);
2009         if (nonNull(vt)) {
2010             return fst(vt);
2011         }
2012         ERRMSG(line) "Undefined type variable \"%s\"", textToStr(tv)
2013         EEND;
2014     }
2015     return mkOffset(found);
2016 }
2017
2018 static List local checkQuantVars(line,vs,tvs,body)
2019 Int  line;
2020 List vs;                                /* variables to quantify over      */
2021 List tvs;                               /* variables already in scope      */
2022 Cell body; {                            /* type/constr for scope of vars   */
2023     if (nonNull(vs)) {
2024         List bvs = typeVarsIn(body,NIL,NIL,NIL);
2025         List us  = vs;
2026         for (; nonNull(us); us=tl(us)) {
2027             Text u = textOf(hd(us));
2028             if (varIsMember(u,tl(us))) {
2029                 ERRMSG(line) "Duplicated quantified variable %s",
2030                              textToStr(u)
2031                 EEND;
2032             }
2033 #if 0
2034             if (varIsMember(u,tvs)) {
2035                 ERRMSG(line) "Local quantifier for %s hides an outer use",
2036                              textToStr(u)
2037                 EEND;
2038             }
2039 #endif
2040             if (!varIsMember(u,bvs)) {
2041                 ERRMSG(line) "Locally quantified variable %s is not used",
2042                              textToStr(u)
2043                 EEND;
2044             }
2045         }
2046         tvs = appendOnto(tvs,vs);
2047     }
2048     return tvs;
2049 }
2050
2051 /* --------------------------------------------------------------------------
2052  * Check for ambiguous types:
2053  * A type  Preds => type  is ambiguous if not (TV(P) `subset` TV(type))
2054  * ------------------------------------------------------------------------*/
2055
2056 List offsetTyvarsIn(t,vs)               /* add list of offset tyvars in t  */
2057 Type t;                                 /* to list vs                      */
2058 List vs; {
2059     switch (whatIs(t)) {
2060         case AP       : return offsetTyvarsIn(fun(t),
2061                                 offsetTyvarsIn(arg(t),vs));
2062
2063         case OFFSET   : if (cellIsMember(t,vs))
2064                             return vs;
2065                         else
2066                             return cons(t,vs);
2067
2068         case QUAL     : return offsetTyvarsIn(snd(t),vs);
2069
2070         case POLYTYPE : return offsetTyvarsIn(monotypeOf(t),vs);
2071                         /* slightly inaccurate, but won't matter here      */
2072
2073         case EXIST    :
2074         case RANK2    : return offsetTyvarsIn(snd(snd(t)),vs);
2075
2076         default       : return vs;
2077     }
2078 }
2079
2080 List zonkTyvarsIn(t,vs)
2081 Type t;
2082 List vs; {
2083     switch (whatIs(t)) {
2084         case AP       : return zonkTyvarsIn(fun(t),
2085                                  zonkTyvarsIn(arg(t),vs));
2086
2087         case INTCELL  : if (cellIsMember(t,vs))
2088                             return vs;
2089                         else
2090                             return cons(t,vs);
2091
2092         /* this case will lead to a type error --
2093            much better than reporting an internal error ;-) */
2094         /* case OFFSET   : internal("zonkTyvarsIn"); */
2095
2096         default       : return vs;
2097     }
2098 }
2099
2100 static List local otvars(pi,os)         /* os is a list of offsets that    */
2101 Cell pi;                                /* refer to the arguments of pi;   */
2102 List os; {                              /* find list of offsets in those   */
2103     List us = NIL;                      /* positions                       */
2104     for (; nonNull(os); os=tl(os)) {
2105         us = offsetTyvarsIn(nthArg(offsetOf(hd(os)),pi),us);
2106     }
2107     return us;
2108 }
2109
2110 static List local otvarsZonk(pi,os,o)   /* same as above, but zonks        */
2111 Cell pi;
2112 List os; {
2113     List us = NIL;
2114     for (; nonNull(os); os=tl(os)) {
2115         Type t = zonkType(nthArg(offsetOf(hd(os)),pi),o);
2116         us = zonkTyvarsIn(t,us);
2117     }
2118     return us;
2119 }
2120
2121 static Bool local odiff(us,vs)
2122 List us, vs; {
2123     while (nonNull(us) && cellIsMember(hd(us),vs)) {
2124         us = tl(us);
2125     }
2126     return us;
2127 }
2128
2129 static Bool local osubset(us,vs)        /* Determine whether us is subset  */
2130 List us, vs; {                          /* of vs                           */
2131     while (nonNull(us) && cellIsMember(hd(us),vs)) {
2132         us = tl(us);
2133     }
2134     return isNull(us);
2135 }
2136
2137 List oclose(fds,vs)     /* Compute closure of vs wrt to fds*/
2138 List fds;
2139 List vs; {
2140     Bool changed = TRUE;
2141     while (changed) {
2142         List fds1 = NIL;
2143         changed = FALSE;
2144         while (nonNull(fds)) {
2145             Cell fd   = hd(fds);
2146             List next = tl(fds);
2147             if (osubset(fst(fd),vs)) {  /* Test if fd applies              */
2148                 List os = snd(fd);
2149                 for (; nonNull(os); os=tl(os)) {
2150                     if (!cellIsMember(hd(os),vs)) {
2151                         vs      = cons(hd(os),vs);
2152                         changed = TRUE;
2153                     }
2154                 }
2155             } else {                    /* Didn't apply this time, so keep */
2156                 tl(fds) = fds1;
2157                 fds1    = fds;
2158             }
2159             fds = next;
2160         }
2161         fds = fds1;
2162     }
2163     return vs;
2164 }
2165
2166 Bool isAmbiguous(type)                  /* Determine whether type is       */
2167 Type type; {                            /* ambiguous                       */
2168     if (isPolyType(type)) {
2169         type = monotypeOf(type);
2170     }
2171     if (isQualType(type)) {             /* only qualified types can be     */
2172         List ps   = fst(snd(type));     /* ambiguous                       */
2173         List tvps = offsetTyvarsIn(ps,NIL);
2174         List tvts = offsetTyvarsIn(snd(snd(type)),NIL);
2175         List fds  = calcFunDeps(ps);
2176
2177         tvts = oclose(fds,tvts);        /* Close tvts under fds            */
2178         return !osubset(tvps,tvts);
2179     }
2180     return FALSE;
2181 }
2182
2183 List calcFunDeps(ps)
2184 List ps; {
2185     List fds  = NIL;
2186     for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies        */
2187         Cell pi = hd(ps);
2188         Cell c  = getHead(pi);
2189         if (isClass(c)) {
2190             List xfs = cclass(c).xfds;
2191             for (; nonNull(xfs); xfs=tl(xfs)) {
2192                 List fs = snd(hd(xfs));
2193                 for (; nonNull(fs); fs=tl(fs)) {
2194                     fds = cons(pair(otvars(pi,fst(hd(fs))),
2195                                     otvars(pi,snd(hd(fs)))),fds);
2196                 }
2197             }
2198         }
2199 #if IPARAM
2200         else if (isIP(c)) {
2201             fds = cons(pair(NIL,offsetTyvarsIn(arg(pi),NIL)),fds);
2202         }
2203 #endif
2204     }
2205     return fds;
2206 }
2207
2208 List calcFunDepsPreds(ps)
2209 List ps; {
2210     List fds  = NIL;
2211     for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies        */
2212         Cell pi3 = hd(ps);
2213         Cell pi = fst3(pi3);
2214         Cell c  = getHead(pi);
2215         Int o = intOf(snd3(pi3));
2216         if (isClass(c)) {
2217             List xfs = cclass(c).xfds;
2218             for (; nonNull(xfs); xfs=tl(xfs)) {
2219                 List fs = snd(hd(xfs));
2220                 for (; nonNull(fs); fs=tl(fs)) {
2221                     fds = cons(pair(otvarsZonk(pi,fst(hd(fs)),o),
2222                                     otvarsZonk(pi,snd(hd(fs)),o)),fds);
2223                 }
2224             }
2225         }
2226 #if IPARAM
2227         else if (isIP(c)) {
2228             fds = cons(pair(NIL,zonkTyvarsIn(arg(pi),NIL)),fds);
2229         }
2230 #endif
2231     }
2232     return fds;
2233 }
2234
2235 Void ambigError(line,where,e,type)      /* produce error message for       */
2236 Int    line;                            /* ambiguity                       */
2237 String where;
2238 Cell   e;
2239 Type   type; {
2240     ERRMSG(line) "Ambiguous type signature in %s", where ETHEN
2241     ERRTEXT      "\n*** ambiguous type : " ETHEN ERRTYPE(type);
2242     if (nonNull(e)) {
2243         ERRTEXT  "\n*** assigned to    : " ETHEN ERREXPR(e);
2244     }
2245     ERRTEXT      "\n"
2246     EEND;
2247 }
2248
2249 /* --------------------------------------------------------------------------
2250  * Kind inference for simple types:
2251  * ------------------------------------------------------------------------*/
2252
2253 static Void local kindConstr(line,alpha,m,c)
2254 Int  line;                              /* Determine kind of constructor   */
2255 Int  alpha;
2256 Int  m;
2257 Cell c; {
2258     Cell h = getHead(c);
2259     Int  n = argCount;
2260
2261 #ifdef DEBUG_KINDS
2262     Printf("kindConstr: alpha=%d, m=%d, c=",alpha,m);
2263     printType(stdout,c);
2264     Printf("\n");
2265 #endif
2266
2267     switch (whatIs(h)) {
2268         case POLYTYPE : if (n!=0) {
2269                             internal("kindConstr1");
2270                         } else {
2271                             static String pt = "polymorphic type";
2272                             Type  t  = dropRank1(c,alpha,m);
2273                             Kinds ks = polySigOf(t);
2274                             Int   m1 = 0;
2275                             Int   beta;
2276                             for (; isAp(ks); ks=tl(ks)) {
2277                                 m1++;
2278                             }
2279                             beta        = newKindvars(m1);
2280                             unkindTypes = cons(pair(mkInt(beta),t),unkindTypes);
2281                             checkKind(line,beta,m1,monotypeOf(t),NIL,pt,STAR,0);
2282                         }
2283                         return;
2284
2285         case CDICTS   :
2286         case QUAL     : if (n!=0) {
2287                             internal("kindConstr2");
2288                         }
2289                         map3Proc(kindPred,line,alpha,m,fst(snd(c)));
2290                         kindConstr(line,alpha,m,snd(snd(c)));
2291                         return;
2292
2293         case EXIST    :
2294         case RANK2    : kindConstr(line,alpha,m,snd(snd(c)));
2295                         return;
2296
2297 #if TREX
2298         case EXT      : if (n!=2) {
2299                             ERRMSG(line)
2300                                 "Illegal use of row in " ETHEN ERRTYPE(c);
2301                             ERRTEXT "\n"
2302                             EEND;
2303                         }
2304                         break;
2305 #endif
2306
2307         case TYCON    : if (isSynonym(h) && n<tycon(h).arity) {
2308                             ERRMSG(line)
2309                               "Not enough arguments for type synonym \"%s\"",
2310                               textToStr(tycon(h).text)
2311                             EEND;
2312                         }
2313                         break;
2314     }
2315
2316     if (n==0) {                         /* trivial case, no arguments      */
2317         typeIs = kindAtom(alpha,c);
2318     } else {                            /* non-trivial application         */
2319         static String app = "constructor application";
2320         Cell   a = c;
2321         Int    i;
2322         Kind   k;
2323         Int    beta;
2324
2325         varKind(n);
2326         beta   = typeOff;
2327         k      = typeIs;
2328
2329         typeIs = kindAtom(alpha,h);     /* h  :: v1 -> ... -> vn -> w      */
2330         shouldKind(line,h,c,app,k,beta);
2331
2332         for (i=n; i>0; --i) {           /* ci :: vi for each 1 <- 1..n     */
2333             checkKind(line,alpha,m,arg(a),c,app,aVar,beta+i-1);
2334             a = fun(a);
2335         }
2336         tyvarType(beta+n);              /* inferred kind is w              */
2337     }
2338 }
2339
2340 static Kind local kindAtom(alpha,c)     /* Find kind of atomic constructor */
2341 Int  alpha;
2342 Cell c; {
2343     switch (whatIs(c)) {
2344         case TUPLE     : return simpleKind(tupleOf(c)); /*(,)::* -> * -> * */
2345         case OFFSET    : return mkInt(alpha+offsetOf(c));
2346         case TYCON     : return tycon(c).kind;
2347         case INTCELL   : return c;
2348         case VARIDCELL :
2349         case VAROPCELL : {   Cell vt = findBtyvs(textOf(c));
2350                              if (nonNull(vt)) {
2351                                  return snd(vt);
2352                              }
2353                          }
2354 #if TREX
2355         case EXT       : return extKind;
2356 #endif
2357     }
2358 #if DEBUG_KINDS
2359     Printf("kindAtom(%d,whatIs(%d)) on ",alpha,whatIs(c));
2360     printType(stdout,c);
2361     Printf("\n");
2362 #endif
2363     internal("kindAtom");
2364     return STAR;/* not reached */
2365 }
2366
2367 static Void local kindPred(l,alpha,m,pi)/* Check kinds of arguments in pred*/
2368 Int  l;
2369 Int  alpha;
2370 Int  m;
2371 Cell pi; {
2372 #if TREX
2373     if (isAp(pi) && isExt(fun(pi))) {
2374         static String lackspred = "lacks predicate";
2375         checkKind(l,alpha,m,arg(pi),NIL,lackspred,ROW,0);
2376         return;
2377     }
2378 #endif
2379 #if IPARAM
2380     if (isAp(pi) && whatIs(fun(pi)) == IPCELL) {
2381         static String ippred = "iparam predicate";
2382         checkKind(l,alpha,m,arg(pi),NIL,ippred,STAR,0);
2383         return;
2384     }
2385 #endif
2386     {   static String predicate = "class constraint";
2387         Class c  = getHead(pi);
2388         List  as = getArgs(pi);
2389         Kinds ks = cclass(c).kinds;
2390
2391         while (nonNull(ks)) {
2392             checkKind(l,alpha,m,hd(as),NIL,predicate,hd(ks),0);
2393             ks = tl(ks);
2394             as = tl(as);
2395         }
2396     }
2397 }
2398
2399 static Void local kindType(line,wh,type)/* check that (poss qualified) type*/
2400 Int    line;                            /* is well-kinded                  */
2401 String wh;
2402 Type   type; {
2403     checkKind(line,0,0,type,NIL,wh,STAR,0);
2404 }
2405
2406 static Void local fixKinds() {          /* add kind annotations to types   */
2407     for (; nonNull(unkindTypes); unkindTypes=tl(unkindTypes)) {
2408         Pair pr   = hd(unkindTypes);
2409         Int  beta = intOf(fst(pr));
2410         Cell qts  = polySigOf(snd(pr));
2411         for (;;) {
2412             if (isNull(hd(qts))) {
2413                 hd(qts) = copyKindvar(beta++);
2414             } else {
2415                 internal("fixKinds");
2416             }
2417             if (nonNull(tl(qts))) {
2418                 qts = tl(qts);
2419             } else {
2420                 tl(qts) = STAR;
2421                 break;
2422             }
2423         }
2424 #ifdef DEBUG_KINDS
2425         Printf("Type expression: ");
2426         printType(stdout,snd(pr));
2427         Printf(" :: ");
2428         printKind(stdout,polySigOf(snd(pr)));
2429         Printf("\n");
2430 #endif
2431     }
2432 }
2433
2434 /* --------------------------------------------------------------------------
2435  * Kind checking of groups of type constructors and classes:
2436  * ------------------------------------------------------------------------*/
2437
2438 static Void local kindTCGroup(tcs)      /* find kinds for mutually rec. gp */
2439 List tcs; {                             /* of tycons and classes           */
2440     emptySubstitution();
2441     unkindTypes = NIL;
2442     mapProc(initTCKind,tcs);
2443     mapProc(kindTC,tcs);
2444     mapProc(genTC,tcs);
2445     fixKinds();
2446     emptySubstitution();
2447 }
2448     
2449 static Void local initTCKind(c)         /* build initial kind/arity for c  */
2450 Cell c; {
2451     if (isTycon(c)) {                   /* Initial kind of tycon is:       */
2452         Int beta = newKindvars(1);      /*    v1 -> ... -> vn -> vn+1      */
2453         varKind(tycon(c).arity);        /* where n is the arity of c.      */
2454         bindTv(beta,typeIs,typeOff);    /* For data definitions, vn+1 == * */
2455         switch (whatIs(tycon(c).what)) {
2456             case NEWTYPE  :
2457             case DATATYPE : bindTv(typeOff+tycon(c).arity,STAR,0);
2458         }
2459         tycon(c).kind = mkInt(beta);
2460     } else {
2461         Int n    = cclass(c).arity;
2462         Int beta = newKindvars(n);
2463         cclass(c).kinds = NIL;
2464         while (n>0) {
2465             n--;
2466             cclass(c).kinds = pair(mkInt(beta+n),cclass(c).kinds);
2467         }
2468     }
2469 }
2470
2471 static Void local kindTC(c)             /* check each part of a tycon/class*/
2472 Cell c; {                               /* is well-kinded                  */
2473     if (isTycon(c)) {
2474         static String cfun = "constructor function";
2475         static String tsyn = "synonym definition";
2476         Int line = tycon(c).line;
2477         Int beta = tyvar(intOf(tycon(c).kind))->offs;
2478         Int m    = tycon(c).arity;
2479         switch (whatIs(tycon(c).what)) {
2480             case NEWTYPE     :
2481             case DATATYPE    : {   List cs = tycon(c).defn;
2482                                    if (isQualType(cs)) {
2483                                        map3Proc(kindPred,line,beta,m,
2484                                                                 fst(snd(cs)));
2485                                        tycon(c).defn = cs = snd(snd(cs));
2486                                    }
2487                                    for (; hasCfun(cs); cs=tl(cs)) {
2488                                        kindType(line,cfun,name(hd(cs)).type);
2489                                    }
2490                                    break;
2491                                }
2492
2493             default          : checkKind(line,beta,m,tycon(c).defn,NIL,
2494                                                         tsyn,aVar,beta+m);
2495         }
2496     }
2497     else {                              /* scan type exprs in class defn to*/
2498         List ms   = fst(cclass(c).members);
2499         Int  m    = cclass(c).arity;    /* determine the class signature   */
2500         Int  beta = newKindvars(m);
2501         kindPred(cclass(c).line,beta,m,cclass(c).head);
2502         map3Proc(kindPred,cclass(c).line,beta,m,cclass(c).supers);
2503         for (; nonNull(ms); ms=tl(ms)) {
2504             Int  line = intOf(fst3(hd(ms)));
2505             Type type = thd3(hd(ms));
2506             kindType(line,"member function type signature",type);
2507         }
2508     }
2509 }
2510
2511 static Void local genTC(c)              /* generalise kind inferred for    */
2512 Cell c; {                               /* given tycon/class               */
2513     if (isTycon(c)) {
2514         tycon(c).kind = copyKindvar(intOf(tycon(c).kind));
2515 #ifdef DEBUG_KINDS
2516         Printf("%s :: ",textToStr(tycon(c).text));
2517         printKind(stdout,tycon(c).kind);
2518         Putchar('\n');
2519 #endif
2520     } else {
2521         Kinds ks = cclass(c).kinds;
2522         for (; nonNull(ks); ks=tl(ks)) {
2523             hd(ks) = copyKindvar(intOf(hd(ks)));
2524         }
2525 #ifdef DEBUG_KINDS
2526         Printf("%s :: ",textToStr(cclass(c).text));
2527         printKinds(stdout,cclass(c).kinds);
2528         Putchar('\n');
2529 #endif
2530     }
2531 }
2532
2533 /* --------------------------------------------------------------------------
2534  * Static analysis of instance declarations:
2535  *
2536  * The first part of the static analysis is performed as the declarations
2537  * are read during parsing:
2538  * - make new entry in instance table
2539  * - record line number of declaration
2540  * - build list of instances defined in current script for use in later
2541  *   stages of static analysis.
2542  * ------------------------------------------------------------------------*/
2543
2544 Void instDefn(line,head,ms)            /* process new instance definition  */
2545 Int  line;                             /* definition line number           */
2546 Cell head;                             /* inst header :: (context,Class)   */
2547 List ms; {                             /* instance members                 */
2548     Inst nw             = newInst();
2549     inst(nw).line       = line;
2550     inst(nw).specifics  = fst(head);
2551     inst(nw).head       = snd(head);
2552     inst(nw).implements = ms;
2553     instDefns           = cons(nw,instDefns);
2554 }
2555
2556 /* --------------------------------------------------------------------------
2557  * Further static analysis of instance declarations:
2558  *
2559  * Makes the following checks:
2560  * - Class part of header has form C (T a1 ... an) where C is a known
2561  *   class, and T is a known datatype constructor (or restricted synonym),
2562  *   and there is no previous C-T instance, and (T a1 ... an) has a kind
2563  *   appropriate for the class C.
2564  * - Each element of context is a valid class expression, with type vars
2565  *   drawn from a1, ..., an.
2566  * - All bindings are function bindings
2567  * - All bindings define member functions for class C
2568  * - Arrange bindings into appropriate order for member list
2569  * - No top level type signature declarations
2570  * ------------------------------------------------------------------------*/
2571
2572 Bool allowOverlap = FALSE;              /* TRUE => allow overlapping insts */
2573 Name nameListMonad = NIL;               /* builder function for List Monad */
2574
2575 static Void local checkInstDefn(in)     /* Validate instance declaration   */
2576 Inst in; {
2577     Int  line   = inst(in).line;
2578     List tyvars = typeVarsIn(inst(in).head,NIL,NIL,NIL);
2579     List tvps = NIL, tvts = NIL;
2580     List fds = NIL;
2581
2582     if (haskell98) {                    /* Check for `simple' type         */
2583         List tvs = NIL;
2584         Cell t   = arg(inst(in).head);
2585         for (; isAp(t); t=fun(t)) {
2586             if (!isVar(arg(t))) {
2587                 ERRMSG(line)
2588                    "syntax error in instance head (variable expected)"
2589                 EEND;
2590             }
2591             if (varIsMember(textOf(arg(t)),tvs)) {
2592                 ERRMSG(line) "repeated type variable \"%s\" in instance head",
2593                              textToStr(textOf(arg(t)))
2594                 EEND;
2595             }
2596             tvs = cons(arg(t),tvs);
2597         }
2598         if (isVar(t)) {
2599             ERRMSG(line)
2600                 "syntax error in instance head (constructor expected)"
2601             EEND;
2602         }
2603     }
2604
2605     /* add in the tyvars from the `specifics' so that we don't
2606        prematurely complain about undefined tyvars */
2607     tyvars = typeVarsIn(inst(in).specifics,NIL,NIL,tyvars);
2608     inst(in).head = depPredExp(line,tyvars,inst(in).head);
2609
2610     if (haskell98) {
2611         Type h = getHead(arg(inst(in).head));
2612         if (isSynonym(h)) {
2613             ERRMSG(line) "Cannot use type synonym in instance head"
2614             EEND;
2615         }
2616     }
2617
2618     map2Over(depPredExp,line,tyvars,inst(in).specifics);
2619
2620     /* OK, now we start over, and test for ambiguity */
2621     tvts = offsetTyvarsIn(inst(in).head,NIL);
2622     tvps = offsetTyvarsIn(inst(in).specifics,NIL);
2623     fds  = calcFunDeps(inst(in).specifics);
2624     tvts = oclose(fds,tvts);
2625     tvts = odiff(tvps,tvts);
2626     if (!isNull(tvts)) {
2627         ERRMSG(line) "Undefined type variable \"%s\"",
2628           textToStr(textOf(nth(offsetOf(hd(tvts)),tyvars)))
2629         EEND;
2630     }
2631
2632     h98CheckCtxt(line,"instance definition",FALSE,inst(in).specifics,NIL);
2633     inst(in).numSpecifics = length(inst(in).specifics);
2634     inst(in).c            = getHead(inst(in).head);
2635     if (!isClass(inst(in).c)) {
2636         ERRMSG(line) "Illegal predicate in instance declaration"
2637         EEND;
2638     }
2639
2640     if (nonNull(cclass(inst(in).c).fds)) {
2641         List fds = cclass(inst(in).c).fds;
2642         for (; nonNull(fds); fds=tl(fds)) {
2643             List as = otvars(inst(in).head, fst(hd(fds)));
2644             List bs = otvars(inst(in).head, snd(hd(fds)));
2645             List fs = calcFunDeps(inst(in).specifics);
2646             as = oclose(fs,as);
2647             if (!osubset(bs,as)) {
2648                 ERRMSG(inst(in).line)
2649                    "Instance is more general than a dependency allows"
2650                 ETHEN
2651                 ERRTEXT "\n*** Instance         : "
2652                 ETHEN ERRPRED(inst(in).head);
2653                 ERRTEXT "\n*** For class        : "
2654                 ETHEN ERRPRED(cclass(inst(in).c).head);
2655                 ERRTEXT "\n*** Under dependency : "
2656                 ETHEN ERRFD(hd(fds));
2657                 ERRTEXT "\n"
2658                 EEND;
2659             }
2660         }
2661     }
2662
2663     kindInst(in,length(tyvars));
2664     insertInst(in);
2665
2666     if (nonNull(extractSigdecls(inst(in).implements))) {
2667         ERRMSG(line)
2668           "Type signature declarations not permitted in instance declaration"
2669         EEND;
2670     }
2671     if (nonNull(extractFixdecls(inst(in).implements))) {
2672         ERRMSG(line)
2673           "Fixity declarations not permitted in instance declaration"
2674         EEND;
2675     }
2676     inst(in).implements = classBindings("instance",
2677                                         inst(in).c,
2678                                         extractBindings(inst(in).implements));
2679     inst(in).builder    = newInstImp(in);
2680     if (!preludeLoaded && isNull(nameListMonad) && isAp(inst(in).head)
2681         && fun(inst(in).head)==classMonad && arg(inst(in).head)==typeList) {
2682         nameListMonad = inst(in).builder;
2683     }
2684 }
2685
2686 static Void local insertInst(in)        /* Insert instance into class      */
2687 Inst in; {
2688     Class c    = inst(in).c;
2689     List  ins  = cclass(c).instances;
2690     List  prev = NIL;
2691
2692     if (nonNull(cclass(c).fds)) {       /* Check for conflicts with fds    */
2693         List ins1 = cclass(c).instances;
2694         for (; nonNull(ins1); ins1=tl(ins1)) {
2695             List fds = cclass(c).fds;
2696             substitution(RESET);
2697             for (; nonNull(fds); fds=tl(fds)) {
2698                 Int  alpha = newKindedVars(inst(in).kinds);
2699                 Int  beta  = newKindedVars(inst(hd(ins1)).kinds);
2700                 List as    = fst(hd(fds));
2701                 Bool same  = TRUE;
2702                 for (; same && nonNull(as); as=tl(as)) {
2703                     Int n = offsetOf(hd(as));
2704                     same &= unify(nthArg(n,inst(in).head),alpha,
2705                                   nthArg(n,inst(hd(ins1)).head),beta);
2706                 }
2707                 if (isNull(as) && same) {
2708                     for (as=snd(hd(fds)); same && nonNull(as); as=tl(as)) {
2709                         Int n = offsetOf(hd(as));
2710                         same &= sameType(nthArg(n,inst(in).head),alpha,
2711                                          nthArg(n,inst(hd(ins1)).head),beta);
2712                     }
2713                     if (!same) {
2714                         ERRMSG(inst(in).line)
2715                            "Instances are not consistent with dependencies"
2716                         ETHEN
2717                         ERRTEXT "\n*** This instance    : "
2718                         ETHEN ERRPRED(inst(in).head);
2719                         ERRTEXT "\n*** Conflicts with   : "
2720                         ETHEN ERRPRED(inst(hd(ins)).head);
2721                         ERRTEXT "\n*** For class        : "
2722                         ETHEN ERRPRED(cclass(c).head);
2723                         ERRTEXT "\n*** Under dependency : "
2724                         ETHEN ERRFD(hd(fds));
2725                         ERRTEXT "\n"
2726                         EEND;
2727                     }
2728                 }
2729             }
2730         }
2731     }
2732
2733
2734     substitution(RESET);
2735     while (nonNull(ins)) {              /* Look for overlap w/ other insts */
2736         Int alpha = newKindedVars(inst(in).kinds);
2737         Int beta  = newKindedVars(inst(hd(ins)).kinds);
2738         if (unifyPred(inst(in).head,alpha,inst(hd(ins)).head,beta)) {
2739             Cell pi  = copyPred(inst(in).head,alpha);
2740             if (allowOverlap && !haskell98) {
2741                 Bool bef = instCompare(in,hd(ins));
2742                 Bool aft = instCompare(hd(ins),in);
2743                 if (bef && !aft) {      /* in comes strictly before hd(ins)*/
2744                     break;
2745                 }
2746                 if (aft && !bef) {      /* in comes strictly after hd(ins) */
2747                     prev = ins;
2748                     ins  = tl(ins);
2749                     continue;
2750                 }
2751             }
2752 #if MULTI_INST
2753             if (multiInstRes && nonNull(inst(in).specifics)) {
2754                 break;
2755             } else {
2756 #endif
2757             ERRMSG(inst(in).line) "Overlapping instances for class \"%s\"",
2758                                   textToStr(cclass(c).text)
2759             ETHEN
2760             ERRTEXT "\n*** This instance   : " ETHEN ERRPRED(inst(in).head);
2761             ERRTEXT "\n*** Overlaps with   : " ETHEN
2762                                                ERRPRED(inst(hd(ins)).head);
2763             ERRTEXT "\n*** Common instance : " ETHEN
2764                                                ERRPRED(pi);
2765             ERRTEXT "\n"
2766             EEND;
2767         }
2768 #if MULTI_INST
2769             }
2770 #endif
2771         prev = ins;                     /* No overlap detected, so move on */
2772         ins  = tl(ins);                 /* to next instance                */
2773     }
2774     substitution(RESET);
2775
2776     if (nonNull(prev)) {                /* Insert instance at this point   */
2777         tl(prev) = cons(in,ins);
2778     } else {
2779         cclass(c).instances = cons(in,ins);
2780     }
2781 }
2782
2783 static Bool local instCompare(ia,ib)    /* See if ia is an instance of ib  */
2784 Inst ia, ib;{
2785     Int alpha = newKindedVars(inst(ia).kinds);
2786     Int beta  = newKindedVars(inst(ib).kinds);
2787     return matchPred(inst(ia).head,alpha,inst(ib).head,beta);
2788 }
2789
2790 static Name local newInstImp(in)        /* Make definition for inst builder*/
2791 Inst in; {
2792     Name b         = newName(inventText(),in);
2793     name(b).line   = inst(in).line;
2794     name(b).arity  = inst(in).numSpecifics;
2795     name(b).number = DFUNNAME;
2796     return b;
2797 }
2798
2799 /* --------------------------------------------------------------------------
2800  * Kind checking of instance declaration headers:
2801  * ------------------------------------------------------------------------*/
2802
2803 static Void local kindInst(in,freedom)  /* check predicates in instance    */
2804 Inst in;
2805 Int  freedom; {
2806     Int beta;
2807
2808     emptySubstitution();
2809     beta = newKindvars(freedom);
2810     kindPred(inst(in).line,beta,freedom,inst(in).head);
2811     if (whatIs(inst(in).specifics)!=DERIVE) {
2812         map3Proc(kindPred,inst(in).line,beta,freedom,inst(in).specifics);
2813     }
2814     for (inst(in).kinds = NIL; 0<freedom--; ) {
2815         inst(in).kinds = cons(copyKindvar(beta+freedom),inst(in).kinds);
2816     }
2817 #ifdef DEBUG_KINDS
2818     Printf("instance ");
2819     printPred(stdout,inst(in).head);
2820     Printf(" :: ");
2821     printKinds(stdout,inst(in).kinds);
2822     Putchar('\n');
2823 #endif
2824     emptySubstitution();
2825 }
2826
2827 /* --------------------------------------------------------------------------
2828  * Process derived instance requests:
2829  * ------------------------------------------------------------------------*/
2830
2831 static List derivedInsts;               /* list of derived instances       */
2832
2833 static Void local checkDerive(t,p,ts,ct)/* verify derived instance request */
2834 Tycon t;                                /* for tycon t, with explicit      */
2835 List  p;                                /* context p, component types ts   */
2836 List  ts;                               /* and named class ct              */
2837 Cell  ct; {
2838     Int   line = tycon(t).line;
2839     Class c    = findQualClass(ct);
2840     if (isNull(c)) {
2841         ERRMSG(line) "Unknown class \"%s\" in derived instance",
2842                      identToStr(ct)
2843         EEND;
2844     }
2845     addDerInst(line,c,p,dupList(ts),t,tycon(t).arity);
2846 }
2847
2848 static Void local addDerInst(line,c,p,cts,t,a)  /* Add a derived instance  */
2849 Int   line;
2850 Class c;
2851 List  p, cts;
2852 Type  t;
2853 Int   a; {
2854     Inst in;
2855     Cell head = t;                              /* Build instance head     */
2856     Int  i    = 0;
2857
2858     for (; i<a; i++) {
2859         head = ap(head,mkOffset(i));
2860     }
2861     head = ap(c,head);
2862
2863     in                  = newInst();
2864     inst(in).c          = c;
2865     inst(in).line       = line;
2866     inst(in).head       = head;
2867     inst(in).specifics  = ap(DERIVE,pair(dupList(p),cts));
2868     inst(in).implements = NIL;
2869     inst(in).kinds      = mkInt(a);
2870     derivedInsts        = cons(in,derivedInsts);
2871 }
2872
2873 Void addTupInst(c,n)                    /* Request derived instance of c   */
2874 Class c;                                /* for mkTuple(n) constructor      */
2875 Int   n; {
2876     Int  m   = n;
2877     List cts = NIL;
2878     while (0<m--) {
2879         cts = cons(mkOffset(m),cts);
2880     }
2881     cts = rev(cts);
2882     addDerInst(0,c,NIL,cts,mkTuple(n),n);
2883 }
2884
2885 #if TREX
2886 Inst addRecShowInst(c,e)                /* Generate instance for ShowRecRow*/
2887 Class c;                                /* c *must* be ShowRecRow          */
2888 Ext   e; {
2889     Inst in               = newInst();
2890     inst(in).c            = c;
2891     inst(in).head         = ap(c,ap2(e,aVar,bVar));
2892     inst(in).kinds        = extKind;
2893     inst(in).specifics    = cons(ap(classShow,aVar),
2894                                  cons(ap(e,bVar),
2895                                       cons(ap(c,bVar),NIL)));
2896     inst(in).numSpecifics = 3;
2897     inst(in).builder      = implementRecShw(extText(e),in);
2898     cclass(c).instances   = appendOnto(cclass(c).instances,singleton(in));
2899     return in;
2900 }
2901
2902 Inst addRecEqInst(c,e)                  /* Generate instance for EqRecRow  */
2903 Class c;                                /* c *must* be EqRecRow            */
2904 Ext   e; {
2905     Inst in               = newInst();
2906     inst(in).c            = c;
2907     inst(in).head         = ap(c,ap2(e,aVar,bVar));
2908     inst(in).kinds        = extKind;
2909     inst(in).specifics    = cons(ap(classEq,aVar),
2910                                  cons(ap(e,bVar),
2911                                       cons(ap(c,bVar),NIL)));
2912     inst(in).numSpecifics = 3;
2913     inst(in).builder      = implementRecEq(extText(e),in);
2914     cclass(c).instances   = appendOnto(cclass(c).instances,singleton(in));
2915     return in;
2916 }
2917 #endif
2918
2919 /* --------------------------------------------------------------------------
2920  * Calculation of contexts for derived instances:
2921  *
2922  * Allowing arbitrary types to appear in contexts makes it rather harder
2923  * to decide what the context for a derived instance should be.  For
2924  * example, given:
2925  *
2926  *    data T a = MkT [a] deriving Show,
2927  *
2928  * we could have either of the following:
2929  *
2930  *    instance (Show [a]) => Show (T a) where ...
2931  *    instance (Show a) => Show (T a) where ...
2932  *
2933  * (assuming, of course, that instance (Show a) => Show [a]).  For now, we
2934  * choose to reduce contexts in the hope of detecting errors at an earlier
2935  * stage---in contrast with value definitions, there is no way for a user
2936  * to provide something analogous to a `type signature' by which they might
2937  * be able to control this behaviour themselves.  We eliminate tautological
2938  * predicates, but only allow predicates to appear in the final result if
2939  * they have at least one argument with a variable at its head.
2940  *
2941  * In general, we have to deal with mutually recursive instance declarations.
2942  * We find a solution in the obvious way by iterating to find a fixed point.
2943  * Of course, without restrictions on the form of instance declarations, we
2944  * cannot be sure that this will always terminate!
2945  *
2946  * For each instance we maintain a pair of the form DERIVE (ctxt,ps).
2947  * Ctxt is a list giving the parts of the context that have been produced
2948  * so far in the form of predicate skeletons.  During the calculation of
2949  * derived instances, we attach a dummy NIL value to the end of the list
2950  * which acts as a kind of `variable': other parts of the system maintain
2951  * pointers to this variable, and use it to detect when the context has
2952  * been extended with new elements.  Meanwhile, ps is a list containing
2953  * predicates (pi,o) together with (delayed) substitutions of the form
2954  * (o,xs) where o is an offset and xs is one of the context variables
2955  * described above, which may have been partially instantiated.
2956  * ------------------------------------------------------------------------*/
2957
2958 static Bool instsChanged;
2959
2960 static Void local deriveContexts(is)    /* Calc contexts for derived insts */
2961 List is; {
2962     emptySubstitution();
2963     mapProc(initDerInst,is);            /* Prepare derived instances       */
2964
2965     do {                                /* Main calculation of contexts    */
2966         instsChanged = FALSE;
2967         mapProc(calcInstPreds,is);
2968     } while (instsChanged);
2969
2970     mapProc(tidyDerInst,is);            /* Tidy up results                 */
2971 }
2972
2973 static Void local initDerInst(in)       /* Prepare instance for calculation*/
2974 Inst in; {                              /* of derived instance context     */
2975     Cell spcs = inst(in).specifics;
2976     Int  beta = newKindedVars(inst(in).kinds);
2977     if (whatIs(spcs)!=DERIVE) {
2978         internal("initDerInst");
2979     }
2980     fst(snd(spcs)) = appendOnto(fst(snd(spcs)),singleton(NIL));
2981     for (spcs=snd(snd(spcs)); nonNull(spcs); spcs=tl(spcs)) {
2982         hd(spcs) = ap2(inst(in).c,hd(spcs),mkInt(beta));
2983     }
2984     inst(in).numSpecifics = beta;
2985
2986 #ifdef DEBUG_DERIVING
2987     Printf("initDerInst: ");
2988     printPred(stdout,inst(in).head);
2989     Printf("\n");
2990     printContext(stdout,snd(snd(inst(in).specifics)));
2991     Printf("\n");
2992 #endif
2993 }
2994
2995 static Void local calcInstPreds(in)     /* Calculate next approximation    */
2996 Inst in; {                              /* of the context for a derived    */
2997     List retain = NIL;                  /* instance                        */
2998     List ps     = snd(snd(inst(in).specifics));
2999     List spcs   = fst(snd(inst(in).specifics));
3000     Int  beta   = inst(in).numSpecifics;
3001     Int  its    = 1;
3002     Int  factor = 1+length(ps);
3003
3004 #ifdef DEBUG_DERIVING
3005     Printf("calcInstPreds: ");
3006     printPred(stdout,inst(in).head);
3007     Printf("\n");
3008 #endif
3009
3010     while (nonNull(ps)) {
3011         Cell p = hd(ps);
3012         ps     = tl(ps);
3013         if (its++ >= factor*cutoff) {
3014             Cell bpi = inst(in).head;
3015             ERRMSG(inst(in).line) "\n*** Cannot derive " ETHEN ERRPRED(bpi);
3016             ERRTEXT " after %d iterations.", its-1   ETHEN
3017             ERRTEXT
3018                 "\n*** This may indicate that the problem is undecidable.  However,\n"
3019             ETHEN ERRTEXT
3020                 "*** you may still try to increase the cutoff limit using the -c\n"
3021             ETHEN ERRTEXT
3022                 "*** option and then try again.  (The current setting is -c%d)\n",
3023                 cutoff
3024             EEND;
3025         }
3026         if (isInt(fst(p))) {                    /* Delayed substitution?   */
3027             List qs = snd(p);
3028             for (; nonNull(hd(qs)); qs=tl(qs)) {
3029                 ps = cons(pair(hd(qs),fst(p)),ps);
3030             }
3031             retain = cons(pair(fst(p),qs),retain);
3032         }
3033 #if TREX
3034         else if (isExt(fun(fst(p)))) {          /* Lacks predicate         */
3035             Text   l = extText(fun(fst(p)));
3036             Type   t = arg(fst(p));
3037             Int    o = intOf(snd(p));
3038             Type   h;
3039             Tyvar *tyv;
3040
3041             deRef(tyv,t,o);
3042             h = getDerefHead(t,o);
3043             while (isExt(h) && argCount==2 && l!=extText(h)) {
3044                 t = arg(t);
3045                 deRef(tyv,t,o);
3046                 h = getDerefHead(t,o);
3047             }
3048             if (argCount==0 && isOffset(h)) {
3049                 maybeAddPred(ap(fun(fun(p)),h),o,beta,spcs);
3050             } else if (argCount!=0 || h!=typeNoRow) {
3051                 Cell bpi = inst(in).head;
3052                 Cell pi  = copyPred(fun(p),intOf(snd(p)));
3053                 ERRMSG(inst(in).line) "Cannot derive " ETHEN ERRPRED(bpi);
3054                 ERRTEXT " because predicate " ETHEN ERRPRED(pi);
3055                 ERRTEXT " does not hold\n"
3056                 EEND;
3057             }
3058         }
3059 #endif
3060         else {                                  /* Class predicate         */
3061             Cell pi  = fst(p);
3062             Int  o   = intOf(snd(p));
3063             Inst in1 = findInstFor(pi,o);
3064             if (nonNull(in1)) {
3065                 List qs  = inst(in1).specifics;
3066                 Int  off = mkInt(typeOff);
3067                 if (whatIs(qs)==DERIVE) {       /* Still being derived     */
3068                     for (qs=fst(snd(qs)); nonNull(hd(qs)); qs=tl(qs)) {
3069                         ps = cons(pair(hd(qs),off),ps);
3070                     }
3071                     retain = cons(pair(off,qs),retain);
3072                 } else {                        /* Previously def'd inst   */
3073                     for (; nonNull(qs); qs=tl(qs)) {
3074                         ps = cons(pair(hd(qs),off),ps);
3075                     }
3076                 }
3077             } else {                            /* No matching instance    */
3078                 Cell qi = pi;
3079                 while (isAp(qi) && isOffset(getDerefHead(arg(qi),o))) {
3080                     qi = fun(qi);
3081                 }
3082                 if (isAp(qi)) {
3083                     Cell bpi = inst(in).head;
3084                     pi       = copyPred(pi,o);
3085                     ERRMSG(inst(in).line) "An instance of " ETHEN ERRPRED(pi);
3086                     ERRTEXT " is required to derive "       ETHEN ERRPRED(bpi);
3087                     ERRTEXT "\n"
3088                     EEND;
3089                 } else {
3090                     maybeAddPred(pi,o,beta,spcs);
3091                 }
3092             }
3093         }
3094     }
3095     snd(snd(inst(in).specifics)) = retain;
3096 }
3097
3098 static Void local maybeAddPred(pi,o,beta,ps)
3099 Cell pi;                                /* Add predicate pi to the list ps,*/
3100 Int  o;                                 /* setting the instsChanged flag if*/
3101 Int  beta;                              /* pi is not already a member and  */
3102 List ps; {                              /* using beta to adjust vars       */
3103     Cell c = getHead(pi);
3104     for (; nonNull(ps); ps=tl(ps)) {
3105         if (isNull(hd(ps))) {           /* reached the `dummy' end of list?*/
3106             hd(ps)       = copyAdj(pi,o,beta);
3107             tl(ps)       = pair(NIL,NIL);
3108             instsChanged = TRUE;
3109             return;
3110         } else if (c==getHead(hd(ps)) && samePred(pi,o,hd(ps),beta)) {
3111             return;
3112         }
3113     }
3114 }
3115
3116 static Cell local copyAdj(c,o,beta)     /* Copy (c,o), replacing vars with */
3117 Cell c;                                 /* offsets relative to beta.       */
3118 Int  o;
3119 Int  beta; {
3120     switch (whatIs(c)) {
3121         case AP     : {   Cell l = copyAdj(fst(c),o,beta);
3122                           Cell r = copyAdj(snd(c),o,beta);
3123                           return ap(l,r);
3124                       }
3125
3126         case OFFSET : {   Int   vn   = o+offsetOf(c);
3127                           Tyvar *tyv = tyvar(vn);
3128                           if (isBound(tyv)) {
3129                               return copyAdj(tyv->bound,tyv->offs,beta);
3130                           }
3131                           vn -= beta;
3132                           if (vn<0 || vn>=(OFF_MAX-OFF_MIN+1)) {
3133                               internal("copyAdj");
3134                           }
3135                           return mkOffset(vn);
3136                       }
3137     }
3138     return c;
3139 }
3140
3141 static Void local tidyDerInst(in)       /* Tidy up results of derived inst */
3142 Inst in; {                              /* calculations                    */
3143     Int  o  = inst(in).numSpecifics;
3144     List ps = tl(rev(fst(snd(inst(in).specifics))));
3145     clearMarks();
3146     copyPred(inst(in).head,o);
3147     inst(in).specifics    = simpleContext(ps,o);
3148     h98CheckCtxt(inst(in).line,"derived instance",FALSE,inst(in).specifics,in);
3149     inst(in).numSpecifics = length(inst(in).specifics);
3150
3151 #ifdef DEBUG_DERIVING
3152     Printf("Derived instance: ");
3153     printContext(stdout,inst(in).specifics);
3154     Printf(" ||- ");
3155     printPred(stdout,inst(in).head);
3156     Printf("\n");
3157 #endif
3158 }
3159
3160 /* --------------------------------------------------------------------------
3161  * Generate code for derived instances:
3162  * ------------------------------------------------------------------------*/
3163
3164 static Void local addDerivImp(in)
3165 Inst in; {
3166     List  imp = NIL;
3167     Type  t   = getHead(arg(inst(in).head));
3168     Class c   = inst(in).c;
3169     if (c==classEq) {
3170         imp = deriveEq(t);
3171     } else if (c==classOrd) {
3172         imp = deriveOrd(t);
3173     } else if (c==classEnum) {
3174         imp = deriveEnum(t);
3175     } else if (c==classIx) {
3176         imp = deriveIx(t);
3177     } else if (c==classShow) {
3178         imp = deriveShow(t);
3179     } else if (c==classRead) {
3180         imp = deriveRead(t);
3181     } else if (c==classBounded) {
3182         imp = deriveBounded(t);
3183     } else {
3184         ERRMSG(inst(in).line) "Cannot derive instances of class \"%s\"",
3185                               textToStr(cclass(inst(in).c).text)
3186         EEND;
3187     }
3188
3189     kindInst(in,intOf(inst(in).kinds));
3190     insertInst(in);
3191     inst(in).builder    = newInstImp(in);
3192     inst(in).implements = classBindings("derived instance",
3193                                         inst(in).c,
3194                                         imp);
3195 }
3196
3197
3198 /* --------------------------------------------------------------------------
3199  * Default definitions; only one default definition is permitted in a
3200  * given script file.  If no default is supplied, then a standard system
3201  * default will be used where necessary.
3202  * ------------------------------------------------------------------------*/
3203
3204 Void defaultDefn(line,defs)             /* Handle default types definition */
3205 Int  line;
3206 List defs; {
3207     if (defaultLine!=0) {
3208         ERRMSG(line) "Multiple default declarations are not permitted in" ETHEN
3209         ERRTEXT     "a single script file.\n"
3210         EEND;
3211     }
3212     defaultDefns = defs;
3213     defaultLine  = line;
3214 }
3215
3216 static Void local checkDefaultDefns() { /* check that default types are    */
3217     List ds = NIL;                      /* well-kinded instances of Num    */
3218
3219     if (defaultLine!=0) {
3220         map2Over(depTypeExp,defaultLine,NIL,defaultDefns);
3221         emptySubstitution();
3222         unkindTypes = NIL;
3223         map2Proc(kindType,defaultLine,"default type",defaultDefns);
3224         fixKinds();
3225         emptySubstitution();
3226         mapOver(fullExpand,defaultDefns);
3227     } else {
3228         defaultDefns = stdDefaults;
3229     }
3230
3231     if (isNull(classNum)) {
3232         classNum = findClass(findText("Num"));
3233     }
3234
3235     for (ds=defaultDefns; nonNull(ds); ds=tl(ds)) {
3236         if (isNull(provePred(NIL,NIL,ap(classNum,hd(ds))))) {
3237             ERRMSG(defaultLine)
3238                 "Default types must be instances of the Num class"
3239             EEND;
3240         }
3241     }
3242 }
3243
3244
3245 /* --------------------------------------------------------------------------
3246  * Foreign import declarations are Hugs' equivalent of GHC's ccall mechanism.
3247  * They are used to "import" C functions into a module.
3248  * They are usually not written by hand but, rather, generated automatically
3249  * by GreenCard, IDL compilers or whatever.  We support foreign import 
3250  * (static) and foreign import dynamic.  In the latter case, extName==NIL.
3251  *
3252  * Foreign export declarations generate C wrappers for Hugs functions.
3253  * Hugs only provides "foreign export dynamic" because it's not obvious
3254  * what "foreign export static" would mean in an interactive setting.
3255  * ------------------------------------------------------------------------*/
3256
3257 Void foreignImport(line,callconv,extName,intName,type) 
3258                                               /* Handle foreign imports    */
3259 Cell line;
3260 Text callconv;
3261 Pair extName;
3262 Cell intName;
3263 Cell type; {
3264     Text t = textOf(intName);
3265     Name n = findName(t);
3266
3267     if (isNull(n)) {
3268         n = newName(t,NIL);
3269     } else if (name(n).defn!=PREDEFINED) {
3270         ERRMSG(line) "Redeclaration of foreign \"%s\"", textToStr(t)
3271         EEND;
3272     }
3273     name(n).line     = line;
3274     name(n).defn     = extName;
3275     name(n).type     = type;
3276     name(n).callconv = callconv;
3277     foreignImports   = cons(n,foreignImports);
3278 }
3279
3280 static Void local checkForeignImport(p)   /* Check foreign import          */
3281 Name p; {
3282     emptySubstitution();
3283     name(p).type = checkSigType(name(p).line,
3284                                 "foreign import declaration",
3285                                 p,
3286                                 name(p).type);
3287     /* We don't expand synonyms here because we don't want the IO
3288      * part to be expanded.
3289      * name(p).type = fullExpand(name(p).type);
3290      */
3291     implementForeignImport(p);
3292 }
3293
3294 Void foreignExport(line,callconv,extName,intName,type)
3295                                               /* Handle foreign exports    */
3296 Cell line;
3297 Text callconv;
3298 Cell extName;
3299 Cell intName;
3300 Cell type; {
3301     Text t = textOf(intName);
3302     Name n = findName(t);
3303
3304     if (isNull(n)) {
3305         n = newName(t,NIL);
3306     } else if (name(n).defn!=PREDEFINED) {
3307         ERRMSG(line) "Redeclaration of foreign \"%s\"", textToStr(t)
3308         EEND;
3309     }
3310     name(n).line     = line;
3311     name(n).defn     = NIL;  /* nothing to say */
3312     name(n).type     = type;
3313     name(n).callconv = callconv;
3314     foreignExports   = cons(n,foreignExports);
3315 }
3316
3317 static Void local checkForeignExport(p)       /* Check foreign export      */
3318 Name p; {
3319     emptySubstitution();
3320     name(p).type = checkSigType(name(p).line,
3321                                 "foreign export declaration",
3322                                 p,
3323                                 name(p).type);
3324     implementForeignExport(p);
3325 }
3326
3327
3328
3329 /* --------------------------------------------------------------------------
3330  * Static analysis of patterns:
3331  *
3332  * Patterns are parsed as ordinary (atomic) expressions.  Static analysis
3333  * makes the following checks:
3334  *  - Patterns are well formed (according to pattern syntax), including the
3335  *    special case of (n+k) patterns.
3336  *  - All constructor functions have been defined and are used with the
3337  *    correct number of arguments.
3338  *  - No variable name is used more than once in a pattern.
3339  *
3340  * The list of pattern variables occuring in each pattern is accumulated in
3341  * a global list `patVars', which must be initialised to NIL at appropriate
3342  * points before using these routines to check for valid patterns.  This
3343  * mechanism enables the pattern checking routine to be mapped over a list
3344  * of patterns, ensuring that no variable occurs more than once in the
3345  * complete pattern list (as is required on the lhs of a function defn).
3346  * ------------------------------------------------------------------------*/
3347
3348 static List patVars;                   /* List of vars bound in pattern    */
3349
3350 static Cell local checkPat(line,p)     /* Check valid pattern syntax       */
3351 Int  line;
3352 Cell p; {
3353     switch (whatIs(p)) {
3354         case VARIDCELL :
3355         case VAROPCELL : addToPatVars(line,p);
3356                          break;
3357
3358         case INFIX     : return checkPat(line,tidyInfix(line,snd(p)));
3359
3360         case AP        : return checkMaybeCnkPat(line,p);
3361
3362         case NAME      :
3363         case QUALIDENT : 
3364         case CONIDCELL : 
3365         case CONOPCELL : return checkApPat(line,0,p);
3366
3367         case WILDCARD  :
3368         case STRCELL   :
3369         case CHARCELL  :
3370         case FLOATCELL : break;
3371         case INTCELL   : break;
3372
3373         case ASPAT     : addToPatVars(line,fst(snd(p)));
3374                          snd(snd(p)) = checkPat(line,snd(snd(p)));
3375                          break;
3376
3377         case LAZYPAT   : snd(p) = checkPat(line,snd(p));
3378                          break;
3379
3380         case FINLIST   : map1Over(checkPat,line,snd(p));
3381                          break;
3382
3383         case CONFLDS   : depConFlds(line,p,TRUE);
3384                          break;
3385
3386         case ESIGN     : snd(snd(p)) = checkPatType(line,
3387                                                     "pattern",
3388                                                     fst(snd(p)),
3389                                                     snd(snd(p)));
3390                          fst(snd(p)) = checkPat(line,fst(snd(p)));
3391                          break;
3392
3393         default        : ERRMSG(line) "Illegal pattern syntax"
3394                          EEND;
3395     }
3396     return p;
3397 }
3398
3399 static Cell local checkMaybeCnkPat(l,p)/* Check applicative pattern with   */
3400 Int  l;                                /* the possibility of n+k pattern   */
3401 Cell p; {
3402     Cell h = getHead(p);
3403
3404     if (argCount==2 && isVar(h) && textOf(h)==textPlus) {       /* n+k     */
3405         Cell v = arg(fun(p));
3406         if (!isInt(arg(p))) {
3407             ERRMSG(l) "Second argument in (n+k) pattern must be an integer"
3408             EEND;
3409         }
3410         if (intOf(arg(p))<=0) {
3411             ERRMSG(l) "Integer k in (n+k) pattern must be > 0"
3412             EEND;
3413         }
3414         fst(fun(p))      = ADDPAT;
3415         intValOf(fun(p)) = intOf(arg(p));
3416         arg(p)           = checkPat(l,v);
3417         return p;
3418     }
3419     return checkApPat(l,0,p);
3420 }
3421
3422 static Cell local checkApPat(line,args,p)
3423 Int  line;                             /* check validity of application    */
3424 Int  args;                             /* of constructor to arguments      */
3425 Cell p; {
3426     switch (whatIs(p)) {
3427         case AP        : fun(p) = checkApPat(line,args+1,fun(p));
3428                          arg(p) = checkPat(line,arg(p));
3429                          break;
3430
3431         case TUPLE     : if (tupleOf(p)!=args) {
3432                              ERRMSG(line) "Illegal tuple pattern"
3433                              EEND;
3434                          }
3435                          break;
3436
3437 #if TREX
3438         case EXT       : h98DoesntSupport(line,"extensible records");
3439                          if (args!=2) {
3440                              ERRMSG(line) "Illegal record pattern"
3441                              EEND;
3442                          }
3443                          break;
3444 #endif
3445
3446         case QUALIDENT : if (!isQCon(p)) {
3447                             ERRMSG(line)
3448                                 "Illegal use of qualified variable in pattern"
3449                             EEND;
3450                          }
3451                          /* deliberate fall through */
3452         case CONIDCELL :
3453         case CONOPCELL : p = conDefined(line,p);
3454                          checkCfunArgs(line,p,args);
3455                          break;
3456
3457         case NAME      : checkIsCfun(line,p);
3458                          checkCfunArgs(line,p,args);
3459                          break;
3460
3461         default        : ERRMSG(line) "Illegal pattern syntax"
3462                          EEND;
3463     }
3464     return p;
3465 }
3466
3467 static Void local addToPatVars(line,v)  /* Add variable v to list of vars  */
3468 Int  line;                              /* in current pattern, checking    */
3469 Cell v; {                               /* for repeated variables.         */
3470     Text t = textOf(v);
3471     List p = NIL;
3472     List n = patVars;
3473
3474     for (; nonNull(n); p=n, n=tl(n)) {
3475         if (textOf(hd(n))==t) {
3476             ERRMSG(line) "Repeated variable \"%s\" in pattern",
3477                          textToStr(t)
3478             EEND;
3479         }
3480     }
3481
3482     if (isNull(p)) {
3483          patVars = cons(v,NIL);
3484     } else {
3485          tl(p)   = cons(v,NIL);
3486     }
3487 }
3488
3489 static Name local conDefined(line,nm)  /* check that nm is the name of a   */
3490 Int  line;                             /* previously defined constructor   */
3491 Cell nm; {                             /* function.                        */
3492     Name n = findQualName(nm);
3493     if (isNull(n)) {
3494         ERRMSG(line) "Undefined constructor function \"%s\"", identToStr(nm)
3495         EEND;
3496     }
3497     checkIsCfun(line,n);
3498     return n;
3499 }
3500
3501 static Void local checkIsCfun(line,c)  /* Check that c is a constructor fn */
3502 Int  line;
3503 Name c; {
3504     if (!isCfun(c)) {
3505         ERRMSG(line) "\"%s\" is not a constructor function",
3506                      textToStr(name(c).text)
3507         EEND;
3508     }
3509 }
3510
3511 static Void local checkCfunArgs(line,c,args)
3512 Int  line;                             /* Check constructor applied with   */
3513 Cell c;                                /* correct number of arguments      */
3514 Int  args; {
3515     Int a = userArity(c);
3516     if (a!=args) {
3517         ERRMSG(line)
3518           "Constructor \"%s\" must have exactly %d argument%s in pattern",
3519           textToStr(name(c).text), a, ((a==1)?"":"s")
3520         EEND;
3521     }
3522 }
3523
3524 static Cell local checkPatType(l,wh,e,t)/* Check type appearing in pattern */
3525 Int    l;
3526 String wh;
3527 Cell   e;
3528 Type   t; {
3529     List tvs = typeVarsIn(t,NIL,NIL,NIL);
3530     h98DoesntSupport(l,"pattern type annotations");
3531     for (; nonNull(tvs); tvs=tl(tvs)) {
3532         Int beta    = newKindvars(1);
3533         hd(btyvars) = cons(pair(hd(tvs),mkInt(beta)), hd(btyvars));
3534     }
3535     t = checkSigType(l,"pattern type",e,t);
3536     if (isPolyOrQualType(t) || whatIs(t)==RANK2) {
3537         ERRMSG(l) "Illegal syntax in %s type annotation", wh
3538         EEND;
3539     }
3540     return t;
3541 }
3542
3543 static Cell local applyBtyvs(pat)       /* Record bound type vars in pat   */
3544 Cell pat; {
3545     List bts = hd(btyvars);
3546     leaveBtyvs();
3547     if (nonNull(bts)) {
3548         pat = ap(BIGLAM,pair(bts,pat));
3549         for (; nonNull(bts); bts=tl(bts)) {
3550             snd(hd(bts)) = copyKindvar(intOf(snd(hd(bts))));
3551         }
3552     }
3553     return pat;
3554 }
3555
3556 /* --------------------------------------------------------------------------
3557  * Maintaining lists of bound variables and local definitions, for
3558  * dependency and scope analysis.
3559  * ------------------------------------------------------------------------*/
3560
3561 static List bounds;                    /* list of lists of bound vars      */
3562 static List bindings;                  /* list of lists of binds in scope  */
3563 static List depends;                   /* list of lists of dependents      */
3564
3565 /* bounds   :: [[Var]]        -- var equality used on Vars     */
3566 /* bindings :: [[([Var],?)]]  -- var equality used on Vars     */
3567 /* depends  :: [[Var]]        -- pointer equality used on Vars */
3568
3569 #define saveBvars()      hd(bounds)    /* list of bvars in current scope   */
3570 #define restoreBvars(bs) hd(bounds)=bs /* restore list of bound variables  */
3571
3572 static Cell local bindPat(line,p)      /* add new bound vars for pattern   */
3573 Int  line;
3574 Cell p; {
3575     patVars    = NIL;
3576     p          = checkPat(line,p);
3577     hd(bounds) = revOnto(patVars,hd(bounds));
3578     return p;
3579 }
3580
3581 static Void local bindPats(line,ps)    /* add new bound vars for patterns  */
3582 Int  line;
3583 List ps; {
3584     patVars    = NIL;
3585     map1Over(checkPat,line,ps);
3586     hd(bounds) = revOnto(patVars,hd(bounds));
3587 }
3588
3589 /* --------------------------------------------------------------------------
3590  * Before processing value and type signature declarations, all data and
3591  * type definitions have been processed so that:
3592  * - all valid type constructors (with their arities) are known.
3593  * - all valid constructor functions (with their arities and types) are
3594  *   known.
3595  *
3596  * The result of parsing a list of value declarations is a list of Eqns:
3597  *       Eqn ::= (SIGDECL,(Line,[Var],type))
3598  *            |  (FIXDECL,(Line,[Op],SyntaxInt))
3599  *            |  (Expr,Rhs)
3600  * The ordering of the equations in this list is the reverse of the original
3601  * ordering in the script parsed.  This is a consequence of the structure of
3602  * the parser ... but also turns out to be most convenient for the static
3603  * analysis.
3604  *
3605  * As the first stage of the static analysis of value declarations, each
3606  * list of Eqns is converted to a list of Bindings.  As part of this
3607  * process:
3608  * - The ordering of the list of Bindings produced is the same as in the
3609  *   original script.
3610  * - When a variable (function) is defined over a number of lines, all
3611  *   of the definitions should appear together and each should give the
3612  *   same arity to the variable being defined.
3613  * - No variable can have more than one definition.
3614  * - For pattern bindings:
3615  *   - Each lhs is a valid pattern/function lhs, all constructor functions
3616  *     have been defined and are used with the correct number of arguments.
3617  *   - Each lhs contains no repeated pattern variables.
3618  *   - Each equation defines at least one variable (e.g. True = False is
3619  *     not allowed).
3620  * - Types appearing in type signatures are well formed:
3621  *    - Type constructors used are defined and used with correct number
3622  *      of arguments.
3623  *    - type variables are replaced by offsets, type constructor names
3624  *      by Tycons.
3625  * - Every variable named in a type signature declaration is defined by
3626  *   one or more equations elsewhere in the script.
3627  * - No variable has more than one type declaration.
3628  * - Similar properties for fixity declarations.
3629  *
3630  * ------------------------------------------------------------------------*/
3631
3632 #define bindingAttr(b) fst(snd(b))     /* type(s)/fixity(ies) for binding  */
3633 #define fbindAlts(b)   snd(snd(b))     /* alternatives for function binding*/
3634
3635 static List local extractSigdecls(es)  /* Extract the SIGDECLS from list   */
3636 List es; {                             /* of equations                     */
3637     List sigdecls = NIL;               /* :: [(Line,[Var],Type)]           */
3638
3639     for(; nonNull(es); es=tl(es)) {
3640         if (fst(hd(es))==SIGDECL) {                  /* type-declaration?  */
3641             Pair sig  = snd(hd(es));
3642             Int  line = intOf(fst3(sig));
3643             List vs   = snd3(sig);
3644             for(; nonNull(vs); vs=tl(vs)) {
3645                 if (isQualIdent(hd(vs))) {
3646                     ERRMSG(line) "Type signature for qualified variable \"%s\" is not allowed",
3647                                  identToStr(hd(vs))
3648                     EEND;
3649                 }
3650             }
3651             sigdecls = cons(sig,sigdecls);           /* discard SIGDECL tag*/
3652         }
3653     }
3654     return sigdecls;
3655 }
3656
3657 static List local extractFixdecls(es)   /* Extract the FIXDECLS from list  */
3658 List es; {                              /* of equations                    */
3659     List fixdecls = NIL;                /* :: [(Line,SyntaxInt,[Op])]      */
3660
3661     for(; nonNull(es); es=tl(es)) {
3662         if (fst(hd(es))==FIXDECL) {                  /* fixity declaration?*/
3663             fixdecls = cons(snd(hd(es)),fixdecls);   /* discard FIXDECL tag*/
3664         }
3665     }
3666     return fixdecls;
3667 }
3668
3669 static List local extractBindings(ds)   /* extract untyped bindings from   */
3670 List ds; {                              /* given list of equations         */
3671     Cell lastVar   = NIL;               /* = var def'd in last eqn (if any)*/
3672     Int  lastArity = 0;                 /* = number of args in last defn   */
3673     List bs        = NIL;               /* :: [Binding]                    */
3674
3675     for(; nonNull(ds); ds=tl(ds)) {
3676         Cell d = hd(ds);
3677         if (fst(d)==FUNBIND) {          /* Function bindings               */
3678             Cell rhs    = snd(snd(d));
3679             Int  line   = rhsLine(rhs);
3680             Cell lhs    = fst(snd(d));
3681             Cell v      = getHead(lhs);
3682             Cell newAlt = pair(getArgs(lhs),rhs);
3683             if (!isVar(v)) {
3684                 internal("FUNBIND");
3685             }
3686             if (nonNull(lastVar) && textOf(v)==textOf(lastVar)) {
3687                 if (argCount!=lastArity) {
3688                     ERRMSG(line) "Equations give different arities for \"%s\"",
3689                                  textToStr(textOf(v))
3690                     EEND;
3691                 }
3692                 fbindAlts(hd(bs)) = cons(newAlt,fbindAlts(hd(bs)));
3693             }
3694             else {
3695                 lastVar   = v;
3696                 lastArity = argCount;
3697                 notDefined(line,bs,v);
3698                 bs        = cons(pair(v,pair(NIL,singleton(newAlt))),bs);
3699             }
3700
3701         } else if (fst(d)==PATBIND) {   /* Pattern bindings                */
3702             Cell rhs  = snd(snd(d));
3703             Int  line = rhsLine(rhs);
3704             Cell pat  = fst(snd(d));
3705             while (whatIs(pat)==ESIGN) {/* Move type annotations to rhs   */
3706                 Cell p        = fst(snd(pat));
3707                 fst(snd(pat)) = rhs;
3708                 snd(snd(d))   = rhs = pat;
3709                 fst(snd(d))   = pat = p;
3710                 fst(rhs)      = RSIGN;
3711             }
3712             if (isVar(pat)) {           /* Convert simple pattern bind to */
3713                 notDefined(line,bs,pat);/* a function binding             */
3714                 bs = cons(pair(pat,pair(NIL,singleton(pair(NIL,rhs)))),bs);
3715             } else {
3716                 List vs = getPatVars(line,pat,NIL);
3717                 if (isNull(vs)) {
3718                     ERRMSG(line) "No variables defined in lhs pattern"
3719                     EEND;
3720                 }
3721                 map2Proc(notDefined,line,bs,vs);
3722                 bs          = cons(pair(vs,pair(NIL,snd(d))),bs);
3723             }
3724             lastVar = NIL;
3725         }
3726     }
3727     return bs;
3728 }
3729
3730 static List local getPatVars(line,p,vs) /* Find list of variables bound in */
3731 Int  line;                              /* pattern p                       */
3732 Cell p;
3733 List vs; {
3734     switch (whatIs(p)) {
3735         case AP         : do {
3736                               vs = getPatVars(line,arg(p),vs);
3737                               p  = fun(p);
3738                           } while (isAp(p));
3739                           return vs;    /* Ignore head of application      */
3740
3741         case CONFLDS    : {   List pfs = snd(snd(p));
3742                               for (; nonNull(pfs); pfs=tl(pfs)) {
3743                                   if (isVar(hd(pfs))) {
3744                                       vs = addPatVar(line,hd(pfs),vs);
3745                                   } else {
3746                                       vs = getPatVars(line,snd(hd(pfs)),vs);
3747                                   }
3748                               }
3749                           }
3750                           return vs;
3751
3752         case FINLIST    : {   List ps = snd(p);
3753                               for (; nonNull(ps); ps=tl(ps)) {
3754                                   vs = getPatVars(line,hd(ps),vs);
3755                               }
3756                           }
3757                           return vs;
3758
3759         case ESIGN      : return getPatVars(line,fst(snd(p)),vs);
3760
3761         case LAZYPAT    :
3762         case NEG        :
3763         case ONLY       :
3764         case INFIX      : return getPatVars(line,snd(p),vs);
3765
3766         case ASPAT      : return addPatVar(line,fst(snd(p)),
3767                                              getPatVars(line,snd(snd(p)),vs));
3768
3769         case VARIDCELL  :
3770         case VAROPCELL  : return addPatVar(line,p,vs);
3771
3772         case CONIDCELL  :
3773         case CONOPCELL  :
3774         case QUALIDENT  :
3775         case INTCELL    :
3776         case FLOATCELL  :
3777         case CHARCELL   :
3778         case STRCELL    :
3779         case NAME       :
3780         case WILDCARD   : return vs;
3781
3782         default         : internal("getPatVars");
3783     }
3784     return vs;
3785 }
3786
3787 static List local addPatVar(line,v,vs)  /* Add var to list of previously   */
3788 Int  line;                              /* encountered variables           */
3789 Cell v;
3790 List vs; {
3791     if (varIsMember(textOf(v),vs)) {
3792         ERRMSG(line) "Repeated use of variable \"%s\" in pattern binding",
3793                      textToStr(textOf(v))
3794         EEND;
3795     }
3796     return cons(v,vs);
3797 }
3798
3799 static List local eqnsToBindings(es,ts,cs,ps)
3800 List es;                                /* Convert list of equations to    */
3801 List ts;                                /* list of typed bindings          */
3802 List cs;
3803 List ps; {
3804     List bs = extractBindings(es);
3805     map1Proc(addSigdecl,bs,extractSigdecls(es));
3806     map4Proc(addFixdecl,bs,ts,cs,ps,extractFixdecls(es));
3807     return bs;
3808 }
3809
3810 static Void local notDefined(line,bs,v)/* check if name already defined in */
3811 Int  line;                             /* list of bindings                 */
3812 List bs;
3813 Cell v; {
3814     if (nonNull(findBinding(textOf(v),bs))) {
3815         ERRMSG(line) "\"%s\" multiply defined", textToStr(textOf(v))
3816         EEND;
3817     }
3818 }
3819
3820 static Cell local findBinding(t,bs)    /* look for binding for variable t  */
3821 Text t;                                /* in list of bindings bs           */
3822 List bs; {
3823     for (; nonNull(bs); bs=tl(bs)) {
3824         if (isVar(fst(hd(bs)))) {                     /* function-binding? */
3825             if (textOf(fst(hd(bs)))==t) {
3826                 return hd(bs);
3827             }
3828         } else if (nonNull(varIsMember(t,fst(hd(bs))))){/* pattern-binding?*/
3829             return hd(bs);
3830         }
3831     }
3832     return NIL;
3833 }
3834
3835 static Cell local getAttr(bs,v)         /* Locate type/fixity attribute    */
3836 List bs;                                /* for variable v in bindings bs   */
3837 Cell v; {
3838     Text t = textOf(v);
3839     Cell b = findBinding(t,bs);
3840
3841     if (isNull(b)) {                                    /* No binding      */
3842         return NIL;
3843     } else if (isVar(fst(b))) {                         /* func binding?   */
3844         if (isNull(bindingAttr(b))) {
3845             bindingAttr(b) = pair(NIL,NIL);
3846         }
3847         return bindingAttr(b);
3848     } else {                                            /* pat binding?    */
3849         List vs = fst(b);
3850         List as = bindingAttr(b);
3851
3852         if (isNull(as)) {
3853             bindingAttr(b) = as = replicate(length(vs),NIL);
3854         }
3855
3856         while (nonNull(vs) && t!=textOf(hd(vs))) {
3857             vs = tl(vs);
3858             as = tl(as);
3859         }
3860
3861         if (isNull(vs)) {
3862             internal("getAttr");
3863         } else if (isNull(hd(as))) {
3864             hd(as) = pair(NIL,NIL);
3865         }
3866         return hd(as);
3867     }
3868 }
3869
3870 static Void local addSigdecl(bs,sigdecl)/* add type information to bindings*/
3871 List bs;                               /* :: [Binding]                     */
3872 Cell sigdecl; {                        /* :: (Line,[Var],Type)             */
3873     Int  l    = intOf(fst3(sigdecl));
3874     List vs   = snd3(sigdecl);
3875     Type type = checkSigType(l,"type declaration",hd(vs),thd3(sigdecl));
3876
3877     for (; nonNull(vs); vs=tl(vs)) {
3878         Cell v    = hd(vs);
3879         Pair attr = getAttr(bs,v);
3880         if (isNull(attr)) {
3881             ERRMSG(l) "Missing binding for variable \"%s\" in type signature",
3882                       textToStr(textOf(v))
3883             EEND;
3884         } else if (nonNull(fst(attr))) {
3885             ERRMSG(l) "Repeated type signature for \"%s\"",
3886                       textToStr(textOf(v))
3887             EEND;
3888         }
3889         fst(attr) = type;
3890     }
3891 }
3892
3893 static Void local addFixdecl(bs,ts,cs,ps,fixdecl)
3894 List   bs;
3895 List   ts;
3896 List   cs;
3897 List   ps;
3898 Triple fixdecl; {
3899     Int  line = intOf(fst3(fixdecl));
3900     List ops  = snd3(fixdecl);
3901     Cell sy   = thd3(fixdecl);
3902
3903     for (; nonNull(ops); ops=tl(ops)) {
3904         Cell op   = hd(ops);
3905         Text t    = textOf(op);
3906         Cell attr = getAttr(bs,op);
3907         if (nonNull(attr)) {            /* Found name in binding?          */
3908             if (nonNull(snd(attr))) {
3909                 dupFixity(line,t);
3910             }
3911             snd(attr) = sy;
3912         } else {                        /* Look in tycons, classes, prims  */
3913             Name n   = NIL;
3914             List ts1 = ts;
3915             List cs1 = cs;
3916             List ps1 = ps;
3917             for (; isNull(n) && nonNull(ts1); ts1=tl(ts1)) {    /* tycons  */
3918                 Tycon tc = hd(ts1);
3919                 if (tycon(tc).what==DATATYPE || tycon(tc).what==NEWTYPE) {
3920                     n = nameIsMember(t,tycon(tc).defn);
3921                 }
3922             }
3923             for (; isNull(n) && nonNull(cs1); cs1=tl(cs1)) {    /* classes */
3924                 n = nameIsMember(t,cclass(hd(cs1)).members);
3925             }
3926             for (; isNull(n) && nonNull(ps1); ps1=tl(ps1)) {    /* prims   */
3927                 n = nameIsMember(t,hd(ps1));
3928             }
3929
3930             if (isNull(n)) {
3931                 missFixity(line,t);
3932             } else if (name(n).syntax!=NO_SYNTAX) {
3933                 dupFixity(line,t);
3934             }
3935             name(n).syntax = intOf(sy);
3936         }
3937     }
3938 }
3939
3940 static Void local dupFixity(line,t)     /* Report repeated fixity decl     */
3941 Int  line;
3942 Text t; {
3943     ERRMSG(line)
3944         "Repeated fixity declaration for operator \"%s\"", textToStr(t)
3945     EEND;
3946 }
3947
3948 static Void local missFixity(line,t)    /* Report missing op for fixity    */
3949 Int  line;
3950 Text t; {
3951     ERRMSG(line)
3952         "Cannot find binding for operator \"%s\" in fixity declaration",
3953         textToStr(t)
3954     EEND;
3955 }
3956
3957 /* --------------------------------------------------------------------------
3958  * Dealing with infix operators:
3959  *
3960  * Expressions involving infix operators or unary minus are parsed as
3961  * elements of the following type:
3962  *
3963  *     data InfixExp = Only Exp | Neg InfixExp | Infix InfixExp Op Exp
3964  *
3965  * (The algorithms here do not assume that negation can be applied only once,
3966  * i.e., that - - x is a syntax error, as required by the Haskell report.
3967  * Instead, that restriction is captured by the grammar itself, given above.)
3968  *
3969  * There are rules of precedence and grouping, expressed by two functions:
3970  *
3971  *     prec :: Op -> Int;   assoc :: Op -> Assoc    (Assoc = {L, N, R})
3972  *
3973  * InfixExp values are rearranged accordingly when a complete expression
3974  * has been read using a simple shift-reduce parser whose result may be taken
3975  * to be a value of the following type:
3976  *
3977  *     data Exp = Atom Int | Negate Exp | Apply Op Exp Exp | Error String
3978  *
3979  * The machine on which this parser is based can be defined as follows:
3980  *
3981  *     tidy                         :: InfixExp -> [(Op,Exp)] -> Exp
3982  *     tidy (Only a)      []         = a
3983  *     tidy (Only a)      ((o,b):ss) = tidy (Only (Apply o a b)) ss
3984  *     tidy (Infix a o b) []         = tidy a [(o,b)]
3985  *     tidy (Infix a o b) ((p,c):ss)
3986  *                      | shift  o p = tidy a ((o,b):(p,c):ss)
3987  *                      | red    o p = tidy (Infix a o (Apply p b c)) ss
3988  *                      | ambig  o p = Error "ambiguous use of operators"
3989  *     tidy (Neg e)       []         = tidy (tidyNeg e) []
3990  *     tidy (Neg e)       ((o,b):ss)
3991  *                      | nshift o   = tidy (Neg (underNeg o b e)) ss
3992  *                      | nred   o   = tidy (tidyNeg e) ((o,b):ss)
3993  *                      | nambig o   = Error "illegal use of negation"
3994  *
3995  * At each stage, the parser can either shift, reduce, accept, or error.
3996  * The transitions when dealing with juxtaposed operators o and p are
3997  * determined by the following rules:
3998  *
3999  *     shift o p  = (prec o > prec p)
4000  *               || (prec o == prec p && assoc o == L && assoc p == L)
4001  *
4002  *     red o p    = (prec o < prec p)
4003  *               || (prec o == prec p && assoc o == R && assoc p == R)
4004  *
4005  *     ambig o p  = (prec o == prec p)
4006  *               && (assoc o == N || assoc p == N || assoc o /= assoc p)
4007  *
4008  * The transitions when dealing with juxtaposed unary minus and infix
4009  * operators are as follows.  The precedence of unary minus (infixl 6) is
4010  * hardwired in to these definitions, as it is to the definitions of the
4011  * Haskell grammar in the official report.
4012  *
4013  *     nshift o   = (prec o > 6)
4014  *     nred   o   = (prec o < 6) || (prec o == 6 && assoc o == L)
4015  *     nambig o   = prec o == 6 && (assoc o == R || assoc o == N)
4016  *
4017  * An InfixExp of the form (Neg e) means negate the last thing in
4018  * the InfixExp e; we can force this negation using:
4019  *
4020  *     tidyNeg              :: OpExp -> OpExp
4021  *     tidyNeg (Only e)      = Only (Negate e)
4022  *     tidyNeg (Infix a o b) = Infix a o (Negate b)
4023  *     tidyNeg (Neg e)       = tidyNeg (tidyNeg e)
4024  * 
4025  * On the other hand, if we want to sneak application of an infix operator
4026  * under a negation, then we use:
4027  *
4028  *     underNeg                  :: Op -> Exp -> OpExp -> OpExp
4029  *     underNeg o b (Only e)      = Only (Apply o e b)
4030  *     underNeg o b (Neg e)       = Neg (underNeg o b e)
4031  *     underNeg o b (Infix e p f) = Infix e p (Apply o f b)
4032  *
4033  * As a concession to efficiency, we lower the number of calls to syntaxOf
4034  * by keeping track of the values of sye, sys throughout the process.  The
4035  * value APPLIC is used to indicate that the syntax value is unknown.
4036  * ------------------------------------------------------------------------*/
4037
4038 static Cell local tidyInfix(line,e)     /* Convert infixExp to Exp         */
4039 Int  line;
4040 Cell e; {                               /* :: OpExp                        */
4041     Cell   s   = NIL;                   /* :: [(Op,Exp)]                   */
4042     Syntax sye = APPLIC;                /* Syntax of op in e (init unknown)*/
4043     Syntax sys = APPLIC;                /* Syntax of op in s (init unknown)*/
4044     Cell   d   = e;
4045
4046     while (fst(d)!=ONLY) {              /* Attach fixities to operators    */
4047         if (fst(d)==NEG) {
4048             d = snd(d);
4049         } else {
4050             fun(fun(d)) = attachFixity(line,fun(fun(d)));
4051             d           = arg(fun(d));
4052         }
4053     }
4054
4055     for (;;)
4056         switch (whatIs(e)) {
4057             case ONLY : e = snd(e);
4058                         while (nonNull(s)) {
4059                             Cell next   = arg(fun(s));
4060                             arg(fun(s)) = e;
4061                             fun(fun(s)) = snd(fun(fun(s)));
4062                             e           = s;
4063                             s           = next;
4064                         }
4065                         return e;
4066
4067             case NEG  : if (nonNull(s)) {
4068                             if (sys==APPLIC) {  /* calculate sys           */
4069                                 sys = intOf(fst(fun(fun(s))));
4070                             }
4071
4072                             if (precOf(sys)==UMINUS_PREC &&     /* nambig  */
4073                                 assocOf(sys)!=UMINUS_ASSOC) {
4074                                 ERRMSG(line)
4075                                  "Ambiguous use of unary minus with \""
4076                                 ETHEN ERREXPR(snd(fun(fun(s))));
4077                                 ERRTEXT "\""
4078                                 EEND;
4079                             }
4080
4081                             if (precOf(sys)>UMINUS_PREC) {      /* nshift  */
4082                                 Cell e1    = snd(e);
4083                                 Cell t     = s;
4084                                 s          = arg(fun(s));
4085                                 while (whatIs(e1)==NEG)
4086                                     e1 = snd(e1);
4087                                 arg(fun(t)) = arg(e1);
4088                                 fun(fun(t)) = snd(fun(fun(t)));
4089                                 arg(e1)     = t;
4090                                 sys         = APPLIC;
4091                                 continue;
4092                             }
4093                         }
4094
4095                         /* Intentional fall-thru for nreduce and isNull(s) */
4096
4097                         {   Cell prev = e;              /* e := tidyNeg e  */
4098                             Cell temp = arg(prev);
4099                             Int  nneg = 1;
4100                             for (; whatIs(temp)==NEG; nneg++) {
4101                                 fun(prev) = nameNegate;
4102                                 prev      = temp;
4103                                 temp      = arg(prev);
4104                             }
4105                             if (isInt(arg(temp))) {     /* special cases   */
4106                                 if (nneg&1)             /* for literals    */
4107                                     arg(temp) = mkInt(-intOf(arg(temp)));
4108                             }
4109                             else if (isFloat(arg(temp))) {
4110                                 if (nneg&1)
4111                                     arg(temp) = floatNegate(arg(temp));
4112                                                 //mkFloat(-floatOf(arg(temp)));
4113                             }
4114                             else {
4115                                 fun(prev) = nameNegate;
4116                                 arg(prev) = arg(temp);
4117                                 arg(temp) = e;
4118                             }
4119                             e = temp;
4120                         }
4121                         continue;
4122
4123             default   : if (isNull(s)) {/* Move operation onto empty stack */
4124                             Cell next   = arg(fun(e));
4125                             s           = e;
4126                             arg(fun(s)) = NIL;
4127                             e           = next;
4128                             sys         = sye;
4129                             sye         = APPLIC;
4130                         }
4131                         else {          /* deal with pair of operators     */
4132
4133                             if (sye==APPLIC) {  /* calculate sys and sye   */
4134                                 sye = intOf(fst(fun(fun(e))));
4135                             }
4136                             if (sys==APPLIC) {
4137                                 sys = intOf(fst(fun(fun(s))));
4138                             }
4139
4140                             if (precOf(sye)==precOf(sys) &&     /* ambig   */
4141                                 (assocOf(sye)!=assocOf(sys) ||
4142                                  assocOf(sye)==NON_ASS)) {
4143                                 ERRMSG(line) "Ambiguous use of operator \""
4144                                 ETHEN ERREXPR(snd(fun(fun(e))));
4145                                 ERRTEXT "\" with \""
4146                                 ETHEN ERREXPR(snd(fun(fun(s))));
4147                                 ERRTEXT "\""
4148                                 EEND;
4149                             }
4150
4151                             if (precOf(sye)>precOf(sys) ||      /* shift   */
4152                                 (precOf(sye)==precOf(sys) &&
4153                                  assocOf(sye)==LEFT_ASS &&
4154                                  assocOf(sys)==LEFT_ASS)) {
4155                                 Cell next   = arg(fun(e));
4156                                 arg(fun(e)) = s;
4157                                 s           = e;
4158                                 e           = next;
4159                                 sys         = sye;
4160                                 sye         = APPLIC;
4161                             }
4162                             else {                              /* reduce  */
4163                                 Cell next   = arg(fun(s));
4164                                 arg(fun(s)) = arg(e);
4165                                 fun(fun(s)) = snd(fun(fun(s)));
4166                                 arg(e)      = s;
4167                                 s           = next;
4168                                 sys         = APPLIC;
4169                                 /* sye unchanged */
4170                             }
4171                         }
4172                         continue;
4173         }
4174 }
4175
4176 static Pair local attachFixity(line,op) /* Attach fixity to operator in an */
4177 Int  line;                              /* infix expression                */
4178 Cell op; {
4179     Syntax sy = DEF_OPSYNTAX;
4180
4181     switch (whatIs(op)) {
4182         case VAROPCELL :
4183         case VARIDCELL : if ((sy=lookupSyntax(textOf(op)))==NO_SYNTAX) {
4184                              Name n = findName(textOf(op));
4185                              if (isNull(n)) {
4186                                 ERRMSG(line) "Undefined variable \"%s\"",
4187                                              textToStr(textOf(op))
4188                                 EEND;
4189                              }
4190                              sy = syntaxOf(n);
4191                              op = n;
4192                          }
4193                          break;
4194
4195         case CONOPCELL :
4196         case CONIDCELL : sy = syntaxOf(op = conDefined(line,op));
4197                          break;
4198
4199         case QUALIDENT : {   Name n = findQualName(op);
4200                              if (nonNull(n)) {
4201                                  op = n;
4202                                  sy = syntaxOf(n);
4203                              } else {
4204                                  ERRMSG(line)
4205                                    "Undefined qualified variable \"%s\"",
4206                                    identToStr(op)
4207                                  EEND;
4208                              }
4209                          }
4210                          break;
4211     }
4212     if (sy==APPLIC) {
4213         sy = DEF_OPSYNTAX;
4214     }
4215     return pair(mkInt(sy),op);          /* Pair fixity with (possibly)     */
4216                                         /* translated operator             */
4217 }
4218
4219 static Syntax local lookupSyntax(t)     /* Try to find fixity for var in   */
4220 Text t; {                               /* enclosing bindings              */
4221     List bounds1   = bounds;
4222     List bindings1 = bindings;
4223
4224     while (nonNull(bindings1)) {
4225         if (nonNull(varIsMember(t,hd(bounds1)))) {
4226             return DEF_OPSYNTAX;
4227         } else {
4228             Cell b = findBinding(t,hd(bindings1));
4229             if (nonNull(b)) {
4230                 Cell a = fst(snd(b));
4231                 if (isVar(fst(b))) {    /* Function binding                */
4232                     if (nonNull(a) && nonNull(snd(a))) {
4233                         return intOf(snd(a));
4234                     }
4235                 } else {                /* Pattern binding                 */
4236                     List vs = fst(b);
4237                     while (nonNull(vs) && nonNull(a)) {
4238                         if (t==textOf(hd(vs))) {
4239                             if (nonNull(hd(a)) && isInt(snd(hd(a)))) {
4240                                 return intOf(snd(hd(a)));
4241                             }
4242                             break;
4243                         }
4244                         vs = tl(vs);
4245                         a  = tl(a);
4246                     }
4247                 }
4248                 return DEF_OPSYNTAX;
4249             }
4250         }
4251         bounds1   = tl(bounds1);
4252         bindings1 = tl(bindings1);
4253     }
4254     return NO_SYNTAX;
4255 }
4256
4257 /* --------------------------------------------------------------------------
4258  * To facilitate dependency analysis, lists of bindings are temporarily
4259  * augmented with an additional field, which is used in two ways:
4260  * - to build the `adjacency lists' for the dependency graph. Represented by
4261  *   a list of pointers to other bindings in the same list of bindings.
4262  * - to hold strictly positive integer values (depth first search numbers) of
4263  *   elements `on the stack' during the strongly connected components search
4264  *   algorithm, or a special value mkInt(0), once the binding has been added
4265  *   to a particular strongly connected component.
4266  *
4267  * Using this extra field, the type of each list of declarations during
4268  * dependency analysis is [Binding'] where:
4269  *
4270  *    Binding' ::= (Var, (Attr, (Dep, [Alt])))         -- function binding
4271  *              |  ([Var], ([Attr], (Dep, (Pat,Rhs)))) -- pattern binding
4272  *
4273  * ------------------------------------------------------------------------*/
4274
4275 #define depVal(d) (fst(snd(snd(d))))    /* Access to dependency information*/
4276
4277 static List local dependencyAnal(bs)    /* Separate lists of bindings into */
4278 List bs; {                              /* mutually recursive groups in    */
4279                                         /* order of dependency             */
4280     mapProc(addDepField,bs);            /* add extra field for dependents  */
4281     mapProc(depBinding,bs);             /* find dependents of each binding */
4282     bs = bscc(bs);                      /* sort to strongly connected comps*/
4283     mapProc(remDepField,bs);            /* remove dependency info field    */
4284     return bs;
4285 }
4286
4287 static List local topDependAnal(bs)     /* Like dependencyAnal(), but at   */
4288 List bs; {                              /* top level, reporting on progress*/
4289     List xs;
4290     Int  i = 0;
4291
4292     setGoal("Dependency analysis",(Target)(length(bs)));
4293
4294     mapProc(addDepField,bs);           /* add extra field for dependents   */
4295     for (xs=bs; nonNull(xs); xs=tl(xs)) {
4296         emptySubstitution();
4297         depBinding(hd(xs));
4298         soFar((Target)(i++));
4299     }
4300     bs = bscc(bs);                     /* sort to strongly connected comps */
4301     mapProc(remDepField,bs);           /* remove dependency info field     */
4302     done();
4303     return bs;
4304 }
4305
4306 static Void local addDepField(b)       /* add extra field to binding to    */
4307 Cell b; {                              /* hold list of dependents          */
4308     snd(snd(b)) = pair(NIL,snd(snd(b)));
4309 }
4310
4311 static Void local remDepField(bs)      /* remove dependency field from     */
4312 List bs; {                             /* list of bindings                 */
4313     mapProc(remDepField1,bs);
4314 }
4315
4316 static Void local remDepField1(b)      /* remove dependency field from     */
4317 Cell b; {                              /* single binding                   */
4318     snd(snd(b)) = snd(snd(snd(b)));
4319 }
4320
4321 static Void local clearScope() {       /* initialise dependency scoping    */
4322     bounds   = NIL;
4323     bindings = NIL;
4324     depends  = NIL;
4325 }
4326
4327 static Void local withinScope(bs)       /* Enter scope of bindings bs      */
4328 List bs; {
4329     bounds   = cons(NIL,bounds);
4330     bindings = cons(bs,bindings);
4331     depends  = cons(NIL,depends);
4332 }
4333
4334 static Void local leaveScope() {        /* Leave scope of last withinScope */
4335     List bs       = hd(bindings);       /* Remove fixity info from binds   */
4336     Bool toplevel = isNull(tl(bindings));
4337     for (; nonNull(bs); bs=tl(bs)) {
4338         Cell b = hd(bs);
4339         if (isVar(fst(b))) {            /* Variable binding                */
4340             Cell a = fst(snd(b));
4341             if (isPair(a)) {
4342                 if (toplevel) {
4343                     saveSyntax(fst(b),snd(a));
4344                 }
4345                 fst(snd(b)) = fst(a);
4346             }
4347         } else {                        /* Pattern binding                 */
4348             List vs = fst(b);
4349             List as = fst(snd(b));
4350             while (nonNull(vs) && nonNull(as)) {
4351                 if (isPair(hd(as))) {
4352                     if (toplevel) {
4353                         saveSyntax(hd(vs),snd(hd(as)));
4354                     }
4355                     hd(as) = fst(hd(as));
4356                 }
4357                 vs = tl(vs);
4358                 as = tl(as);
4359             }
4360         }
4361     }
4362     bounds   = tl(bounds);
4363     bindings = tl(bindings);
4364     depends  = tl(depends);
4365 }
4366
4367 static Void local saveSyntax(v,sy)      /* Save syntax of top-level var    */
4368 Cell v;                                 /* in corresponding Name           */
4369 Cell sy; {
4370     Name n = findName(textOf(v));
4371     if (isNull(n) || name(n).syntax!=NO_SYNTAX) {
4372         internal("saveSyntax");
4373     }
4374     if (nonNull(sy)) {
4375         name(n).syntax = intOf(sy);
4376     }
4377 }
4378
4379 /* --------------------------------------------------------------------------
4380  * As a side effect of the dependency analysis we also make the following
4381  * checks:
4382  * - Each lhs is a valid pattern/function lhs, all constructor functions
4383  *   have been defined and are used with the correct number of arguments.
4384  * - No lhs contains repeated pattern variables.
4385  * - Expressions used on the rhs of an eqn should be well formed.  This
4386  *   includes:
4387  *   - Checking for valid patterns (including repeated vars) in lambda,
4388  *     case, and list comprehension expressions.
4389  *   - Recursively checking local lists of equations.
4390  * - No free (i.e. unbound) variables are used in the declaration list.
4391  * ------------------------------------------------------------------------*/
4392
4393 static Void local depBinding(b)        /* find dependents of binding       */
4394 Cell b; {
4395     Cell defpart = snd(snd(snd(b)));   /* definition part of binding       */
4396
4397     hd(depends) = NIL;
4398
4399     if (isVar(fst(b))) {               /* function-binding?                */
4400         mapProc(depAlt,defpart);
4401         if (isNull(fst(snd(b)))) {      /* Save dep info if no type sig    */
4402             fst(snd(b)) = pair(ap(IMPDEPS,hd(depends)),NIL);
4403         } else if (isNull(fst(fst(snd(b))))) {
4404             fst(fst(snd(b))) = ap(IMPDEPS,hd(depends));
4405         }
4406     } else {                           /* pattern-binding?                 */
4407         Int line = rhsLine(snd(defpart));
4408         enterBtyvs();
4409         patVars = NIL;
4410         fst(defpart) = checkPat(line,fst(defpart));
4411         depRhs(snd(defpart));
4412 #if 0
4413         if (nonNull(hd(btyvars))) {
4414             ERRMSG(line)
4415               "Sorry, no type variables are allowed in pattern binding type annotations"
4416             EEND;
4417         }
4418 #endif
4419         fst(defpart) = applyBtyvs(fst(defpart));
4420     }
4421     depVal(b) = hd(depends);
4422 }
4423
4424 static Void local depDefaults(c)       /* dependency analysis on defaults  */
4425 Class c; {                             /* from class definition            */
4426     depClassBindings(cclass(c).defaults);
4427 }
4428
4429 static Void local depInsts(in)         /* dependency analysis on instance  */
4430 Inst in; {                             /* bindings                         */
4431     depClassBindings(inst(in).implements);
4432 }
4433
4434 static Void local depClassBindings(bs) /* dependency analysis on list of   */
4435 List bs; {                             /* bindings, possibly containing    */
4436     for (; nonNull(bs); bs=tl(bs)) {   /* NIL bindings ...                 */
4437         if (nonNull(hd(bs))) {         /* No need to add extra field for   */
4438            mapProc(depAlt,snd(hd(bs)));/* dependency information...        */
4439         }
4440     }
4441 }
4442
4443 static Void local depAlt(a)             /* Find dependents of alternative  */
4444 Cell a; {
4445     List obvs = saveBvars();            /* Save list of bound variables    */
4446     enterBtyvs();
4447     bindPats(rhsLine(snd(a)),fst(a));   /* add new bound vars for patterns */
4448     depRhs(snd(a));                     /* find dependents of rhs          */
4449     fst(a)    = applyBtyvs(fst(a));
4450     restoreBvars(obvs);                 /* restore original list of bvars  */
4451 }
4452
4453 static Void local depRhs(r)             /* Find dependents of rhs          */
4454 Cell r; {
4455     switch (whatIs(r)) {
4456         case GUARDED : mapProc(depGuard,snd(r));
4457                        break;
4458
4459         case LETREC  : fst(snd(r)) = eqnsToBindings(fst(snd(r)),NIL,NIL,NIL);
4460                        withinScope(fst(snd(r)));
4461                        fst(snd(r)) = dependencyAnal(fst(snd(r)));
4462                        hd(depends) = fst(snd(r));
4463                        depRhs(snd(snd(r)));
4464                        leaveScope();
4465                        break;
4466
4467         case RSIGN   : snd(snd(r)) = checkPatType(rhsLine(fst(snd(r))),
4468                                                   "result",
4469                                                   rhsExpr(fst(snd(r))),
4470                                                   snd(snd(r)));
4471                        depRhs(fst(snd(r)));
4472                        break;
4473
4474         default      : snd(r) = depExpr(intOf(fst(r)),snd(r));
4475                        break;
4476     }
4477 }
4478
4479 static Void local depGuard(g)          /* find dependents of single guarded*/
4480 Cell g; {                              /* expression                       */
4481     depPair(intOf(fst(g)),snd(g));
4482 }
4483
4484 static Cell local depExpr(line,e)      /* find dependents of expression    */
4485 Int  line;
4486 Cell e; {
4487   //Printf( "\n\n"); print(e,100); Printf("\n");
4488   //printExp(stdout,e);
4489     switch (whatIs(e)) {
4490
4491         case VARIDCELL  :
4492         case VAROPCELL  : return depVar(line,e);
4493
4494         case CONIDCELL  :
4495         case CONOPCELL  : return conDefined(line,e);
4496
4497         case QUALIDENT  : if (isQVar(e)) {
4498                               return depQVar(line,e);
4499                           } else { /* QConOrConOp */
4500                               return conDefined(line,e);
4501                           }
4502
4503         case INFIX     : return depExpr(line,tidyInfix(line,snd(e)));
4504
4505 #if TREX
4506         case RECSEL     : break;
4507
4508         case AP         : if (isAp(e) && isAp(fun(e)) && isExt(fun(fun(e)))) {
4509                               return depRecord(line,e);
4510                           } else {
4511                               Cell nx = e;
4512                               Cell a;
4513                               do {
4514                                   a      = nx;
4515                                   arg(a) = depExpr(line,arg(a));
4516                                   nx     = fun(a);
4517                               } while (isAp(nx));
4518                               fun(a) = depExpr(line,fun(a));
4519                           }
4520                           break;
4521 #else
4522         case AP         : depPair(line,e);
4523                           break;
4524 #endif
4525
4526 #if IPARAM
4527         case IPVAR      :
4528 #endif
4529
4530         case NAME       :
4531         case TUPLE      :
4532         case STRCELL    :
4533         case CHARCELL   :
4534         case FLOATCELL  :
4535         case BIGCELL    :
4536         case INTCELL    : break;
4537
4538         case COND       : depTriple(line,snd(e));
4539                           break;
4540
4541         case FINLIST    : map1Over(depExpr,line,snd(e));
4542                           break;
4543
4544         case LETREC     : fst(snd(e)) = eqnsToBindings(fst(snd(e)),NIL,NIL,NIL);
4545                           withinScope(fst(snd(e)));
4546                           fst(snd(e)) = dependencyAnal(fst(snd(e)));
4547                           hd(depends) = fst(snd(e));
4548                           snd(snd(e)) = depExpr(line,snd(snd(e)));
4549                           leaveScope();
4550                           break;
4551
4552         case LAMBDA     : depAlt(snd(e));
4553                           break;
4554
4555         case DOCOMP     : /* fall-thru */
4556         case COMP       : depComp(line,snd(e),snd(snd(e)));
4557                           break;
4558
4559         case ESIGN      : fst(snd(e)) = depExpr(line,fst(snd(e)));
4560                           snd(snd(e)) = checkSigType(line,
4561                                                      "expression",
4562                                                      fst(snd(e)),
4563                                                      snd(snd(e)));
4564                           break;
4565
4566         case CASE       : fst(snd(e)) = depExpr(line,fst(snd(e)));
4567                           map1Proc(depCaseAlt,line,snd(snd(e)));
4568                           break;
4569
4570         case CONFLDS    : depConFlds(line,e,FALSE);
4571                           break;
4572
4573         case UPDFLDS    : depUpdFlds(line,e);
4574                           break;
4575
4576 #if IPARAM
4577         case WITHEXP    : depWith(line,e);
4578                           break;
4579 #endif
4580
4581         case ASPAT      : ERRMSG(line) "Illegal `@' in expression"
4582                           EEND;
4583
4584         case LAZYPAT    : ERRMSG(line) "Illegal `~' in expression"
4585                           EEND;
4586
4587         case WILDCARD   : ERRMSG(line) "Illegal `_' in expression"
4588                           EEND;
4589
4590 #if TREX
4591         case EXT        : ERRMSG(line) "Illegal application of record"
4592                           EEND;
4593 #endif
4594
4595         default         : internal("depExpr");
4596    }
4597    return e;
4598 }
4599
4600 static Void local depPair(line,e)       /* find dependents of pair of exprs*/
4601 Int  line;
4602 Cell e; {
4603     fst(e) = depExpr(line,fst(e));
4604     snd(e) = depExpr(line,snd(e));
4605 }
4606
4607 static Void local depTriple(line,e)     /* find dependents of triple exprs */
4608 Int  line;
4609 Cell e; {
4610     fst3(e) = depExpr(line,fst3(e));
4611     snd3(e) = depExpr(line,snd3(e));
4612     thd3(e) = depExpr(line,thd3(e));
4613 }
4614
4615 static Void local depComp(l,e,qs)       /* find dependents of comprehension*/
4616 Int  l;
4617 Cell e;
4618 List qs; {
4619     if (isNull(qs)) {
4620         fst(e) = depExpr(l,fst(e));
4621     } else {
4622         Cell q   = hd(qs);
4623         List qs1 = tl(qs);
4624         switch (whatIs(q)) {
4625             case FROMQUAL : {   List obvs   = saveBvars();
4626                                 snd(snd(q)) = depExpr(l,snd(snd(q)));
4627                                 enterBtyvs();
4628                                 fst(snd(q)) = bindPat(l,fst(snd(q)));
4629                                 depComp(l,e,qs1);
4630                                 fst(snd(q)) = applyBtyvs(fst(snd(q)));
4631                                 restoreBvars(obvs);
4632                             }
4633                             break;
4634
4635             case QWHERE   : snd(q)      = eqnsToBindings(snd(q),NIL,NIL,NIL);
4636                             withinScope(snd(q));
4637                             snd(q)      = dependencyAnal(snd(q));
4638                             hd(depends) = snd(q);
4639                             depComp(l,e,qs1);
4640                             leaveScope();
4641                             break;
4642
4643             case DOQUAL   : /* fall-thru */
4644             case BOOLQUAL : snd(q) = depExpr(l,snd(q));
4645                             depComp(l,e,qs1);
4646                             break;
4647         }
4648     }
4649 }
4650
4651 static Void local depCaseAlt(line,a)    /* Find dependents of case altern. */
4652 Int  line;
4653 Cell a; {
4654     List obvs = saveBvars();            /* Save list of bound variables    */
4655     enterBtyvs();
4656     fst(a)    = bindPat(line,fst(a));   /* Add new bound vars for pats     */
4657     depRhs(snd(a));                     /* Find dependents of rhs          */
4658     fst(a)    = applyBtyvs(fst(a));
4659     restoreBvars(obvs);                 /* Restore original list of bvars  */
4660 }
4661
4662 static Cell local depVar(line,e)        /* Register occurrence of variable */
4663 Int line;
4664 Cell e; {
4665     List bounds1   = bounds;
4666     List bindings1 = bindings;
4667     List depends1  = depends;
4668     Text t         = textOf(e);
4669     Cell n;
4670
4671     while (nonNull(bindings1)) {
4672         n = varIsMember(t,hd(bounds1));   /* look for t in bound variables */
4673         if (nonNull(n)) {
4674             return n;
4675         }
4676         n = findBinding(t,hd(bindings1)); /* look for t in var bindings    */
4677         if (nonNull(n)) {
4678             if (!cellIsMember(n,hd(depends1))) {
4679                 hd(depends1) = cons(n,hd(depends1));
4680             }
4681            return (isVar(fst(n)) ? fst(n) : e);
4682         }
4683
4684         bounds1   = tl(bounds1);
4685         bindings1 = tl(bindings1);
4686         depends1  = tl(depends1);
4687     }
4688
4689     if (isNull(n=findName(t))) {               /* check global definitions */
4690         ERRMSG(line) "Undefined variable \"%s\"", textToStr(t)
4691         EEND;
4692     }
4693
4694     /* Later phases of the system cannot cope if we resolve references
4695      * to unprocessed objects too early.  This is the main reason that
4696      * we cannot cope with recursive modules at the moment.
4697      */
4698     return e;
4699 }
4700
4701 static Cell local depQVar(line,e)/* register occurrence of qualified variable */
4702 Int line;
4703 Cell e; {
4704     Name n = findQualName(e);
4705     if (isNull(n)) {                            /* check global definitions */
4706         ERRMSG(line) "Undefined qualified variable \"%s\"", identToStr(e)
4707         EEND;
4708     }
4709     if (name(n).mod != currentModule) {
4710         return n;
4711     }
4712     if (fst(e) == VARIDCELL) {
4713         e = mkVar(qtextOf(e));
4714     } else {
4715         e = mkVarop(qtextOf(e));
4716     }
4717     return depVar(line,e);
4718 }
4719
4720 static Void local depConFlds(line,e,isP)/* check construction using fields */
4721 Int  line;
4722 Cell e;
4723 Bool isP; {
4724     Name c = conDefined(line,fst(snd(e)));
4725     if (isNull(snd(snd(e))) ||
4726         nonNull(cellIsMember(c,depFields(line,e,snd(snd(e)),isP)))) {
4727         fst(snd(e)) = c;
4728     } else {
4729         ERRMSG(line) "Constructor \"%s\" does not have selected fields in ",
4730                      textToStr(name(c).text)
4731         ETHEN ERREXPR(e);
4732         ERRTEXT "\n"
4733         EEND;
4734     }
4735     if (!isP && isPair(name(c).defn)) { /* Check that banged fields defined*/
4736         List scs = fst(name(c).defn);   /* List of strict components       */
4737         Type t   = name(c).type;
4738         Int  a   = userArity(c);
4739         List fs  = snd(snd(e));
4740         List ss;
4741         if (isPolyType(t)) {            /* Find tycon that c belongs to    */
4742             t = monotypeOf(t);
4743         }
4744         if (isQualType(t)) {
4745             t = snd(snd(t));
4746         }
4747         if (whatIs(t)==CDICTS) {
4748             t = snd(snd(t));
4749         }
4750         while (0<a--) {
4751             t = arg(t);
4752         }
4753         while (isAp(t)) {
4754             t = fun(t);
4755         }
4756         for (ss=tycon(t).defn; hasCfun(ss); ss=tl(ss)) {
4757         }
4758         /* Now we know the tycon t that c belongs to, and the corresponding
4759          * list of selectors for that type, ss.  Now we have to check that
4760          * each of the fields identified by scs appears in fs, using ss to
4761          * cross reference, and convert integers to selector names.
4762          */
4763         for (; nonNull(scs); scs=tl(scs)) {
4764             Int  i   = intOf(hd(scs));
4765             List ss1 = ss;
4766             for (; nonNull(ss1); ss1=tl(ss1)) {
4767                 List cns = name(hd(ss1)).defn;
4768                 for (; nonNull(cns); cns=tl(cns)) {
4769                     if (fst(hd(cns))==c) {
4770                         break;
4771                     }
4772                 }
4773                 if (nonNull(cns) && intOf(snd(hd(cns)))==i) {
4774                     break;
4775                 }
4776             }
4777             if (isNull(ss1)) {
4778                 internal("depConFlds");
4779             } else {
4780                 Name s   = hd(ss1);
4781                 List fs1 = fs;
4782                 for (; nonNull(fs1) && s!=fst(hd(fs1)); fs1=tl(fs1)) {
4783                 }
4784                 if (isNull(fs1)) {
4785                     ERRMSG(line) "Construction does not define strict field"
4786                     ETHEN
4787                     ERRTEXT      "\nExpression : " ETHEN ERREXPR(e);
4788                     ERRTEXT      "\nField      : " ETHEN ERREXPR(s);
4789                     ERRTEXT      "\n"
4790                     EEND;
4791                 }
4792             }
4793         }
4794     }
4795 }
4796
4797 static Void local depUpdFlds(line,e)    /* check update using fields       */
4798 Int  line;
4799 Cell e; {
4800     if (isNull(thd3(snd(e)))) {
4801         ERRMSG(line) "Empty field list in update"
4802         EEND;
4803     }
4804     fst3(snd(e)) = depExpr(line,fst3(snd(e)));
4805     snd3(snd(e)) = depFields(line,e,thd3(snd(e)),FALSE);
4806 }
4807
4808 static List local depFields(l,e,fs,isP) /* check field binding list        */
4809 Int  l;
4810 Cell e;
4811 List fs;
4812 Bool isP; {
4813     List cs = NIL;
4814     List ss = NIL;
4815
4816     for (; nonNull(fs); fs=tl(fs)) {    /* for each field binding          */
4817         Cell fb = hd(fs);
4818         Name s;
4819
4820         if (isVar(fb)) {                /* expand  var  to  var = var      */
4821             h98DoesntSupport(l,"missing field bindings");
4822             fb = hd(fs) = pair(fb,fb);
4823         }
4824
4825         s = findQualName(fst(fb));      /* check for selector              */
4826         if (nonNull(s) && isSfun(s)) {
4827             fst(fb) = s;
4828         } else {
4829             ERRMSG(l) "\"%s\" is not a selector function/field name",
4830                       textToStr(textOf(fst(fb)))
4831             EEND;
4832         }
4833
4834         if (isNull(ss)) {               /* for first named selector        */
4835             List scs = name(s).defn;    /* calculate list of constructors  */
4836             for (; nonNull(scs); scs=tl(scs)) {
4837                 cs = cons(fst(hd(scs)),cs);
4838             }
4839             ss = singleton(s);          /* initialize selector list        */
4840         } else {                        /* for subsequent selectors        */
4841             List ds = cs;               /* intersect constructor lists     */
4842             for (cs=NIL; nonNull(ds); ) {
4843                 List scs = name(s).defn;
4844                 while (nonNull(scs) && fst(hd(scs))!=hd(ds)) {
4845                     scs = tl(scs);
4846                 }
4847                 if (isNull(scs)) {
4848                     ds = tl(ds);
4849                 } else {
4850                     List next = tl(ds);
4851                     tl(ds)    = cs;
4852                     cs        = ds;
4853                     ds        = next;
4854                 }
4855             }
4856
4857             if (cellIsMember(s,ss)) {   /* check for repeated uses         */
4858                 ERRMSG(l) "Repeated field name \"%s\" in field list",
4859                           textToStr(name(s).text)
4860                 EEND;
4861             }
4862             ss = cons(s,ss);
4863         }
4864
4865         if (isNull(cs)) {               /* Are there any matching constrs? */
4866             ERRMSG(l) "No constructor has all of the fields specified in "
4867             ETHEN ERREXPR(e);
4868             ERRTEXT "\n"
4869             EEND;
4870         }
4871
4872         snd(fb) = (isP ? checkPat(l,snd(fb)) : depExpr(l,snd(fb)));
4873     }
4874     return cs;
4875 }
4876
4877 #if IPARAM
4878 static Void local depWith(line,e)       /* check with using fields         */
4879 Int  line;
4880 Cell e; {
4881     fst(snd(e)) = depExpr(line,fst(snd(e)));
4882     snd(snd(e)) = depDwFlds(line,e,snd(snd(e)));
4883 }
4884
4885 static List local depDwFlds(l,e,fs)/* check field binding list     */
4886 Int  l;
4887 Cell e;
4888 List fs;
4889 {
4890     Cell c = fs;
4891     for (; nonNull(c); c=tl(c)) {       /* for each field binding          */
4892         snd(hd(c)) = depExpr(l,snd(hd(c)));
4893     }
4894     return fs;
4895 }
4896 #endif
4897
4898 #if TREX
4899 static Cell local depRecord(line,e)     /* find dependents of record and   */
4900 Int  line;                              /* sort fields into approp. order  */
4901 Cell e; {                               /* to make construction and update */
4902     List exts = NIL;                    /* more efficient.                 */
4903     Cell r    = e;
4904
4905     h98DoesntSupport(line,"extensible records");
4906     do {                                /* build up list of extensions     */
4907         Text   t    = extText(fun(fun(r)));
4908         String s    = textToStr(t);
4909         List   prev = NIL;
4910         List   nx   = exts;
4911         while (nonNull(nx) && strcmp(textToStr(extText(fun(fun(nx)))),s)>0) {
4912             prev = nx;
4913             nx   = extRow(nx);
4914         }
4915         if (nonNull(nx) && t==extText(fun(fun(nx)))) {
4916             ERRMSG(line) "Repeated label \"%s\" in record ", s
4917             ETHEN ERREXPR(e);
4918             ERRTEXT "\n"
4919             EEND;
4920         }
4921         if (isNull(prev)) {
4922             exts = cons(fun(r),exts);
4923         } else {
4924             tl(prev) = cons(fun(r),nx);
4925         }
4926         extField(r) = depExpr(line,extField(r));
4927         r           = extRow(r);
4928     } while (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r))));
4929     r = depExpr(line,r);
4930     return revOnto(exts,r);
4931 }
4932 #endif
4933
4934
4935 /* --------------------------------------------------------------------------
4936  * Several parts of this program require an algorithm for sorting a list
4937  * of values (with some added dependency information) into a list of strongly
4938  * connected components in which each value appears before its dependents.
4939  *
4940  * Each of these algorithms is obtained by parameterising a standard
4941  * algorithm in "scc.c" as shown below.
4942  * ------------------------------------------------------------------------*/
4943
4944 #define  SCC2            tcscc          /* make scc algorithm for Tycons   */
4945 #define  LOWLINK         tclowlink
4946 #define  DEPENDS(c)      (isTycon(c) ? tycon(c).kind : cclass(c).kinds)
4947 #define  SETDEPENDS(c,v) if(isTycon(c)) tycon(c).kind=v; else cclass(c).kinds=v
4948 #include "scc.c"
4949 #undef   SETDEPENDS
4950 #undef   DEPENDS
4951 #undef   LOWLINK
4952 #undef   SCC2
4953
4954 #define  SCC             bscc           /* make scc algorithm for Bindings */
4955 #define  LOWLINK         blowlink
4956 #define  DEPENDS(t)      depVal(t)
4957 #define  SETDEPENDS(c,v) depVal(c)=v
4958 #include "scc.c"
4959 #undef   SETDEPENDS
4960 #undef   DEPENDS
4961 #undef   LOWLINK
4962 #undef   SCC
4963
4964 /* --------------------------------------------------------------------------
4965  * Main static analysis:
4966  * ------------------------------------------------------------------------*/
4967
4968 Void checkExp() {                       /* Top level static check on Expr  */
4969     staticAnalysis(RESET);
4970     clearScope();                       /* Analyse expression in the scope */
4971     withinScope(NIL);                   /* of no local bindings            */
4972     inputExpr = depExpr(0,inputExpr);
4973     leaveScope();
4974     staticAnalysis(RESET);
4975 }
4976
4977 #if EXPLAIN_INSTANCE_RESOLUTION
4978 Void checkContext(void) {               /* Top level static check on Expr  */
4979     List vs, qs;
4980
4981     staticAnalysis(RESET);
4982     clearScope();                       /* Analyse expression in the scope */
4983     withinScope(NIL);                   /* of no local bindings            */
4984     qs = inputContext;
4985     for (vs = NIL; nonNull(qs); qs=tl(qs)) {
4986         vs = typeVarsIn(hd(qs),NIL,NIL,vs);
4987     }
4988     map2Proc(depPredExp,0,vs,inputContext);
4989     leaveScope();
4990     staticAnalysis(RESET);
4991 }
4992 #endif
4993
4994 Void checkDefns ( Module thisModule ) { /* Top level static analysis       */
4995     Text modName = module(thisModule).text;
4996
4997     staticAnalysis(RESET);
4998
4999     setCurrModule(thisModule);
5000
5001     /* Resolve module references */
5002     mapProc(checkQualImport,  module(thisModule).qualImports);
5003     mapProc(checkUnqualImport,unqualImports);
5004     /* Add "import Prelude" if there`s no explicit import */
5005     if (modName == textPrelPrim || modName == textPrelude) {
5006       /* Nothing. */
5007     } else if (isNull(cellAssoc(modulePrelude,unqualImports))
5008                && isNull(cellRevAssoc(modulePrelude,module(thisModule).qualImports))) {
5009       unqualImports = cons(pair(modulePrelude,DOTDOT),unqualImports);
5010     } else {
5011       /* Every module implicitly contains "import qualified Prelude" 
5012        */
5013       module(thisModule).qualImports
5014         =cons(pair(mkCon(textPrelude),modulePrelude),
5015               module(thisModule).qualImports);
5016     }
5017     mapProc(checkImportList, unqualImports);
5018
5019     /* Note: there's a lot of side-effecting going on here, so
5020        don't monkey about with the order of operations here unless
5021        you know what you are doing */
5022     if (!combined) linkPreludeTC();     /* Get prelude tycons and classes  */
5023
5024     mapProc(checkTyconDefn,tyconDefns); /* validate tycon definitions      */
5025     checkSynonyms(tyconDefns);          /* check synonym definitions       */
5026     mapProc(checkClassDefn,classDefns); /* process class definitions       */
5027     mapProc(kindTCGroup,tcscc(tyconDefns,classDefns)); /* attach kinds     */
5028     mapProc(visitClass,classDefns);     /* check class hierarchy           */
5029     mapProc(extendFundeps,classDefns);  /* finish class definitions        */
5030                                         /* (convenient if we do this after */
5031                                         /* calling `visitClass' so that we */
5032                                         /* know the class hierarchy is     */
5033                                         /* acyclic)                        */
5034
5035     mapProc(addMembers,classDefns);     /* add definitions for member funs */
5036
5037     if (!combined) linkPreludeCM();     /* Get prelude cfuns and mfuns     */
5038     
5039     instDefns = rev(instDefns);         /* process instance definitions    */
5040     mapProc(checkInstDefn,instDefns);
5041
5042     setCurrModule(thisModule);
5043     mapProc(addRSsigdecls,typeInDefns); /* add sigdecls for RESTRICTSYN    */
5044     valDefns   = eqnsToBindings(valDefns,tyconDefns,classDefns,/*primDefns*/NIL);
5045     mapProc(allNoPrevDef,valDefns);     /* check against previous defns    */
5046     mapProc(addDerivImp,derivedInsts);  /* Add impls for derived instances */
5047     deriveContexts(derivedInsts);       /* Calculate derived inst contexts */
5048     instDefns  = appendOnto(instDefns,derivedInsts);
5049     checkDefaultDefns();                /* validate default definitions    */
5050
5051     mapProc(allNoPrevDef,valDefns);     /* check against previous defns    */
5052
5053     if (!combined) linkPrimNames();     /* link primitive names           */
5054
5055     mapProc(checkForeignImport,foreignImports); /* check foreign imports   */
5056     mapProc(checkForeignExport,foreignExports); /* check foreign exports   */
5057     foreignImports = NIL;
5058     foreignExports = NIL;
5059
5060     /* Every top-level name has now been created - so we can build the     */
5061     /* export list.  Note that this has to happen before dependency        */
5062     /* analysis so that references to Prelude.foo will be resolved         */
5063     /* when compiling the prelude.                                         */
5064     module(thisModule).exports 
5065        = checkExports ( module(thisModule).exports, thisModule );
5066
5067     mapProc(checkTypeIn,typeInDefns);   /* check restricted synonym defns  */
5068
5069     clearScope();
5070     withinScope(valDefns);
5071     valDefns = topDependAnal(valDefns); /* top level dependency ordering   */
5072     mapProc(depDefaults,classDefns);    /* dep. analysis on class defaults */
5073     mapProc(depInsts,instDefns);        /* dep. analysis on inst defns     */
5074     leaveScope();
5075
5076     /* ToDo: evalDefaults should match current evaluation module */
5077     evalDefaults = defaultDefns;        /* Set defaults for evaluator      */
5078
5079     staticAnalysis(RESET);
5080 }
5081
5082
5083
5084
5085 static Void local addRSsigdecls(pr)     /* add sigdecls from TYPE ... IN ..*/
5086 Pair pr; {
5087     List vs = snd(pr);                  /* get list of variables           */
5088     for (; nonNull(vs); vs=tl(vs)) {
5089         if (fst(hd(vs))==SIGDECL) {     /* find a sigdecl                  */
5090             valDefns = cons(hd(vs),valDefns);   /* add to valDefns         */
5091             hd(vs)   = hd(snd3(snd(hd(vs))));   /* and replace with var    */
5092         }
5093     }
5094 }
5095
5096 static Void local allNoPrevDef(b)        /* ensure no previous bindings for*/
5097 Cell b; {                                /* variables in new binding       */
5098     if (isVar(fst(b))) {
5099         noPrevDef(rhsLine(snd(hd(snd(snd(b))))),fst(b));
5100     } else {
5101         Int line = rhsLine(snd(snd(snd(b))));
5102         map1Proc(noPrevDef,line,fst(b));
5103     }
5104 }
5105
5106 static Void local noPrevDef(line,v)      /* ensure no previous binding for */
5107 Int  line;                               /* new variable                   */
5108 Cell v; {
5109     Name n = findName(textOf(v));
5110
5111     if (isNull(n)) {
5112         n            = newName(textOf(v),NIL);
5113         name(n).defn = PREDEFINED;
5114     } else if (name(n).defn!=PREDEFINED) {
5115         duplicateError(line,name(n).mod,name(n).text,"variable");
5116     }
5117     name(n).line = line;
5118 }
5119
5120 static Void local duplicateErrorAux(line,mod,t,kind)/* report duplicate defn */
5121 Int    line;
5122 Module mod;
5123 Text   t;
5124 String kind; {
5125     if (mod == currentModule) {
5126         ERRMSG(line) "Repeated definition for %s \"%s\"", kind, 
5127                      textToStr(t)
5128         EEND;
5129     } else {
5130         ERRMSG(line) "Definition of %s \"%s\" clashes with import", kind,
5131                      textToStr(t)
5132         EEND;
5133     }
5134 }
5135
5136 static Void local checkTypeIn(cvs)      /* Check that vars in restricted   */
5137 Pair cvs; {                             /* synonym are defined             */
5138     Tycon c  = fst(cvs);
5139     List  vs = snd(cvs);
5140
5141     for (; nonNull(vs); vs=tl(vs)) {
5142         if (isNull(findName(textOf(hd(vs))))) {
5143             ERRMSG(tycon(c).line)
5144                 "No top level binding of \"%s\" for restricted synonym \"%s\"",
5145                 textToStr(textOf(hd(vs))), textToStr(tycon(c).text)
5146             EEND;
5147         }
5148     }
5149 }
5150
5151 /* --------------------------------------------------------------------------
5152  * Haskell 98 compatibility tests:
5153  * ------------------------------------------------------------------------*/
5154
5155 Bool h98Pred(allowArgs,pi)              /* Check syntax of Hask98 predicate*/
5156 Bool allowArgs;
5157 Cell pi; {
5158     return isClass(getHead(pi)) && argCount==1 &&
5159            isOffset(getHead(arg(pi))) && (argCount==0 || allowArgs);
5160 }
5161
5162 Cell h98Context(allowArgs,ps)           /* Check syntax of Hask98 context  */
5163 Bool allowArgs;
5164 List ps; {
5165     for (; nonNull(ps); ps=tl(ps)) {
5166         if (!h98Pred(allowArgs,hd(ps))) {
5167             return hd(ps);
5168         }
5169     }
5170     return NIL;
5171 }
5172
5173 Void h98CheckCtxt(line,wh,allowArgs,ps,in)
5174 Int    line;                            /* Report illegal context/predicate*/
5175 String wh;
5176 Bool   allowArgs;
5177 List   ps;
5178 Inst   in; {
5179     if (haskell98) {
5180         Cell pi = h98Context(allowArgs,ps);
5181         if (nonNull(pi)) {
5182             ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh ETHEN
5183             if (nonNull(in)) {
5184                 ERRTEXT  "\n*** Instance   : " ETHEN ERRPRED(inst(in).head);
5185             }
5186             ERRTEXT      "\n*** Constraint : " ETHEN ERRPRED(pi);
5187             if (nonNull(ps) && nonNull(tl(ps))) {
5188                 ERRTEXT  "\n*** Context    : " ETHEN ERRCONTEXT(ps);
5189             }
5190             ERRTEXT      "\n"
5191             EEND;
5192         }
5193     }
5194 }
5195
5196 Void h98CheckType(line,wh,e,t)          /* Check for Haskell 98 type       */
5197 Int    line;
5198 String wh;
5199 Cell   e;
5200 Type   t; {
5201     if (haskell98) {
5202         Type ty = t;
5203         if (isPolyType(t))
5204             t = monotypeOf(t);
5205         if (isQualType(t)) {
5206             Cell pi = h98Context(TRUE,fst(snd(t)));
5207             if (nonNull(pi)) {
5208                 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh
5209                 ETHEN
5210                 ERRTEXT  "\n*** Expression : " ETHEN ERREXPR(e);
5211                 ERRTEXT  "\n*** Type       : " ETHEN ERRTYPE(ty);
5212                 ERRTEXT  "\n"
5213                 EEND;
5214             }
5215         }
5216     }
5217 }
5218
5219 Void h98DoesntSupport(line,wh)          /* Report feature missing in H98   */
5220 Int    line;
5221 String wh; {
5222     if (haskell98) {
5223         ERRMSG(line) "Haskell 98 does not support %s", wh
5224         EEND;
5225     }
5226 }
5227
5228 /* --------------------------------------------------------------------------
5229  * Static Analysis control:
5230  * ------------------------------------------------------------------------*/
5231
5232 Void staticAnalysis(what)
5233 Int what; {
5234     switch (what) {
5235         case RESET   : cfunSfuns    = NIL;
5236                        daSccs       = NIL;
5237                        patVars      = NIL;
5238                        bounds       = NIL;
5239                        bindings     = NIL;
5240                        depends      = NIL;
5241                        tcDeps       = NIL;
5242                        derivedInsts = NIL;
5243                        diVars       = NIL;
5244                        diNum        = 0;
5245                        unkindTypes  = NIL;
5246                        break;
5247
5248         case MARK    : mark(daSccs);
5249                        mark(patVars);
5250                        mark(bounds);
5251                        mark(bindings);
5252                        mark(depends);
5253                        mark(tcDeps);
5254                        mark(derivedInsts);
5255                        mark(diVars);
5256                        mark(cfunSfuns);
5257                        mark(unkindTypes);
5258 #if TREX
5259                        mark(extKind);
5260 #endif
5261                        break;
5262
5263         case POSTPREL: break;
5264
5265         case PREPREL : staticAnalysis(RESET);
5266 #if TREX
5267                        extKind = pair(STAR,pair(ROW,ROW));
5268 #endif
5269     }
5270 }
5271
5272 /*-------------------------------------------------------------------------*/