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