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