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