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