2 /* --------------------------------------------------------------------------
3 * Static Analysis for Hugs
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.
11 * $RCSfile: static.c,v $
13 * $Date: 2000/03/10 14:53:00 $
14 * ------------------------------------------------------------------------*/
24 /* --------------------------------------------------------------------------
25 * local function prototypes:
26 * ------------------------------------------------------------------------*/
28 static Void local kindError Args((Int,Constr,Constr,String,Kind,Int));
29 static Void local checkQualImport Args((Pair));
30 static Void local checkUnqualImport Args((Triple));
32 static Name local lookupName Args((Text,List));
33 static List local checkSubentities Args((List,List,List,String,Text));
34 static List local checkExportTycon Args((List,Text,Cell,Tycon));
35 static List local checkExportClass Args((List,Text,Cell,Class));
36 static List local checkExport Args((List,Text,Cell));
37 static List local checkImportEntity Args((List,Module,Bool,Cell));
38 static List local resolveImportList Args((Module,Cell,Bool));
39 static Void local checkImportList Args((Pair));
41 static Void local importEntity Args((Module,Cell));
42 static Void local importName Args((Module,Name));
43 static Void local importTycon Args((Module,Tycon));
44 static Void local importClass Args((Module,Class));
45 static List local checkExports Args((List));
47 static Void local checkTyconDefn Args((Tycon));
48 static Void local depConstrs Args((Tycon,List,Cell));
49 static List local addSels Args((Int,Name,List,List));
50 static List local selectCtxt Args((List,List));
51 static Void local checkSynonyms Args((List));
52 static List local visitSyn Args((List,Tycon,List));
53 static Type local instantiateSyn Args((Type,Type));
55 static Void local checkClassDefn Args((Class));
56 static Cell local depPredExp Args((Int,List,Cell));
57 static Void local checkMems Args((Class,List,Cell));
58 static Void local checkMems2 Args((Class,Cell));
59 static Void local addMembers Args((Class));
60 static Name local newMember Args((Int,Int,Cell,Type,Class));
61 static Text local generateText Args((String,Class));
63 static List local classBindings Args((String,Class,List));
64 static Name local memberName Args((Class,Text));
65 static List local numInsert Args((Int,Cell,List));
67 static List local maybeAppendVar Args((Cell,List));
69 static Type local checkSigType Args((Int,String,Cell,Type));
70 static Void local checkOptQuantVars Args((Int,List,List));
71 static Type local depTopType Args((Int,List,Type));
72 static Type local depCompType Args((Int,List,Type));
73 static Type local depTypeExp Args((Int,List,Type));
74 static Type local depTypeVar Args((Int,List,Text));
75 static List local checkQuantVars Args((Int,List,List,Cell));
76 static List local otvars Args((Cell,List));
77 static Bool local osubset Args((List,List));
78 static Void local kindConstr Args((Int,Int,Int,Constr));
79 static Kind local kindAtom Args((Int,Constr));
80 static Void local kindPred Args((Int,Int,Int,Cell));
81 static Void local kindType Args((Int,String,Type));
82 static Void local fixKinds Args((Void));
84 static Void local kindTCGroup Args((List));
85 static Void local initTCKind Args((Cell));
86 static Void local kindTC Args((Cell));
87 static Void local genTC Args((Cell));
89 static Void local checkInstDefn Args((Inst));
90 static Void local insertInst Args((Inst));
91 static Bool local instCompare Args((Inst,Inst));
92 static Name local newInstImp Args((Inst));
93 static Void local kindInst Args((Inst,Int));
94 static Void local checkDerive Args((Tycon,List,List,Cell));
95 static Void local addDerInst Args((Int,Class,List,List,Type,Int));
96 static Void local deriveContexts Args((List));
97 static Void local initDerInst Args((Inst));
98 static Void local calcInstPreds Args((Inst));
99 static Void local maybeAddPred Args((Cell,Int,Int,List));
100 static List local calcFunDeps Args((List));
101 static Cell local copyAdj Args((Cell,Int,Int));
102 static Void local tidyDerInst Args((Inst));
103 static List local otvarsZonk Args((Cell,List,Int));
105 static Void local addDerivImp Args((Inst));
107 static Void local checkDefaultDefns Args((Void));
109 static Void local checkForeignImport Args((Name));
110 static Void local checkForeignExport Args((Name));
112 static Cell local tidyInfix Args((Int,Cell));
113 static Pair local attachFixity Args((Int,Cell));
114 static Syntax local lookupSyntax Args((Text));
116 static Cell local checkPat Args((Int,Cell));
117 static Cell local checkMaybeCnkPat Args((Int,Cell));
118 static Cell local checkApPat Args((Int,Int,Cell));
119 static Void local addToPatVars Args((Int,Cell));
120 static Name local conDefined Args((Int,Cell));
121 static Void local checkIsCfun Args((Int,Name));
122 static Void local checkCfunArgs Args((Int,Cell,Int));
123 static Cell local checkPatType Args((Int,String,Cell,Type));
124 static Cell local applyBtyvs Args((Cell));
125 static Cell local bindPat Args((Int,Cell));
126 static Void local bindPats Args((Int,List));
128 static List local extractSigdecls Args((List));
129 static List local extractFixdecls Args((List));
130 static List local extractBindings Args((List));
131 static List local getPatVars Args((Int,Cell,List));
132 static List local addPatVar Args((Int,Cell,List));
133 static List local eqnsToBindings Args((List,List,List,List));
134 static Void local notDefined Args((Int,List,Cell));
135 static Cell local findBinding Args((Text,List));
136 static Cell local getAttr Args((List,Cell));
137 static Void local addSigdecl Args((List,Cell));
138 static Void local addFixdecl Args((List,List,List,List,Triple));
139 static Void local dupFixity Args((Int,Text));
140 static Void local missFixity Args((Int,Text));
142 static List local dependencyAnal Args((List));
143 static List local topDependAnal Args((List));
144 static Void local addDepField Args((Cell));
145 static Void local remDepField Args((List));
146 static Void local remDepField1 Args((Cell));
147 static Void local clearScope Args((Void));
148 static Void local withinScope Args((List));
149 static Void local leaveScope Args((Void));
150 static Void local saveSyntax Args((Cell,Cell));
152 static Void local depBinding Args((Cell));
153 static Void local depDefaults Args((Class));
154 static Void local depInsts Args((Inst));
155 static Void local depClassBindings Args((List));
156 static Void local depAlt Args((Cell));
157 static Void local depRhs Args((Cell));
158 static Void local depGuard Args((Cell));
159 static Cell local depExpr Args((Int,Cell));
160 static Void local depPair Args((Int,Cell));
161 static Void local depTriple Args((Int,Cell));
162 static Void local depComp Args((Int,Cell,List));
163 static Void local depCaseAlt Args((Int,Cell));
164 static Cell local depVar Args((Int,Cell));
165 static Cell local depQVar Args((Int,Cell));
166 static Void local depConFlds Args((Int,Cell,Bool));
167 static Void local depUpdFlds Args((Int,Cell));
168 static List local depFields Args((Int,Cell,List,Bool));
170 static Void local depWith Args((Int,Cell));
171 static List local depDwFlds Args((Int,Cell,List));
174 static Cell local depRecord Args((Int,Cell));
177 static List local tcscc Args((List,List));
178 static List local bscc Args((List));
180 static Void local addRSsigdecls Args((Pair));
181 static Void local allNoPrevDef Args((Cell));
182 static Void local noPrevDef Args((Int,Cell));
183 static Bool local odiff Args((List,List));
185 static Void local duplicateErrorAux Args((Int,Module,Text,String));
186 #define duplicateError(l,m,t,k) duplicateErrorAux(l,m,t,k)
187 static Void local checkTypeIn Args((Pair));
189 /* --------------------------------------------------------------------------
190 * The code in this file is arranged in roughly the following order:
191 * - Kind inference preliminaries
192 * - Module declarations
193 * - Type declarations (data, type, newtype, type in)
194 * - Class declarations
196 * - Instance declarations
197 * - Default declarations
198 * - Primitive definitions
200 * - Infix expressions
201 * - Value definitions
202 * - Top-level static analysis and control
203 * - Haskell 98 compatibility tests
204 * ------------------------------------------------------------------------*/
206 /* --------------------------------------------------------------------------
207 * Kind checking preliminaries:
208 * ------------------------------------------------------------------------*/
210 Bool kindExpert = FALSE; /* TRUE => display kind errors in */
213 static Void local kindError(l,c,in,wh,k,o)
214 Int l; /* line number near constuctor exp */
215 Constr c; /* constructor */
216 Constr in; /* context (if any) */
217 String wh; /* place in which error occurs */
218 Kind k; /* expected kind (k,o) */
219 Int o; { /* inferred kind (typeIs,typeOff) */
222 if (!kindExpert) { /* for those with a fear of kinds */
223 ERRMSG(l) "Illegal type" ETHEN
225 ERRTEXT " \"" ETHEN ERRTYPE(in);
228 ERRTEXT " in %s\n", wh
232 ERRMSG(l) "Kind error in %s", wh ETHEN
234 ERRTEXT "\n*** expression : " ETHEN ERRTYPE(in);
236 ERRTEXT "\n*** constructor : " ETHEN ERRTYPE(c);
237 ERRTEXT "\n*** kind : " ETHEN ERRKIND(copyType(typeIs,typeOff));
238 ERRTEXT "\n*** does not match : " ETHEN ERRKIND(copyType(k,o));
240 ERRTEXT "\n*** because : %s", unifyFails ETHEN
246 #define shouldKind(l,c,in,wh,k,o) if (!kunify(typeIs,typeOff,k,o)) \
247 kindError(l,c,in,wh,k,o)
248 #define checkKind(l,a,m,c,in,wh,k,o) kindConstr(l,a,m,c); \
249 shouldKind(l,c,in,wh,k,o)
250 #define inferKind(k,o) typeIs=k; typeOff=o
252 static List unkindTypes; /* types in need of kind annotation*/
254 Kind extKind; /* Kind of extension, *->row->row */
257 /* --------------------------------------------------------------------------
258 * Static analysis of modules:
259 * ------------------------------------------------------------------------*/
265 Void startModule(nm) /* switch to a new module */
268 if (!isCon(nm)) internal("startModule");
269 if (isNull(m = findModule(textOf(nm))))
270 m = newModule(textOf(nm));
271 else if (!isPreludeScript()) {
272 /* You're allowed to break the rules in the Prelude! */
274 reloadModule = textToStr(textOf(nm));
276 ERRMSG(0) "Module \"%s\" already loaded", textToStr(textOf(nm))
282 Void setExportList(exps) /* Add export list to current module */
284 module(currentModule).exports = exps;
287 Void addQualImport(orig,new) /* Add to qualified import list */
288 Cell orig; /* Original name of module */
289 Cell new; { /* Name module is called within this module (or NIL) */
290 module(currentModule).qualImports =
291 cons(pair(isNull(new)?orig:new,orig),module(currentModule).qualImports);
294 Void addUnqualImport(mod,entities) /* Add to unqualified import list */
295 Cell mod; /* Name of module */
296 List entities; { /* List of entity names */
297 unqualImports = cons(pair(mod,entities),unqualImports);
300 static Void local checkQualImport(i) /* Process qualified import */
302 Module m = findModid(snd(i));
304 ERRMSG(0) "Module \"%s\" not previously loaded",
305 textToStr(textOf(snd(i)))
311 static Void local checkUnqualImport(i) /* Process unqualified import */
313 Module m = findModid(fst(i));
315 ERRMSG(0) "Module \"%s\" not previously loaded",
316 textToStr(textOf(fst(i)))
322 static Name local lookupName(t,nms) /* find text t in list of Names */
324 List nms; { /* :: [Name] */
325 for(; nonNull(nms); nms=tl(nms)) {
326 if (t == name(hd(nms)).text)
332 static List local checkSubentities(imports,named,wanted,description,textParent)
334 List named; /* :: [ Q?(Var|Con)(Id|Op) ] */
335 List wanted; /* :: [Name] */
336 String description; /* "<constructor>|<member> of <type>|<class>" */
338 for(; nonNull(named); named=tl(named)) {
340 /* ToDo: ignores qualifier; doesn't check that entity is in scope */
341 Text t = isPair(snd(x)) ? qtextOf(x) : textOf(x);
342 Name n = lookupName(t,wanted);
344 ERRMSG(0) "Entity \"%s\" is not a %s \"%s\"",
347 textToStr(textParent)
350 imports = cons(n,imports);
355 static List local checkImportEntity(imports,exporter,priv,entity)
356 List imports; /* Accumulated list of things to import */
359 Cell entity; { /* Entry from import list */
360 List oldImports = imports;
361 Text t = isIdent(entity) ? textOf(entity) : textOf(fst(entity));
364 es = module(exporter).names;
365 es = dupOnto(module(exporter).tycons,es);
366 es = dupOnto(module(exporter).classes,es);
368 es = module(exporter).exports;
371 for(; nonNull(es); es=tl(es)) {
372 Cell e = hd(es); /* :: Entity
373 | (Entity, NIL|DOTDOT)
380 if (tycon(f).text == t) {
381 imports = cons(f,imports);
382 if (!isIdent(entity)) {
383 switch (tycon(f).what) {
386 if (DOTDOT == snd(entity)) {
387 imports=dupOnto(tycon(f).defn,imports);
389 imports=checkSubentities(imports,snd(entity),tycon(f).defn,
390 "constructor of type",t);
394 /* deliberate fall thru */
398 } else if (isClass(f)) {
399 if (cclass(f).text == t) {
400 imports = cons(f,imports);
401 if (!isIdent(entity)) {
402 if (DOTDOT == snd(entity)) {
403 return dupOnto(cclass(f).members,imports);
405 return checkSubentities(imports,snd(entity),cclass(f).members,
406 "member of class",t);
411 internal("checkImportEntity2");
413 } else if (isName(e)) {
414 if (isIdent(entity) && name(e).text == t) {
415 imports = cons(e,imports);
417 } else if (isTycon(e) && priv) {
418 if (tycon(e).text == t) {
419 imports = cons(e,imports);
420 return dupOnto(tycon(e).defn,imports);
422 } else if (isClass(e) && priv) {
423 if (cclass(e).text == t) {
424 imports = cons(e,imports);
425 return dupOnto(cclass(e).members,imports);
427 } else if (whatIs(e) == TUPLE && priv) {
430 internal("checkImportEntity3");
433 if (imports == oldImports) {
434 ERRMSG(0) "Unknown entity \"%s\" imported from module \"%s\"",
436 textToStr(module(exporter ).text)
442 static List local resolveImportList(m,impList,priv)
443 Module m; /* exporting module */
447 if (DOTDOT == impList) {
448 List es = module(m).exports;
449 for(; nonNull(es); es=tl(es)) {
452 imports = cons(e,imports);
455 List subentities = NIL;
456 imports = cons(c,imports);
458 && (tycon(c).what == DATATYPE
459 || tycon(c).what == NEWTYPE))
460 subentities = tycon(c).defn;
462 subentities = cclass(c).members;
463 if (DOTDOT == snd(e)) {
464 imports = dupOnto(subentities,imports);
469 map2Accum(checkImportEntity,imports,m,priv,impList);
474 static Void local checkImportList(importSpec) /*Import a module unqualified*/
476 Module m = fst(importSpec);
477 Cell impList = snd(importSpec);
479 List imports = NIL; /* entities we want to import */
480 List hidden = NIL; /* entities we want to hide */
482 if (moduleThisScript(m)) {
483 ERRMSG(0) "Module \"%s\" recursively imports itself",
484 textToStr(module(m).text)
487 if (isPair(impList) && HIDDEN == fst(impList)) {
488 /* Somewhat inefficient - but obviously correct:
489 * imports = importsOf("module Foo") `setDifference` hidden;
491 hidden = resolveImportList(m, snd(impList),FALSE);
492 imports = resolveImportList(m, DOTDOT,FALSE);
493 } else if (isPair(impList) && STAR == fst(impList)) {
495 imports = resolveImportList(m, DOTDOT, FALSE);
496 privileged = resolveImportList(m, snd(impList),TRUE);
497 imports = dupOnto(privileged,imports);
499 imports = resolveImportList(m, impList,FALSE);
502 for(; nonNull(imports); imports=tl(imports)) {
503 Cell e = hd(imports);
504 if (!cellIsMember(e,hidden))
507 /* ToDo: hang onto the imports list for processing export list entries
508 * of the form "module Foo"
512 static Void local importEntity(source,e)
516 case NAME : importName(source,e);
519 case TYCON : importTycon(source,e);
521 case CLASS : importClass(source,e);
523 default: internal("importEntity");
527 static Void local importName(source,n)
530 Name clash = addName(n);
531 if (nonNull(clash) && clash!=n) {
532 ERRMSG(0) "Entity \"%s\" imported from module \"%s\" already defined in module \"%s\"",
533 textToStr(name(n).text),
534 textToStr(module(source).text),
535 textToStr(module(name(clash).mod).text)
540 static Void local importTycon(source,tc)
543 Tycon clash=addTycon(tc);
544 if (nonNull(clash) && clash!=tc) {
545 ERRMSG(0) "Tycon \"%s\" imported from \"%s\" already defined in module \"%s\"",
546 textToStr(tycon(tc).text),
547 textToStr(module(source).text),
548 textToStr(module(tycon(clash).mod).text)
551 if (nonNull(findClass(tycon(tc).text))) {
552 ERRMSG(0) "Import of type constructor \"%s\" clashes with class in module \"%s\"",
553 textToStr(tycon(tc).text),
554 textToStr(module(tycon(tc).mod).text)
559 static Void local importClass(source,c)
562 Class clash=addClass(c);
563 if (nonNull(clash) && clash!=c) {
564 ERRMSG(0) "Class \"%s\" imported from \"%s\" already defined in module \"%s\"",
565 textToStr(cclass(c).text),
566 textToStr(module(source).text),
567 textToStr(module(cclass(clash).mod).text)
570 if (nonNull(findTycon(cclass(c).text))) {
571 ERRMSG(0) "Import of class \"%s\" clashes with type constructor in module \"%s\"",
572 textToStr(cclass(c).text),
573 textToStr(module(source).text)
578 static List local checkExportTycon(exports,mt,spec,tc)
583 if (DOTDOT == spec || SYNONYM == tycon(tc).what) {
584 return cons(pair(tc,DOTDOT), exports);
586 return cons(pair(tc,NIL), exports);
590 static List local checkExportClass(exports,mt,spec,cl)
595 if (DOTDOT == spec) {
596 return cons(pair(cl,DOTDOT), exports);
598 return cons(pair(cl,NIL), exports);
602 static List local checkExport(exports,mt,e) /* Process entry in export list*/
608 List origExports = exports;
609 if (nonNull(export=findQualName(e))) {
610 exports=cons(export,exports);
612 if (isQCon(e) && nonNull(export=findQualTycon(e))) {
613 exports = checkExportTycon(exports,mt,NIL,export);
615 if (isQCon(e) && nonNull(export=findQualClass(e))) {
616 /* opaque class export */
617 exports = checkExportClass(exports,mt,NIL,export);
619 if (exports == origExports) {
620 ERRMSG(0) "Unknown entity \"%s\" exported from module \"%s\"",
626 } else if (MODULEENT == fst(e)) {
627 Module m = findModid(snd(e));
628 /* ToDo: shouldn't allow export of module we didn't import */
630 ERRMSG(0) "Unknown module \"%s\" exported from module \"%s\"",
631 textToStr(textOf(snd(e))),
635 if (m == currentModule) {
636 /* Exporting the current module exports local definitions */
638 for(xs=module(m).classes; nonNull(xs); xs=tl(xs)) {
639 if (cclass(hd(xs)).mod==m)
640 exports = checkExportClass(exports,mt,DOTDOT,hd(xs));
642 for(xs=module(m).tycons; nonNull(xs); xs=tl(xs)) {
643 if (tycon(hd(xs)).mod==m)
644 exports = checkExportTycon(exports,mt,DOTDOT,hd(xs));
646 for(xs=module(m).names; nonNull(xs); xs=tl(xs)) {
647 if (name(hd(xs)).mod==m)
648 exports = cons(hd(xs),exports);
651 /* Exporting other modules imports all things imported
652 * unqualified from it.
653 * ToDo: we reexport everything exported by a module -
654 * whether we imported it or not. This gives the wrong
655 * result for "module M(module N) where import N(x)"
657 exports = dupOnto(module(m).exports,exports);
661 Cell ident = fst(e); /* class name or type name */
662 Cell parts = snd(e); /* members or constructors */
664 if (isQCon(ident) && nonNull(nm=findQualTycon(ident))) {
665 switch (tycon(nm).what) {
668 ERRMSG(0) "Explicit constructor list given for type synonym"
669 " \"%s\" in export list of module \"%s\"",
674 return cons(pair(nm,DOTDOT),exports);
676 ERRMSG(0) "Transparent export of restricted type synonym"
677 " \"%s\" in export list of module \"%s\"",
681 return exports; /* Not reached */
685 return cons(pair(nm,DOTDOT),exports);
687 exports = checkSubentities(exports,parts,tycon(nm).defn,
688 "constructor of type",
690 return cons(pair(nm,DOTDOT), exports);
693 internal("checkExport1");
695 } else if (isQCon(ident) && nonNull(nm=findQualClass(ident))) {
696 if (DOTDOT == parts) {
697 return cons(pair(nm,DOTDOT),exports);
699 exports = checkSubentities(exports,parts,cclass(nm).members,
700 "member of class",cclass(nm).text);
701 return cons(pair(nm,DOTDOT), exports);
704 ERRMSG(0) "Explicit export list given for non-class/datatype \"%s\" in export list of module \"%s\"",
710 return exports; /* NOTUSED */
713 static List local checkExports(exports)
715 Module m = lastModule();
716 Text mt = module(m).text;
719 map1Accum(checkExport,es,mt,exports);
722 for(xs=es; nonNull(xs); xs=tl(xs)) {
723 Printf(" %s", textToStr(textOfEntity(hd(xs))));
730 /* --------------------------------------------------------------------------
731 * Static analysis of type declarations:
733 * Type declarations come in two forms:
734 * - data declarations - define new constructed data types
735 * - type declarations - define new type synonyms
737 * A certain amount of work is carried out as the declarations are
738 * read during parsing. In particular, for each type constructor
739 * definition encountered:
740 * - check that there is no previous definition of constructor
741 * - ensure type constructor not previously used as a class name
742 * - make a new entry in the type constructor table
743 * - record line number of declaration
744 * - Build separate lists of newly defined constructors for later use.
745 * ------------------------------------------------------------------------*/
747 Void tyconDefn(line,lhs,rhs,what) /* process new type definition */
748 Int line; /* definition line number */
749 Cell lhs; /* left hand side of definition */
750 Cell rhs; /* right hand side of definition */
751 Cell what; { /* SYNONYM/DATATYPE/etc... */
752 Text t = textOf(getHead(lhs));
754 if (nonNull(findTycon(t))) {
755 ERRMSG(line) "Repeated definition of type constructor \"%s\"",
759 else if (nonNull(findClass(t))) {
760 ERRMSG(line) "\"%s\" used as both class and type constructor",
765 Tycon nw = newTycon(t);
766 tyconDefns = cons(nw,tyconDefns);
767 tycon(nw).line = line;
768 tycon(nw).arity = argCount;
769 tycon(nw).what = what;
770 if (what==RESTRICTSYN) {
771 h98DoesntSupport(line,"restricted type synonyms");
772 typeInDefns = cons(pair(nw,snd(rhs)),typeInDefns);
775 tycon(nw).defn = pair(lhs,rhs);
779 Void setTypeIns(bs) /* set local synonyms for given */
780 List bs; { /* binding group */
781 List cvs = typeInDefns;
782 for (; nonNull(cvs); cvs=tl(cvs)) {
783 Tycon c = fst(hd(cvs));
784 List vs = snd(hd(cvs));
785 for (tycon(c).what = RESTRICTSYN; nonNull(vs); vs=tl(vs)) {
786 if (nonNull(findBinding(textOf(hd(vs)),bs))) {
787 tycon(c).what = SYNONYM;
794 Void clearTypeIns() { /* clear list of local synonyms */
795 for (; nonNull(typeInDefns); typeInDefns=tl(typeInDefns))
796 tycon(fst(hd(typeInDefns))).what = RESTRICTSYN;
799 /* --------------------------------------------------------------------------
800 * Further analysis of Type declarations:
802 * In order to allow the definition of mutually recursive families of
803 * data types, the static analysis of the right hand sides of type
804 * declarations cannot be performed until all of the type declarations
807 * Once parsing is complete, we carry out the following:
809 * - check format of lhs, extracting list of bound vars and ensuring that
810 * there are no repeated variables and no Skolem variables.
811 * - run dependency analysis on rhs to check that only bound type vars
812 * appear in type and that all constructors are defined.
813 * Replace type variables by offsets, constructors by Tycons.
814 * - use list of dependents to sort into strongly connected components.
815 * - ensure that there is not more than one synonym in each group.
816 * - kind-check each group of type definitions.
818 * - check that there are no previous definitions for constructor
819 * functions in data type definitions.
820 * - install synonym expansions and constructor definitions.
821 * ------------------------------------------------------------------------*/
823 static List tcDeps = NIL; /* list of dependent tycons/classes*/
825 static Void local checkTyconDefn(d) /* validate type constructor defn */
827 Cell lhs = fst(tycon(d).defn);
828 Cell rhs = snd(tycon(d).defn);
829 Int line = tycon(d).line;
830 List tyvars = getArgs(lhs);
832 /* check for repeated tyvars on lhs*/
833 for (temp=tyvars; nonNull(temp); temp=tl(temp))
834 if (nonNull(varIsMember(textOf(hd(temp)),tl(temp)))) {
835 ERRMSG(line) "Repeated type variable \"%s\" on left hand side",
836 textToStr(textOf(hd(temp)))
840 tcDeps = NIL; /* find dependents */
841 switch (whatIs(tycon(d).what)) {
843 case SYNONYM : rhs = depTypeExp(line,tyvars,rhs);
844 if (cellIsMember(d,tcDeps)) {
845 ERRMSG(line) "Recursive type synonym \"%s\"",
846 textToStr(tycon(d).text)
852 case NEWTYPE : depConstrs(d,tyvars,rhs);
856 default : internal("checkTyconDefn");
861 tycon(d).kind = tcDeps;
865 static Void local depConstrs(t,tyvars,cd)
866 Tycon t; /* Define constructor functions and*/
867 List tyvars; /* do dependency analysis for data */
868 Cell cd; { /* definitions (w or w/o deriving) */
869 Int line = tycon(t).line;
874 List derivs = snd(cd);
875 List compTypes = NIL;
879 for (i=0; i<tycon(t).arity; ++i) /* build representation for tycon */
880 lhs = ap(lhs,mkOffset(i)); /* applied to full comp. of args */
882 if (isQualType(cs)) { /* allow for possible context */
885 map2Over(depPredExp,line,tyvars,ctxt);
886 h98CheckCtxt(line,"context",TRUE,ctxt,NIL);
889 if (nonNull(cs) && isNull(tl(cs))) /* Single constructor datatype? */
892 for (; nonNull(cs); cs=tl(cs)) { /* For each constructor function: */
894 List sig = dupList(tyvars);
895 List evs = NIL; /* locally quantified vars */
896 List lps = NIL; /* locally bound predicates */
897 List ctxt1 = ctxt; /* constructor function context */
898 List scs = NIL; /* strict components */
899 List fs = NONE; /* selector names */
900 Type type = lhs; /* constructor function type */
901 Int arity = 0; /* arity of constructor function */
902 Int nr2 = 0; /* Number of rank 2 args */
903 Name n; /* name for constructor function */
905 if (whatIs(con)==POLYTYPE) { /* Locally quantified vars */
908 sig = checkQuantVars(line,evs,sig,con);
911 if (isQualType(con)) { /* Local predicates */
914 for (us = typeVarsIn(lps,NIL,NIL,NIL); nonNull(us); us=tl(us))
915 if (!varIsMember(textOf(hd(us)),evs)) {
917 "Variable \"%s\" in constraint is not locally bound",
918 textToStr(textOf(hd(us)))
921 map2Over(depPredExp,line,sig,lps);
926 if (whatIs(con)==LABC) { /* Skeletize constr components */
927 Cell fls = snd(snd(con)); /* get field specifications */
930 for (; nonNull(fls); fls=tl(fls)) { /* for each field spec: */
931 List vs = fst(hd(fls));
932 Type t = snd(hd(fls)); /* - scrutinize type */
933 Bool banged = whatIs(t)==BANG;
934 t = depCompType(line,sig,(banged ? arg(t) : t));
935 while (nonNull(vs)) { /* - add named components */
943 scs = cons(mkInt(arity),scs);
947 scs = rev(scs); /* put strict comps in ascend ord */
949 else { /* Non-labelled constructor */
952 for (; isAp(c); c=fun(c))
954 for (compNo=arity, c=con; isAp(c); c=fun(c)) {
956 if (whatIs(t)==BANG) {
957 scs = cons(mkInt(compNo),scs);
961 arg(c) = depCompType(line,sig,t);
965 if (nonNull(ctxt1)) /* Extract relevant part of context*/
966 ctxt1 = selectCtxt(ctxt1,offsetTyvarsIn(con,NIL));
968 for (i=arity; isAp(con); i--) { /* Calculate type of constructor */
971 fun(con) = typeArrow;
972 if (isPolyOrQualType(cmp)) {
973 if (nonNull(derivs)) {
974 ERRMSG(line) "Cannot derive instances for types" ETHEN
975 ERRTEXT " with polymorphic or qualified components"
981 if (nonNull(derivs)) /* and build list of components */
982 compTypes = cons(cmp,compTypes);
987 if (nr2>0) { /* Add rank 2 annotation */
988 type = ap(RANK2,pair(mkInt(nr2-length(lps)),type));
991 if (nonNull(evs)) { /* Add existential annotation */
992 if (nonNull(derivs)) {
993 ERRMSG(line) "Cannot derive instances for types" ETHEN
994 ERRTEXT " with existentially typed components"
999 "Cannot use selectors with existentially typed components"
1002 type = ap(EXIST,pair(mkInt(length(evs)),type));
1005 if (nonNull(lps)) { /* Add local preds part to type */
1006 type = ap(CDICTS,pair(lps,type));
1009 if (nonNull(ctxt1)) { /* Add context part to type */
1010 type = ap(QUAL,pair(ctxt1,type));
1013 if (nonNull(sig)) { /* Add quantifiers to type */
1015 for (; nonNull(ts1); ts1=tl(ts1)) {
1018 type = mkPolyType(sig,type);
1021 n = findName(textOf(con)); /* Allocate constructor fun name */
1023 n = newName(textOf(con),NIL);
1024 } else if (name(n).defn!=PREDEFINED) {
1025 duplicateError(line,name(n).mod,name(n).text,
1026 "constructor function");
1028 name(n).arity = arity; /* Save constructor fun details */
1029 name(n).line = line;
1031 name(n).number = cfunNo(conNo++);
1032 name(n).type = type;
1033 if (tycon(t).what==NEWTYPE) {
1036 "A newtype constructor cannot have class constraints"
1041 "A newtype constructor must have exactly one argument"
1046 "Illegal strictess annotation for newtype constructor"
1049 name(n).defn = nameId;
1051 implementCfun(n,scs);
1056 sels = addSels(line,n,fs,sels);
1060 if (nonNull(sels)) {
1062 fst(cd) = appendOnto(fst(cd),sels);
1063 selDefns = cons(sels,selDefns);
1066 if (nonNull(derivs)) { /* Generate derived instances */
1067 map3Proc(checkDerive,t,ctxt,compTypes,derivs);
1071 Int userArity(c) /* Find arity for cfun, ignoring */
1072 Name c; { /* CDICTS parameters */
1073 Int a = name(c).arity;
1074 Type t = name(c).type;
1076 if (isPolyType(t)) {
1079 if ((w=whatIs(t))==QUAL) {
1080 w = whatIs(t=snd(snd(t)));
1083 a -= length(fst(snd(t)));
1089 static List local addSels(line,c,fs,ss) /* Add fields to selector list */
1090 Int line; /* line number of constructor */
1091 Name c; /* corresponding constr function */
1092 List fs; /* list of fields (varids) */
1093 List ss; { /* list of existing selectors */
1095 cfunSfuns = cons(pair(c,fs),cfunSfuns);
1096 for (; nonNull(fs); fs=tl(fs), ++sn) {
1098 Text t = textOf(hd(fs));
1100 if (nonNull(varIsMember(t,tl(fs)))) {
1101 ERRMSG(line) "Repeated field name \"%s\" for constructor \"%s\"",
1102 textToStr(t), textToStr(name(c).text)
1106 while (nonNull(ns) && t!=name(hd(ns)).text) {
1111 name(hd(ns)).defn = cons(pair(c,mkInt(sn)),name(hd(ns)).defn);
1113 Name n = findName(t);
1115 ERRMSG(line) "Repeated definition for selector \"%s\"",
1120 name(n).line = line;
1121 name(n).number = SELNAME;
1122 name(n).defn = singleton(pair(c,mkInt(sn)));
1129 static List local selectCtxt(ctxt,vs) /* calculate subset of context */
1136 for (; nonNull(ctxt); ctxt=tl(ctxt)) {
1137 List us = offsetTyvarsIn(hd(ctxt),NIL);
1138 for (; nonNull(us) && cellIsMember(hd(us),vs); us=tl(us)) {
1141 ps = cons(hd(ctxt),ps);
1148 static Void local checkSynonyms(ts) /* Check for mutually recursive */
1149 List ts; { /* synonyms */
1151 for (; nonNull(ts); ts=tl(ts)) { /* build list of all synonyms */
1153 switch (whatIs(tycon(t).what)) {
1155 case RESTRICTSYN : syns = cons(t,syns);
1159 while (nonNull(syns)) { /* then visit each synonym */
1160 syns = visitSyn(NIL,hd(syns),syns);
1164 static List local visitSyn(path,t,syns) /* visit synonym definition to look*/
1165 List path; /* for cycles */
1168 if (cellIsMember(t,path)) { /* every elt in path depends on t */
1169 ERRMSG(tycon(t).line)
1170 "Type synonyms \"%s\" and \"%s\" are mutually recursive",
1171 textToStr(tycon(t).text), textToStr(tycon(hd(path)).text)
1174 List ds = tycon(t).kind;
1176 for (; nonNull(ds); ds=tl(ds)) {
1177 if (cellIsMember(hd(ds),syns)) {
1178 if (isNull(path1)) {
1179 path1 = cons(t,path);
1181 syns = visitSyn(path1,hd(ds),syns);
1185 tycon(t).defn = fullExpand(tycon(t).defn);
1186 return removeCell(t,syns);
1189 /* --------------------------------------------------------------------------
1190 * Expanding out all type synonyms in a type expression:
1191 * ------------------------------------------------------------------------*/
1193 Type fullExpand(t) /* find full expansion of type exp */
1194 Type t; { /* assuming that all relevant */
1195 Cell h = t; /* synonym defns of lower rank have*/
1196 Int n = 0; /* already been fully expanded */
1198 for (args=NIL; isAp(h); h=fun(h), n++) {
1199 args = cons(fullExpand(arg(h)),args);
1201 t = applyToArgs(h,args);
1202 if (isSynonym(h) && n>=tycon(h).arity) {
1203 if (n==tycon(h).arity) {
1204 t = instantiateSyn(tycon(h).defn,t);
1207 while (--n > tycon(h).arity) {
1210 fun(p) = instantiateSyn(tycon(h).defn,fun(p));
1216 static Type local instantiateSyn(t,env) /* instantiate type according using*/
1217 Type t; /* env to determine appropriate */
1218 Type env; { /* values for OFFSET type vars */
1219 switch (whatIs(t)) {
1220 case AP : return ap(instantiateSyn(fun(t),env),
1221 instantiateSyn(arg(t),env));
1223 case OFFSET : return nthArg(offsetOf(t),env);
1229 /* --------------------------------------------------------------------------
1230 * Static analysis of class declarations:
1232 * Performed in a similar manner to that used for type declarations.
1234 * The first part of the static analysis is performed as the declarations
1235 * are read during parsing. The parser ensures that:
1236 * - the class header and all superclass predicates are of the form
1239 * The classDefn() function:
1240 * - ensures that there is no previous definition for class
1241 * - checks that class name has not previously been used as a type constr.
1242 * - make new entry in class table
1243 * - record line number of declaration
1244 * - build list of classes defined in current script for use in later
1245 * stages of static analysis.
1246 * ------------------------------------------------------------------------*/
1248 Void classDefn(line,head,ms,fds) /* process new class definition */
1249 Int line; /* definition line number */
1250 Cell head; /* class header :: ([Supers],Class) */
1251 List ms; /* class definition body */
1252 List fds; { /* functional dependencies */
1253 Text ct = textOf(getHead(snd(head)));
1254 Int arity = argCount;
1256 if (nonNull(findClass(ct))) {
1257 ERRMSG(line) "Repeated definition of class \"%s\"",
1260 } else if (nonNull(findTycon(ct))) {
1261 ERRMSG(line) "\"%s\" used as both class and type constructor",
1265 Class nw = newClass(ct);
1266 cclass(nw).line = line;
1267 cclass(nw).arity = arity;
1268 cclass(nw).head = snd(head);
1269 cclass(nw).supers = fst(head);
1270 cclass(nw).members = ms;
1271 cclass(nw).level = 0;
1272 cclass(nw).fds = fds;
1273 cclass(nw).xfds = NIL;
1274 classDefns = cons(nw,classDefns);
1276 h98DoesntSupport(line,"multiple parameter classes");
1280 /* --------------------------------------------------------------------------
1281 * Further analysis of class declarations:
1283 * Full static analysis of class definitions must be postponed until the
1284 * complete script has been read and all static analysis on type definitions
1285 * has been completed.
1287 * Once this has been achieved, we carry out the following checks on each
1289 * - check that variables in header are distinct
1290 * - replace head by skeleton
1291 * - check superclass declarations, replace by skeletons
1292 * - split body of class into members and declarations
1293 * - make new name entry for each member function
1294 * - record member function number (eventually an offset into dictionary!)
1295 * - no member function has a previous definition ...
1296 * - no member function is mentioned more than once in the list of members
1297 * - each member function type is valid, replace vars by offsets
1298 * - qualify each member function type by class header
1299 * - only bindings for members appear in defaults
1300 * - only function bindings appear in defaults
1301 * - check that extended class hierarchy does not contain any cycles
1302 * ------------------------------------------------------------------------*/
1304 static Void local checkClassDefn(c) /* validate class definition */
1307 Int args = cclass(c).arity - 1;
1308 Cell temp = cclass(c).head;
1312 for (; isAp(temp); temp=fun(temp)) {
1313 if (!isVar(arg(temp))) {
1314 ERRMSG(cclass(c).line) "Type variable required in class head"
1317 if (nonNull(varIsMember(textOf(arg(temp)),tyvars))) {
1318 ERRMSG(cclass(c).line)
1319 "Repeated type variable \"%s\" in class head",
1320 textToStr(textOf(arg(temp)))
1323 tyvars = cons(arg(temp),tyvars);
1326 for (fs=cclass(c).fds; nonNull(fs); fs=tl(fs)) {
1330 /* Check for trivial dependency
1333 ERRMSG(cclass(c).line) "Functional dependency is trivial"
1337 /* Check for duplicated vars on right hand side, and for vars on
1338 * right that also appear on the left:
1340 for (vs=snd(fd); nonNull(vs); vs=tl(vs)) {
1341 if (varIsMember(textOf(hd(vs)),fst(fd))) {
1342 ERRMSG(cclass(c).line)
1343 "Trivial dependency for variable \"%s\"",
1344 textToStr(textOf(hd(vs)))
1347 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1348 ERRMSG(cclass(c).line)
1349 "Repeated variable \"%s\" in functional dependency",
1350 textToStr(textOf(hd(vs)))
1353 hd(vs) = depTypeVar(cclass(c).line,tyvars,textOf(hd(vs)));
1356 /* Check for duplicated vars on left hand side:
1358 for (vs=fst(fd); nonNull(vs); vs=tl(vs)) {
1359 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1360 ERRMSG(cclass(c).line)
1361 "Repeated variable \"%s\" in functional dependency",
1362 textToStr(textOf(hd(vs)))
1365 hd(vs) = depTypeVar(cclass(c).line,tyvars,textOf(hd(vs)));
1369 if (cclass(c).arity==0) {
1372 Int args = cclass(c).arity - 1;
1373 for (temp=cclass(c).head; args>0; temp=fun(temp), args--) {
1374 arg(temp) = mkOffset(args);
1376 arg(temp) = mkOffset(0);
1380 tcDeps = NIL; /* find dependents */
1381 map2Over(depPredExp,cclass(c).line,tyvars,cclass(c).supers);
1382 h98CheckCtxt(cclass(c).line,"class definition",FALSE,cclass(c).supers,NIL);
1383 cclass(c).numSupers = length(cclass(c).supers);
1384 cclass(c).defaults = extractBindings(cclass(c).members); /* defaults*/
1385 ss = extractSigdecls(cclass(c).members);
1386 fs = extractFixdecls(cclass(c).members);
1387 cclass(c).members = pair(ss,fs);
1388 map2Proc(checkMems,c,tyvars,ss);
1390 cclass(c).kinds = tcDeps;
1395 /* --------------------------------------------------------------------------
1396 * Functional dependencies are inherited from superclasses.
1397 * For example, if I've got the following classes:
1399 * class C a b | a -> b
1400 * class C [b] a => D a b
1402 * then C will have the dependency ([a], [b]) as expected, and D will inherit
1403 * the dependency ([b], [a]) from C.
1404 * When doing pairwise improvement, we have to consider not just improving
1405 * when we see a pair of Cs or a pair of Ds in the context, but when we've
1406 * got a C and a D as well. In this case, we only improve when the
1407 * predicate in question matches the type skeleton in the relevant superclass
1408 * constraint. E.g., we improve the pair (C [Int] a, D b Int) (unifying
1409 * a and b), but we don't improve the pair (C Int a, D b Int).
1410 * To implement functional dependency inheritance, we calculate
1411 * the closure of all functional dependencies, and store the result
1412 * in an additional field `xfds' (extended functional dependencies).
1413 * The `xfds' field is a list of functional dependency lists, annotated
1414 * with a list of predicate skeletons constraining when improvement can
1415 * happen against this dependency list. For example, the xfds field
1416 * for C above would be:
1417 * [([C a b], [([a], [b])])]
1418 * and the xfds field for D would be:
1419 * [([C [b] a, D a b], [([b], [a])])]
1420 * Self-improvement (of a C with a C, or a D with a D) is treated as a
1421 * special case of an inherited dependency.
1422 * ------------------------------------------------------------------------*/
1423 static List local inheritFundeps ( Class c, Cell pi, Int o )
1425 Int alpha = newKindedVars(cclass(c).kinds);
1426 List scs = cclass(c).supers;
1429 /* better not fail ;-) */
1430 if (!matchPred(pi,o,cclass(c).head,alpha))
1431 internal("inheritFundeps - predicate failed to match it's own head!");
1432 this = copyPred(pi,o);
1433 for (; nonNull(scs); scs=tl(scs)) {
1434 Class s = getHead(hd(scs));
1436 List sfds = inheritFundeps(s,hd(scs),alpha);
1437 for (; nonNull(sfds); sfds=tl(sfds)) {
1439 xfds = cons(pair(cons(this,fst(h)),snd(h)),xfds);
1443 if (nonNull(cclass(c).fds)) {
1444 List fds = NIL, fs = cclass(c).fds;
1445 for (; nonNull(fs); fs=tl(fs)) {
1446 fds = cons(pair(otvars(this,fst(hd(fs))),
1447 otvars(this,snd(hd(fs)))),fds);
1449 xfds = cons(pair(cons(this,NIL),fds),xfds);
1454 static Void local extendFundeps ( Class c )
1457 emptySubstitution();
1458 alpha = newKindedVars(cclass(c).kinds);
1459 cclass(c).xfds = inheritFundeps(c,cclass(c).head,alpha);
1461 /* we can now check for ambiguity */
1462 map1Proc(checkMems2,c,fst(cclass(c).members));
1466 static Cell local depPredExp(line,tyvars,pred)
1473 for (; isAp(h); args++) {
1474 arg(h) = depTypeExp(line,tyvars,arg(h));
1480 h98DoesntSupport(line,"tag classes");
1481 } else if (args!=1) {
1482 h98DoesntSupport(line,"multiple parameter classes");
1485 if (isQCon(h)) { /* standard class constraint */
1486 Class c = findQualClass(h);
1488 ERRMSG(line) "Undefined class \"%s\"", identToStr(h)
1496 if (args!=cclass(c).arity) {
1497 ERRMSG(line) "Wrong number of arguments for class \"%s\"",
1498 textToStr(cclass(c).text)
1501 if (cellIsMember(c,classDefns) && !cellIsMember(c,tcDeps)) {
1502 tcDeps = cons(c,tcDeps);
1506 else if (isExt(h)) { /* Lacks predicate */
1507 if (args!=1) { /* parser shouldn't let this happen*/
1508 ERRMSG(line) "Wrong number of arguments for lacks predicate"
1515 if (whatIs(h) != IPCELL)
1518 internal("depPredExp");
1523 static Void local checkMems(c,tyvars,m) /* check member function details */
1527 Int line = intOf(fst3(m));
1534 if (isPolyType(t)) {
1540 tyvars = typeVarsIn(t,NIL,xtvs,tyvars);
1541 /* Look for extra type vars. */
1542 checkOptQuantVars(line,xtvs,tyvars);
1544 if (isQualType(t)) { /* Overloaded member signatures? */
1545 map2Over(depPredExp,line,tyvars,fst(snd(t)));
1547 t = ap(QUAL,pair(NIL,t));
1550 fst(snd(t)) = cons(cclass(c).head,fst(snd(t)));/* Add main predicate */
1551 snd(snd(t)) = depTopType(line,tyvars,snd(snd(t)));
1553 for (tvs=tyvars; nonNull(tvs); tvs=tl(tvs)){/* Quantify */
1557 t = mkPolyType(sig,t);
1559 thd3(m) = t; /* Save type */
1560 take(cclass(c).arity,tyvars); /* Delete extra type vars */
1562 if (isAmbiguous(t)) {
1563 ambigError(line,"class declaration",hd(vs),t);
1565 h98CheckType(line,"member type",hd(vs),t);
1568 static Void local checkMems2(c,m) /* check member function details */
1571 Int line = intOf(fst3(m));
1576 static Void local addMembers(c) /* Add definitions of member funs */
1577 Class c; { /* and other parts of class struct.*/
1578 List ms = fst(cclass(c).members);
1579 List fs = snd(cclass(c).members);
1580 List ns = NIL; /* List of names */
1581 Int mno; /* Member function number */
1583 for (mno=0; mno<cclass(c).numSupers; mno++) {
1584 ns = cons(newDSel(c,mno),ns);
1586 cclass(c).dsels = rev(ns); /* Save dictionary selectors */
1588 for (mno=1, ns=NIL; nonNull(ms); ms=tl(ms)) {
1589 Int line = intOf(fst3(hd(ms)));
1590 List vs = rev(snd3(hd(ms)));
1591 Type t = thd3(hd(ms));
1592 for (; nonNull(vs); vs=tl(vs)) {
1593 ns = cons(newMember(line,mno++,hd(vs),t,c),ns);
1596 cclass(c).members = rev(ns); /* Save list of members */
1597 cclass(c).numMembers = length(cclass(c).members);
1599 for (; nonNull(fs); fs=tl(fs)) { /* fixity declarations */
1600 Int line = intOf(fst3(hd(fs)));
1601 List ops = snd3(hd(fs));
1602 Syntax s = intOf(thd3(hd(fs)));
1603 for (; nonNull(ops); ops=tl(ops)) {
1604 Name n = nameIsMember(textOf(hd(ops)),cclass(c).members);
1606 missFixity(line,textOf(hd(ops)));
1607 } else if (name(n).syntax!=NO_SYNTAX) {
1608 dupFixity(line,textOf(hd(ops)));
1614 /* Not actually needed just yet; for the time being, dictionary code will
1615 not be passed through the type checker.
1617 cclass(c).dtycon = addPrimTycon(generateText("Dict.%s",c),
1624 mno = cclass(c).numSupers + cclass(c).numMembers;
1625 /* cclass(c).dcon = addPrimCfun(generateText("Make.%s",c),mno,0,NIL); */
1626 cclass(c).dcon = addPrimCfun(generateText(":D%s",c),mno,0,NIL);
1627 /* implementCfun(cclass(c).dcon,NIL);
1628 Don't manufacture a wrapper fn for dictionary constructors.
1629 Applications of dictionary constructors are always saturated,
1630 and translate.c:stgExpr() special-cases saturated constructor apps.
1633 if (mno==1) { /* Single entry dicts use newtype */
1634 name(cclass(c).dcon).defn = nameId;
1635 if (nonNull(cclass(c).members)) {
1636 name(hd(cclass(c).members)).number = mfunNo(0);
1639 cclass(c).defaults = classBindings("class",c,cclass(c).defaults);
1642 static Name local newMember(l,no,v,t,parent)
1643 Int l; /* Make definition for member fn */
1648 Name m = findName(textOf(v));
1651 m = newName(textOf(v),parent);
1652 } else if (name(m).defn!=PREDEFINED) {
1653 ERRMSG(l) "Repeated definition for member function \"%s\"",
1654 textToStr(name(m).text)
1660 name(m).number = mfunNo(no);
1665 Name newDSel(c,no) /* Make definition for dict selectr*/
1671 /* sprintf(buf,"sc%d.%s",no,"%s"); */
1672 sprintf(buf,"$p%d%s",no+1,"%s");
1673 s = newName(generateText(buf,c),c);
1674 name(s).line = cclass(c).line;
1676 name(s).number = DFUNNAME;
1682 static Text local generateText(sk,c) /* We need to generate names for */
1683 String sk; /* certain objects corresponding */
1684 Class c; { /* to each class. */
1685 String cname = textToStr(cclass(c).text);
1686 char buffer[MAX_GEN+1];
1688 if ((strlen(sk)+strlen(cname))>=MAX_GEN) {
1689 ERRMSG(0) "Please use a shorter name for class \"%s\"", cname
1692 sprintf(buffer,sk,cname);
1693 return findText(buffer);
1696 Int visitClass(c) /* visit class defn to check that */
1697 Class c; { /* class hierarchy is acyclic */
1699 if (isExt(c)) { /* special case for lacks preds */
1703 if (cclass(c).level < 0) { /* already visiting this class? */
1704 ERRMSG(cclass(c).line) "Class hierarchy for \"%s\" is not acyclic",
1705 textToStr(cclass(c).text)
1707 } else if (cclass(c).level == 0) { /* visiting class for first time */
1708 List scs = cclass(c).supers;
1710 cclass(c).level = (-1);
1711 for (; nonNull(scs); scs=tl(scs)) {
1712 Int l = visitClass(getHead(hd(scs)));
1715 cclass(c).level = 1+lev; /* level = 1 + max level of supers */
1717 return cclass(c).level;
1720 /* --------------------------------------------------------------------------
1721 * Process class and instance declaration binding groups:
1722 * ------------------------------------------------------------------------*/
1724 static List local classBindings(where,c,bs)
1725 String where; /* Check validity of bindings bs */
1726 Class c; /* for class c (or an inst of c) */
1727 List bs; { /* sort into approp. member order */
1730 for (; nonNull(bs); bs=tl(bs)) {
1732 Cell body = snd(snd(b));
1735 if (!isVar(fst(b))) { /* Only allow function bindings */
1736 ERRMSG(rhsLine(snd(body)))
1737 "Pattern binding illegal in %s declaration", where
1741 if (isNull(mnm=memberName(c,textOf(fst(b))))) {
1742 ERRMSG(rhsLine(snd(hd(body))))
1743 "No member \"%s\" in class \"%s\"",
1744 textToStr(textOf(fst(b))), textToStr(cclass(c).text)
1748 nbs = numInsert(mfunOf(mnm)-1,b,nbs);
1753 static Name local memberName(c,t) /* return name of member function */
1754 Class c; /* with name t in class c */
1755 Text t; { /* return NIL if not a member */
1756 List ms = cclass(c).members;
1757 for (; nonNull(ms); ms=tl(ms)) {
1758 if (t==name(hd(ms)).text) {
1765 static List local numInsert(n,x,xs) /* insert x at nth position in xs, */
1766 Int n; /* filling gaps with NIL */
1769 List start = isNull(xs) ? cons(NIL,NIL) : xs;
1771 for (xs=start; 0<n--; xs=tl(xs)) {
1772 if (isNull(tl(xs))) {
1773 tl(xs) = cons(NIL,NIL);
1780 /* --------------------------------------------------------------------------
1781 * Calculate set of variables appearing in a given type expression (possibly
1782 * qualified) as a list of distinct values. The order in which variables
1783 * appear in the list is the same as the order in which those variables
1784 * occur in the type expression when read from left to right.
1785 * ------------------------------------------------------------------------*/
1787 List local typeVarsIn(ty,us,ws,vs) /*Calculate list of type variables*/
1788 Cell ty; /* used in type expression, reading*/
1789 List us; /* from left to right ignoring any */
1790 List ws; /* listed in us. */
1791 List vs; { /* ws = explicitly quantified vars */
1792 if (isNull(ty)) return vs;
1793 switch (whatIs(ty)) {
1794 case DICTAP : return typeVarsIn(snd(snd(ty)),us,ws,vs);
1795 case UNBOXEDTUP: return typeVarsIn(snd(ty),us,ws,vs);
1797 case AP : return typeVarsIn(snd(ty),us,ws,
1798 typeVarsIn(fst(ty),us,ws,vs));
1801 case VAROPCELL : if ((nonNull(findBtyvs(textOf(ty)))
1802 && !varIsMember(textOf(ty),ws))
1803 || varIsMember(textOf(ty),us)) {
1806 return maybeAppendVar(ty,vs);
1809 case POLYTYPE : return typeVarsIn(monotypeOf(ty),polySigOf(ty),ws,vs);
1811 case QUAL : { vs = typeVarsIn(fst(snd(ty)),us,ws,vs);
1812 return typeVarsIn(snd(snd(ty)),us,ws,vs);
1815 case BANG : return typeVarsIn(snd(ty),us,ws,vs);
1817 case LABC : { List fs = snd(snd(ty));
1818 for (; nonNull(fs); fs=tl(fs)) {
1819 vs = typeVarsIn(snd(hd(fs)),us,ws,vs);
1826 case QUALIDENT: return vs;
1828 default: fprintf(stderr, " bad tag = %d\n", whatIs(ty));internal("typeVarsIn");
1833 static List local maybeAppendVar(v,vs) /* append variable to list if not */
1834 Cell v; /* already included */
1840 while (nonNull(c)) {
1841 if (textOf(hd(c))==t) {
1849 tl(p) = cons(v,NIL);
1857 /* --------------------------------------------------------------------------
1858 * Static analysis for type expressions is required to:
1859 * - ensure that each type constructor or class used has been defined.
1860 * - replace type variables by offsets, constructor names by Tycons.
1861 * - ensure that the type is well-kinded.
1862 * ------------------------------------------------------------------------*/
1864 static Type local checkSigType(line,where,e,type)
1865 Int line; /* Check validity of type expr in */
1866 String where; /* explicit type signature */
1873 if (isPolyType(type)) {
1874 xtvs = fst(snd(type));
1875 type = monotypeOf(type);
1877 tvs = typeVarsIn(type,NIL,xtvs,NIL);
1879 checkOptQuantVars(line,xtvs,tvs);
1881 if (isQualType(type)) {
1882 map2Over(depPredExp,line,tvs,fst(snd(type)));
1883 snd(snd(type)) = depTopType(line,tvs,snd(snd(type)));
1885 if (isAmbiguous(type)) {
1886 ambigError(line,where,e,type);
1889 type = depTopType(line,tvs,type);
1893 if (length(tvs)>=NUM_OFFSETS) {
1894 ERRMSG(line) "Too many type variables in %s\n", where
1898 for (; nonNull(ts); ts=tl(ts)) {
1901 type = mkPolyType(tvs,type);
1906 kindType(line,"type expression",type);
1910 h98CheckType(line,where,e,type);
1914 static Void local checkOptQuantVars(line,xtvs,tvs)
1916 List xtvs; /* Explicitly quantified vars */
1917 List tvs; { /* Implicitly quantified vars */
1918 if (nonNull(xtvs)) {
1920 for (; nonNull(vs); vs=tl(vs)) {
1921 if (!varIsMember(textOf(hd(vs)),xtvs)) {
1922 ERRMSG(line) "Quantifier does not mention type variable \"%s\"",
1923 textToStr(textOf(hd(vs)))
1927 for (vs=xtvs; nonNull(vs); vs=tl(vs)) {
1928 if (!varIsMember(textOf(hd(vs)),tvs)) {
1929 ERRMSG(line) "Quantified type variable \"%s\" is not used",
1930 textToStr(textOf(hd(vs)))
1933 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1934 ERRMSG(line) "Quantified type variable \"%s\" is repeated",
1935 textToStr(textOf(hd(vs)))
1942 static Type local depTopType(l,tvs,t) /* Check top-level of type sig */
1950 for (; getHead(t1)==typeArrow && argCount==2; ++i) {
1951 arg(fun(t1)) = depCompType(l,tvs,arg(fun(t1)));
1952 if (isPolyOrQualType(arg(fun(t1)))) {
1958 if (nonNull(prev)) {
1959 arg(prev) = depTypeExp(l,tvs,t1);
1961 t = depTypeExp(l,tvs,t1);
1964 t = ap(RANK2,pair(mkInt(nr2),t));
1969 static Type local depCompType(l,tvs,t) /* Check component type for constr */
1973 Int ntvs = length(tvs);
1975 if (isPolyType(t)) {
1976 List vs = fst(snd(t));
1978 tvs = checkQuantVars(l,vs,tvs,t);
1979 nfr = replicate(length(vs),NIL);
1981 if (isQualType(t)) {
1982 map2Over(depPredExp,l,tvs,fst(snd(t)));
1983 snd(snd(t)) = depTypeExp(l,tvs,snd(snd(t)));
1984 if (isAmbiguous(t)) {
1985 ambigError(l,"type component",NIL,t);
1988 t = depTypeExp(l,tvs,t);
1994 return mkPolyType(nfr,t);
1997 static Type local depTypeExp(line,tyvars,type)
2001 switch (whatIs(type)) {
2002 case AP : fst(type) = depTypeExp(line,tyvars,fst(type));
2003 snd(type) = depTypeExp(line,tyvars,snd(type));
2006 case VARIDCELL : return depTypeVar(line,tyvars,textOf(type));
2008 case QUALIDENT : if (isQVar(type)) {
2009 ERRMSG(line) "Qualified type variables not allowed"
2012 /* deliberate fall through */
2013 case CONIDCELL : { Tycon tc = findQualTycon(type);
2016 "Undefined type constructor \"%s\"",
2020 if (cellIsMember(tc,tyconDefns) &&
2021 !cellIsMember(tc,tcDeps)) {
2022 tcDeps = cons(tc,tcDeps);
2028 case EXT : h98DoesntSupport(line,"extensible records");
2033 default : internal("depTypeExp");
2038 static Type local depTypeVar(line,tyvars,tv)
2045 for (; nonNull(tyvars); offset++) {
2046 if (tv==textOf(hd(tyvars))) {
2049 tyvars = tl(tyvars);
2052 Cell vt = findBtyvs(tv);
2056 ERRMSG(line) "Undefined type variable \"%s\"", textToStr(tv)
2059 return mkOffset(found);
2062 static List local checkQuantVars(line,vs,tvs,body)
2064 List vs; /* variables to quantify over */
2065 List tvs; /* variables already in scope */
2066 Cell body; { /* type/constr for scope of vars */
2068 List bvs = typeVarsIn(body,NIL,NIL,NIL);
2070 for (; nonNull(us); us=tl(us)) {
2071 Text u = textOf(hd(us));
2072 if (varIsMember(u,tl(us))) {
2073 ERRMSG(line) "Duplicated quantified variable %s",
2078 if (varIsMember(u,tvs)) {
2079 ERRMSG(line) "Local quantifier for %s hides an outer use",
2084 if (!varIsMember(u,bvs)) {
2085 ERRMSG(line) "Locally quantified variable %s is not used",
2090 tvs = appendOnto(tvs,vs);
2095 /* --------------------------------------------------------------------------
2096 * Check for ambiguous types:
2097 * A type Preds => type is ambiguous if not (TV(P) `subset` TV(type))
2098 * ------------------------------------------------------------------------*/
2100 List offsetTyvarsIn(t,vs) /* add list of offset tyvars in t */
2101 Type t; /* to list vs */
2103 switch (whatIs(t)) {
2104 case AP : return offsetTyvarsIn(fun(t),
2105 offsetTyvarsIn(arg(t),vs));
2107 case OFFSET : if (cellIsMember(t,vs))
2112 case QUAL : return offsetTyvarsIn(snd(t),vs);
2114 case POLYTYPE : return offsetTyvarsIn(monotypeOf(t),vs);
2115 /* slightly inaccurate, but won't matter here */
2118 case RANK2 : return offsetTyvarsIn(snd(snd(t)),vs);
2120 default : return vs;
2124 List zonkTyvarsIn(t,vs)
2127 switch (whatIs(t)) {
2128 case AP : return zonkTyvarsIn(fun(t),
2129 zonkTyvarsIn(arg(t),vs));
2131 case INTCELL : if (cellIsMember(t,vs))
2136 /* this case will lead to a type error --
2137 much better than reporting an internal error ;-) */
2138 /* case OFFSET : internal("zonkTyvarsIn"); */
2140 default : return vs;
2144 static List local otvars(pi,os) /* os is a list of offsets that */
2145 Cell pi; /* refer to the arguments of pi; */
2146 List os; { /* find list of offsets in those */
2147 List us = NIL; /* positions */
2148 for (; nonNull(os); os=tl(os)) {
2149 us = offsetTyvarsIn(nthArg(offsetOf(hd(os)),pi),us);
2154 static List local otvarsZonk(pi,os,o) /* same as above, but zonks */
2158 for (; nonNull(os); os=tl(os)) {
2159 Type t = zonkType(nthArg(offsetOf(hd(os)),pi),o);
2160 us = zonkTyvarsIn(t,us);
2165 static Bool local odiff(us,vs)
2167 while (nonNull(us) && cellIsMember(hd(us),vs)) {
2173 static Bool local osubset(us,vs) /* Determine whether us is subset */
2174 List us, vs; { /* of vs */
2175 while (nonNull(us) && cellIsMember(hd(us),vs)) {
2181 List oclose(fds,vs) /* Compute closure of vs wrt to fds*/
2184 Bool changed = TRUE;
2188 while (nonNull(fds)) {
2190 List next = tl(fds);
2191 if (osubset(fst(fd),vs)) { /* Test if fd applies */
2193 for (; nonNull(os); os=tl(os)) {
2194 if (!cellIsMember(hd(os),vs)) {
2195 vs = cons(hd(os),vs);
2199 } else { /* Didn't apply this time, so keep */
2210 Bool isAmbiguous(type) /* Determine whether type is */
2211 Type type; { /* ambiguous */
2212 if (isPolyType(type)) {
2213 type = monotypeOf(type);
2215 if (isQualType(type)) { /* only qualified types can be */
2216 List ps = fst(snd(type)); /* ambiguous */
2217 List tvps = offsetTyvarsIn(ps,NIL);
2218 List tvts = offsetTyvarsIn(snd(snd(type)),NIL);
2219 List fds = calcFunDeps(ps);
2221 tvts = oclose(fds,tvts); /* Close tvts under fds */
2222 return !osubset(tvps,tvts);
2227 List calcFunDeps(ps)
2230 for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies */
2232 Cell c = getHead(pi);
2234 List xfs = cclass(c).xfds;
2235 for (; nonNull(xfs); xfs=tl(xfs)) {
2236 List fs = snd(hd(xfs));
2237 for (; nonNull(fs); fs=tl(fs)) {
2238 fds = cons(pair(otvars(pi,fst(hd(fs))),
2239 otvars(pi,snd(hd(fs)))),fds);
2245 fds = cons(pair(NIL,offsetTyvarsIn(arg(pi),NIL)),fds);
2252 List calcFunDepsPreds(ps)
2255 for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies */
2257 Cell pi = fst3(pi3);
2258 Cell c = getHead(pi);
2259 Int o = intOf(snd3(pi3));
2261 List xfs = cclass(c).xfds;
2262 for (; nonNull(xfs); xfs=tl(xfs)) {
2263 List fs = snd(hd(xfs));
2264 for (; nonNull(fs); fs=tl(fs)) {
2265 fds = cons(pair(otvarsZonk(pi,fst(hd(fs)),o),
2266 otvarsZonk(pi,snd(hd(fs)),o)),fds);
2272 fds = cons(pair(NIL,zonkTyvarsIn(arg(pi),NIL)),fds);
2279 Void ambigError(line,where,e,type) /* produce error message for */
2280 Int line; /* ambiguity */
2284 ERRMSG(line) "Ambiguous type signature in %s", where ETHEN
2285 ERRTEXT "\n*** ambiguous type : " ETHEN ERRTYPE(type);
2287 ERRTEXT "\n*** assigned to : " ETHEN ERREXPR(e);
2293 /* --------------------------------------------------------------------------
2294 * Kind inference for simple types:
2295 * ------------------------------------------------------------------------*/
2297 static Void local kindConstr(line,alpha,m,c)
2298 Int line; /* Determine kind of constructor */
2302 Cell h = getHead(c);
2306 Printf("kindConstr: alpha=%d, m=%d, c=",alpha,m);
2307 printType(stdout,c);
2311 switch (whatIs(h)) {
2312 case POLYTYPE : if (n!=0) {
2313 internal("kindConstr1");
2315 static String pt = "polymorphic type";
2316 Type t = dropRank1(c,alpha,m);
2317 Kinds ks = polySigOf(t);
2320 for (; isAp(ks); ks=tl(ks)) {
2323 beta = newKindvars(m1);
2324 unkindTypes = cons(pair(mkInt(beta),t),unkindTypes);
2325 checkKind(line,beta,m1,monotypeOf(t),NIL,pt,STAR,0);
2330 case QUAL : if (n!=0) {
2331 internal("kindConstr2");
2333 map3Proc(kindPred,line,alpha,m,fst(snd(c)));
2334 kindConstr(line,alpha,m,snd(snd(c)));
2338 case RANK2 : kindConstr(line,alpha,m,snd(snd(c)));
2342 case EXT : if (n!=2) {
2344 "Illegal use of row in " ETHEN ERRTYPE(c);
2351 case TYCON : if (isSynonym(h) && n<tycon(h).arity) {
2353 "Not enough arguments for type synonym \"%s\"",
2354 textToStr(tycon(h).text)
2360 if (n==0) { /* trivial case, no arguments */
2361 typeIs = kindAtom(alpha,c);
2362 } else { /* non-trivial application */
2363 static String app = "constructor application";
2373 typeIs = kindAtom(alpha,h); /* h :: v1 -> ... -> vn -> w */
2374 shouldKind(line,h,c,app,k,beta);
2376 for (i=n; i>0; --i) { /* ci :: vi for each 1 <- 1..n */
2377 checkKind(line,alpha,m,arg(a),c,app,aVar,beta+i-1);
2380 tyvarType(beta+n); /* inferred kind is w */
2384 static Kind local kindAtom(alpha,c) /* Find kind of atomic constructor */
2387 switch (whatIs(c)) {
2388 case TUPLE : return simpleKind(tupleOf(c)); /*(,)::* -> * -> * */
2389 case OFFSET : return mkInt(alpha+offsetOf(c));
2390 case TYCON : return tycon(c).kind;
2391 case INTCELL : return c;
2393 case VAROPCELL : { Cell vt = findBtyvs(textOf(c));
2399 case EXT : return extKind;
2403 Printf("kindAtom(%d,whatIs(%d)) on ",alpha,whatIs(c));
2404 printType(stdout,c);
2407 internal("kindAtom");
2408 return STAR;/* not reached */
2411 static Void local kindPred(l,alpha,m,pi)/* Check kinds of arguments in pred*/
2417 if (isAp(pi) && isExt(fun(pi))) {
2418 static String lackspred = "lacks predicate";
2419 checkKind(l,alpha,m,arg(pi),NIL,lackspred,ROW,0);
2424 if (isAp(pi) && whatIs(fun(pi)) == IPCELL) {
2425 static String ippred = "iparam predicate";
2426 checkKind(l,alpha,m,arg(pi),NIL,ippred,STAR,0);
2430 { static String predicate = "class constraint";
2431 Class c = getHead(pi);
2432 List as = getArgs(pi);
2433 Kinds ks = cclass(c).kinds;
2435 while (nonNull(ks)) {
2436 checkKind(l,alpha,m,hd(as),NIL,predicate,hd(ks),0);
2443 static Void local kindType(line,wh,type)/* check that (poss qualified) type*/
2444 Int line; /* is well-kinded */
2447 checkKind(line,0,0,type,NIL,wh,STAR,0);
2450 static Void local fixKinds() { /* add kind annotations to types */
2451 for (; nonNull(unkindTypes); unkindTypes=tl(unkindTypes)) {
2452 Pair pr = hd(unkindTypes);
2453 Int beta = intOf(fst(pr));
2454 Cell qts = polySigOf(snd(pr));
2456 if (isNull(hd(qts))) {
2457 hd(qts) = copyKindvar(beta++);
2459 internal("fixKinds");
2461 if (nonNull(tl(qts))) {
2469 Printf("Type expression: ");
2470 printType(stdout,snd(pr));
2472 printKind(stdout,polySigOf(snd(pr)));
2478 /* --------------------------------------------------------------------------
2479 * Kind checking of groups of type constructors and classes:
2480 * ------------------------------------------------------------------------*/
2482 static Void local kindTCGroup(tcs) /* find kinds for mutually rec. gp */
2483 List tcs; { /* of tycons and classes */
2484 emptySubstitution();
2486 mapProc(initTCKind,tcs);
2487 mapProc(kindTC,tcs);
2490 emptySubstitution();
2493 static Void local initTCKind(c) /* build initial kind/arity for c */
2495 if (isTycon(c)) { /* Initial kind of tycon is: */
2496 Int beta = newKindvars(1); /* v1 -> ... -> vn -> vn+1 */
2497 varKind(tycon(c).arity); /* where n is the arity of c. */
2498 bindTv(beta,typeIs,typeOff); /* For data definitions, vn+1 == * */
2499 switch (whatIs(tycon(c).what)) {
2501 case DATATYPE : bindTv(typeOff+tycon(c).arity,STAR,0);
2503 tycon(c).kind = mkInt(beta);
2505 Int n = cclass(c).arity;
2506 Int beta = newKindvars(n);
2507 cclass(c).kinds = NIL;
2510 cclass(c).kinds = pair(mkInt(beta+n),cclass(c).kinds);
2515 static Void local kindTC(c) /* check each part of a tycon/class*/
2516 Cell c; { /* is well-kinded */
2518 static String cfun = "constructor function";
2519 static String tsyn = "synonym definition";
2520 Int line = tycon(c).line;
2521 Int beta = tyvar(intOf(tycon(c).kind))->offs;
2522 Int m = tycon(c).arity;
2523 switch (whatIs(tycon(c).what)) {
2525 case DATATYPE : { List cs = tycon(c).defn;
2526 if (isQualType(cs)) {
2527 map3Proc(kindPred,line,beta,m,
2529 tycon(c).defn = cs = snd(snd(cs));
2531 for (; hasCfun(cs); cs=tl(cs)) {
2532 kindType(line,cfun,name(hd(cs)).type);
2537 default : checkKind(line,beta,m,tycon(c).defn,NIL,
2541 else { /* scan type exprs in class defn to*/
2542 List ms = fst(cclass(c).members);
2543 Int m = cclass(c).arity; /* determine the class signature */
2544 Int beta = newKindvars(m);
2545 kindPred(cclass(c).line,beta,m,cclass(c).head);
2546 map3Proc(kindPred,cclass(c).line,beta,m,cclass(c).supers);
2547 for (; nonNull(ms); ms=tl(ms)) {
2548 Int line = intOf(fst3(hd(ms)));
2549 Type type = thd3(hd(ms));
2550 kindType(line,"member function type signature",type);
2555 static Void local genTC(c) /* generalise kind inferred for */
2556 Cell c; { /* given tycon/class */
2558 tycon(c).kind = copyKindvar(intOf(tycon(c).kind));
2560 Printf("%s :: ",textToStr(tycon(c).text));
2561 printKind(stdout,tycon(c).kind);
2565 Kinds ks = cclass(c).kinds;
2566 for (; nonNull(ks); ks=tl(ks)) {
2567 hd(ks) = copyKindvar(intOf(hd(ks)));
2570 Printf("%s :: ",textToStr(cclass(c).text));
2571 printKinds(stdout,cclass(c).kinds);
2577 /* --------------------------------------------------------------------------
2578 * Static analysis of instance declarations:
2580 * The first part of the static analysis is performed as the declarations
2581 * are read during parsing:
2582 * - make new entry in instance table
2583 * - record line number of declaration
2584 * - build list of instances defined in current script for use in later
2585 * stages of static analysis.
2586 * ------------------------------------------------------------------------*/
2588 Void instDefn(line,head,ms) /* process new instance definition */
2589 Int line; /* definition line number */
2590 Cell head; /* inst header :: (context,Class) */
2591 List ms; { /* instance members */
2592 Inst nw = newInst();
2593 inst(nw).line = line;
2594 inst(nw).specifics = fst(head);
2595 inst(nw).head = snd(head);
2596 inst(nw).implements = ms;
2597 instDefns = cons(nw,instDefns);
2600 /* --------------------------------------------------------------------------
2601 * Further static analysis of instance declarations:
2603 * Makes the following checks:
2604 * - Class part of header has form C (T a1 ... an) where C is a known
2605 * class, and T is a known datatype constructor (or restricted synonym),
2606 * and there is no previous C-T instance, and (T a1 ... an) has a kind
2607 * appropriate for the class C.
2608 * - Each element of context is a valid class expression, with type vars
2609 * drawn from a1, ..., an.
2610 * - All bindings are function bindings
2611 * - All bindings define member functions for class C
2612 * - Arrange bindings into appropriate order for member list
2613 * - No top level type signature declarations
2614 * ------------------------------------------------------------------------*/
2616 Bool allowOverlap = FALSE; /* TRUE => allow overlapping insts */
2617 Name nameListMonad = NIL; /* builder function for List Monad */
2619 static Void local checkInstDefn(in) /* Validate instance declaration */
2621 Int line = inst(in).line;
2622 List tyvars = typeVarsIn(inst(in).head,NIL,NIL,NIL);
2623 List tvps = NIL, tvts = NIL;
2626 if (haskell98) { /* Check for `simple' type */
2628 Cell t = arg(inst(in).head);
2629 for (; isAp(t); t=fun(t)) {
2630 if (!isVar(arg(t))) {
2632 "syntax error in instance head (variable expected)"
2635 if (varIsMember(textOf(arg(t)),tvs)) {
2636 ERRMSG(line) "repeated type variable \"%s\" in instance head",
2637 textToStr(textOf(arg(t)))
2640 tvs = cons(arg(t),tvs);
2644 "syntax error in instance head (constructor expected)"
2649 /* add in the tyvars from the `specifics' so that we don't
2650 prematurely complain about undefined tyvars */
2651 tyvars = typeVarsIn(inst(in).specifics,NIL,NIL,tyvars);
2652 inst(in).head = depPredExp(line,tyvars,inst(in).head);
2655 Type h = getHead(arg(inst(in).head));
2657 ERRMSG(line) "Cannot use type synonym in instance head"
2662 map2Over(depPredExp,line,tyvars,inst(in).specifics);
2664 /* OK, now we start over, and test for ambiguity */
2665 tvts = offsetTyvarsIn(inst(in).head,NIL);
2666 tvps = offsetTyvarsIn(inst(in).specifics,NIL);
2667 fds = calcFunDeps(inst(in).specifics);
2668 tvts = oclose(fds,tvts);
2669 tvts = odiff(tvps,tvts);
2670 if (!isNull(tvts)) {
2671 ERRMSG(line) "Undefined type variable \"%s\"",
2672 textToStr(textOf(nth(offsetOf(hd(tvts)),tyvars)))
2676 h98CheckCtxt(line,"instance definition",FALSE,inst(in).specifics,NIL);
2677 inst(in).numSpecifics = length(inst(in).specifics);
2678 inst(in).c = getHead(inst(in).head);
2679 if (!isClass(inst(in).c)) {
2680 ERRMSG(line) "Illegal predicate in instance declaration"
2684 if (nonNull(cclass(inst(in).c).fds)) {
2685 List fds = cclass(inst(in).c).fds;
2686 for (; nonNull(fds); fds=tl(fds)) {
2687 List as = otvars(inst(in).head, fst(hd(fds)));
2688 List bs = otvars(inst(in).head, snd(hd(fds)));
2689 List fs = calcFunDeps(inst(in).specifics);
2691 if (!osubset(bs,as)) {
2692 ERRMSG(inst(in).line)
2693 "Instance is more general than a dependency allows"
2695 ERRTEXT "\n*** Instance : "
2696 ETHEN ERRPRED(inst(in).head);
2697 ERRTEXT "\n*** For class : "
2698 ETHEN ERRPRED(cclass(inst(in).c).head);
2699 ERRTEXT "\n*** Under dependency : "
2700 ETHEN ERRFD(hd(fds));
2707 kindInst(in,length(tyvars));
2710 if (nonNull(extractSigdecls(inst(in).implements))) {
2712 "Type signature declarations not permitted in instance declaration"
2715 if (nonNull(extractFixdecls(inst(in).implements))) {
2717 "Fixity declarations not permitted in instance declaration"
2720 inst(in).implements = classBindings("instance",
2722 extractBindings(inst(in).implements));
2723 inst(in).builder = newInstImp(in);
2724 if (!preludeLoaded && isNull(nameListMonad) && isAp(inst(in).head)
2725 && fun(inst(in).head)==classMonad && arg(inst(in).head)==typeList) {
2726 nameListMonad = inst(in).builder;
2730 static Void local insertInst(in) /* Insert instance into class */
2732 Class c = inst(in).c;
2733 List ins = cclass(c).instances;
2736 if (nonNull(cclass(c).fds)) { /* Check for conflicts with fds */
2737 List ins1 = cclass(c).instances;
2738 for (; nonNull(ins1); ins1=tl(ins1)) {
2739 List fds = cclass(c).fds;
2740 substitution(RESET);
2741 for (; nonNull(fds); fds=tl(fds)) {
2742 Int alpha = newKindedVars(inst(in).kinds);
2743 Int beta = newKindedVars(inst(hd(ins1)).kinds);
2744 List as = fst(hd(fds));
2746 for (; same && nonNull(as); as=tl(as)) {
2747 Int n = offsetOf(hd(as));
2748 same &= unify(nthArg(n,inst(in).head),alpha,
2749 nthArg(n,inst(hd(ins1)).head),beta);
2751 if (isNull(as) && same) {
2752 for (as=snd(hd(fds)); same && nonNull(as); as=tl(as)) {
2753 Int n = offsetOf(hd(as));
2754 same &= sameType(nthArg(n,inst(in).head),alpha,
2755 nthArg(n,inst(hd(ins1)).head),beta);
2758 ERRMSG(inst(in).line)
2759 "Instances are not consistent with dependencies"
2761 ERRTEXT "\n*** This instance : "
2762 ETHEN ERRPRED(inst(in).head);
2763 ERRTEXT "\n*** Conflicts with : "
2764 ETHEN ERRPRED(inst(hd(ins)).head);
2765 ERRTEXT "\n*** For class : "
2766 ETHEN ERRPRED(cclass(c).head);
2767 ERRTEXT "\n*** Under dependency : "
2768 ETHEN ERRFD(hd(fds));
2778 substitution(RESET);
2779 while (nonNull(ins)) { /* Look for overlap w/ other insts */
2780 Int alpha = newKindedVars(inst(in).kinds);
2781 Int beta = newKindedVars(inst(hd(ins)).kinds);
2782 if (unifyPred(inst(in).head,alpha,inst(hd(ins)).head,beta)) {
2783 Cell pi = copyPred(inst(in).head,alpha);
2784 if (allowOverlap && !haskell98) {
2785 Bool bef = instCompare(in,hd(ins));
2786 Bool aft = instCompare(hd(ins),in);
2787 if (bef && !aft) { /* in comes strictly before hd(ins)*/
2790 if (aft && !bef) { /* in comes strictly after hd(ins) */
2797 if (multiInstRes && nonNull(inst(in).specifics)) {
2801 ERRMSG(inst(in).line) "Overlapping instances for class \"%s\"",
2802 textToStr(cclass(c).text)
2804 ERRTEXT "\n*** This instance : " ETHEN ERRPRED(inst(in).head);
2805 ERRTEXT "\n*** Overlaps with : " ETHEN
2806 ERRPRED(inst(hd(ins)).head);
2807 ERRTEXT "\n*** Common instance : " ETHEN
2815 prev = ins; /* No overlap detected, so move on */
2816 ins = tl(ins); /* to next instance */
2818 substitution(RESET);
2820 if (nonNull(prev)) { /* Insert instance at this point */
2821 tl(prev) = cons(in,ins);
2823 cclass(c).instances = cons(in,ins);
2827 static Bool local instCompare(ia,ib) /* See if ia is an instance of ib */
2829 Int alpha = newKindedVars(inst(ia).kinds);
2830 Int beta = newKindedVars(inst(ib).kinds);
2831 return matchPred(inst(ia).head,alpha,inst(ib).head,beta);
2834 static Name local newInstImp(in) /* Make definition for inst builder*/
2836 Name b = newName(inventText(),in);
2837 name(b).line = inst(in).line;
2838 name(b).arity = inst(in).numSpecifics;
2839 name(b).number = DFUNNAME;
2843 /* --------------------------------------------------------------------------
2844 * Kind checking of instance declaration headers:
2845 * ------------------------------------------------------------------------*/
2847 static Void local kindInst(in,freedom) /* check predicates in instance */
2852 emptySubstitution();
2853 beta = newKindvars(freedom);
2854 kindPred(inst(in).line,beta,freedom,inst(in).head);
2855 if (whatIs(inst(in).specifics)!=DERIVE) {
2856 map3Proc(kindPred,inst(in).line,beta,freedom,inst(in).specifics);
2858 for (inst(in).kinds = NIL; 0<freedom--; ) {
2859 inst(in).kinds = cons(copyKindvar(beta+freedom),inst(in).kinds);
2862 Printf("instance ");
2863 printPred(stdout,inst(in).head);
2865 printKinds(stdout,inst(in).kinds);
2868 emptySubstitution();
2871 /* --------------------------------------------------------------------------
2872 * Process derived instance requests:
2873 * ------------------------------------------------------------------------*/
2875 static List derivedInsts; /* list of derived instances */
2877 static Void local checkDerive(t,p,ts,ct)/* verify derived instance request */
2878 Tycon t; /* for tycon t, with explicit */
2879 List p; /* context p, component types ts */
2880 List ts; /* and named class ct */
2882 Int line = tycon(t).line;
2883 Class c = findQualClass(ct);
2885 ERRMSG(line) "Unknown class \"%s\" in derived instance",
2889 addDerInst(line,c,p,dupList(ts),t,tycon(t).arity);
2892 static Void local addDerInst(line,c,p,cts,t,a) /* Add a derived instance */
2899 Cell head = t; /* Build instance head */
2903 head = ap(head,mkOffset(i));
2909 inst(in).line = line;
2910 inst(in).head = head;
2911 inst(in).specifics = ap(DERIVE,pair(dupList(p),cts));
2912 inst(in).implements = NIL;
2913 inst(in).kinds = mkInt(a);
2914 derivedInsts = cons(in,derivedInsts);
2917 Void addTupInst(c,n) /* Request derived instance of c */
2918 Class c; /* for mkTuple(n) constructor */
2923 cts = cons(mkOffset(m),cts);
2926 addDerInst(0,c,NIL,cts,mkTuple(n),n);
2930 Inst addRecShowInst(c,e) /* Generate instance for ShowRecRow*/
2931 Class c; /* c *must* be ShowRecRow */
2933 Inst in = newInst();
2935 inst(in).head = ap(c,ap2(e,aVar,bVar));
2936 inst(in).kinds = extKind;
2937 inst(in).specifics = cons(ap(classShow,aVar),
2939 cons(ap(c,bVar),NIL)));
2940 inst(in).numSpecifics = 3;
2941 inst(in).builder = implementRecShw(extText(e),in);
2942 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2946 Inst addRecEqInst(c,e) /* Generate instance for EqRecRow */
2947 Class c; /* c *must* be EqRecRow */
2949 Inst in = newInst();
2951 inst(in).head = ap(c,ap2(e,aVar,bVar));
2952 inst(in).kinds = extKind;
2953 inst(in).specifics = cons(ap(classEq,aVar),
2955 cons(ap(c,bVar),NIL)));
2956 inst(in).numSpecifics = 3;
2957 inst(in).builder = implementRecEq(extText(e),in);
2958 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2963 /* --------------------------------------------------------------------------
2964 * Calculation of contexts for derived instances:
2966 * Allowing arbitrary types to appear in contexts makes it rather harder
2967 * to decide what the context for a derived instance should be. For
2970 * data T a = MkT [a] deriving Show,
2972 * we could have either of the following:
2974 * instance (Show [a]) => Show (T a) where ...
2975 * instance (Show a) => Show (T a) where ...
2977 * (assuming, of course, that instance (Show a) => Show [a]). For now, we
2978 * choose to reduce contexts in the hope of detecting errors at an earlier
2979 * stage---in contrast with value definitions, there is no way for a user
2980 * to provide something analogous to a `type signature' by which they might
2981 * be able to control this behaviour themselves. We eliminate tautological
2982 * predicates, but only allow predicates to appear in the final result if
2983 * they have at least one argument with a variable at its head.
2985 * In general, we have to deal with mutually recursive instance declarations.
2986 * We find a solution in the obvious way by iterating to find a fixed point.
2987 * Of course, without restrictions on the form of instance declarations, we
2988 * cannot be sure that this will always terminate!
2990 * For each instance we maintain a pair of the form DERIVE (ctxt,ps).
2991 * Ctxt is a list giving the parts of the context that have been produced
2992 * so far in the form of predicate skeletons. During the calculation of
2993 * derived instances, we attach a dummy NIL value to the end of the list
2994 * which acts as a kind of `variable': other parts of the system maintain
2995 * pointers to this variable, and use it to detect when the context has
2996 * been extended with new elements. Meanwhile, ps is a list containing
2997 * predicates (pi,o) together with (delayed) substitutions of the form
2998 * (o,xs) where o is an offset and xs is one of the context variables
2999 * described above, which may have been partially instantiated.
3000 * ------------------------------------------------------------------------*/
3002 static Bool instsChanged;
3004 static Void local deriveContexts(is) /* Calc contexts for derived insts */
3006 emptySubstitution();
3007 mapProc(initDerInst,is); /* Prepare derived instances */
3009 do { /* Main calculation of contexts */
3010 instsChanged = FALSE;
3011 mapProc(calcInstPreds,is);
3012 } while (instsChanged);
3014 mapProc(tidyDerInst,is); /* Tidy up results */
3017 static Void local initDerInst(in) /* Prepare instance for calculation*/
3018 Inst in; { /* of derived instance context */
3019 Cell spcs = inst(in).specifics;
3020 Int beta = newKindedVars(inst(in).kinds);
3021 if (whatIs(spcs)!=DERIVE) {
3022 internal("initDerInst");
3024 fst(snd(spcs)) = appendOnto(fst(snd(spcs)),singleton(NIL));
3025 for (spcs=snd(snd(spcs)); nonNull(spcs); spcs=tl(spcs)) {
3026 hd(spcs) = ap2(inst(in).c,hd(spcs),mkInt(beta));
3028 inst(in).numSpecifics = beta;
3030 #ifdef DEBUG_DERIVING
3031 Printf("initDerInst: ");
3032 printPred(stdout,inst(in).head);
3034 printContext(stdout,snd(snd(inst(in).specifics)));
3039 static Void local calcInstPreds(in) /* Calculate next approximation */
3040 Inst in; { /* of the context for a derived */
3041 List retain = NIL; /* instance */
3042 List ps = snd(snd(inst(in).specifics));
3043 List spcs = fst(snd(inst(in).specifics));
3044 Int beta = inst(in).numSpecifics;
3046 Int factor = 1+length(ps);
3048 #ifdef DEBUG_DERIVING
3049 Printf("calcInstPreds: ");
3050 printPred(stdout,inst(in).head);
3054 while (nonNull(ps)) {
3057 if (its++ >= factor*cutoff) {
3058 Cell bpi = inst(in).head;
3059 ERRMSG(inst(in).line) "\n*** Cannot derive " ETHEN ERRPRED(bpi);
3060 ERRTEXT " after %d iterations.", its-1 ETHEN
3062 "\n*** This may indicate that the problem is undecidable. However,\n"
3064 "*** you may still try to increase the cutoff limit using the -c\n"
3066 "*** option and then try again. (The current setting is -c%d)\n",
3070 if (isInt(fst(p))) { /* Delayed substitution? */
3072 for (; nonNull(hd(qs)); qs=tl(qs)) {
3073 ps = cons(pair(hd(qs),fst(p)),ps);
3075 retain = cons(pair(fst(p),qs),retain);
3078 else if (isExt(fun(fst(p)))) { /* Lacks predicate */
3079 Text l = extText(fun(fst(p)));
3080 Type t = arg(fst(p));
3081 Int o = intOf(snd(p));
3086 h = getDerefHead(t,o);
3087 while (isExt(h) && argCount==2 && l!=extText(h)) {
3090 h = getDerefHead(t,o);
3092 if (argCount==0 && isOffset(h)) {
3093 maybeAddPred(ap(fun(fun(p)),h),o,beta,spcs);
3094 } else if (argCount!=0 || h!=typeNoRow) {
3095 Cell bpi = inst(in).head;
3096 Cell pi = copyPred(fun(p),intOf(snd(p)));
3097 ERRMSG(inst(in).line) "Cannot derive " ETHEN ERRPRED(bpi);
3098 ERRTEXT " because predicate " ETHEN ERRPRED(pi);
3099 ERRTEXT " does not hold\n"
3104 else { /* Class predicate */
3106 Int o = intOf(snd(p));
3107 Inst in1 = findInstFor(pi,o);
3109 List qs = inst(in1).specifics;
3110 Int off = mkInt(typeOff);
3111 if (whatIs(qs)==DERIVE) { /* Still being derived */
3112 for (qs=fst(snd(qs)); nonNull(hd(qs)); qs=tl(qs)) {
3113 ps = cons(pair(hd(qs),off),ps);
3115 retain = cons(pair(off,qs),retain);
3116 } else { /* Previously def'd inst */
3117 for (; nonNull(qs); qs=tl(qs)) {
3118 ps = cons(pair(hd(qs),off),ps);
3121 } else { /* No matching instance */
3123 while (isAp(qi) && isOffset(getDerefHead(arg(qi),o))) {
3127 Cell bpi = inst(in).head;
3128 pi = copyPred(pi,o);
3129 ERRMSG(inst(in).line) "An instance of " ETHEN ERRPRED(pi);
3130 ERRTEXT " is required to derive " ETHEN ERRPRED(bpi);
3134 maybeAddPred(pi,o,beta,spcs);
3139 snd(snd(inst(in).specifics)) = retain;
3142 static Void local maybeAddPred(pi,o,beta,ps)
3143 Cell pi; /* Add predicate pi to the list ps,*/
3144 Int o; /* setting the instsChanged flag if*/
3145 Int beta; /* pi is not already a member and */
3146 List ps; { /* using beta to adjust vars */
3147 Cell c = getHead(pi);
3148 for (; nonNull(ps); ps=tl(ps)) {
3149 if (isNull(hd(ps))) { /* reached the `dummy' end of list?*/
3150 hd(ps) = copyAdj(pi,o,beta);
3151 tl(ps) = pair(NIL,NIL);
3152 instsChanged = TRUE;
3154 } else if (c==getHead(hd(ps)) && samePred(pi,o,hd(ps),beta)) {
3160 static Cell local copyAdj(c,o,beta) /* Copy (c,o), replacing vars with */
3161 Cell c; /* offsets relative to beta. */
3164 switch (whatIs(c)) {
3165 case AP : { Cell l = copyAdj(fst(c),o,beta);
3166 Cell r = copyAdj(snd(c),o,beta);
3170 case OFFSET : { Int vn = o+offsetOf(c);
3171 Tyvar *tyv = tyvar(vn);
3173 return copyAdj(tyv->bound,tyv->offs,beta);
3176 if (vn<0 || vn>=NUM_OFFSETS) {
3177 internal("copyAdj");
3179 return mkOffset(vn);
3185 static Void local tidyDerInst(in) /* Tidy up results of derived inst */
3186 Inst in; { /* calculations */
3187 Int o = inst(in).numSpecifics;
3188 List ps = tl(rev(fst(snd(inst(in).specifics))));
3190 copyPred(inst(in).head,o);
3191 inst(in).specifics = simpleContext(ps,o);
3192 h98CheckCtxt(inst(in).line,"derived instance",FALSE,inst(in).specifics,in);
3193 inst(in).numSpecifics = length(inst(in).specifics);
3195 #ifdef DEBUG_DERIVING
3196 Printf("Derived instance: ");
3197 printContext(stdout,inst(in).specifics);
3199 printPred(stdout,inst(in).head);
3204 /* --------------------------------------------------------------------------
3205 * Generate code for derived instances:
3206 * ------------------------------------------------------------------------*/
3208 static Void local addDerivImp(in)
3211 Type t = getHead(arg(inst(in).head));
3212 Class c = inst(in).c;
3215 } else if (c==classOrd) {
3217 } else if (c==classEnum) {
3218 imp = deriveEnum(t);
3219 } else if (c==classIx) {
3221 } else if (c==classShow) {
3222 imp = deriveShow(t);
3223 } else if (c==classRead) {
3224 imp = deriveRead(t);
3225 } else if (c==classBounded) {
3226 imp = deriveBounded(t);
3228 ERRMSG(inst(in).line) "Cannot derive instances of class \"%s\"",
3229 textToStr(cclass(inst(in).c).text)
3233 kindInst(in,intOf(inst(in).kinds));
3235 inst(in).builder = newInstImp(in);
3236 inst(in).implements = classBindings("derived instance",
3242 /* --------------------------------------------------------------------------
3243 * Default definitions; only one default definition is permitted in a
3244 * given script file. If no default is supplied, then a standard system
3245 * default will be used where necessary.
3246 * ------------------------------------------------------------------------*/
3248 Void defaultDefn(line,defs) /* Handle default types definition */
3251 if (defaultLine!=0) {
3252 ERRMSG(line) "Multiple default declarations are not permitted in" ETHEN
3253 ERRTEXT "a single script file.\n"
3256 defaultDefns = defs;
3260 static Void local checkDefaultDefns() { /* check that default types are */
3261 List ds = NIL; /* well-kinded instances of Num */
3263 if (defaultLine!=0) {
3264 map2Over(depTypeExp,defaultLine,NIL,defaultDefns);
3265 emptySubstitution();
3267 map2Proc(kindType,defaultLine,"default type",defaultDefns);
3269 emptySubstitution();
3270 mapOver(fullExpand,defaultDefns);
3272 defaultDefns = stdDefaults;
3275 if (isNull(classNum)) {
3276 classNum = findClass(findText("Num"));
3279 for (ds=defaultDefns; nonNull(ds); ds=tl(ds)) {
3280 if (isNull(provePred(NIL,NIL,ap(classNum,hd(ds))))) {
3282 "Default types must be instances of the Num class"
3289 /* --------------------------------------------------------------------------
3290 * Foreign import declarations are Hugs' equivalent of GHC's ccall mechanism.
3291 * They are used to "import" C functions into a module.
3292 * They are usually not written by hand but, rather, generated automatically
3293 * by GreenCard, IDL compilers or whatever. We support foreign import
3294 * (static) and foreign import dynamic. In the latter case, extName==NIL.
3296 * Foreign export declarations generate C wrappers for Hugs functions.
3297 * Hugs only provides "foreign export dynamic" because it's not obvious
3298 * what "foreign export static" would mean in an interactive setting.
3299 * ------------------------------------------------------------------------*/
3301 Void foreignImport(line,callconv,extName,intName,type)
3302 /* Handle foreign imports */
3308 Text t = textOf(intName);
3309 Name n = findName(t);
3310 Int l = intOf(line);
3314 } else if (name(n).defn!=PREDEFINED) {
3315 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
3319 name(n).defn = extName;
3320 name(n).type = type;
3321 name(n).callconv = callconv;
3322 foreignImports = cons(n,foreignImports);
3325 static Void local checkForeignImport(p) /* Check foreign import */
3327 emptySubstitution();
3328 name(p).type = checkSigType(name(p).line,
3329 "foreign import declaration",
3332 /* We don't expand synonyms here because we don't want the IO
3333 * part to be expanded.
3334 * name(p).type = fullExpand(name(p).type);
3336 implementForeignImport(p);
3339 Void foreignExport(line,callconv,extName,intName,type)
3340 /* Handle foreign exports */
3346 Text t = textOf(intName);
3347 Name n = findName(t);
3348 Int l = intOf(line);
3352 } else if (name(n).defn!=PREDEFINED) {
3353 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
3357 name(n).defn = NIL; /* nothing to say */
3358 name(n).type = type;
3359 name(n).callconv = callconv;
3360 foreignExports = cons(n,foreignExports);
3363 static Void local checkForeignExport(p) /* Check foreign export */
3365 emptySubstitution();
3366 name(p).type = checkSigType(name(p).line,
3367 "foreign export declaration",
3370 implementForeignExport(p);
3375 /* --------------------------------------------------------------------------
3376 * Static analysis of patterns:
3378 * Patterns are parsed as ordinary (atomic) expressions. Static analysis
3379 * makes the following checks:
3380 * - Patterns are well formed (according to pattern syntax), including the
3381 * special case of (n+k) patterns.
3382 * - All constructor functions have been defined and are used with the
3383 * correct number of arguments.
3384 * - No variable name is used more than once in a pattern.
3386 * The list of pattern variables occuring in each pattern is accumulated in
3387 * a global list `patVars', which must be initialised to NIL at appropriate
3388 * points before using these routines to check for valid patterns. This
3389 * mechanism enables the pattern checking routine to be mapped over a list
3390 * of patterns, ensuring that no variable occurs more than once in the
3391 * complete pattern list (as is required on the lhs of a function defn).
3392 * ------------------------------------------------------------------------*/
3394 static List patVars; /* List of vars bound in pattern */
3396 static Cell local checkPat(line,p) /* Check valid pattern syntax */
3399 switch (whatIs(p)) {
3401 case VAROPCELL : addToPatVars(line,p);
3404 case INFIX : return checkPat(line,tidyInfix(line,snd(p)));
3406 case AP : return checkMaybeCnkPat(line,p);
3411 case CONOPCELL : return checkApPat(line,0,p);
3416 case FLOATCELL : break;
3417 case INTCELL : break;
3419 case ASPAT : addToPatVars(line,fst(snd(p)));
3420 snd(snd(p)) = checkPat(line,snd(snd(p)));
3423 case LAZYPAT : snd(p) = checkPat(line,snd(p));
3426 case FINLIST : map1Over(checkPat,line,snd(p));
3429 case CONFLDS : depConFlds(line,p,TRUE);
3432 case ESIGN : snd(snd(p)) = checkPatType(line,
3436 fst(snd(p)) = checkPat(line,fst(snd(p)));
3439 default : ERRMSG(line) "Illegal pattern syntax"
3445 static Cell local checkMaybeCnkPat(l,p)/* Check applicative pattern with */
3446 Int l; /* the possibility of n+k pattern */
3448 Cell h = getHead(p);
3450 if (argCount==2 && isVar(h) && textOf(h)==textPlus) { /* n+k */
3451 Cell v = arg(fun(p));
3452 if (!isInt(arg(p))) {
3453 ERRMSG(l) "Second argument in (n+k) pattern must be an integer"
3456 if (intOf(arg(p))<=0) {
3457 ERRMSG(l) "Integer k in (n+k) pattern must be > 0"
3460 fst(fun(p)) = ADDPAT;
3461 intValOf(fun(p)) = intOf(arg(p));
3462 arg(p) = checkPat(l,v);
3465 return checkApPat(l,0,p);
3468 static Cell local checkApPat(line,args,p)
3469 Int line; /* check validity of application */
3470 Int args; /* of constructor to arguments */
3472 switch (whatIs(p)) {
3473 case AP : fun(p) = checkApPat(line,args+1,fun(p));
3474 arg(p) = checkPat(line,arg(p));
3477 case TUPLE : if (tupleOf(p)!=args) {
3478 ERRMSG(line) "Illegal tuple pattern"
3484 case EXT : h98DoesntSupport(line,"extensible records");
3486 ERRMSG(line) "Illegal record pattern"
3492 case QUALIDENT : if (!isQCon(p)) {
3494 "Illegal use of qualified variable in pattern"
3497 /* deliberate fall through */
3499 case CONOPCELL : p = conDefined(line,p);
3500 checkCfunArgs(line,p,args);
3503 case NAME : checkIsCfun(line,p);
3504 checkCfunArgs(line,p,args);
3507 default : ERRMSG(line) "Illegal pattern syntax"
3513 static Void local addToPatVars(line,v) /* Add variable v to list of vars */
3514 Int line; /* in current pattern, checking */
3515 Cell v; { /* for repeated variables. */
3520 for (; nonNull(n); p=n, n=tl(n)) {
3521 if (textOf(hd(n))==t) {
3522 ERRMSG(line) "Repeated variable \"%s\" in pattern",
3529 patVars = cons(v,NIL);
3531 tl(p) = cons(v,NIL);
3535 static Name local conDefined(line,nm) /* check that nm is the name of a */
3536 Int line; /* previously defined constructor */
3537 Cell nm; { /* function. */
3538 Name n = findQualName(nm);
3540 ERRMSG(line) "Undefined constructor function \"%s\"", identToStr(nm)
3543 checkIsCfun(line,n);
3547 static Void local checkIsCfun(line,c) /* Check that c is a constructor fn */
3551 ERRMSG(line) "\"%s\" is not a constructor function",
3552 textToStr(name(c).text)
3557 static Void local checkCfunArgs(line,c,args)
3558 Int line; /* Check constructor applied with */
3559 Cell c; /* correct number of arguments */
3561 Int a = userArity(c);
3564 "Constructor \"%s\" must have exactly %d argument%s in pattern",
3565 textToStr(name(c).text), a, ((a==1)?"":"s")
3570 static Cell local checkPatType(l,wh,e,t)/* Check type appearing in pattern */
3575 List tvs = typeVarsIn(t,NIL,NIL,NIL);
3576 h98DoesntSupport(l,"pattern type annotations");
3577 for (; nonNull(tvs); tvs=tl(tvs)) {
3578 Int beta = newKindvars(1);
3579 hd(btyvars) = cons(pair(hd(tvs),mkInt(beta)), hd(btyvars));
3581 t = checkSigType(l,"pattern type",e,t);
3582 if (isPolyOrQualType(t) || whatIs(t)==RANK2) {
3583 ERRMSG(l) "Illegal syntax in %s type annotation", wh
3589 static Cell local applyBtyvs(pat) /* Record bound type vars in pat */
3591 List bts = hd(btyvars);
3594 pat = ap(BIGLAM,pair(bts,pat));
3595 for (; nonNull(bts); bts=tl(bts)) {
3596 snd(hd(bts)) = copyKindvar(intOf(snd(hd(bts))));
3602 /* --------------------------------------------------------------------------
3603 * Maintaining lists of bound variables and local definitions, for
3604 * dependency and scope analysis.
3605 * ------------------------------------------------------------------------*/
3607 static List bounds; /* list of lists of bound vars */
3608 static List bindings; /* list of lists of binds in scope */
3609 static List depends; /* list of lists of dependents */
3611 /* bounds :: [[Var]] -- var equality used on Vars */
3612 /* bindings :: [[([Var],?)]] -- var equality used on Vars */
3613 /* depends :: [[Var]] -- pointer equality used on Vars */
3615 #define saveBvars() hd(bounds) /* list of bvars in current scope */
3616 #define restoreBvars(bs) hd(bounds)=bs /* restore list of bound variables */
3618 static Cell local bindPat(line,p) /* add new bound vars for pattern */
3622 p = checkPat(line,p);
3623 hd(bounds) = revOnto(patVars,hd(bounds));
3627 static Void local bindPats(line,ps) /* add new bound vars for patterns */
3631 map1Over(checkPat,line,ps);
3632 hd(bounds) = revOnto(patVars,hd(bounds));
3635 /* --------------------------------------------------------------------------
3636 * Before processing value and type signature declarations, all data and
3637 * type definitions have been processed so that:
3638 * - all valid type constructors (with their arities) are known.
3639 * - all valid constructor functions (with their arities and types) are
3642 * The result of parsing a list of value declarations is a list of Eqns:
3643 * Eqn ::= (SIGDECL,(Line,[Var],type))
3644 * | (FIXDECL,(Line,[Op],SyntaxInt))
3646 * The ordering of the equations in this list is the reverse of the original
3647 * ordering in the script parsed. This is a consequence of the structure of
3648 * the parser ... but also turns out to be most convenient for the static
3651 * As the first stage of the static analysis of value declarations, each
3652 * list of Eqns is converted to a list of Bindings. As part of this
3654 * - The ordering of the list of Bindings produced is the same as in the
3656 * - When a variable (function) is defined over a number of lines, all
3657 * of the definitions should appear together and each should give the
3658 * same arity to the variable being defined.
3659 * - No variable can have more than one definition.
3660 * - For pattern bindings:
3661 * - Each lhs is a valid pattern/function lhs, all constructor functions
3662 * have been defined and are used with the correct number of arguments.
3663 * - Each lhs contains no repeated pattern variables.
3664 * - Each equation defines at least one variable (e.g. True = False is
3666 * - Types appearing in type signatures are well formed:
3667 * - Type constructors used are defined and used with correct number
3669 * - type variables are replaced by offsets, type constructor names
3671 * - Every variable named in a type signature declaration is defined by
3672 * one or more equations elsewhere in the script.
3673 * - No variable has more than one type declaration.
3674 * - Similar properties for fixity declarations.
3676 * ------------------------------------------------------------------------*/
3678 #define bindingAttr(b) fst(snd(b)) /* type(s)/fixity(ies) for binding */
3679 #define fbindAlts(b) snd(snd(b)) /* alternatives for function binding*/
3681 static List local extractSigdecls(es) /* Extract the SIGDECLS from list */
3682 List es; { /* of equations */
3683 List sigdecls = NIL; /* :: [(Line,[Var],Type)] */
3685 for(; nonNull(es); es=tl(es)) {
3686 if (fst(hd(es))==SIGDECL) { /* type-declaration? */
3687 Pair sig = snd(hd(es));
3688 Int line = intOf(fst3(sig));
3689 List vs = snd3(sig);
3690 for(; nonNull(vs); vs=tl(vs)) {
3691 if (isQualIdent(hd(vs))) {
3692 ERRMSG(line) "Type signature for qualified variable \"%s\" is not allowed",
3697 sigdecls = cons(sig,sigdecls); /* discard SIGDECL tag*/
3703 static List local extractFixdecls(es) /* Extract the FIXDECLS from list */
3704 List es; { /* of equations */
3705 List fixdecls = NIL; /* :: [(Line,SyntaxInt,[Op])] */
3707 for(; nonNull(es); es=tl(es)) {
3708 if (fst(hd(es))==FIXDECL) { /* fixity declaration?*/
3709 fixdecls = cons(snd(hd(es)),fixdecls); /* discard FIXDECL tag*/
3715 static List local extractBindings(ds) /* extract untyped bindings from */
3716 List ds; { /* given list of equations */
3717 Cell lastVar = NIL; /* = var def'd in last eqn (if any)*/
3718 Int lastArity = 0; /* = number of args in last defn */
3719 List bs = NIL; /* :: [Binding] */
3721 for(; nonNull(ds); ds=tl(ds)) {
3723 if (fst(d)==FUNBIND) { /* Function bindings */
3724 Cell rhs = snd(snd(d));
3725 Int line = rhsLine(rhs);
3726 Cell lhs = fst(snd(d));
3727 Cell v = getHead(lhs);
3728 Cell newAlt = pair(getArgs(lhs),rhs);
3730 internal("FUNBIND");
3732 if (nonNull(lastVar) && textOf(v)==textOf(lastVar)) {
3733 if (argCount!=lastArity) {
3734 ERRMSG(line) "Equations give different arities for \"%s\"",
3735 textToStr(textOf(v))
3738 fbindAlts(hd(bs)) = cons(newAlt,fbindAlts(hd(bs)));
3742 lastArity = argCount;
3743 notDefined(line,bs,v);
3744 bs = cons(pair(v,pair(NIL,singleton(newAlt))),bs);
3747 } else if (fst(d)==PATBIND) { /* Pattern bindings */
3748 Cell rhs = snd(snd(d));
3749 Int line = rhsLine(rhs);
3750 Cell pat = fst(snd(d));
3751 while (whatIs(pat)==ESIGN) {/* Move type annotations to rhs */
3752 Cell p = fst(snd(pat));
3753 fst(snd(pat)) = rhs;
3754 snd(snd(d)) = rhs = pat;
3755 fst(snd(d)) = pat = p;
3758 if (isVar(pat)) { /* Convert simple pattern bind to */
3759 notDefined(line,bs,pat);/* a function binding */
3760 bs = cons(pair(pat,pair(NIL,singleton(pair(NIL,rhs)))),bs);
3762 List vs = getPatVars(line,pat,NIL);
3764 ERRMSG(line) "No variables defined in lhs pattern"
3767 map2Proc(notDefined,line,bs,vs);
3768 bs = cons(pair(vs,pair(NIL,snd(d))),bs);
3776 static List local getPatVars(line,p,vs) /* Find list of variables bound in */
3777 Int line; /* pattern p */
3780 switch (whatIs(p)) {
3782 vs = getPatVars(line,arg(p),vs);
3785 return vs; /* Ignore head of application */
3787 case CONFLDS : { List pfs = snd(snd(p));
3788 for (; nonNull(pfs); pfs=tl(pfs)) {
3789 if (isVar(hd(pfs))) {
3790 vs = addPatVar(line,hd(pfs),vs);
3792 vs = getPatVars(line,snd(hd(pfs)),vs);
3798 case FINLIST : { List ps = snd(p);
3799 for (; nonNull(ps); ps=tl(ps)) {
3800 vs = getPatVars(line,hd(ps),vs);
3805 case ESIGN : return getPatVars(line,fst(snd(p)),vs);
3810 case INFIX : return getPatVars(line,snd(p),vs);
3812 case ASPAT : return addPatVar(line,fst(snd(p)),
3813 getPatVars(line,snd(snd(p)),vs));
3816 case VAROPCELL : return addPatVar(line,p,vs);
3826 case WILDCARD : return vs;
3828 default : internal("getPatVars");
3833 static List local addPatVar(line,v,vs) /* Add var to list of previously */
3834 Int line; /* encountered variables */
3837 if (varIsMember(textOf(v),vs)) {
3838 ERRMSG(line) "Repeated use of variable \"%s\" in pattern binding",
3839 textToStr(textOf(v))
3845 static List local eqnsToBindings(es,ts,cs,ps)
3846 List es; /* Convert list of equations to */
3847 List ts; /* list of typed bindings */
3850 List bs = extractBindings(es);
3851 map1Proc(addSigdecl,bs,extractSigdecls(es));
3852 map4Proc(addFixdecl,bs,ts,cs,ps,extractFixdecls(es));
3856 static Void local notDefined(line,bs,v)/* check if name already defined in */
3857 Int line; /* list of bindings */
3860 if (nonNull(findBinding(textOf(v),bs))) {
3861 ERRMSG(line) "\"%s\" multiply defined", textToStr(textOf(v))
3866 static Cell local findBinding(t,bs) /* look for binding for variable t */
3867 Text t; /* in list of bindings bs */
3869 for (; nonNull(bs); bs=tl(bs)) {
3870 if (isVar(fst(hd(bs)))) { /* function-binding? */
3871 if (textOf(fst(hd(bs)))==t) {
3874 } else if (nonNull(varIsMember(t,fst(hd(bs))))){/* pattern-binding?*/
3881 static Cell local getAttr(bs,v) /* Locate type/fixity attribute */
3882 List bs; /* for variable v in bindings bs */
3885 Cell b = findBinding(t,bs);
3887 if (isNull(b)) { /* No binding */
3889 } else if (isVar(fst(b))) { /* func binding? */
3890 if (isNull(bindingAttr(b))) {
3891 bindingAttr(b) = pair(NIL,NIL);
3893 return bindingAttr(b);
3894 } else { /* pat binding? */
3896 List as = bindingAttr(b);
3899 bindingAttr(b) = as = replicate(length(vs),NIL);
3902 while (nonNull(vs) && t!=textOf(hd(vs))) {
3908 internal("getAttr");
3909 } else if (isNull(hd(as))) {
3910 hd(as) = pair(NIL,NIL);
3916 static Void local addSigdecl(bs,sigdecl)/* add type information to bindings*/
3917 List bs; /* :: [Binding] */
3918 Cell sigdecl; { /* :: (Line,[Var],Type) */
3919 Int l = intOf(fst3(sigdecl));
3920 List vs = snd3(sigdecl);
3921 Type type = checkSigType(l,"type declaration",hd(vs),thd3(sigdecl));
3923 for (; nonNull(vs); vs=tl(vs)) {
3925 Pair attr = getAttr(bs,v);
3927 ERRMSG(l) "Missing binding for variable \"%s\" in type signature",
3928 textToStr(textOf(v))
3930 } else if (nonNull(fst(attr))) {
3931 ERRMSG(l) "Repeated type signature for \"%s\"",
3932 textToStr(textOf(v))
3939 static Void local addFixdecl(bs,ts,cs,ps,fixdecl)
3945 Int line = intOf(fst3(fixdecl));
3946 List ops = snd3(fixdecl);
3947 Cell sy = thd3(fixdecl);
3949 for (; nonNull(ops); ops=tl(ops)) {
3951 Text t = textOf(op);
3952 Cell attr = getAttr(bs,op);
3953 if (nonNull(attr)) { /* Found name in binding? */
3954 if (nonNull(snd(attr))) {
3958 } else { /* Look in tycons, classes, prims */
3963 for (; isNull(n) && nonNull(ts1); ts1=tl(ts1)) { /* tycons */
3965 if (tycon(tc).what==DATATYPE || tycon(tc).what==NEWTYPE) {
3966 n = nameIsMember(t,tycon(tc).defn);
3969 for (; isNull(n) && nonNull(cs1); cs1=tl(cs1)) { /* classes */
3970 n = nameIsMember(t,cclass(hd(cs1)).members);
3972 for (; isNull(n) && nonNull(ps1); ps1=tl(ps1)) { /* prims */
3973 n = nameIsMember(t,hd(ps1));
3978 } else if (name(n).syntax!=NO_SYNTAX) {
3981 name(n).syntax = intOf(sy);
3986 static Void local dupFixity(line,t) /* Report repeated fixity decl */
3990 "Repeated fixity declaration for operator \"%s\"", textToStr(t)
3994 static Void local missFixity(line,t) /* Report missing op for fixity */
3998 "Cannot find binding for operator \"%s\" in fixity declaration",
4003 /* --------------------------------------------------------------------------
4004 * Dealing with infix operators:
4006 * Expressions involving infix operators or unary minus are parsed as
4007 * elements of the following type:
4009 * data InfixExp = Only Exp | Neg InfixExp | Infix InfixExp Op Exp
4011 * (The algorithms here do not assume that negation can be applied only once,
4012 * i.e., that - - x is a syntax error, as required by the Haskell report.
4013 * Instead, that restriction is captured by the grammar itself, given above.)
4015 * There are rules of precedence and grouping, expressed by two functions:
4017 * prec :: Op -> Int; assoc :: Op -> Assoc (Assoc = {L, N, R})
4019 * InfixExp values are rearranged accordingly when a complete expression
4020 * has been read using a simple shift-reduce parser whose result may be taken
4021 * to be a value of the following type:
4023 * data Exp = Atom Int | Negate Exp | Apply Op Exp Exp | Error String
4025 * The machine on which this parser is based can be defined as follows:
4027 * tidy :: InfixExp -> [(Op,Exp)] -> Exp
4028 * tidy (Only a) [] = a
4029 * tidy (Only a) ((o,b):ss) = tidy (Only (Apply o a b)) ss
4030 * tidy (Infix a o b) [] = tidy a [(o,b)]
4031 * tidy (Infix a o b) ((p,c):ss)
4032 * | shift o p = tidy a ((o,b):(p,c):ss)
4033 * | red o p = tidy (Infix a o (Apply p b c)) ss
4034 * | ambig o p = Error "ambiguous use of operators"
4035 * tidy (Neg e) [] = tidy (tidyNeg e) []
4036 * tidy (Neg e) ((o,b):ss)
4037 * | nshift o = tidy (Neg (underNeg o b e)) ss
4038 * | nred o = tidy (tidyNeg e) ((o,b):ss)
4039 * | nambig o = Error "illegal use of negation"
4041 * At each stage, the parser can either shift, reduce, accept, or error.
4042 * The transitions when dealing with juxtaposed operators o and p are
4043 * determined by the following rules:
4045 * shift o p = (prec o > prec p)
4046 * || (prec o == prec p && assoc o == L && assoc p == L)
4048 * red o p = (prec o < prec p)
4049 * || (prec o == prec p && assoc o == R && assoc p == R)
4051 * ambig o p = (prec o == prec p)
4052 * && (assoc o == N || assoc p == N || assoc o /= assoc p)
4054 * The transitions when dealing with juxtaposed unary minus and infix
4055 * operators are as follows. The precedence of unary minus (infixl 6) is
4056 * hardwired in to these definitions, as it is to the definitions of the
4057 * Haskell grammar in the official report.
4059 * nshift o = (prec o > 6)
4060 * nred o = (prec o < 6) || (prec o == 6 && assoc o == L)
4061 * nambig o = prec o == 6 && (assoc o == R || assoc o == N)
4063 * An InfixExp of the form (Neg e) means negate the last thing in
4064 * the InfixExp e; we can force this negation using:
4066 * tidyNeg :: OpExp -> OpExp
4067 * tidyNeg (Only e) = Only (Negate e)
4068 * tidyNeg (Infix a o b) = Infix a o (Negate b)
4069 * tidyNeg (Neg e) = tidyNeg (tidyNeg e)
4071 * On the other hand, if we want to sneak application of an infix operator
4072 * under a negation, then we use:
4074 * underNeg :: Op -> Exp -> OpExp -> OpExp
4075 * underNeg o b (Only e) = Only (Apply o e b)
4076 * underNeg o b (Neg e) = Neg (underNeg o b e)
4077 * underNeg o b (Infix e p f) = Infix e p (Apply o f b)
4079 * As a concession to efficiency, we lower the number of calls to syntaxOf
4080 * by keeping track of the values of sye, sys throughout the process. The
4081 * value APPLIC is used to indicate that the syntax value is unknown.
4082 * ------------------------------------------------------------------------*/
4084 static Cell local tidyInfix(line,e) /* Convert infixExp to Exp */
4086 Cell e; { /* :: OpExp */
4087 Cell s = NIL; /* :: [(Op,Exp)] */
4088 Syntax sye = APPLIC; /* Syntax of op in e (init unknown)*/
4089 Syntax sys = APPLIC; /* Syntax of op in s (init unknown)*/
4092 while (fst(d)!=ONLY) { /* Attach fixities to operators */
4096 fun(fun(d)) = attachFixity(line,fun(fun(d)));
4102 switch (whatIs(e)) {
4103 case ONLY : e = snd(e);
4104 while (nonNull(s)) {
4105 Cell next = arg(fun(s));
4107 fun(fun(s)) = snd(fun(fun(s)));
4113 case NEG : if (nonNull(s)) {
4114 if (sys==APPLIC) { /* calculate sys */
4115 sys = intOf(fst(fun(fun(s))));
4118 if (precOf(sys)==UMINUS_PREC && /* nambig */
4119 assocOf(sys)!=UMINUS_ASSOC) {
4121 "Ambiguous use of unary minus with \""
4122 ETHEN ERREXPR(snd(fun(fun(s))));
4127 if (precOf(sys)>UMINUS_PREC) { /* nshift */
4131 while (whatIs(e1)==NEG)
4133 arg(fun(t)) = arg(e1);
4134 fun(fun(t)) = snd(fun(fun(t)));
4141 /* Intentional fall-thru for nreduce and isNull(s) */
4143 { Cell prev = e; /* e := tidyNeg e */
4144 Cell temp = arg(prev);
4146 for (; whatIs(temp)==NEG; nneg++) {
4147 fun(prev) = nameNegate;
4151 if (isInt(arg(temp))) { /* special cases */
4152 if (nneg&1) /* for literals */
4153 arg(temp) = mkInt(-intOf(arg(temp)));
4155 else if (isFloat(arg(temp))) {
4157 arg(temp) = floatNegate(arg(temp));
4158 //mkFloat(-floatOf(arg(temp)));
4161 fun(prev) = nameNegate;
4162 arg(prev) = arg(temp);
4169 default : if (isNull(s)) {/* Move operation onto empty stack */
4170 Cell next = arg(fun(e));
4177 else { /* deal with pair of operators */
4179 if (sye==APPLIC) { /* calculate sys and sye */
4180 sye = intOf(fst(fun(fun(e))));
4183 sys = intOf(fst(fun(fun(s))));
4186 if (precOf(sye)==precOf(sys) && /* ambig */
4187 (assocOf(sye)!=assocOf(sys) ||
4188 assocOf(sye)==NON_ASS)) {
4189 ERRMSG(line) "Ambiguous use of operator \""
4190 ETHEN ERREXPR(snd(fun(fun(e))));
4191 ERRTEXT "\" with \""
4192 ETHEN ERREXPR(snd(fun(fun(s))));
4197 if (precOf(sye)>precOf(sys) || /* shift */
4198 (precOf(sye)==precOf(sys) &&
4199 assocOf(sye)==LEFT_ASS &&
4200 assocOf(sys)==LEFT_ASS)) {
4201 Cell next = arg(fun(e));
4209 Cell next = arg(fun(s));
4210 arg(fun(s)) = arg(e);
4211 fun(fun(s)) = snd(fun(fun(s)));
4222 static Pair local attachFixity(line,op) /* Attach fixity to operator in an */
4223 Int line; /* infix expression */
4225 Syntax sy = DEF_OPSYNTAX;
4227 switch (whatIs(op)) {
4229 case VARIDCELL : if ((sy=lookupSyntax(textOf(op)))==NO_SYNTAX) {
4230 Name n = findName(textOf(op));
4232 ERRMSG(line) "Undefined variable \"%s\"",
4233 textToStr(textOf(op))
4242 case CONIDCELL : sy = syntaxOf(op = conDefined(line,op));
4245 case QUALIDENT : { Name n = findQualName(op);
4251 "Undefined qualified variable \"%s\"",
4261 return pair(mkInt(sy),op); /* Pair fixity with (possibly) */
4262 /* translated operator */
4265 static Syntax local lookupSyntax(t) /* Try to find fixity for var in */
4266 Text t; { /* enclosing bindings */
4267 List bounds1 = bounds;
4268 List bindings1 = bindings;
4270 while (nonNull(bindings1)) {
4271 if (nonNull(varIsMember(t,hd(bounds1)))) {
4272 return DEF_OPSYNTAX;
4274 Cell b = findBinding(t,hd(bindings1));
4276 Cell a = fst(snd(b));
4277 if (isVar(fst(b))) { /* Function binding */
4278 if (nonNull(a) && nonNull(snd(a))) {
4279 return intOf(snd(a));
4281 } else { /* Pattern binding */
4283 while (nonNull(vs) && nonNull(a)) {
4284 if (t==textOf(hd(vs))) {
4285 if (nonNull(hd(a)) && isInt(snd(hd(a)))) {
4286 return intOf(snd(hd(a)));
4294 return DEF_OPSYNTAX;
4297 bounds1 = tl(bounds1);
4298 bindings1 = tl(bindings1);
4303 /* --------------------------------------------------------------------------
4304 * To facilitate dependency analysis, lists of bindings are temporarily
4305 * augmented with an additional field, which is used in two ways:
4306 * - to build the `adjacency lists' for the dependency graph. Represented by
4307 * a list of pointers to other bindings in the same list of bindings.
4308 * - to hold strictly positive integer values (depth first search numbers) of
4309 * elements `on the stack' during the strongly connected components search
4310 * algorithm, or a special value mkInt(0), once the binding has been added
4311 * to a particular strongly connected component.
4313 * Using this extra field, the type of each list of declarations during
4314 * dependency analysis is [Binding'] where:
4316 * Binding' ::= (Var, (Attr, (Dep, [Alt]))) -- function binding
4317 * | ([Var], ([Attr], (Dep, (Pat,Rhs)))) -- pattern binding
4319 * ------------------------------------------------------------------------*/
4321 #define depVal(d) (fst(snd(snd(d)))) /* Access to dependency information*/
4323 static List local dependencyAnal(bs) /* Separate lists of bindings into */
4324 List bs; { /* mutually recursive groups in */
4325 /* order of dependency */
4326 mapProc(addDepField,bs); /* add extra field for dependents */
4327 mapProc(depBinding,bs); /* find dependents of each binding */
4328 bs = bscc(bs); /* sort to strongly connected comps*/
4329 mapProc(remDepField,bs); /* remove dependency info field */
4333 static List local topDependAnal(bs) /* Like dependencyAnal(), but at */
4334 List bs; { /* top level, reporting on progress*/
4338 setGoal("Dependency analysis",(Target)(length(bs)));
4340 mapProc(addDepField,bs); /* add extra field for dependents */
4341 for (xs=bs; nonNull(xs); xs=tl(xs)) {
4342 emptySubstitution();
4344 soFar((Target)(i++));
4346 bs = bscc(bs); /* sort to strongly connected comps */
4347 mapProc(remDepField,bs); /* remove dependency info field */
4352 static Void local addDepField(b) /* add extra field to binding to */
4353 Cell b; { /* hold list of dependents */
4354 snd(snd(b)) = pair(NIL,snd(snd(b)));
4357 static Void local remDepField(bs) /* remove dependency field from */
4358 List bs; { /* list of bindings */
4359 mapProc(remDepField1,bs);
4362 static Void local remDepField1(b) /* remove dependency field from */
4363 Cell b; { /* single binding */
4364 snd(snd(b)) = snd(snd(snd(b)));
4367 static Void local clearScope() { /* initialise dependency scoping */
4373 static Void local withinScope(bs) /* Enter scope of bindings bs */
4375 bounds = cons(NIL,bounds);
4376 bindings = cons(bs,bindings);
4377 depends = cons(NIL,depends);
4380 static Void local leaveScope() { /* Leave scope of last withinScope */
4381 List bs = hd(bindings); /* Remove fixity info from binds */
4382 Bool toplevel = isNull(tl(bindings));
4383 for (; nonNull(bs); bs=tl(bs)) {
4385 if (isVar(fst(b))) { /* Variable binding */
4386 Cell a = fst(snd(b));
4389 saveSyntax(fst(b),snd(a));
4391 fst(snd(b)) = fst(a);
4393 } else { /* Pattern binding */
4395 List as = fst(snd(b));
4396 while (nonNull(vs) && nonNull(as)) {
4397 if (isPair(hd(as))) {
4399 saveSyntax(hd(vs),snd(hd(as)));
4401 hd(as) = fst(hd(as));
4408 bounds = tl(bounds);
4409 bindings = tl(bindings);
4410 depends = tl(depends);
4413 static Void local saveSyntax(v,sy) /* Save syntax of top-level var */
4414 Cell v; /* in corresponding Name */
4416 Name n = findName(textOf(v));
4417 if (isNull(n) || name(n).syntax!=NO_SYNTAX) {
4418 internal("saveSyntax");
4421 name(n).syntax = intOf(sy);
4425 /* --------------------------------------------------------------------------
4426 * As a side effect of the dependency analysis we also make the following
4428 * - Each lhs is a valid pattern/function lhs, all constructor functions
4429 * have been defined and are used with the correct number of arguments.
4430 * - No lhs contains repeated pattern variables.
4431 * - Expressions used on the rhs of an eqn should be well formed. This
4433 * - Checking for valid patterns (including repeated vars) in lambda,
4434 * case, and list comprehension expressions.
4435 * - Recursively checking local lists of equations.
4436 * - No free (i.e. unbound) variables are used in the declaration list.
4437 * ------------------------------------------------------------------------*/
4439 static Void local depBinding(b) /* find dependents of binding */
4441 Cell defpart = snd(snd(snd(b))); /* definition part of binding */
4445 if (isVar(fst(b))) { /* function-binding? */
4446 mapProc(depAlt,defpart);
4447 if (isNull(fst(snd(b)))) { /* Save dep info if no type sig */
4448 fst(snd(b)) = pair(ap(IMPDEPS,hd(depends)),NIL);
4449 } else if (isNull(fst(fst(snd(b))))) {
4450 fst(fst(snd(b))) = ap(IMPDEPS,hd(depends));
4452 } else { /* pattern-binding? */
4453 Int line = rhsLine(snd(defpart));
4456 fst(defpart) = checkPat(line,fst(defpart));
4457 depRhs(snd(defpart));
4459 if (nonNull(hd(btyvars))) {
4461 "Sorry, no type variables are allowed in pattern binding type annotations"
4465 fst(defpart) = applyBtyvs(fst(defpart));
4467 depVal(b) = hd(depends);
4470 static Void local depDefaults(c) /* dependency analysis on defaults */
4471 Class c; { /* from class definition */
4472 depClassBindings(cclass(c).defaults);
4475 static Void local depInsts(in) /* dependency analysis on instance */
4476 Inst in; { /* bindings */
4477 depClassBindings(inst(in).implements);
4480 static Void local depClassBindings(bs) /* dependency analysis on list of */
4481 List bs; { /* bindings, possibly containing */
4482 for (; nonNull(bs); bs=tl(bs)) { /* NIL bindings ... */
4483 if (nonNull(hd(bs))) { /* No need to add extra field for */
4484 mapProc(depAlt,snd(hd(bs)));/* dependency information... */
4489 static Void local depAlt(a) /* Find dependents of alternative */
4491 List obvs = saveBvars(); /* Save list of bound variables */
4493 bindPats(rhsLine(snd(a)),fst(a)); /* add new bound vars for patterns */
4494 depRhs(snd(a)); /* find dependents of rhs */
4495 fst(a) = applyBtyvs(fst(a));
4496 restoreBvars(obvs); /* restore original list of bvars */
4499 static Void local depRhs(r) /* Find dependents of rhs */
4501 switch (whatIs(r)) {
4502 case GUARDED : mapProc(depGuard,snd(r));
4505 case LETREC : fst(snd(r)) = eqnsToBindings(fst(snd(r)),NIL,NIL,NIL);
4506 withinScope(fst(snd(r)));
4507 fst(snd(r)) = dependencyAnal(fst(snd(r)));
4508 hd(depends) = fst(snd(r));
4509 depRhs(snd(snd(r)));
4513 case RSIGN : snd(snd(r)) = checkPatType(rhsLine(fst(snd(r))),
4515 rhsExpr(fst(snd(r))),
4517 depRhs(fst(snd(r)));
4520 default : snd(r) = depExpr(intOf(fst(r)),snd(r));
4525 static Void local depGuard(g) /* find dependents of single guarded*/
4526 Cell g; { /* expression */
4527 depPair(intOf(fst(g)),snd(g));
4530 static Cell local depExpr(line,e) /* find dependents of expression */
4533 // Printf( "\n\n"); print(e,100); Printf("\n");
4534 //printExp(stdout,e);
4535 switch (whatIs(e)) {
4538 case VAROPCELL : return depVar(line,e);
4541 case CONOPCELL : return conDefined(line,e);
4543 case QUALIDENT : if (isQVar(e)) {
4544 return depQVar(line,e);
4545 } else { /* QConOrConOp */
4546 return conDefined(line,e);
4549 case INFIX : return depExpr(line,tidyInfix(line,snd(e)));
4552 case RECSEL : break;
4554 case AP : if (isAp(e) && isAp(fun(e)) && isExt(fun(fun(e)))) {
4555 return depRecord(line,e);
4561 arg(a) = depExpr(line,arg(a));
4564 fun(a) = depExpr(line,fun(a));
4568 case AP : depPair(line,e);
4582 case INTCELL : break;
4584 case COND : depTriple(line,snd(e));
4587 case FINLIST : map1Over(depExpr,line,snd(e));
4590 case LETREC : fst(snd(e)) = eqnsToBindings(fst(snd(e)),NIL,NIL,NIL);
4591 withinScope(fst(snd(e)));
4592 fst(snd(e)) = dependencyAnal(fst(snd(e)));
4593 hd(depends) = fst(snd(e));
4594 snd(snd(e)) = depExpr(line,snd(snd(e)));
4598 case LAMBDA : depAlt(snd(e));
4601 case DOCOMP : /* fall-thru */
4602 case COMP : depComp(line,snd(e),snd(snd(e)));
4605 case ESIGN : fst(snd(e)) = depExpr(line,fst(snd(e)));
4606 snd(snd(e)) = checkSigType(line,
4612 case CASE : fst(snd(e)) = depExpr(line,fst(snd(e)));
4613 map1Proc(depCaseAlt,line,snd(snd(e)));
4616 case CONFLDS : depConFlds(line,e,FALSE);
4619 case UPDFLDS : depUpdFlds(line,e);
4623 case WITHEXP : depWith(line,e);
4627 case ASPAT : ERRMSG(line) "Illegal `@' in expression"
4630 case LAZYPAT : ERRMSG(line) "Illegal `~' in expression"
4633 case WILDCARD : ERRMSG(line) "Illegal `_' in expression"
4637 case EXT : ERRMSG(line) "Illegal application of record"
4641 default : internal("depExpr");
4646 static Void local depPair(line,e) /* find dependents of pair of exprs*/
4649 fst(e) = depExpr(line,fst(e));
4650 snd(e) = depExpr(line,snd(e));
4653 static Void local depTriple(line,e) /* find dependents of triple exprs */
4656 fst3(e) = depExpr(line,fst3(e));
4657 snd3(e) = depExpr(line,snd3(e));
4658 thd3(e) = depExpr(line,thd3(e));
4661 static Void local depComp(l,e,qs) /* find dependents of comprehension*/
4666 fst(e) = depExpr(l,fst(e));
4670 switch (whatIs(q)) {
4671 case FROMQUAL : { List obvs = saveBvars();
4672 snd(snd(q)) = depExpr(l,snd(snd(q)));
4674 fst(snd(q)) = bindPat(l,fst(snd(q)));
4676 fst(snd(q)) = applyBtyvs(fst(snd(q)));
4681 case QWHERE : snd(q) = eqnsToBindings(snd(q),NIL,NIL,NIL);
4682 withinScope(snd(q));
4683 snd(q) = dependencyAnal(snd(q));
4684 hd(depends) = snd(q);
4689 case DOQUAL : /* fall-thru */
4690 case BOOLQUAL : snd(q) = depExpr(l,snd(q));
4697 static Void local depCaseAlt(line,a) /* Find dependents of case altern. */
4700 List obvs = saveBvars(); /* Save list of bound variables */
4702 fst(a) = bindPat(line,fst(a)); /* Add new bound vars for pats */
4703 depRhs(snd(a)); /* Find dependents of rhs */
4704 fst(a) = applyBtyvs(fst(a));
4705 restoreBvars(obvs); /* Restore original list of bvars */
4708 static Cell local depVar(line,e) /* Register occurrence of variable */
4711 List bounds1 = bounds;
4712 List bindings1 = bindings;
4713 List depends1 = depends;
4717 while (nonNull(bindings1)) {
4718 n = varIsMember(t,hd(bounds1)); /* look for t in bound variables */
4722 n = findBinding(t,hd(bindings1)); /* look for t in var bindings */
4724 if (!cellIsMember(n,hd(depends1))) {
4725 hd(depends1) = cons(n,hd(depends1));
4727 return (isVar(fst(n)) ? fst(n) : e);
4730 bounds1 = tl(bounds1);
4731 bindings1 = tl(bindings1);
4732 depends1 = tl(depends1);
4735 if (isNull(n=findName(t))) { /* check global definitions */
4736 ERRMSG(line) "Undefined variable \"%s\"", textToStr(t)
4740 if (!moduleThisScript(name(n).mod)) {
4743 /* Later phases of the system cannot cope if we resolve references
4744 * to unprocessed objects too early. This is the main reason that
4745 * we cannot cope with recursive modules at the moment.
4750 static Cell local depQVar(line,e)/* register occurrence of qualified variable */
4753 Name n = findQualName(e);
4754 if (isNull(n)) { /* check global definitions */
4755 ERRMSG(line) "Undefined qualified variable \"%s\"", identToStr(e)
4758 if (name(n).mod != currentModule) {
4761 if (fst(e) == VARIDCELL) {
4762 e = mkVar(qtextOf(e));
4764 e = mkVarop(qtextOf(e));
4766 return depVar(line,e);
4769 static Void local depConFlds(line,e,isP)/* check construction using fields */
4773 Name c = conDefined(line,fst(snd(e)));
4774 if (isNull(snd(snd(e))) ||
4775 nonNull(cellIsMember(c,depFields(line,e,snd(snd(e)),isP)))) {
4778 ERRMSG(line) "Constructor \"%s\" does not have selected fields in ",
4779 textToStr(name(c).text)
4784 if (!isP && isPair(name(c).defn)) { /* Check that banged fields defined*/
4785 List scs = fst(name(c).defn); /* List of strict components */
4786 Type t = name(c).type;
4787 Int a = userArity(c);
4788 List fs = snd(snd(e));
4790 if (isPolyType(t)) { /* Find tycon that c belongs to */
4793 if (isQualType(t)) {
4796 if (whatIs(t)==CDICTS) {
4805 for (ss=tycon(t).defn; hasCfun(ss); ss=tl(ss)) {
4807 /* Now we know the tycon t that c belongs to, and the corresponding
4808 * list of selectors for that type, ss. Now we have to check that
4809 * each of the fields identified by scs appears in fs, using ss to
4810 * cross reference, and convert integers to selector names.
4812 for (; nonNull(scs); scs=tl(scs)) {
4813 Int i = intOf(hd(scs));
4815 for (; nonNull(ss1); ss1=tl(ss1)) {
4816 List cns = name(hd(ss1)).defn;
4817 for (; nonNull(cns); cns=tl(cns)) {
4818 if (fst(hd(cns))==c) {
4822 if (nonNull(cns) && intOf(snd(hd(cns)))==i) {
4827 internal("depConFlds");
4831 for (; nonNull(fs1) && s!=fst(hd(fs1)); fs1=tl(fs1)) {
4834 ERRMSG(line) "Construction does not define strict field"
4836 ERRTEXT "\nExpression : " ETHEN ERREXPR(e);
4837 ERRTEXT "\nField : " ETHEN ERREXPR(s);
4846 static Void local depUpdFlds(line,e) /* check update using fields */
4849 if (isNull(thd3(snd(e)))) {
4850 ERRMSG(line) "Empty field list in update"
4853 fst3(snd(e)) = depExpr(line,fst3(snd(e)));
4854 snd3(snd(e)) = depFields(line,e,thd3(snd(e)),FALSE);
4857 static List local depFields(l,e,fs,isP) /* check field binding list */
4865 for (; nonNull(fs); fs=tl(fs)) { /* for each field binding */
4869 if (isVar(fb)) { /* expand var to var = var */
4870 h98DoesntSupport(l,"missing field bindings");
4871 fb = hd(fs) = pair(fb,fb);
4874 s = findQualName(fst(fb)); /* check for selector */
4875 if (nonNull(s) && isSfun(s)) {
4878 ERRMSG(l) "\"%s\" is not a selector function/field name",
4879 textToStr(textOf(fst(fb)))
4883 if (isNull(ss)) { /* for first named selector */
4884 List scs = name(s).defn; /* calculate list of constructors */
4885 for (; nonNull(scs); scs=tl(scs)) {
4886 cs = cons(fst(hd(scs)),cs);
4888 ss = singleton(s); /* initialize selector list */
4889 } else { /* for subsequent selectors */
4890 List ds = cs; /* intersect constructor lists */
4891 for (cs=NIL; nonNull(ds); ) {
4892 List scs = name(s).defn;
4893 while (nonNull(scs) && fst(hd(scs))!=hd(ds)) {
4906 if (cellIsMember(s,ss)) { /* check for repeated uses */
4907 ERRMSG(l) "Repeated field name \"%s\" in field list",
4908 textToStr(name(s).text)
4914 if (isNull(cs)) { /* Are there any matching constrs? */
4915 ERRMSG(l) "No constructor has all of the fields specified in "
4921 snd(fb) = (isP ? checkPat(l,snd(fb)) : depExpr(l,snd(fb)));
4927 static Void local depWith(line,e) /* check with using fields */
4930 fst(snd(e)) = depExpr(line,fst(snd(e)));
4931 snd(snd(e)) = depDwFlds(line,e,snd(snd(e)));
4934 static List local depDwFlds(l,e,fs)/* check field binding list */
4940 for (; nonNull(c); c=tl(c)) { /* for each field binding */
4941 snd(hd(c)) = depExpr(l,snd(hd(c)));
4948 static Cell local depRecord(line,e) /* find dependents of record and */
4949 Int line; /* sort fields into approp. order */
4950 Cell e; { /* to make construction and update */
4951 List exts = NIL; /* more efficient. */
4954 h98DoesntSupport(line,"extensible records");
4955 do { /* build up list of extensions */
4956 Text t = extText(fun(fun(r)));
4957 String s = textToStr(t);
4960 while (nonNull(nx) && strcmp(textToStr(extText(fun(fun(nx)))),s)>0) {
4964 if (nonNull(nx) && t==extText(fun(fun(nx)))) {
4965 ERRMSG(line) "Repeated label \"%s\" in record ", s
4971 exts = cons(fun(r),exts);
4973 tl(prev) = cons(fun(r),nx);
4975 extField(r) = depExpr(line,extField(r));
4977 } while (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r))));
4978 r = depExpr(line,r);
4979 return revOnto(exts,r);
4984 /* --------------------------------------------------------------------------
4985 * Several parts of this program require an algorithm for sorting a list
4986 * of values (with some added dependency information) into a list of strongly
4987 * connected components in which each value appears before its dependents.
4989 * Each of these algorithms is obtained by parameterising a standard
4990 * algorithm in "scc.c" as shown below.
4991 * ------------------------------------------------------------------------*/
4993 #define SCC2 tcscc /* make scc algorithm for Tycons */
4994 #define LOWLINK tclowlink
4995 #define DEPENDS(c) (isTycon(c) ? tycon(c).kind : cclass(c).kinds)
4996 #define SETDEPENDS(c,v) if(isTycon(c)) tycon(c).kind=v; else cclass(c).kinds=v
5003 #define SCC bscc /* make scc algorithm for Bindings */
5004 #define LOWLINK blowlink
5005 #define DEPENDS(t) depVal(t)
5006 #define SETDEPENDS(c,v) depVal(c)=v
5013 /* --------------------------------------------------------------------------
5014 * Main static analysis:
5015 * ------------------------------------------------------------------------*/
5017 Void checkExp() { /* Top level static check on Expr */
5018 staticAnalysis(RESET);
5019 clearScope(); /* Analyse expression in the scope */
5020 withinScope(NIL); /* of no local bindings */
5021 inputExpr = depExpr(0,inputExpr);
5023 staticAnalysis(RESET);
5026 #if EXPLAIN_INSTANCE_RESOLUTION
5027 Void checkContext(void) { /* Top level static check on Expr */
5030 staticAnalysis(RESET);
5031 clearScope(); /* Analyse expression in the scope */
5032 withinScope(NIL); /* of no local bindings */
5034 for (vs = NIL; nonNull(qs); qs=tl(qs)) {
5035 vs = typeVarsIn(hd(qs),NIL,NIL,vs);
5037 map2Proc(depPredExp,0,vs,inputContext);
5039 staticAnalysis(RESET);
5043 Void checkDefns() { /* Top level static analysis */
5044 Module thisModule = lastModule();
5045 staticAnalysis(RESET);
5047 setCurrModule(thisModule);
5049 /* Resolve module references */
5050 mapProc(checkQualImport, module(thisModule).qualImports);
5051 mapProc(checkUnqualImport,unqualImports);
5052 /* Add "import Prelude" if there`s no explicit import */
5053 if (thisModule!=modulePrelude
5054 && isNull(cellAssoc(modulePrelude,unqualImports))
5055 && isNull(cellRevAssoc(modulePrelude,module(thisModule).qualImports))) {
5056 unqualImports = cons(pair(modulePrelude,DOTDOT),unqualImports);
5058 /* Every module (including the Prelude) implicitly contains
5059 * "import qualified Prelude"
5061 module(thisModule).qualImports=cons(pair(mkCon(textPrelude),modulePrelude),
5062 module(thisModule).qualImports);
5064 mapProc(checkImportList, unqualImports);
5066 /* Note: there's a lot of side-effecting going on here, so
5067 don't monkey about with the order of operations here unless
5068 you know what you are doing */
5069 if (!combined) linkPreludeTC(); /* Get prelude tycons and classes */
5071 mapProc(checkTyconDefn,tyconDefns); /* validate tycon definitions */
5072 checkSynonyms(tyconDefns); /* check synonym definitions */
5073 mapProc(checkClassDefn,classDefns); /* process class definitions */
5074 mapProc(kindTCGroup,tcscc(tyconDefns,classDefns)); /* attach kinds */
5075 mapProc(visitClass,classDefns); /* check class hierarchy */
5076 mapProc(extendFundeps,classDefns); /* finish class definitions */
5077 /* (convenient if we do this after */
5078 /* calling `visitClass' so that we */
5079 /* know the class hierarchy is */
5082 mapProc(addMembers,classDefns); /* add definitions for member funs */
5084 if (!combined) linkPreludeCM(); /* Get prelude cfuns and mfuns */
5086 instDefns = rev(instDefns); /* process instance definitions */
5087 mapProc(checkInstDefn,instDefns);
5089 setCurrModule(thisModule);
5090 mapProc(addRSsigdecls,typeInDefns); /* add sigdecls for RESTRICTSYN */
5091 valDefns = eqnsToBindings(valDefns,tyconDefns,classDefns,/*primDefns*/NIL);
5092 mapProc(allNoPrevDef,valDefns); /* check against previous defns */
5093 mapProc(addDerivImp,derivedInsts); /* Add impls for derived instances */
5094 deriveContexts(derivedInsts); /* Calculate derived inst contexts */
5095 instDefns = appendOnto(instDefns,derivedInsts);
5096 checkDefaultDefns(); /* validate default definitions */
5098 mapProc(allNoPrevDef,valDefns); /* check against previous defns */
5100 if (!combined) linkPrimitiveNames(); /* link primitive names */
5102 mapProc(checkForeignImport,foreignImports); /* check foreign imports */
5103 mapProc(checkForeignExport,foreignExports); /* check foreign exports */
5104 foreignImports = NIL;
5105 foreignExports = NIL;
5107 /* Every top-level name has now been created - so we can build the */
5108 /* export list. Note that this has to happen before dependency */
5109 /* analysis so that references to Prelude.foo will be resolved */
5110 /* when compiling the prelude. */
5111 module(thisModule).exports = checkExports(module(thisModule).exports);
5113 mapProc(checkTypeIn,typeInDefns); /* check restricted synonym defns */
5116 withinScope(valDefns);
5117 valDefns = topDependAnal(valDefns); /* top level dependency ordering */
5118 mapProc(depDefaults,classDefns); /* dep. analysis on class defaults */
5119 mapProc(depInsts,instDefns); /* dep. analysis on inst defns */
5122 /* ToDo: evalDefaults should match current evaluation module */
5123 evalDefaults = defaultDefns; /* Set defaults for evaluator */
5125 staticAnalysis(RESET);
5131 static Void local addRSsigdecls(pr) /* add sigdecls from TYPE ... IN ..*/
5133 List vs = snd(pr); /* get list of variables */
5134 for (; nonNull(vs); vs=tl(vs)) {
5135 if (fst(hd(vs))==SIGDECL) { /* find a sigdecl */
5136 valDefns = cons(hd(vs),valDefns); /* add to valDefns */
5137 hd(vs) = hd(snd3(snd(hd(vs)))); /* and replace with var */
5142 static Void local allNoPrevDef(b) /* ensure no previous bindings for*/
5143 Cell b; { /* variables in new binding */
5144 if (isVar(fst(b))) {
5145 noPrevDef(rhsLine(snd(hd(snd(snd(b))))),fst(b));
5147 Int line = rhsLine(snd(snd(snd(b))));
5148 map1Proc(noPrevDef,line,fst(b));
5152 static Void local noPrevDef(line,v) /* ensure no previous binding for */
5153 Int line; /* new variable */
5155 Name n = findName(textOf(v));
5158 n = newName(textOf(v),NIL);
5159 name(n).defn = PREDEFINED;
5160 } else if (name(n).defn!=PREDEFINED) {
5161 duplicateError(line,name(n).mod,name(n).text,"variable");
5163 name(n).line = line;
5166 static Void local duplicateErrorAux(line,mod,t,kind)/* report duplicate defn */
5171 if (mod == currentModule) {
5172 ERRMSG(line) "Repeated definition for %s \"%s\"", kind,
5176 ERRMSG(line) "Definition of %s \"%s\" clashes with import", kind,
5182 static Void local checkTypeIn(cvs) /* Check that vars in restricted */
5183 Pair cvs; { /* synonym are defined */
5187 for (; nonNull(vs); vs=tl(vs)) {
5188 if (isNull(findName(textOf(hd(vs))))) {
5189 ERRMSG(tycon(c).line)
5190 "No top level binding of \"%s\" for restricted synonym \"%s\"",
5191 textToStr(textOf(hd(vs))), textToStr(tycon(c).text)
5197 /* --------------------------------------------------------------------------
5198 * Haskell 98 compatibility tests:
5199 * ------------------------------------------------------------------------*/
5201 Bool h98Pred(allowArgs,pi) /* Check syntax of Hask98 predicate*/
5204 return isClass(getHead(pi)) && argCount==1 &&
5205 isOffset(getHead(arg(pi))) && (argCount==0 || allowArgs);
5208 Cell h98Context(allowArgs,ps) /* Check syntax of Hask98 context */
5211 for (; nonNull(ps); ps=tl(ps)) {
5212 if (!h98Pred(allowArgs,hd(ps))) {
5219 Void h98CheckCtxt(line,wh,allowArgs,ps,in)
5220 Int line; /* Report illegal context/predicate*/
5226 Cell pi = h98Context(allowArgs,ps);
5228 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh ETHEN
5230 ERRTEXT "\n*** Instance : " ETHEN ERRPRED(inst(in).head);
5232 ERRTEXT "\n*** Constraint : " ETHEN ERRPRED(pi);
5233 if (nonNull(ps) && nonNull(tl(ps))) {
5234 ERRTEXT "\n*** Context : " ETHEN ERRCONTEXT(ps);
5242 Void h98CheckType(line,wh,e,t) /* Check for Haskell 98 type */
5251 if (isQualType(t)) {
5252 Cell pi = h98Context(TRUE,fst(snd(t)));
5254 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh
5256 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
5257 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(ty);
5265 Void h98DoesntSupport(line,wh) /* Report feature missing in H98 */
5269 ERRMSG(line) "Haskell 98 does not support %s", wh
5274 /* --------------------------------------------------------------------------
5275 * Static Analysis control:
5276 * ------------------------------------------------------------------------*/
5278 Void staticAnalysis(what)
5281 case RESET : cfunSfuns = NIL;
5294 case MARK : mark(daSccs);
5309 case POSTPREL: break;
5311 case PREPREL : staticAnalysis(RESET);
5313 extKind = pair(STAR,pair(ROW,ROW));
5318 /*-------------------------------------------------------------------------*/