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: 1999/10/26 17:27:45 $
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,Cell));
38 static List local resolveImportList Args((Module,Cell));
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 addMembers Args((Class));
59 static Name local newMember Args((Int,Int,Cell,Type,Class));
60 static Name local newDSel Args((Class,Int));
61 static Text local generateText Args((String,Class));
62 static Int local visitClass Args((Class));
64 static List local classBindings Args((String,Class,List));
65 static Name local memberName Args((Class,Text));
66 static List local numInsert Args((Int,Cell,List));
68 List local typeVarsIn Args((Cell,List,List,List));
69 static List local maybeAppendVar Args((Cell,List));
71 static Type local checkSigType Args((Int,String,Cell,Type));
72 static Void local checkOptQuantVars Args((Int,List,List));
73 static Type local depTopType Args((Int,List,Type));
74 static Type local depCompType Args((Int,List,Type));
75 static Type local depTypeExp Args((Int,List,Type));
76 static Type local depTypeVar Args((Int,List,Text));
77 static List local checkQuantVars Args((Int,List,List,Cell));
78 static List local otvars Args((Cell,List));
79 static Bool local osubset Args((List,List));
80 static Void local kindConstr Args((Int,Int,Int,Constr));
81 static Kind local kindAtom Args((Int,Constr));
82 static Void local kindPred Args((Int,Int,Int,Cell));
83 static Void local kindType Args((Int,String,Type));
84 static Void local fixKinds Args((Void));
86 static Void local kindTCGroup Args((List));
87 static Void local initTCKind Args((Cell));
88 static Void local kindTC Args((Cell));
89 static Void local genTC Args((Cell));
91 static Void local checkInstDefn Args((Inst));
92 static Void local insertInst Args((Inst));
93 static Bool local instCompare Args((Inst,Inst));
94 static Name local newInstImp Args((Inst));
95 static Void local kindInst Args((Inst,Int));
96 static Void local checkDerive Args((Tycon,List,List,Cell));
97 static Void local addDerInst Args((Int,Class,List,List,Type,Int));
98 static Void local deriveContexts Args((List));
99 static Void local initDerInst Args((Inst));
100 static Void local calcInstPreds Args((Inst));
101 static Void local maybeAddPred Args((Cell,Int,Int,List));
102 static List local calcFunDeps Args((List));
103 static Cell local copyAdj Args((Cell,Int,Int));
104 static Void local tidyDerInst Args((Inst));
105 static List local otvarsZonk Args((Cell,List,Int));
107 static Void local addDerivImp Args((Inst));
109 static Void local checkDefaultDefns Args((Void));
111 static Void local checkForeignImport Args((Name));
112 static Void local checkForeignExport Args((Name));
114 static Cell local tidyInfix Args((Int,Cell));
115 static Pair local attachFixity Args((Int,Cell));
116 static Syntax local lookupSyntax Args((Text));
118 static Cell local checkPat Args((Int,Cell));
119 static Cell local checkMaybeCnkPat Args((Int,Cell));
120 static Cell local checkApPat Args((Int,Int,Cell));
121 static Void local addToPatVars Args((Int,Cell));
122 static Name local conDefined Args((Int,Cell));
123 static Void local checkIsCfun Args((Int,Name));
124 static Void local checkCfunArgs Args((Int,Cell,Int));
125 static Cell local checkPatType Args((Int,String,Cell,Type));
126 static Cell local applyBtyvs Args((Cell));
127 static Cell local bindPat Args((Int,Cell));
128 static Void local bindPats Args((Int,List));
130 static List local extractSigdecls Args((List));
131 static List local extractFixdecls Args((List));
132 static List local extractBindings Args((List));
133 static List local getPatVars Args((Int,Cell,List));
134 static List local addPatVar Args((Int,Cell,List));
135 static List local eqnsToBindings Args((List,List,List,List));
136 static Void local notDefined Args((Int,List,Cell));
137 static Cell local findBinding Args((Text,List));
138 static Cell local getAttr Args((List,Cell));
139 static Void local addSigdecl Args((List,Cell));
140 static Void local addFixdecl Args((List,List,List,List,Triple));
141 static Void local dupFixity Args((Int,Text));
142 static Void local missFixity Args((Int,Text));
144 static List local dependencyAnal Args((List));
145 static List local topDependAnal Args((List));
146 static Void local addDepField Args((Cell));
147 static Void local remDepField Args((List));
148 static Void local remDepField1 Args((Cell));
149 static Void local clearScope Args((Void));
150 static Void local withinScope Args((List));
151 static Void local leaveScope Args((Void));
152 static Void local saveSyntax Args((Cell,Cell));
154 static Void local depBinding Args((Cell));
155 static Void local depDefaults Args((Class));
156 static Void local depInsts Args((Inst));
157 static Void local depClassBindings Args((List));
158 static Void local depAlt Args((Cell));
159 static Void local depRhs Args((Cell));
160 static Void local depGuard Args((Cell));
161 static Cell local depExpr Args((Int,Cell));
162 static Void local depPair Args((Int,Cell));
163 static Void local depTriple Args((Int,Cell));
164 static Void local depComp Args((Int,Cell,List));
165 static Void local depCaseAlt Args((Int,Cell));
166 static Cell local depVar Args((Int,Cell));
167 static Cell local depQVar Args((Int,Cell));
168 static Void local depConFlds Args((Int,Cell,Bool));
169 static Void local depUpdFlds Args((Int,Cell));
170 static List local depFields Args((Int,Cell,List,Bool));
172 static Void local depWith Args((Int,Cell));
173 static List local depDwFlds Args((Int,Cell,List));
176 static Cell local depRecord Args((Int,Cell));
179 static List local tcscc Args((List,List));
180 static List local bscc Args((List));
182 static Void local addRSsigdecls Args((Pair));
183 static Void local allNoPrevDef Args((Cell));
184 static Void local noPrevDef Args((Int,Cell));
185 static Bool local odiff Args((List,List));
187 static Void local duplicateErrorAux Args((Int,Module,Text,String));
188 #define duplicateError(l,m,t,k) duplicateErrorAux(l,m,t,k)
189 static Void local checkTypeIn Args((Pair));
191 /* --------------------------------------------------------------------------
192 * The code in this file is arranged in roughly the following order:
193 * - Kind inference preliminaries
194 * - Module declarations
195 * - Type declarations (data, type, newtype, type in)
196 * - Class declarations
198 * - Instance declarations
199 * - Default declarations
200 * - Primitive definitions
202 * - Infix expressions
203 * - Value definitions
204 * - Top-level static analysis and control
205 * - Haskell 98 compatibility tests
206 * ------------------------------------------------------------------------*/
208 /* --------------------------------------------------------------------------
209 * Kind checking preliminaries:
210 * ------------------------------------------------------------------------*/
212 Bool kindExpert = FALSE; /* TRUE => display kind errors in */
215 static Void local kindError(l,c,in,wh,k,o)
216 Int l; /* line number near constuctor exp */
217 Constr c; /* constructor */
218 Constr in; /* context (if any) */
219 String wh; /* place in which error occurs */
220 Kind k; /* expected kind (k,o) */
221 Int o; { /* inferred kind (typeIs,typeOff) */
224 if (!kindExpert) { /* for those with a fear of kinds */
225 ERRMSG(l) "Illegal type" ETHEN
227 ERRTEXT " \"" ETHEN ERRTYPE(in);
230 ERRTEXT " in %s\n", wh
234 ERRMSG(l) "Kind error in %s", wh ETHEN
236 ERRTEXT "\n*** expression : " ETHEN ERRTYPE(in);
238 ERRTEXT "\n*** constructor : " ETHEN ERRTYPE(c);
239 ERRTEXT "\n*** kind : " ETHEN ERRKIND(copyType(typeIs,typeOff));
240 ERRTEXT "\n*** does not match : " ETHEN ERRKIND(copyType(k,o));
242 ERRTEXT "\n*** because : %s", unifyFails ETHEN
248 #define shouldKind(l,c,in,wh,k,o) if (!kunify(typeIs,typeOff,k,o)) \
249 kindError(l,c,in,wh,k,o)
250 #define checkKind(l,a,m,c,in,wh,k,o) kindConstr(l,a,m,c); \
251 shouldKind(l,c,in,wh,k,o)
252 #define inferKind(k,o) typeIs=k; typeOff=o
254 static List unkindTypes; /* types in need of kind annotation*/
256 Kind extKind; /* Kind of extension, *->row->row */
259 /* --------------------------------------------------------------------------
260 * Static analysis of modules:
261 * ------------------------------------------------------------------------*/
267 Void startModule(nm) /* switch to a new module */
270 if (!isCon(nm)) internal("startModule");
271 if (isNull(m = findModule(textOf(nm))))
272 m = newModule(textOf(nm));
273 else if (!isPreludeScript()) {
274 /* You're allowed to break the rules in the Prelude! */
276 reloadModule = textToStr(textOf(nm));
278 ERRMSG(0) "Module \"%s\" already loaded", textToStr(textOf(nm))
284 Void setExportList(exps) /* Add export list to current module */
286 module(currentModule).exports = exps;
289 Void addQualImport(orig,new) /* Add to qualified import list */
290 Cell orig; /* Original name of module */
291 Cell new; { /* Name module is called within this module (or NIL) */
292 module(currentModule).qualImports =
293 cons(pair(isNull(new)?orig:new,orig),module(currentModule).qualImports);
296 Void addUnqualImport(mod,entities) /* Add to unqualified import list */
297 Cell mod; /* Name of module */
298 List entities; { /* List of entity names */
299 unqualImports = cons(pair(mod,entities),unqualImports);
302 static Void local checkQualImport(i) /* Process qualified import */
304 Module m = findModid(snd(i));
306 ERRMSG(0) "Module \"%s\" not previously loaded",
307 textToStr(textOf(snd(i)))
313 static Void local checkUnqualImport(i) /* Process unqualified import */
315 Module m = findModid(fst(i));
317 ERRMSG(0) "Module \"%s\" not previously loaded",
318 textToStr(textOf(fst(i)))
324 static Name local lookupName(t,nms) /* find text t in list of Names */
326 List nms; { /* :: [Name] */
327 for(; nonNull(nms); nms=tl(nms)) {
328 if (t == name(hd(nms)).text)
334 static List local checkSubentities(imports,named,wanted,description,textParent)
336 List named; /* :: [ Q?(Var|Con)(Id|Op) ] */
337 List wanted; /* :: [Name] */
338 String description; /* "<constructor>|<member> of <type>|<class>" */
340 for(; nonNull(named); named=tl(named)) {
342 /* ToDo: ignores qualifier; doesn't check that entity is in scope */
343 Text t = isPair(snd(x)) ? qtextOf(x) : textOf(x);
344 Name n = lookupName(t,wanted);
346 ERRMSG(0) "Entity \"%s\" is not a %s \"%s\"",
349 textToStr(textParent)
352 imports = cons(n,imports);
357 static List local checkImportEntity(imports,exporter,entity)
358 List imports; /* Accumulated list of things to import */
360 Cell entity; { /* Entry from import list */
361 List oldImports = imports;
362 Text t = isIdent(entity) ? textOf(entity) : textOf(fst(entity));
363 List es = module(exporter).exports;
364 for(; nonNull(es); es=tl(es)) {
365 Cell e = hd(es); /* :: Entity | (Entity, NIL|DOTDOT) */
369 if (tycon(f).text == t) {
370 imports = cons(f,imports);
371 if (!isIdent(entity)) {
372 switch (tycon(f).what) {
375 if (DOTDOT == snd(entity)) {
376 imports=dupOnto(tycon(f).defn,imports);
378 imports=checkSubentities(imports,snd(entity),tycon(f).defn,
379 "constructor of type",t);
383 /* deliberate fall thru */
387 } else if (isClass(f)) {
388 if (cclass(f).text == t) {
389 imports = cons(f,imports);
390 if (!isIdent(entity)) {
391 if (DOTDOT == snd(entity)) {
392 return dupOnto(cclass(f).members,imports);
394 return checkSubentities(imports,snd(entity),cclass(f).members,
395 "member of class",t);
400 internal("checkImportEntity2");
402 } else if (isName(e)) {
403 if (isIdent(entity) && name(e).text == t) {
404 imports = cons(e,imports);
407 internal("checkImportEntity3");
410 if (imports == oldImports) {
411 ERRMSG(0) "Unknown entity \"%s\" imported from module \"%s\"",
413 textToStr(module(exporter ).text)
419 static List local resolveImportList(m,impList)
420 Module m; /* exporting module */
423 if (DOTDOT == impList) {
424 List es = module(m).exports;
425 for(; nonNull(es); es=tl(es)) {
428 imports = cons(e,imports);
431 List subentities = NIL;
432 imports = cons(c,imports);
434 && (tycon(c).what == DATATYPE
435 || tycon(c).what == NEWTYPE))
436 subentities = tycon(c).defn;
438 subentities = cclass(c).members;
439 if (DOTDOT == snd(e)) {
440 imports = dupOnto(subentities,imports);
445 map1Accum(checkImportEntity,imports,m,impList);
450 static Void local checkImportList(importSpec) /*Import a module unqualified*/
452 Module m = fst(importSpec);
453 Cell impList = snd(importSpec);
455 List imports = NIL; /* entities we want to import */
456 List hidden = NIL; /* entities we want to hide */
458 if (moduleThisScript(m)) {
459 ERRMSG(0) "Module \"%s\" recursively imports itself",
460 textToStr(module(m).text)
463 if (isPair(impList) && HIDDEN == fst(impList)) {
464 /* Somewhat inefficient - but obviously correct:
465 * imports = importsOf("module Foo") `setDifference` hidden;
467 hidden = resolveImportList(m, snd(impList));
468 imports = resolveImportList(m, DOTDOT);
470 imports = resolveImportList(m, impList);
472 for(; nonNull(imports); imports=tl(imports)) {
473 Cell e = hd(imports);
474 if (!cellIsMember(e,hidden))
477 /* ToDo: hang onto the imports list for processing export list entries
478 * of the form "module Foo"
482 static Void local importEntity(source,e)
486 case NAME : importName(source,e);
488 case TYCON : importTycon(source,e);
490 case CLASS : importClass(source,e);
492 default: internal("importEntity");
496 static Void local importName(source,n)
499 Name clash = addName(n);
500 if (nonNull(clash) && clash!=n) {
501 ERRMSG(0) "Entity \"%s\" imported from module \"%s\" already defined in module \"%s\"",
502 textToStr(name(n).text),
503 textToStr(module(source).text),
504 textToStr(module(name(clash).mod).text)
509 static Void local importTycon(source,tc)
512 Tycon clash=addTycon(tc);
513 if (nonNull(clash) && clash!=tc) {
514 ERRMSG(0) "Tycon \"%s\" imported from \"%s\" already defined in module \"%s\"",
515 textToStr(tycon(tc).text),
516 textToStr(module(source).text),
517 textToStr(module(tycon(clash).mod).text)
520 if (nonNull(findClass(tycon(tc).text))) {
521 ERRMSG(0) "Import of type constructor \"%s\" clashes with class in module \"%s\"",
522 textToStr(tycon(tc).text),
523 textToStr(module(tycon(tc).mod).text)
528 static Void local importClass(source,c)
531 Class clash=addClass(c);
532 if (nonNull(clash) && clash!=c) {
533 ERRMSG(0) "Class \"%s\" imported from \"%s\" already defined in module \"%s\"",
534 textToStr(cclass(c).text),
535 textToStr(module(source).text),
536 textToStr(module(cclass(clash).mod).text)
539 if (nonNull(findTycon(cclass(c).text))) {
540 ERRMSG(0) "Import of class \"%s\" clashes with type constructor in module \"%s\"",
541 textToStr(cclass(c).text),
542 textToStr(module(source).text)
547 static List local checkExportTycon(exports,mt,spec,tc)
552 if (DOTDOT == spec || SYNONYM == tycon(tc).what) {
553 return cons(pair(tc,DOTDOT), exports);
555 return cons(pair(tc,NIL), exports);
559 static List local checkExportClass(exports,mt,spec,cl)
564 if (DOTDOT == spec) {
565 return cons(pair(cl,DOTDOT), exports);
567 return cons(pair(cl,NIL), exports);
571 static List local checkExport(exports,mt,e) /* Process entry in export list*/
577 List origExports = exports;
578 if (nonNull(export=findQualName(e))) {
579 exports=cons(export,exports);
581 if (isQCon(e) && nonNull(export=findQualTycon(e))) {
582 exports = checkExportTycon(exports,mt,NIL,export);
584 if (isQCon(e) && nonNull(export=findQualClass(e))) {
585 /* opaque class export */
586 exports = checkExportClass(exports,mt,NIL,export);
588 if (exports == origExports) {
589 ERRMSG(0) "Unknown entity \"%s\" exported from module \"%s\"",
595 } else if (MODULEENT == fst(e)) {
596 Module m = findModid(snd(e));
597 /* ToDo: shouldn't allow export of module we didn't import */
599 ERRMSG(0) "Unknown module \"%s\" exported from module \"%s\"",
600 textToStr(textOf(snd(e))),
604 if (m == currentModule) {
605 /* Exporting the current module exports local definitions */
607 for(xs=module(m).classes; nonNull(xs); xs=tl(xs)) {
608 if (cclass(hd(xs)).mod==m)
609 exports = checkExportClass(exports,mt,DOTDOT,hd(xs));
611 for(xs=module(m).tycons; nonNull(xs); xs=tl(xs)) {
612 if (tycon(hd(xs)).mod==m)
613 exports = checkExportTycon(exports,mt,DOTDOT,hd(xs));
615 for(xs=module(m).names; nonNull(xs); xs=tl(xs)) {
616 if (name(hd(xs)).mod==m)
617 exports = cons(hd(xs),exports);
620 /* Exporting other modules imports all things imported
621 * unqualified from it.
622 * ToDo: we reexport everything exported by a module -
623 * whether we imported it or not. This gives the wrong
624 * result for "module M(module N) where import N(x)"
626 exports = dupOnto(module(m).exports,exports);
630 Cell ident = fst(e); /* class name or type name */
631 Cell parts = snd(e); /* members or constructors */
633 if (isQCon(ident) && nonNull(nm=findQualTycon(ident))) {
634 switch (tycon(nm).what) {
637 ERRMSG(0) "Explicit constructor list given for type synonym"
638 " \"%s\" in export list of module \"%s\"",
643 return cons(pair(nm,DOTDOT),exports);
645 ERRMSG(0) "Transparent export of restricted type synonym"
646 " \"%s\" in export list of module \"%s\"",
650 return exports; /* Not reached */
654 return cons(pair(nm,DOTDOT),exports);
656 exports = checkSubentities(exports,parts,tycon(nm).defn,
657 "constructor of type",
659 return cons(pair(nm,DOTDOT), exports);
662 internal("checkExport1");
664 } else if (isQCon(ident) && nonNull(nm=findQualClass(ident))) {
665 if (DOTDOT == parts) {
666 return cons(pair(nm,DOTDOT),exports);
668 exports = checkSubentities(exports,parts,cclass(nm).members,
669 "member of class",cclass(nm).text);
670 return cons(pair(nm,DOTDOT), exports);
673 ERRMSG(0) "Explicit export list given for non-class/datatype \"%s\" in export list of module \"%s\"",
679 return exports; /* NOTUSED */
682 static List local checkExports(exports)
684 Module m = lastModule();
685 Text mt = module(m).text;
688 map1Accum(checkExport,es,mt,exports);
691 for(xs=es; nonNull(xs); xs=tl(xs)) {
692 Printf(" %s", textToStr(textOfEntity(hd(xs))));
699 /* --------------------------------------------------------------------------
700 * Static analysis of type declarations:
702 * Type declarations come in two forms:
703 * - data declarations - define new constructed data types
704 * - type declarations - define new type synonyms
706 * A certain amount of work is carried out as the declarations are
707 * read during parsing. In particular, for each type constructor
708 * definition encountered:
709 * - check that there is no previous definition of constructor
710 * - ensure type constructor not previously used as a class name
711 * - make a new entry in the type constructor table
712 * - record line number of declaration
713 * - Build separate lists of newly defined constructors for later use.
714 * ------------------------------------------------------------------------*/
716 Void tyconDefn(line,lhs,rhs,what) /* process new type definition */
717 Int line; /* definition line number */
718 Cell lhs; /* left hand side of definition */
719 Cell rhs; /* right hand side of definition */
720 Cell what; { /* SYNONYM/DATATYPE/etc... */
721 Text t = textOf(getHead(lhs));
723 if (nonNull(findTycon(t))) {
724 ERRMSG(line) "Repeated definition of type constructor \"%s\"",
728 else if (nonNull(findClass(t))) {
729 ERRMSG(line) "\"%s\" used as both class and type constructor",
734 Tycon nw = newTycon(t);
735 tyconDefns = cons(nw,tyconDefns);
736 tycon(nw).line = line;
737 tycon(nw).arity = argCount;
738 tycon(nw).what = what;
739 if (what==RESTRICTSYN) {
740 h98DoesntSupport(line,"restricted type synonyms");
741 typeInDefns = cons(pair(nw,snd(rhs)),typeInDefns);
744 tycon(nw).defn = pair(lhs,rhs);
748 Void setTypeIns(bs) /* set local synonyms for given */
749 List bs; { /* binding group */
750 List cvs = typeInDefns;
751 for (; nonNull(cvs); cvs=tl(cvs)) {
752 Tycon c = fst(hd(cvs));
753 List vs = snd(hd(cvs));
754 for (tycon(c).what = RESTRICTSYN; nonNull(vs); vs=tl(vs)) {
755 if (nonNull(findBinding(textOf(hd(vs)),bs))) {
756 tycon(c).what = SYNONYM;
763 Void clearTypeIns() { /* clear list of local synonyms */
764 for (; nonNull(typeInDefns); typeInDefns=tl(typeInDefns))
765 tycon(fst(hd(typeInDefns))).what = RESTRICTSYN;
768 /* --------------------------------------------------------------------------
769 * Further analysis of Type declarations:
771 * In order to allow the definition of mutually recursive families of
772 * data types, the static analysis of the right hand sides of type
773 * declarations cannot be performed until all of the type declarations
776 * Once parsing is complete, we carry out the following:
778 * - check format of lhs, extracting list of bound vars and ensuring that
779 * there are no repeated variables and no Skolem variables.
780 * - run dependency analysis on rhs to check that only bound type vars
781 * appear in type and that all constructors are defined.
782 * Replace type variables by offsets, constructors by Tycons.
783 * - use list of dependents to sort into strongly connected components.
784 * - ensure that there is not more than one synonym in each group.
785 * - kind-check each group of type definitions.
787 * - check that there are no previous definitions for constructor
788 * functions in data type definitions.
789 * - install synonym expansions and constructor definitions.
790 * ------------------------------------------------------------------------*/
792 static List tcDeps = NIL; /* list of dependent tycons/classes*/
794 static Void local checkTyconDefn(d) /* validate type constructor defn */
796 Cell lhs = fst(tycon(d).defn);
797 Cell rhs = snd(tycon(d).defn);
798 Int line = tycon(d).line;
799 List tyvars = getArgs(lhs);
801 /* check for repeated tyvars on lhs*/
802 for (temp=tyvars; nonNull(temp); temp=tl(temp))
803 if (nonNull(varIsMember(textOf(hd(temp)),tl(temp)))) {
804 ERRMSG(line) "Repeated type variable \"%s\" on left hand side",
805 textToStr(textOf(hd(temp)))
809 tcDeps = NIL; /* find dependents */
810 switch (whatIs(tycon(d).what)) {
812 case SYNONYM : rhs = depTypeExp(line,tyvars,rhs);
813 if (cellIsMember(d,tcDeps)) {
814 ERRMSG(line) "Recursive type synonym \"%s\"",
815 textToStr(tycon(d).text)
821 case NEWTYPE : depConstrs(d,tyvars,rhs);
825 default : internal("checkTyconDefn");
830 tycon(d).kind = tcDeps;
834 static Void local depConstrs(t,tyvars,cd)
835 Tycon t; /* Define constructor functions and*/
836 List tyvars; /* do dependency analysis for data */
837 Cell cd; { /* definitions (w or w/o deriving) */
838 Int line = tycon(t).line;
843 List derivs = snd(cd);
844 List compTypes = NIL;
848 for (i=0; i<tycon(t).arity; ++i) /* build representation for tycon */
849 lhs = ap(lhs,mkOffset(i)); /* applied to full comp. of args */
851 if (isQualType(cs)) { /* allow for possible context */
854 map2Over(depPredExp,line,tyvars,ctxt);
855 h98CheckCtxt(line,"context",TRUE,ctxt,NIL);
858 if (nonNull(cs) && isNull(tl(cs))) /* Single constructor datatype? */
861 for (; nonNull(cs); cs=tl(cs)) { /* For each constructor function: */
863 List sig = dupList(tyvars);
864 List evs = NIL; /* locally quantified vars */
865 List lps = NIL; /* locally bound predicates */
866 List ctxt1 = ctxt; /* constructor function context */
867 List scs = NIL; /* strict components */
868 List fs = NONE; /* selector names */
869 Type type = lhs; /* constructor function type */
870 Int arity = 0; /* arity of constructor function */
871 Int nr2 = 0; /* Number of rank 2 args */
872 Name n; /* name for constructor function */
874 if (whatIs(con)==POLYTYPE) { /* Locally quantified vars */
877 sig = checkQuantVars(line,evs,sig,con);
880 if (isQualType(con)) { /* Local predicates */
883 for (us = typeVarsIn(lps,NIL,NIL,NIL); nonNull(us); us=tl(us))
884 if (!varIsMember(textOf(hd(us)),evs)) {
886 "Variable \"%s\" in constraint is not locally bound",
887 textToStr(textOf(hd(us)))
890 map2Over(depPredExp,line,sig,lps);
895 if (whatIs(con)==LABC) { /* Skeletize constr components */
896 Cell fls = snd(snd(con)); /* get field specifications */
899 for (; nonNull(fls); fls=tl(fls)) { /* for each field spec: */
900 List vs = fst(hd(fls));
901 Type t = snd(hd(fls)); /* - scrutinize type */
902 Bool banged = whatIs(t)==BANG;
903 t = depCompType(line,sig,(banged ? arg(t) : t));
904 while (nonNull(vs)) { /* - add named components */
912 scs = cons(mkInt(arity),scs);
916 scs = rev(scs); /* put strict comps in ascend ord */
918 else { /* Non-labelled constructor */
921 for (; isAp(c); c=fun(c))
923 for (compNo=arity, c=con; isAp(c); c=fun(c)) {
925 if (whatIs(t)==BANG) {
926 scs = cons(mkInt(compNo),scs);
930 arg(c) = depCompType(line,sig,t);
934 if (nonNull(ctxt1)) /* Extract relevant part of context*/
935 ctxt1 = selectCtxt(ctxt1,offsetTyvarsIn(con,NIL));
937 for (i=arity; isAp(con); i--) { /* Calculate type of constructor */
940 fun(con) = typeArrow;
941 if (isPolyOrQualType(cmp)) {
942 if (nonNull(derivs)) {
943 ERRMSG(line) "Cannot derive instances for types" ETHEN
944 ERRTEXT " with polymorphic or qualified components"
950 if (nonNull(derivs)) /* and build list of components */
951 compTypes = cons(cmp,compTypes);
956 if (nr2>0) /* Add rank 2 annotation */
957 type = ap(RANK2,pair(mkInt(nr2),type));
959 if (nonNull(evs)) { /* Add existential annotation */
960 if (nonNull(derivs)) {
961 ERRMSG(line) "Cannot derive instances for types" ETHEN
962 ERRTEXT " with existentially typed components"
967 "Cannot use selectors with existentially typed components"
970 type = ap(EXIST,pair(mkInt(length(evs)),type));
973 if (nonNull(lps)) { /* Add local preds part to type */
974 type = ap(CDICTS,pair(lps,type));
977 if (nonNull(ctxt1)) { /* Add context part to type */
978 type = ap(QUAL,pair(ctxt1,type));
981 if (nonNull(sig)) { /* Add quantifiers to type */
983 for (; nonNull(ts1); ts1=tl(ts1)) {
986 type = mkPolyType(sig,type);
989 n = findName(textOf(con)); /* Allocate constructor fun name */
991 n = newName(textOf(con),NIL);
992 } else if (name(n).defn!=PREDEFINED) {
993 duplicateError(line,name(n).mod,name(n).text,
994 "constructor function");
996 name(n).arity = arity; /* Save constructor fun details */
999 name(n).number = cfunNo(conNo++);
1000 name(n).type = type;
1001 if (tycon(t).what==NEWTYPE) {
1004 "A newtype constructor cannot have class constraints"
1009 "A newtype constructor must have exactly one argument"
1014 "Illegal strictess annotation for newtype constructor"
1017 name(n).defn = nameId;
1019 implementCfun(n,scs);
1024 sels = addSels(line,n,fs,sels);
1028 if (nonNull(sels)) {
1030 fst(cd) = appendOnto(fst(cd),sels);
1031 selDefns = cons(sels,selDefns);
1034 if (nonNull(derivs)) { /* Generate derived instances */
1035 map3Proc(checkDerive,t,ctxt,compTypes,derivs);
1039 Int userArity(c) /* Find arity for cfun, ignoring */
1040 Name c; { /* CDICTS parameters */
1041 Int a = name(c).arity;
1042 Type t = name(c).type;
1044 if (isPolyType(t)) {
1047 if ((w=whatIs(t))==QUAL) {
1048 w = whatIs(t=snd(snd(t)));
1051 a -= length(fst(snd(t)));
1057 static List local addSels(line,c,fs,ss) /* Add fields to selector list */
1058 Int line; /* line number of constructor */
1059 Name c; /* corresponding constr function */
1060 List fs; /* list of fields (varids) */
1061 List ss; { /* list of existing selectors */
1063 cfunSfuns = cons(pair(c,fs),cfunSfuns);
1064 for (; nonNull(fs); fs=tl(fs), ++sn) {
1066 Text t = textOf(hd(fs));
1068 if (nonNull(varIsMember(t,tl(fs)))) {
1069 ERRMSG(line) "Repeated field name \"%s\" for constructor \"%s\"",
1070 textToStr(t), textToStr(name(c).text)
1074 while (nonNull(ns) && t!=name(hd(ns)).text) {
1079 name(hd(ns)).defn = cons(pair(c,mkInt(sn)),name(hd(ns)).defn);
1081 Name n = findName(t);
1083 ERRMSG(line) "Repeated definition for selector \"%s\"",
1088 name(n).line = line;
1089 name(n).number = SELNAME;
1090 name(n).defn = singleton(pair(c,mkInt(sn)));
1097 static List local selectCtxt(ctxt,vs) /* calculate subset of context */
1104 for (; nonNull(ctxt); ctxt=tl(ctxt)) {
1105 List us = offsetTyvarsIn(hd(ctxt),NIL);
1106 for (; nonNull(us) && cellIsMember(hd(us),vs); us=tl(us)) {
1109 ps = cons(hd(ctxt),ps);
1116 static Void local checkSynonyms(ts) /* Check for mutually recursive */
1117 List ts; { /* synonyms */
1119 for (; nonNull(ts); ts=tl(ts)) { /* build list of all synonyms */
1121 switch (whatIs(tycon(t).what)) {
1123 case RESTRICTSYN : syns = cons(t,syns);
1127 while (nonNull(syns)) { /* then visit each synonym */
1128 syns = visitSyn(NIL,hd(syns),syns);
1132 static List local visitSyn(path,t,syns) /* visit synonym definition to look*/
1133 List path; /* for cycles */
1136 if (cellIsMember(t,path)) { /* every elt in path depends on t */
1137 ERRMSG(tycon(t).line)
1138 "Type synonyms \"%s\" and \"%s\" are mutually recursive",
1139 textToStr(tycon(t).text), textToStr(tycon(hd(path)).text)
1142 List ds = tycon(t).kind;
1144 for (; nonNull(ds); ds=tl(ds)) {
1145 if (cellIsMember(hd(ds),syns)) {
1146 if (isNull(path1)) {
1147 path1 = cons(t,path);
1149 syns = visitSyn(path1,hd(ds),syns);
1153 tycon(t).defn = fullExpand(tycon(t).defn);
1154 return removeCell(t,syns);
1157 /* --------------------------------------------------------------------------
1158 * Expanding out all type synonyms in a type expression:
1159 * ------------------------------------------------------------------------*/
1161 Type fullExpand(t) /* find full expansion of type exp */
1162 Type t; { /* assuming that all relevant */
1163 Cell h = t; /* synonym defns of lower rank have*/
1164 Int n = 0; /* already been fully expanded */
1166 for (args=NIL; isAp(h); h=fun(h), n++) {
1167 args = cons(fullExpand(arg(h)),args);
1169 t = applyToArgs(h,args);
1170 if (isSynonym(h) && n>=tycon(h).arity) {
1171 if (n==tycon(h).arity) {
1172 t = instantiateSyn(tycon(h).defn,t);
1175 while (--n > tycon(h).arity) {
1178 fun(p) = instantiateSyn(tycon(h).defn,fun(p));
1184 static Type local instantiateSyn(t,env) /* instantiate type according using*/
1185 Type t; /* env to determine appropriate */
1186 Type env; { /* values for OFFSET type vars */
1187 switch (whatIs(t)) {
1188 case AP : return ap(instantiateSyn(fun(t),env),
1189 instantiateSyn(arg(t),env));
1191 case OFFSET : return nthArg(offsetOf(t),env);
1197 /* --------------------------------------------------------------------------
1198 * Static analysis of class declarations:
1200 * Performed in a similar manner to that used for type declarations.
1202 * The first part of the static analysis is performed as the declarations
1203 * are read during parsing. The parser ensures that:
1204 * - the class header and all superclass predicates are of the form
1207 * The classDefn() function:
1208 * - ensures that there is no previous definition for class
1209 * - checks that class name has not previously been used as a type constr.
1210 * - make new entry in class table
1211 * - record line number of declaration
1212 * - build list of classes defined in current script for use in later
1213 * stages of static analysis.
1214 * ------------------------------------------------------------------------*/
1216 Void classDefn(line,head,ms,fds) /* process new class definition */
1217 Int line; /* definition line number */
1218 Cell head; /* class header :: ([Supers],Class) */
1219 List ms; /* class definition body */
1220 List fds; { /* functional dependencies */
1221 Text ct = textOf(getHead(snd(head)));
1222 Int arity = argCount;
1224 if (nonNull(findClass(ct))) {
1225 ERRMSG(line) "Repeated definition of class \"%s\"",
1228 } else if (nonNull(findTycon(ct))) {
1229 ERRMSG(line) "\"%s\" used as both class and type constructor",
1233 Class nw = newClass(ct);
1234 cclass(nw).line = line;
1235 cclass(nw).arity = arity;
1236 cclass(nw).head = snd(head);
1237 cclass(nw).supers = fst(head);
1238 cclass(nw).members = ms;
1239 cclass(nw).level = 0;
1240 cclass(nw).fds = fds;
1241 classDefns = cons(nw,classDefns);
1243 h98DoesntSupport(line,"multiple parameter classes");
1247 /* --------------------------------------------------------------------------
1248 * Further analysis of class declarations:
1250 * Full static analysis of class definitions must be postponed until the
1251 * complete script has been read and all static analysis on type definitions
1252 * has been completed.
1254 * Once this has been achieved, we carry out the following checks on each
1256 * - check that variables in header are distinct
1257 * - replace head by skeleton
1258 * - check superclass declarations, replace by skeletons
1259 * - split body of class into members and declarations
1260 * - make new name entry for each member function
1261 * - record member function number (eventually an offset into dictionary!)
1262 * - no member function has a previous definition ...
1263 * - no member function is mentioned more than once in the list of members
1264 * - each member function type is valid, replace vars by offsets
1265 * - qualify each member function type by class header
1266 * - only bindings for members appear in defaults
1267 * - only function bindings appear in defaults
1268 * - check that extended class hierarchy does not contain any cycles
1269 * ------------------------------------------------------------------------*/
1271 static Void local checkClassDefn(c) /* validate class definition */
1274 Int args = cclass(c).arity - 1;
1275 Cell temp = cclass(c).head;
1279 for (; isAp(temp); temp=fun(temp)) {
1280 if (!isVar(arg(temp))) {
1281 ERRMSG(cclass(c).line) "Type variable required in class head"
1284 if (nonNull(varIsMember(textOf(arg(temp)),tyvars))) {
1285 ERRMSG(cclass(c).line)
1286 "Repeated type variable \"%s\" in class head",
1287 textToStr(textOf(arg(temp)))
1290 tyvars = cons(arg(temp),tyvars);
1293 for (fs=cclass(c).fds; nonNull(fs); fs=tl(fs)) {
1297 /* Check for trivial dependency
1299 if (isNull(snd(fd))) {
1300 ERRMSG(cclass(c).line) "Functional dependency is trivial"
1304 /* Check for duplicated vars on right hand side, and for vars on
1305 * right that also appear on the left:
1307 for (vs=snd(fd); nonNull(vs); vs=tl(vs)) {
1308 if (varIsMember(textOf(hd(vs)),fst(fd))) {
1309 ERRMSG(cclass(c).line)
1310 "Trivial dependency for variable \"%s\"",
1311 textToStr(textOf(hd(vs)))
1314 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1315 ERRMSG(cclass(c).line)
1316 "Repeated variable \"%s\" in functional dependency",
1317 textToStr(textOf(hd(vs)))
1320 hd(vs) = depTypeVar(cclass(c).line,tyvars,textOf(hd(vs)));
1323 /* Check for duplicated vars on left hand side:
1325 for (vs=fst(fd); nonNull(vs); vs=tl(vs)) {
1326 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1327 ERRMSG(cclass(c).line)
1328 "Repeated variable \"%s\" in functional dependency",
1329 textToStr(textOf(hd(vs)))
1332 hd(vs) = depTypeVar(cclass(c).line,tyvars,textOf(hd(vs)));
1336 if (cclass(c).arity==0) {
1339 Int args = cclass(c).arity - 1;
1340 for (temp=cclass(c).head; args>0; temp=fun(temp), args--) {
1341 arg(temp) = mkOffset(args);
1343 arg(temp) = mkOffset(0);
1347 tcDeps = NIL; /* find dependents */
1348 map2Over(depPredExp,cclass(c).line,tyvars,cclass(c).supers);
1349 h98CheckCtxt(cclass(c).line,"class definition",FALSE,cclass(c).supers,NIL);
1350 cclass(c).numSupers = length(cclass(c).supers);
1351 cclass(c).defaults = extractBindings(cclass(c).members); /* defaults*/
1352 ss = extractSigdecls(cclass(c).members);
1353 fs = extractFixdecls(cclass(c).members);
1354 cclass(c).members = pair(ss,fs);
1355 map2Proc(checkMems,c,tyvars,ss);
1357 cclass(c).kinds = tcDeps;
1361 static Cell local depPredExp(line,tyvars,pred)
1368 for (; isAp(h); args++) {
1369 arg(h) = depTypeExp(line,tyvars,arg(h));
1375 h98DoesntSupport(line,"tag classes");
1376 } else if (args!=1) {
1377 h98DoesntSupport(line,"multiple parameter classes");
1380 if (isQCon(h)) { /* standard class constraint */
1381 Class c = findQualClass(h);
1383 ERRMSG(line) "Undefined class \"%s\"", identToStr(h)
1391 if (args!=cclass(c).arity) {
1392 ERRMSG(line) "Wrong number of arguments for class \"%s\"",
1393 textToStr(cclass(c).text)
1396 if (cellIsMember(c,classDefns) && !cellIsMember(c,tcDeps)) {
1397 tcDeps = cons(c,tcDeps);
1401 else if (isExt(h)) { /* Lacks predicate */
1402 if (args!=1) { /* parser shouldn't let this happen*/
1403 ERRMSG(line) "Wrong number of arguments for lacks predicate"
1410 if (whatIs(h) != IPCELL)
1413 internal("depPredExp");
1418 static Void local checkMems(c,tyvars,m) /* check member function details */
1422 Int line = intOf(fst3(m));
1429 if (isPolyType(t)) {
1435 tyvars = typeVarsIn(t,NIL,xtvs,tyvars);
1436 /* Look for extra type vars. */
1437 checkOptQuantVars(line,xtvs,tyvars);
1439 if (isQualType(t)) { /* Overloaded member signatures? */
1440 map2Over(depPredExp,line,tyvars,fst(snd(t)));
1442 t = ap(QUAL,pair(NIL,t));
1445 fst(snd(t)) = cons(cclass(c).head,fst(snd(t)));/* Add main predicate */
1446 snd(snd(t)) = depTopType(line,tyvars,snd(snd(t)));
1448 for (tvs=tyvars; nonNull(tvs); tvs=tl(tvs)){/* Quantify */
1452 t = mkPolyType(sig,t);
1454 thd3(m) = t; /* Save type */
1455 take(cclass(c).arity,tyvars); /* Delete extra type vars */
1457 if (isAmbiguous(t)) {
1458 ambigError(line,"class declaration",hd(vs),t);
1460 h98CheckType(line,"member type",hd(vs),t);
1463 static Void local addMembers(c) /* Add definitions of member funs */
1464 Class c; { /* and other parts of class struct.*/
1465 List ms = fst(cclass(c).members);
1466 List fs = snd(cclass(c).members);
1467 List ns = NIL; /* List of names */
1468 Int mno; /* Member function number */
1470 for (mno=0; mno<cclass(c).numSupers; mno++) {
1471 ns = cons(newDSel(c,mno),ns);
1473 cclass(c).dsels = rev(ns); /* Save dictionary selectors */
1475 for (mno=1, ns=NIL; nonNull(ms); ms=tl(ms)) {
1476 Int line = intOf(fst3(hd(ms)));
1477 List vs = rev(snd3(hd(ms)));
1478 Type t = thd3(hd(ms));
1479 for (; nonNull(vs); vs=tl(vs)) {
1480 ns = cons(newMember(line,mno++,hd(vs),t,c),ns);
1483 cclass(c).members = rev(ns); /* Save list of members */
1484 cclass(c).numMembers = length(cclass(c).members);
1486 for (; nonNull(fs); fs=tl(fs)) { /* fixity declarations */
1487 Int line = intOf(fst3(hd(fs)));
1488 List ops = snd3(hd(fs));
1489 Syntax s = intOf(thd3(hd(fs)));
1490 for (; nonNull(ops); ops=tl(ops)) {
1491 Name n = nameIsMember(textOf(hd(ops)),cclass(c).members);
1493 missFixity(line,textOf(hd(ops)));
1494 } else if (name(n).syntax!=NO_SYNTAX) {
1495 dupFixity(line,textOf(hd(ops)));
1501 /* Not actually needed just yet; for the time being, dictionary code will
1502 not be passed through the type checker.
1504 cclass(c).dtycon = addPrimTycon(generateText("Dict.%s",c),
1511 mno = cclass(c).numSupers + cclass(c).numMembers;
1512 cclass(c).dcon = addPrimCfun(generateText("Make.%s",c),mno,0,NIL);
1513 implementCfun(cclass(c).dcon,NIL); /* ADR addition */
1515 if (mno==1) { /* Single entry dicts use newtype */
1516 name(cclass(c).dcon).defn = nameId;
1517 if (nonNull(cclass(c).members)) {
1518 name(hd(cclass(c).members)).number = mfunNo(0);
1521 cclass(c).defaults = classBindings("class",c,cclass(c).defaults);
1524 static Name local newMember(l,no,v,t,parent)
1525 Int l; /* Make definition for member fn */
1530 Name m = findName(textOf(v));
1533 m = newName(textOf(v),parent);
1534 } else if (name(m).defn!=PREDEFINED) {
1535 ERRMSG(l) "Repeated definition for member function \"%s\"",
1536 textToStr(name(m).text)
1542 name(m).number = mfunNo(no);
1544 name(m).inlineMe = TRUE;
1548 static Name local newDSel(c,no) /* Make definition for dict selectr*/
1554 sprintf(buf,"sc%d.%s",no,"%s");
1555 s = newName(generateText(buf,c),c);
1556 name(s).line = cclass(c).line;
1558 name(s).number = DFUNNAME;
1564 static Text local generateText(sk,c) /* We need to generate names for */
1565 String sk; /* certain objects corresponding */
1566 Class c; { /* to each class. */
1567 String cname = textToStr(cclass(c).text);
1568 char buffer[MAX_GEN+1];
1570 if ((strlen(sk)+strlen(cname))>=MAX_GEN) {
1571 ERRMSG(0) "Please use a shorter name for class \"%s\"", cname
1574 sprintf(buffer,sk,cname);
1575 return findText(buffer);
1578 static Int local visitClass(c) /* visit class defn to check that */
1579 Class c; { /* class hierarchy is acyclic */
1581 if (isExt(c)) { /* special case for lacks preds */
1585 if (cclass(c).level < 0) { /* already visiting this class? */
1586 ERRMSG(cclass(c).line) "Class hierarchy for \"%s\" is not acyclic",
1587 textToStr(cclass(c).text)
1589 } else if (cclass(c).level == 0) { /* visiting class for first time */
1590 List scs = cclass(c).supers;
1592 cclass(c).level = (-1);
1593 for (; nonNull(scs); scs=tl(scs)) {
1594 Int l = visitClass(getHead(hd(scs)));
1597 cclass(c).level = 1+lev; /* level = 1 + max level of supers */
1599 return cclass(c).level;
1602 /* --------------------------------------------------------------------------
1603 * Process class and instance declaration binding groups:
1604 * ------------------------------------------------------------------------*/
1606 static List local classBindings(where,c,bs)
1607 String where; /* Check validity of bindings bs */
1608 Class c; /* for class c (or an inst of c) */
1609 List bs; { /* sort into approp. member order */
1612 for (; nonNull(bs); bs=tl(bs)) {
1614 Cell body = snd(snd(b));
1617 if (!isVar(fst(b))) { /* Only allow function bindings */
1618 ERRMSG(rhsLine(snd(body)))
1619 "Pattern binding illegal in %s declaration", where
1623 if (isNull(mnm=memberName(c,textOf(fst(b))))) {
1624 ERRMSG(rhsLine(snd(hd(body))))
1625 "No member \"%s\" in class \"%s\"",
1626 textToStr(textOf(fst(b))), textToStr(cclass(c).text)
1630 nbs = numInsert(mfunOf(mnm)-1,b,nbs);
1635 static Name local memberName(c,t) /* return name of member function */
1636 Class c; /* with name t in class c */
1637 Text t; { /* return NIL if not a member */
1638 List ms = cclass(c).members;
1639 for (; nonNull(ms); ms=tl(ms)) {
1640 if (t==name(hd(ms)).text) {
1647 static List local numInsert(n,x,xs) /* insert x at nth position in xs, */
1648 Int n; /* filling gaps with NIL */
1651 List start = isNull(xs) ? cons(NIL,NIL) : xs;
1653 for (xs=start; 0<n--; xs=tl(xs)) {
1654 if (isNull(tl(xs))) {
1655 tl(xs) = cons(NIL,NIL);
1662 /* --------------------------------------------------------------------------
1663 * Calculate set of variables appearing in a given type expression (possibly
1664 * qualified) as a list of distinct values. The order in which variables
1665 * appear in the list is the same as the order in which those variables
1666 * occur in the type expression when read from left to right.
1667 * ------------------------------------------------------------------------*/
1669 List local typeVarsIn(ty,us,ws,vs) /*Calculate list of type variables*/
1670 Cell ty; /* used in type expression, reading*/
1671 List us; /* from left to right ignoring any */
1672 List ws; /* listed in us. */
1673 List vs; { /* ws = explicitly quantified vars */
1674 switch (whatIs(ty)) {
1675 case AP : return typeVarsIn(snd(ty),us,ws,
1676 typeVarsIn(fst(ty),us,ws,vs));
1679 case VAROPCELL : if ((nonNull(findBtyvs(textOf(ty)))
1680 && !varIsMember(textOf(ty),ws))
1681 || varIsMember(textOf(ty),us)) {
1684 return maybeAppendVar(ty,vs);
1687 case POLYTYPE : return typeVarsIn(monotypeOf(ty),polySigOf(ty),ws,vs);
1689 case QUAL : { vs = typeVarsIn(fst(snd(ty)),us,ws,vs);
1690 return typeVarsIn(snd(snd(ty)),us,ws,vs);
1693 case BANG : return typeVarsIn(snd(ty),us,ws,vs);
1695 case LABC : { List fs = snd(snd(ty));
1696 for (; nonNull(fs); fs=tl(fs)) {
1697 vs = typeVarsIn(snd(hd(fs)),us,ws,vs);
1705 static List local maybeAppendVar(v,vs) /* append variable to list if not */
1706 Cell v; /* already included */
1712 while (nonNull(c)) {
1713 if (textOf(hd(c))==t) {
1721 tl(p) = cons(v,NIL);
1729 /* --------------------------------------------------------------------------
1730 * Static analysis for type expressions is required to:
1731 * - ensure that each type constructor or class used has been defined.
1732 * - replace type variables by offsets, constructor names by Tycons.
1733 * - ensure that the type is well-kinded.
1734 * ------------------------------------------------------------------------*/
1736 static Type local checkSigType(line,where,e,type)
1737 Int line; /* Check validity of type expr in */
1738 String where; /* explicit type signature */
1745 if (isPolyType(type)) {
1746 xtvs = fst(snd(type));
1747 type = monotypeOf(type);
1749 tvs = typeVarsIn(type,NIL,xtvs,NIL);
1751 checkOptQuantVars(line,xtvs,tvs);
1753 if (isQualType(type)) {
1754 map2Over(depPredExp,line,tvs,fst(snd(type)));
1755 snd(snd(type)) = depTopType(line,tvs,snd(snd(type)));
1757 if (isAmbiguous(type)) {
1758 ambigError(line,where,e,type);
1761 type = depTopType(line,tvs,type);
1765 if (length(tvs)>=NUM_OFFSETS) {
1766 ERRMSG(line) "Too many type variables in %s\n", where
1770 for (; nonNull(ts); ts=tl(ts)) {
1773 type = mkPolyType(tvs,type);
1778 kindType(line,"type expression",type);
1782 h98CheckType(line,where,e,type);
1786 static Void local checkOptQuantVars(line,xtvs,tvs)
1788 List xtvs; /* Explicitly quantified vars */
1789 List tvs; { /* Implicitly quantified vars */
1790 if (nonNull(xtvs)) {
1792 for (; nonNull(vs); vs=tl(vs)) {
1793 if (!varIsMember(textOf(hd(vs)),xtvs)) {
1794 ERRMSG(line) "Quantifier does not mention type variable \"%s\"",
1795 textToStr(textOf(hd(vs)))
1799 for (vs=xtvs; nonNull(vs); vs=tl(vs)) {
1800 if (!varIsMember(textOf(hd(vs)),tvs)) {
1801 ERRMSG(line) "Quantified type variable \"%s\" is not used",
1802 textToStr(textOf(hd(vs)))
1805 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1806 ERRMSG(line) "Quantified type variable \"%s\" is repeated",
1807 textToStr(textOf(hd(vs)))
1814 static Type local depTopType(l,tvs,t) /* Check top-level of type sig */
1822 for (; getHead(t1)==typeArrow && argCount==2; ++i) {
1823 arg(fun(t1)) = depCompType(l,tvs,arg(fun(t1)));
1824 if (isPolyOrQualType(arg(fun(t1)))) {
1830 if (nonNull(prev)) {
1831 arg(prev) = depTypeExp(l,tvs,t1);
1833 t = depTypeExp(l,tvs,t1);
1836 t = ap(RANK2,pair(mkInt(nr2),t));
1841 static Type local depCompType(l,tvs,t) /* Check component type for constr */
1845 Int ntvs = length(tvs);
1847 if (isPolyType(t)) {
1848 List vs = fst(snd(t));
1850 tvs = checkQuantVars(l,vs,tvs,t);
1851 nfr = replicate(length(vs),NIL);
1853 if (isQualType(t)) {
1854 map2Over(depPredExp,l,tvs,fst(snd(t)));
1855 snd(snd(t)) = depTypeExp(l,tvs,snd(snd(t)));
1856 if (isAmbiguous(t)) {
1857 ambigError(l,"type component",NIL,t);
1860 t = depTypeExp(l,tvs,t);
1866 return mkPolyType(nfr,t);
1869 static Type local depTypeExp(line,tyvars,type)
1873 switch (whatIs(type)) {
1874 case AP : fst(type) = depTypeExp(line,tyvars,fst(type));
1875 snd(type) = depTypeExp(line,tyvars,snd(type));
1878 case VARIDCELL : return depTypeVar(line,tyvars,textOf(type));
1880 case QUALIDENT : if (isQVar(type)) {
1881 ERRMSG(line) "Qualified type variables not allowed"
1884 /* deliberate fall through */
1885 case CONIDCELL : { Tycon tc = findQualTycon(type);
1888 "Undefined type constructor \"%s\"",
1892 if (cellIsMember(tc,tyconDefns) &&
1893 !cellIsMember(tc,tcDeps)) {
1894 tcDeps = cons(tc,tcDeps);
1900 case EXT : h98DoesntSupport(line,"extensible records");
1905 default : internal("depTypeExp");
1910 static Type local depTypeVar(line,tyvars,tv)
1917 for (; nonNull(tyvars); offset++) {
1918 if (tv==textOf(hd(tyvars))) {
1921 tyvars = tl(tyvars);
1924 Cell vt = findBtyvs(tv);
1928 ERRMSG(line) "Undefined type variable \"%s\"", textToStr(tv)
1931 return mkOffset(found);
1934 static List local checkQuantVars(line,vs,tvs,body)
1936 List vs; /* variables to quantify over */
1937 List tvs; /* variables already in scope */
1938 Cell body; { /* type/constr for scope of vars */
1940 List bvs = typeVarsIn(body,NIL,NIL,NIL);
1942 for (; nonNull(us); us=tl(us)) {
1943 Text u = textOf(hd(us));
1944 if (varIsMember(u,tl(us))) {
1945 ERRMSG(line) "Duplicated quantified variable %s",
1950 if (varIsMember(u,tvs)) {
1951 ERRMSG(line) "Local quantifier for %s hides an outer use",
1956 if (!varIsMember(u,bvs)) {
1957 ERRMSG(line) "Locally quantified variable %s is not used",
1962 tvs = appendOnto(tvs,vs);
1967 /* --------------------------------------------------------------------------
1968 * Check for ambiguous types:
1969 * A type Preds => type is ambiguous if not (TV(P) `subset` TV(type))
1970 * ------------------------------------------------------------------------*/
1972 List offsetTyvarsIn(t,vs) /* add list of offset tyvars in t */
1973 Type t; /* to list vs */
1975 switch (whatIs(t)) {
1976 case AP : return offsetTyvarsIn(fun(t),
1977 offsetTyvarsIn(arg(t),vs));
1979 case OFFSET : if (cellIsMember(t,vs))
1984 case QUAL : return offsetTyvarsIn(snd(t),vs);
1986 case POLYTYPE : return offsetTyvarsIn(monotypeOf(t),vs);
1987 /* slightly inaccurate, but won't matter here */
1990 case RANK2 : return offsetTyvarsIn(snd(snd(t)),vs);
1992 default : return vs;
1996 List zonkTyvarsIn(t,vs)
1999 switch (whatIs(t)) {
2000 case AP : return zonkTyvarsIn(fun(t),
2001 zonkTyvarsIn(arg(t),vs));
2003 case INTCELL : if (cellIsMember(t,vs))
2008 case OFFSET : internal("zonkTyvarsIn");
2010 default : return vs;
2014 static List local otvars(pi,os) /* os is a list of offsets that */
2015 Cell pi; /* refer to the arguments of pi; */
2016 List os; { /* find list of offsets in those */
2017 List us = NIL; /* positions */
2018 for (; nonNull(os); os=tl(os)) {
2019 us = offsetTyvarsIn(nthArg(offsetOf(hd(os)),pi),us);
2024 static List local otvarsZonk(pi,os,o) /* same as above, but zonks */
2029 for (; nonNull(os); os=tl(os)) {
2030 Type t = zonkType(nthArg(offsetOf(hd(os)),pi),o);
2031 us = zonkTyvarsIn(t,us);
2036 static Bool local odiff(us,vs)
2038 while (nonNull(us) && cellIsMember(hd(us),vs)) {
2044 static Bool local osubset(us,vs) /* Determine whether us is subset */
2045 List us, vs; { /* of vs */
2046 while (nonNull(us) && cellIsMember(hd(us),vs)) {
2052 List oclose(fds,vs) /* Compute closure of vs wrt to fds*/
2055 Bool changed = TRUE;
2059 while (nonNull(fds)) {
2061 List next = tl(fds);
2062 if (osubset(fst(fd),vs)) { /* Test if fd applies */
2064 for (; nonNull(os); os=tl(os)) {
2065 if (!cellIsMember(hd(os),vs)) {
2066 vs = cons(hd(os),vs);
2070 } else { /* Didn't apply this time, so keep */
2081 Bool isAmbiguous(type) /* Determine whether type is */
2082 Type type; { /* ambiguous */
2083 if (isPolyType(type)) {
2084 type = monotypeOf(type);
2086 if (isQualType(type)) { /* only qualified types can be */
2087 List ps = fst(snd(type)); /* ambiguous */
2088 List tvps = offsetTyvarsIn(ps,NIL);
2089 List tvts = offsetTyvarsIn(snd(snd(type)),NIL);
2090 List fds = calcFunDeps(ps);
2092 tvts = oclose(fds,tvts); /* Close tvts under fds */
2093 return !osubset(tvps,tvts);
2098 List calcFunDeps(ps)
2101 for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies */
2103 Cell c = getHead(pi);
2105 List fs = cclass(c).fds;
2106 for (; nonNull(fs); fs=tl(fs)) {
2107 fds = cons(pair(otvars(pi,fst(hd(fs))),
2108 otvars(pi,snd(hd(fs)))),fds);
2113 fds = cons(pair(NIL,offsetTyvarsIn(arg(pi),NIL)),fds);
2120 List calcFunDepsPreds(ps)
2123 for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies */
2125 Cell pi = fst3(pi3);
2126 Cell c = getHead(pi);
2127 Int o = intOf(snd3(pi3));
2129 List fs = cclass(c).fds;
2130 for (; nonNull(fs); fs=tl(fs)) {
2131 fds = cons(pair(otvarsZonk(pi,fst(hd(fs)),o),
2132 otvarsZonk(pi,snd(hd(fs)),o)),fds);
2137 fds = cons(pair(NIL,zonkTyvarsIn(arg(pi),NIL)),fds);
2144 Void ambigError(line,where,e,type) /* produce error message for */
2145 Int line; /* ambiguity */
2149 ERRMSG(line) "Ambiguous type signature in %s", where ETHEN
2150 ERRTEXT "\n*** ambiguous type : " ETHEN ERRTYPE(type);
2152 ERRTEXT "\n*** assigned to : " ETHEN ERREXPR(e);
2158 /* --------------------------------------------------------------------------
2159 * Kind inference for simple types:
2160 * ------------------------------------------------------------------------*/
2162 static Void local kindConstr(line,alpha,m,c)
2163 Int line; /* Determine kind of constructor */
2167 Cell h = getHead(c);
2171 Printf("kindConstr: alpha=%d, m=%d, c=",alpha,m);
2172 printType(stdout,c);
2176 switch (whatIs(h)) {
2177 case POLYTYPE : if (n!=0) {
2178 internal("kindConstr1");
2180 static String pt = "polymorphic type";
2181 Type t = dropRank1(c,alpha,m);
2182 Kinds ks = polySigOf(t);
2185 for (; isAp(ks); ks=tl(ks)) {
2188 beta = newKindvars(m1);
2189 unkindTypes = cons(pair(mkInt(beta),t),unkindTypes);
2190 checkKind(line,beta,m1,monotypeOf(t),NIL,pt,STAR,0);
2195 case QUAL : if (n!=0) {
2196 internal("kindConstr2");
2198 map3Proc(kindPred,line,alpha,m,fst(snd(c)));
2199 kindConstr(line,alpha,m,snd(snd(c)));
2203 case RANK2 : kindConstr(line,alpha,m,snd(snd(c)));
2207 case EXT : if (n!=2) {
2209 "Illegal use of row in " ETHEN ERRTYPE(c);
2216 case TYCON : if (isSynonym(h) && n<tycon(h).arity) {
2218 "Not enough arguments for type synonym \"%s\"",
2219 textToStr(tycon(h).text)
2225 if (n==0) { /* trivial case, no arguments */
2226 typeIs = kindAtom(alpha,c);
2227 } else { /* non-trivial application */
2228 static String app = "constructor application";
2238 typeIs = kindAtom(alpha,h); /* h :: v1 -> ... -> vn -> w */
2239 shouldKind(line,h,c,app,k,beta);
2241 for (i=n; i>0; --i) { /* ci :: vi for each 1 <- 1..n */
2242 checkKind(line,alpha,m,arg(a),c,app,aVar,beta+i-1);
2245 tyvarType(beta+n); /* inferred kind is w */
2249 static Kind local kindAtom(alpha,c) /* Find kind of atomic constructor */
2252 switch (whatIs(c)) {
2253 case TUPLE : return simpleKind(tupleOf(c)); /*(,)::* -> * -> * */
2254 case OFFSET : return mkInt(alpha+offsetOf(c));
2255 case TYCON : return tycon(c).kind;
2256 case INTCELL : return c;
2258 case VAROPCELL : { Cell vt = findBtyvs(textOf(c));
2264 case EXT : return extKind;
2268 Printf("kindAtom(%d,whatIs(%d)) on ",alpha,whatIs(c));
2269 printType(stdout,c);
2272 internal("kindAtom");
2273 return STAR;/* not reached */
2276 static Void local kindPred(l,alpha,m,pi)/* Check kinds of arguments in pred*/
2282 if (isAp(pi) && isExt(fun(pi))) {
2283 static String lackspred = "lacks predicate";
2284 checkKind(l,alpha,m,arg(pi),NIL,lackspred,ROW,0);
2289 if (isAp(pi) && whatIs(fun(pi)) == IPCELL) {
2290 static String ippred = "iparam predicate";
2291 checkKind(l,alpha,m,arg(pi),NIL,ippred,STAR,0);
2295 { static String predicate = "class constraint";
2296 Class c = getHead(pi);
2297 List as = getArgs(pi);
2298 Kinds ks = cclass(c).kinds;
2300 while (nonNull(ks)) {
2301 checkKind(l,alpha,m,hd(as),NIL,predicate,hd(ks),0);
2308 static Void local kindType(line,wh,type)/* check that (poss qualified) type*/
2309 Int line; /* is well-kinded */
2312 checkKind(line,0,0,type,NIL,wh,STAR,0);
2315 static Void local fixKinds() { /* add kind annotations to types */
2316 for (; nonNull(unkindTypes); unkindTypes=tl(unkindTypes)) {
2317 Pair pr = hd(unkindTypes);
2318 Int beta = intOf(fst(pr));
2319 Cell qts = polySigOf(snd(pr));
2321 if (isNull(hd(qts))) {
2322 hd(qts) = copyKindvar(beta++);
2324 internal("fixKinds");
2326 if (nonNull(tl(qts))) {
2334 Printf("Type expression: ");
2335 printType(stdout,snd(pr));
2337 printKind(stdout,polySigOf(snd(pr)));
2343 /* --------------------------------------------------------------------------
2344 * Kind checking of groups of type constructors and classes:
2345 * ------------------------------------------------------------------------*/
2347 static Void local kindTCGroup(tcs) /* find kinds for mutually rec. gp */
2348 List tcs; { /* of tycons and classes */
2349 emptySubstitution();
2351 mapProc(initTCKind,tcs);
2352 mapProc(kindTC,tcs);
2355 emptySubstitution();
2358 static Void local initTCKind(c) /* build initial kind/arity for c */
2360 if (isTycon(c)) { /* Initial kind of tycon is: */
2361 Int beta = newKindvars(1); /* v1 -> ... -> vn -> vn+1 */
2362 varKind(tycon(c).arity); /* where n is the arity of c. */
2363 bindTv(beta,typeIs,typeOff); /* For data definitions, vn+1 == * */
2364 switch (whatIs(tycon(c).what)) {
2366 case DATATYPE : bindTv(typeOff+tycon(c).arity,STAR,0);
2368 tycon(c).kind = mkInt(beta);
2370 Int n = cclass(c).arity;
2371 Int beta = newKindvars(n);
2372 cclass(c).kinds = NIL;
2375 cclass(c).kinds = pair(mkInt(beta+n),cclass(c).kinds);
2380 static Void local kindTC(c) /* check each part of a tycon/class*/
2381 Cell c; { /* is well-kinded */
2383 static String cfun = "constructor function";
2384 static String tsyn = "synonym definition";
2385 Int line = tycon(c).line;
2386 Int beta = tyvar(intOf(tycon(c).kind))->offs;
2387 Int m = tycon(c).arity;
2388 switch (whatIs(tycon(c).what)) {
2390 case DATATYPE : { List cs = tycon(c).defn;
2391 if (isQualType(cs)) {
2392 map3Proc(kindPred,line,beta,m,
2394 tycon(c).defn = cs = snd(snd(cs));
2396 for (; hasCfun(cs); cs=tl(cs)) {
2397 kindType(line,cfun,name(hd(cs)).type);
2402 default : checkKind(line,beta,m,tycon(c).defn,NIL,
2406 else { /* scan type exprs in class defn to*/
2407 List ms = fst(cclass(c).members);
2408 Int m = cclass(c).arity; /* determine the class signature */
2409 Int beta = newKindvars(m);
2410 kindPred(cclass(c).line,beta,m,cclass(c).head);
2411 map3Proc(kindPred,cclass(c).line,beta,m,cclass(c).supers);
2412 for (; nonNull(ms); ms=tl(ms)) {
2413 Int line = intOf(fst3(hd(ms)));
2414 Type type = thd3(hd(ms));
2415 kindType(line,"member function type signature",type);
2420 static Void local genTC(c) /* generalise kind inferred for */
2421 Cell c; { /* given tycon/class */
2423 tycon(c).kind = copyKindvar(intOf(tycon(c).kind));
2425 Printf("%s :: ",textToStr(tycon(c).text));
2426 printKind(stdout,tycon(c).kind);
2430 Kinds ks = cclass(c).kinds;
2431 for (; nonNull(ks); ks=tl(ks)) {
2432 hd(ks) = copyKindvar(intOf(hd(ks)));
2435 Printf("%s :: ",textToStr(cclass(c).text));
2436 printKinds(stdout,cclass(c).kinds);
2442 /* --------------------------------------------------------------------------
2443 * Static analysis of instance declarations:
2445 * The first part of the static analysis is performed as the declarations
2446 * are read during parsing:
2447 * - make new entry in instance table
2448 * - record line number of declaration
2449 * - build list of instances defined in current script for use in later
2450 * stages of static analysis.
2451 * ------------------------------------------------------------------------*/
2453 Void instDefn(line,head,ms) /* process new instance definition */
2454 Int line; /* definition line number */
2455 Cell head; /* inst header :: (context,Class) */
2456 List ms; { /* instance members */
2457 Inst nw = newInst();
2458 inst(nw).line = line;
2459 inst(nw).specifics = fst(head);
2460 inst(nw).head = snd(head);
2461 inst(nw).implements = ms;
2462 instDefns = cons(nw,instDefns);
2465 /* --------------------------------------------------------------------------
2466 * Further static analysis of instance declarations:
2468 * Makes the following checks:
2469 * - Class part of header has form C (T a1 ... an) where C is a known
2470 * class, and T is a known datatype constructor (or restricted synonym),
2471 * and there is no previous C-T instance, and (T a1 ... an) has a kind
2472 * appropriate for the class C.
2473 * - Each element of context is a valid class expression, with type vars
2474 * drawn from a1, ..., an.
2475 * - All bindings are function bindings
2476 * - All bindings define member functions for class C
2477 * - Arrange bindings into appropriate order for member list
2478 * - No top level type signature declarations
2479 * ------------------------------------------------------------------------*/
2481 Bool allowOverlap = FALSE; /* TRUE => allow overlapping insts */
2482 Name nameListMonad = NIL; /* builder function for List Monad */
2484 static Void local checkInstDefn(in) /* Validate instance declaration */
2486 Int line = inst(in).line;
2487 List tyvars = typeVarsIn(inst(in).head,NIL,NIL,NIL);
2488 List tvps = NIL, tvts = NIL;
2491 if (haskell98) { /* Check for `simple' type */
2493 Cell t = arg(inst(in).head);
2494 for (; isAp(t); t=fun(t)) {
2495 if (!isVar(arg(t))) {
2497 "syntax error in instance head (variable expected)"
2500 if (varIsMember(textOf(arg(t)),tvs)) {
2501 ERRMSG(line) "repeated type variable \"%s\" in instance head",
2502 textToStr(textOf(arg(t)))
2505 tvs = cons(arg(t),tvs);
2509 "syntax error in instance head (constructor expected)"
2514 /* add in the tyvars from the `specifics' so that we don't
2515 prematurely complain about undefined tyvars */
2516 tyvars = typeVarsIn(inst(in).specifics,NIL,NIL,tyvars);
2517 inst(in).head = depPredExp(line,tyvars,inst(in).head);
2520 Type h = getHead(arg(inst(in).head));
2522 ERRMSG(line) "Cannot use type synonym in instance head"
2527 map2Over(depPredExp,line,tyvars,inst(in).specifics);
2529 /* OK, now we start over, and test for ambiguity */
2530 tvts = offsetTyvarsIn(inst(in).head,NIL);
2531 tvps = offsetTyvarsIn(inst(in).specifics,NIL);
2532 fds = calcFunDeps(inst(in).specifics);
2533 tvts = oclose(fds,tvts);
2534 tvts = odiff(tvps,tvts);
2535 if (!isNull(tvts)) {
2536 ERRMSG(line) "Undefined type variable \"%s\"",
2537 textToStr(textOf(nth(offsetOf(hd(tvts)),tyvars)))
2541 h98CheckCtxt(line,"instance definition",FALSE,inst(in).specifics,NIL);
2542 inst(in).numSpecifics = length(inst(in).specifics);
2543 inst(in).c = getHead(inst(in).head);
2544 if (!isClass(inst(in).c)) {
2545 ERRMSG(line) "Illegal predicate in instance declaration"
2548 kindInst(in,length(tyvars));
2551 if (nonNull(extractSigdecls(inst(in).implements))) {
2553 "Type signature declarations not permitted in instance declaration"
2556 if (nonNull(extractFixdecls(inst(in).implements))) {
2558 "Fixity declarations not permitted in instance declaration"
2561 inst(in).implements = classBindings("instance",
2563 extractBindings(inst(in).implements));
2564 inst(in).builder = newInstImp(in);
2565 if (!preludeLoaded && isNull(nameListMonad) && isAp(inst(in).head)
2566 && fun(inst(in).head)==classMonad && arg(inst(in).head)==typeList) {
2567 nameListMonad = inst(in).builder;
2571 static Void local insertInst(in) /* Insert instance into class */
2573 Class c = inst(in).c;
2574 List ins = cclass(c).instances;
2577 if (nonNull(cclass(c).fds)) { /* Check for conflicts with fds */
2578 List ins1 = cclass(c).instances;
2579 for (; nonNull(ins1); ins1=tl(ins1)) {
2580 List fds = cclass(c).fds;
2581 substitution(RESET);
2582 for (; nonNull(fds); fds=tl(fds)) {
2583 Int alpha = newKindedVars(inst(in).kinds);
2584 Int beta = newKindedVars(inst(hd(ins1)).kinds);
2585 List as = fst(hd(fds));
2587 for (; same && nonNull(as); as=tl(as)) {
2588 Int n = offsetOf(hd(as));
2589 same &= unify(nthArg(n,inst(in).head),alpha,
2590 nthArg(n,inst(hd(ins1)).head),beta);
2592 if (isNull(as) && same) {
2593 for (as=snd(hd(fds)); same && nonNull(as); as=tl(as)) {
2594 Int n = offsetOf(hd(as));
2595 same &= sameType(nthArg(n,inst(in).head),alpha,
2596 nthArg(n,inst(hd(ins1)).head),beta);
2599 ERRMSG(inst(in).line)
2600 "Instances are not consistent with dependencies"
2602 ERRTEXT "\n*** This instance : "
2603 ETHEN ERRPRED(inst(in).head);
2604 ERRTEXT "\n*** Conflicts with : "
2605 ETHEN ERRPRED(inst(hd(ins)).head);
2606 ERRTEXT "\n*** For class : "
2607 ETHEN ERRPRED(cclass(c).head);
2608 ERRTEXT "\n*** Under dependency : "
2609 ETHEN ERRFD(hd(fds));
2619 substitution(RESET);
2620 while (nonNull(ins)) { /* Look for overlap w/ other insts */
2621 Int alpha = newKindedVars(inst(in).kinds);
2622 Int beta = newKindedVars(inst(hd(ins)).kinds);
2623 if (unifyPred(inst(in).head,alpha,inst(hd(ins)).head,beta)) {
2624 Cell pi = copyPred(inst(in).head,alpha);
2625 if (allowOverlap && !haskell98) {
2626 Bool bef = instCompare(in,hd(ins));
2627 Bool aft = instCompare(hd(ins),in);
2628 if (bef && !aft) { /* in comes strictly before hd(ins)*/
2631 if (aft && !bef) { /* in comes strictly after hd(ins) */
2638 if (multiInstRes && nonNull(inst(in).specifics)) {
2642 ERRMSG(inst(in).line) "Overlapping instances for class \"%s\"",
2643 textToStr(cclass(c).text)
2645 ERRTEXT "\n*** This instance : " ETHEN ERRPRED(inst(in).head);
2646 ERRTEXT "\n*** Overlaps with : " ETHEN
2647 ERRPRED(inst(hd(ins)).head);
2648 ERRTEXT "\n*** Common instance : " ETHEN
2656 prev = ins; /* No overlap detected, so move on */
2657 ins = tl(ins); /* to next instance */
2659 substitution(RESET);
2661 if (nonNull(prev)) { /* Insert instance at this point */
2662 tl(prev) = cons(in,ins);
2664 cclass(c).instances = cons(in,ins);
2668 static Bool local instCompare(ia,ib) /* See if ia is an instance of ib */
2670 Int alpha = newKindedVars(inst(ia).kinds);
2671 Int beta = newKindedVars(inst(ib).kinds);
2672 return matchPred(inst(ia).head,alpha,inst(ib).head,beta);
2675 static Name local newInstImp(in) /* Make definition for inst builder*/
2677 Name b = newName(inventText(),in);
2678 name(b).line = inst(in).line;
2679 name(b).arity = inst(in).numSpecifics;
2680 name(b).number = DFUNNAME;
2684 /* --------------------------------------------------------------------------
2685 * Kind checking of instance declaration headers:
2686 * ------------------------------------------------------------------------*/
2688 static Void local kindInst(in,freedom) /* check predicates in instance */
2693 emptySubstitution();
2694 beta = newKindvars(freedom);
2695 kindPred(inst(in).line,beta,freedom,inst(in).head);
2696 if (whatIs(inst(in).specifics)!=DERIVE) {
2697 map3Proc(kindPred,inst(in).line,beta,freedom,inst(in).specifics);
2699 for (inst(in).kinds = NIL; 0<freedom--; ) {
2700 inst(in).kinds = cons(copyKindvar(beta+freedom),inst(in).kinds);
2703 Printf("instance ");
2704 printPred(stdout,inst(in).head);
2706 printKinds(stdout,inst(in).kinds);
2709 emptySubstitution();
2712 /* --------------------------------------------------------------------------
2713 * Process derived instance requests:
2714 * ------------------------------------------------------------------------*/
2716 static List derivedInsts; /* list of derived instances */
2718 static Void local checkDerive(t,p,ts,ct)/* verify derived instance request */
2719 Tycon t; /* for tycon t, with explicit */
2720 List p; /* context p, component types ts */
2721 List ts; /* and named class ct */
2723 Int line = tycon(t).line;
2724 Class c = findQualClass(ct);
2726 ERRMSG(line) "Unknown class \"%s\" in derived instance",
2730 addDerInst(line,c,p,dupList(ts),t,tycon(t).arity);
2733 static Void local addDerInst(line,c,p,cts,t,a) /* Add a derived instance */
2740 Cell head = t; /* Build instance head */
2744 head = ap(head,mkOffset(i));
2750 inst(in).line = line;
2751 inst(in).head = head;
2752 inst(in).specifics = ap(DERIVE,pair(dupList(p),cts));
2753 inst(in).implements = NIL;
2754 inst(in).kinds = mkInt(a);
2755 derivedInsts = cons(in,derivedInsts);
2758 Void addTupInst(c,n) /* Request derived instance of c */
2759 Class c; /* for mkTuple(n) constructor */
2764 cts = cons(mkOffset(m),cts);
2767 addDerInst(0,c,NIL,cts,mkTuple(n),n);
2771 Inst addRecShowInst(c,e) /* Generate instance for ShowRecRow*/
2772 Class c; /* c *must* be ShowRecRow */
2774 Inst in = newInst();
2776 inst(in).head = ap(c,ap2(e,aVar,bVar));
2777 inst(in).kinds = extKind;
2778 inst(in).specifics = cons(ap(classShow,aVar),
2780 cons(ap(c,bVar),NIL)));
2781 inst(in).numSpecifics = 3;
2782 inst(in).builder = implementRecShw(extText(e),in);
2783 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2787 Inst addRecEqInst(c,e) /* Generate instance for EqRecRow */
2788 Class c; /* c *must* be EqRecRow */
2790 Inst in = newInst();
2792 inst(in).head = ap(c,ap2(e,aVar,bVar));
2793 inst(in).kinds = extKind;
2794 inst(in).specifics = cons(ap(classEq,aVar),
2796 cons(ap(c,bVar),NIL)));
2797 inst(in).numSpecifics = 3;
2798 inst(in).builder = implementRecEq(extText(e),in);
2799 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2804 /* --------------------------------------------------------------------------
2805 * Calculation of contexts for derived instances:
2807 * Allowing arbitrary types to appear in contexts makes it rather harder
2808 * to decide what the context for a derived instance should be. For
2811 * data T a = MkT [a] deriving Show,
2813 * we could have either of the following:
2815 * instance (Show [a]) => Show (T a) where ...
2816 * instance (Show a) => Show (T a) where ...
2818 * (assuming, of course, that instance (Show a) => Show [a]). For now, we
2819 * choose to reduce contexts in the hope of detecting errors at an earlier
2820 * stage---in contrast with value definitions, there is no way for a user
2821 * to provide something analogous to a `type signature' by which they might
2822 * be able to control this behaviour themselves. We eliminate tautological
2823 * predicates, but only allow predicates to appear in the final result if
2824 * they have at least one argument with a variable at its head.
2826 * In general, we have to deal with mutually recursive instance declarations.
2827 * We find a solution in the obvious way by iterating to find a fixed point.
2828 * Of course, without restrictions on the form of instance declarations, we
2829 * cannot be sure that this will always terminate!
2831 * For each instance we maintain a pair of the form DERIVE (ctxt,ps).
2832 * Ctxt is a list giving the parts of the context that have been produced
2833 * so far in the form of predicate skeletons. During the calculation of
2834 * derived instances, we attach a dummy NIL value to the end of the list
2835 * which acts as a kind of `variable': other parts of the system maintain
2836 * pointers to this variable, and use it to detect when the context has
2837 * been extended with new elements. Meanwhile, ps is a list containing
2838 * predicates (pi,o) together with (delayed) substitutions of the form
2839 * (o,xs) where o is an offset and xs is one of the context variables
2840 * described above, which may have been partially instantiated.
2841 * ------------------------------------------------------------------------*/
2843 static Bool instsChanged;
2845 static Void local deriveContexts(is) /* Calc contexts for derived insts */
2847 emptySubstitution();
2848 mapProc(initDerInst,is); /* Prepare derived instances */
2850 do { /* Main calculation of contexts */
2851 instsChanged = FALSE;
2852 mapProc(calcInstPreds,is);
2853 } while (instsChanged);
2855 mapProc(tidyDerInst,is); /* Tidy up results */
2858 static Void local initDerInst(in) /* Prepare instance for calculation*/
2859 Inst in; { /* of derived instance context */
2860 Cell spcs = inst(in).specifics;
2861 Int beta = newKindedVars(inst(in).kinds);
2862 if (whatIs(spcs)!=DERIVE) {
2863 internal("initDerInst");
2865 fst(snd(spcs)) = appendOnto(fst(snd(spcs)),singleton(NIL));
2866 for (spcs=snd(snd(spcs)); nonNull(spcs); spcs=tl(spcs)) {
2867 hd(spcs) = ap2(inst(in).c,hd(spcs),mkInt(beta));
2869 inst(in).numSpecifics = beta;
2871 #ifdef DEBUG_DERIVING
2872 Printf("initDerInst: ");
2873 printPred(stdout,inst(in).head);
2875 printContext(stdout,snd(snd(inst(in).specifics)));
2880 static Void local calcInstPreds(in) /* Calculate next approximation */
2881 Inst in; { /* of the context for a derived */
2882 List retain = NIL; /* instance */
2883 List ps = snd(snd(inst(in).specifics));
2884 List spcs = fst(snd(inst(in).specifics));
2885 Int beta = inst(in).numSpecifics;
2888 #ifdef DEBUG_DERIVING
2889 Printf("calcInstPreds: ");
2890 printPred(stdout,inst(in).head);
2894 while (nonNull(ps)) {
2897 if (its++ >= cutoff) {
2898 Cell bpi = inst(in).head;
2899 Cell pi = copyPred(fun(p),intOf(snd(p)));
2900 ERRMSG(inst(in).line) "\n*** Cannot derive " ETHEN ERRPRED(bpi);
2901 ERRTEXT " after %d iterations.", its-1 ETHEN
2903 "\n*** This may indicate that the problem is undecidable. However,\n"
2905 "*** you may still try to increase the cutoff limit using the -c\n"
2907 "*** option and then try again. (The current setting is -c%d)\n",
2911 if (isInt(fst(p))) { /* Delayed substitution? */
2913 for (; nonNull(hd(qs)); qs=tl(qs)) {
2914 ps = cons(pair(hd(qs),fst(p)),ps);
2916 retain = cons(pair(fst(p),qs),retain);
2919 else if (isExt(fun(fst(p)))) { /* Lacks predicate */
2920 Text l = extText(fun(fst(p)));
2921 Type t = arg(fst(p));
2922 Int o = intOf(snd(p));
2927 h = getDerefHead(t,o);
2928 while (isExt(h) && argCount==2 && l!=extText(h)) {
2931 h = getDerefHead(t,o);
2933 if (argCount==0 && isOffset(h)) {
2934 maybeAddPred(ap(fun(fun(p)),h),o,beta,spcs);
2935 } else if (argCount!=0 || h!=typeNoRow) {
2936 Cell bpi = inst(in).head;
2937 Cell pi = copyPred(fun(p),intOf(snd(p)));
2938 ERRMSG(inst(in).line) "Cannot derive " ETHEN ERRPRED(bpi);
2939 ERRTEXT " because predicate " ETHEN ERRPRED(pi);
2940 ERRTEXT " does not hold\n"
2945 else { /* Class predicate */
2947 Int o = intOf(snd(p));
2948 Inst in1 = findInstFor(pi,o);
2950 List qs = inst(in1).specifics;
2951 Int off = mkInt(typeOff);
2952 if (whatIs(qs)==DERIVE) { /* Still being derived */
2953 for (qs=fst(snd(qs)); nonNull(hd(qs)); qs=tl(qs)) {
2954 ps = cons(pair(hd(qs),off),ps);
2956 retain = cons(pair(off,qs),retain);
2957 } else { /* Previously def'd inst */
2958 for (; nonNull(qs); qs=tl(qs)) {
2959 ps = cons(pair(hd(qs),off),ps);
2962 } else { /* No matching instance */
2964 while (isAp(qi) && isOffset(getDerefHead(arg(qi),o))) {
2968 Cell bpi = inst(in).head;
2969 pi = copyPred(pi,o);
2970 ERRMSG(inst(in).line) "An instance of " ETHEN ERRPRED(pi);
2971 ERRTEXT " is required to derive " ETHEN ERRPRED(bpi);
2975 maybeAddPred(pi,o,beta,spcs);
2980 snd(snd(inst(in).specifics)) = retain;
2983 static Void local maybeAddPred(pi,o,beta,ps)
2984 Cell pi; /* Add predicate pi to the list ps,*/
2985 Int o; /* setting the instsChanged flag if*/
2986 Int beta; /* pi is not already a member and */
2987 List ps; { /* using beta to adjust vars */
2988 Cell c = getHead(pi);
2989 for (; nonNull(ps); ps=tl(ps)) {
2990 if (isNull(hd(ps))) { /* reached the `dummy' end of list?*/
2991 hd(ps) = copyAdj(pi,o,beta);
2992 tl(ps) = pair(NIL,NIL);
2993 instsChanged = TRUE;
2995 } else if (c==getHead(hd(ps)) && samePred(pi,o,hd(ps),beta)) {
3001 static Cell local copyAdj(c,o,beta) /* Copy (c,o), replacing vars with */
3002 Cell c; /* offsets relative to beta. */
3005 switch (whatIs(c)) {
3006 case AP : { Cell l = copyAdj(fst(c),o,beta);
3007 Cell r = copyAdj(snd(c),o,beta);
3011 case OFFSET : { Int vn = o+offsetOf(c);
3012 Tyvar *tyv = tyvar(vn);
3014 return copyAdj(tyv->bound,tyv->offs,beta);
3017 if (vn<0 || vn>=NUM_OFFSETS) {
3018 internal("copyAdj");
3020 return mkOffset(vn);
3026 static Void local tidyDerInst(in) /* Tidy up results of derived inst */
3027 Inst in; { /* calculations */
3028 Int o = inst(in).numSpecifics;
3029 List ps = tl(rev(fst(snd(inst(in).specifics))));
3031 copyPred(inst(in).head,o);
3032 inst(in).specifics = simpleContext(ps,o);
3033 h98CheckCtxt(inst(in).line,"derived instance",FALSE,inst(in).specifics,in);
3034 inst(in).numSpecifics = length(inst(in).specifics);
3036 #ifdef DEBUG_DERIVING
3037 Printf("Derived instance: ");
3038 printContext(stdout,inst(in).specifics);
3040 printPred(stdout,inst(in).head);
3045 /* --------------------------------------------------------------------------
3046 * Generate code for derived instances:
3047 * ------------------------------------------------------------------------*/
3049 static Void local addDerivImp(in)
3052 Type t = getHead(arg(inst(in).head));
3053 Class c = inst(in).c;
3056 } else if (c==classOrd) {
3058 } else if (c==classEnum) {
3059 imp = deriveEnum(t);
3060 } else if (c==classIx) {
3062 } else if (c==classShow) {
3063 imp = deriveShow(t);
3064 } else if (c==classRead) {
3065 imp = deriveRead(t);
3066 } else if (c==classBounded) {
3067 imp = deriveBounded(t);
3069 ERRMSG(inst(in).line) "Cannot derive instances of class \"%s\"",
3070 textToStr(cclass(inst(in).c).text)
3074 kindInst(in,intOf(inst(in).kinds));
3076 inst(in).builder = newInstImp(in);
3077 inst(in).implements = classBindings("derived instance",
3083 /* --------------------------------------------------------------------------
3084 * Default definitions; only one default definition is permitted in a
3085 * given script file. If no default is supplied, then a standard system
3086 * default will be used where necessary.
3087 * ------------------------------------------------------------------------*/
3089 Void defaultDefn(line,defs) /* Handle default types definition */
3092 if (defaultLine!=0) {
3093 ERRMSG(line) "Multiple default declarations are not permitted in" ETHEN
3094 ERRTEXT "a single script file.\n"
3097 defaultDefns = defs;
3101 static Void local checkDefaultDefns() { /* check that default types are */
3102 List ds = NIL; /* well-kinded instances of Num */
3104 if (defaultLine!=0) {
3105 map2Over(depTypeExp,defaultLine,NIL,defaultDefns);
3106 emptySubstitution();
3108 map2Proc(kindType,defaultLine,"default type",defaultDefns);
3110 emptySubstitution();
3111 mapOver(fullExpand,defaultDefns);
3113 defaultDefns = stdDefaults;
3116 if (isNull(classNum)) {
3117 classNum = findClass(findText("Num"));
3120 for (ds=defaultDefns; nonNull(ds); ds=tl(ds)) {
3121 if (isNull(provePred(NIL,NIL,ap(classNum,hd(ds))))) {
3123 "Default types must be instances of the Num class"
3130 /* --------------------------------------------------------------------------
3131 * Foreign import declarations are Hugs' equivalent of GHC's ccall mechanism.
3132 * They are used to "import" C functions into a module.
3133 * They are usually not written by hand but, rather, generated automatically
3134 * by GreenCard, IDL compilers or whatever.
3136 * Foreign export declarations generate C wrappers for Hugs functions.
3137 * Hugs only provides "foreign export dynamic" because it's not obvious
3138 * what "foreign export static" would mean in an interactive setting.
3139 * ------------------------------------------------------------------------*/
3141 Void foreignImport(line,callconv,extName,intName,type)
3142 /* Handle foreign imports */
3148 Text t = textOf(intName);
3149 Name n = findName(t);
3150 Int l = intOf(line);
3154 } else if (name(n).defn!=PREDEFINED) {
3155 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
3159 name(n).defn = extName;
3160 name(n).type = type;
3161 name(n).callconv = callconv;
3162 foreignImports = cons(n,foreignImports);
3165 static Void local checkForeignImport(p) /* Check foreign import */
3167 emptySubstitution();
3168 name(p).type = checkSigType(name(p).line,
3169 "foreign import declaration",
3172 /* We don't expand synonyms here because we don't want the IO
3173 * part to be expanded.
3174 * name(p).type = fullExpand(name(p).type);
3176 implementForeignImport(p);
3179 Void foreignExport(line,callconv,extName,intName,type)
3180 /* Handle foreign exports */
3186 Text t = textOf(intName);
3187 Name n = findName(t);
3188 Int l = intOf(line);
3192 } else if (name(n).defn!=PREDEFINED) {
3193 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
3197 name(n).defn = NIL; /* nothing to say */
3198 name(n).type = type;
3199 name(n).callconv = callconv;
3200 foreignExports = cons(n,foreignExports);
3203 static Void local checkForeignExport(p) /* Check foreign export */
3205 emptySubstitution();
3206 name(p).type = checkSigType(name(p).line,
3207 "foreign export declaration",
3210 implementForeignExport(p);
3215 /* --------------------------------------------------------------------------
3216 * Static analysis of patterns:
3218 * Patterns are parsed as ordinary (atomic) expressions. Static analysis
3219 * makes the following checks:
3220 * - Patterns are well formed (according to pattern syntax), including the
3221 * special case of (n+k) patterns.
3222 * - All constructor functions have been defined and are used with the
3223 * correct number of arguments.
3224 * - No variable name is used more than once in a pattern.
3226 * The list of pattern variables occuring in each pattern is accumulated in
3227 * a global list `patVars', which must be initialised to NIL at appropriate
3228 * points before using these routines to check for valid patterns. This
3229 * mechanism enables the pattern checking routine to be mapped over a list
3230 * of patterns, ensuring that no variable occurs more than once in the
3231 * complete pattern list (as is required on the lhs of a function defn).
3232 * ------------------------------------------------------------------------*/
3234 static List patVars; /* List of vars bound in pattern */
3236 static Cell local checkPat(line,p) /* Check valid pattern syntax */
3239 switch (whatIs(p)) {
3241 case VAROPCELL : addToPatVars(line,p);
3244 case INFIX : return checkPat(line,tidyInfix(line,snd(p)));
3246 case AP : return checkMaybeCnkPat(line,p);
3251 case CONOPCELL : return checkApPat(line,0,p);
3256 case FLOATCELL : break;
3257 case INTCELL : break;
3259 case ASPAT : addToPatVars(line,fst(snd(p)));
3260 snd(snd(p)) = checkPat(line,snd(snd(p)));
3263 case LAZYPAT : snd(p) = checkPat(line,snd(p));
3266 case FINLIST : map1Over(checkPat,line,snd(p));
3269 case CONFLDS : depConFlds(line,p,TRUE);
3272 case ESIGN : snd(snd(p)) = checkPatType(line,
3276 fst(snd(p)) = checkPat(line,fst(snd(p)));
3279 default : ERRMSG(line) "Illegal pattern syntax"
3285 static Cell local checkMaybeCnkPat(l,p)/* Check applicative pattern with */
3286 Int l; /* the possibility of n+k pattern */
3289 Cell h = getHead(p);
3291 if (argCount==2 && isVar(h) && textOf(h)==textPlus) { /* n+k */
3292 Cell v = arg(fun(p));
3293 if (!isInt(arg(p))) {
3294 ERRMSG(l) "Second argument in (n+k) pattern must be an integer"
3297 if (intOf(arg(p))<=0) {
3298 ERRMSG(l) "Integer k in (n+k) pattern must be > 0"
3301 fst(fun(p)) = ADDPAT;
3302 intValOf(fun(p)) = intOf(arg(p));
3303 arg(p) = checkPat(l,v);
3307 return checkApPat(l,0,p);
3310 static Cell local checkApPat(line,args,p)
3311 Int line; /* check validity of application */
3312 Int args; /* of constructor to arguments */
3314 switch (whatIs(p)) {
3315 case AP : fun(p) = checkApPat(line,args+1,fun(p));
3316 arg(p) = checkPat(line,arg(p));
3319 case TUPLE : if (tupleOf(p)!=args) {
3320 ERRMSG(line) "Illegal tuple pattern"
3326 case EXT : h98DoesntSupport(line,"extensible records");
3328 ERRMSG(line) "Illegal record pattern"
3334 case QUALIDENT : if (!isQCon(p)) {
3336 "Illegal use of qualified variable in pattern"
3339 /* deliberate fall through */
3341 case CONOPCELL : p = conDefined(line,p);
3342 checkCfunArgs(line,p,args);
3345 case NAME : checkIsCfun(line,p);
3346 checkCfunArgs(line,p,args);
3349 default : ERRMSG(line) "Illegal pattern syntax"
3355 static Void local addToPatVars(line,v) /* Add variable v to list of vars */
3356 Int line; /* in current pattern, checking */
3357 Cell v; { /* for repeated variables. */
3362 for (; nonNull(n); p=n, n=tl(n)) {
3363 if (textOf(hd(n))==t) {
3364 ERRMSG(line) "Repeated variable \"%s\" in pattern",
3371 patVars = cons(v,NIL);
3373 tl(p) = cons(v,NIL);
3377 static Name local conDefined(line,nm) /* check that nm is the name of a */
3378 Int line; /* previously defined constructor */
3379 Cell nm; { /* function. */
3380 Name n = findQualName(nm);
3382 ERRMSG(line) "Undefined constructor function \"%s\"", identToStr(nm)
3385 checkIsCfun(line,n);
3389 static Void local checkIsCfun(line,c) /* Check that c is a constructor fn */
3393 ERRMSG(line) "\"%s\" is not a constructor function",
3394 textToStr(name(c).text)
3399 static Void local checkCfunArgs(line,c,args)
3400 Int line; /* Check constructor applied with */
3401 Cell c; /* correct number of arguments */
3403 Int a = userArity(c);
3406 "Constructor \"%s\" must have exactly %d argument%s in pattern",
3407 textToStr(name(c).text), a, ((a==1)?"":"s")
3412 static Cell local checkPatType(l,wh,e,t)/* Check type appearing in pattern */
3417 List tvs = typeVarsIn(t,NIL,NIL,NIL);
3418 h98DoesntSupport(l,"pattern type annotations");
3419 for (; nonNull(tvs); tvs=tl(tvs)) {
3420 Int beta = newKindvars(1);
3421 hd(btyvars) = cons(pair(hd(tvs),mkInt(beta)), hd(btyvars));
3423 t = checkSigType(l,"pattern type",e,t);
3424 if (isPolyOrQualType(t) || whatIs(t)==RANK2) {
3425 ERRMSG(l) "Illegal syntax in %s type annotation", wh
3431 static Cell local applyBtyvs(pat) /* Record bound type vars in pat */
3433 List bts = hd(btyvars);
3436 pat = ap(BIGLAM,pair(bts,pat));
3437 for (; nonNull(bts); bts=tl(bts)) {
3438 snd(hd(bts)) = copyKindvar(intOf(snd(hd(bts))));
3444 /* --------------------------------------------------------------------------
3445 * Maintaining lists of bound variables and local definitions, for
3446 * dependency and scope analysis.
3447 * ------------------------------------------------------------------------*/
3449 static List bounds; /* list of lists of bound vars */
3450 static List bindings; /* list of lists of binds in scope */
3451 static List depends; /* list of lists of dependents */
3453 /* bounds :: [[Var]] -- var equality used on Vars */
3454 /* bindings :: [[([Var],?)]] -- var equality used on Vars */
3455 /* depends :: [[Var]] -- pointer equality used on Vars */
3457 #define saveBvars() hd(bounds) /* list of bvars in current scope */
3458 #define restoreBvars(bs) hd(bounds)=bs /* restore list of bound variables */
3460 static Cell local bindPat(line,p) /* add new bound vars for pattern */
3464 p = checkPat(line,p);
3465 hd(bounds) = revOnto(patVars,hd(bounds));
3469 static Void local bindPats(line,ps) /* add new bound vars for patterns */
3473 map1Over(checkPat,line,ps);
3474 hd(bounds) = revOnto(patVars,hd(bounds));
3477 /* --------------------------------------------------------------------------
3478 * Before processing value and type signature declarations, all data and
3479 * type definitions have been processed so that:
3480 * - all valid type constructors (with their arities) are known.
3481 * - all valid constructor functions (with their arities and types) are
3484 * The result of parsing a list of value declarations is a list of Eqns:
3485 * Eqn ::= (SIGDECL,(Line,[Var],type))
3486 * | (FIXDECL,(Line,[Op],SyntaxInt))
3488 * The ordering of the equations in this list is the reverse of the original
3489 * ordering in the script parsed. This is a consequence of the structure of
3490 * the parser ... but also turns out to be most convenient for the static
3493 * As the first stage of the static analysis of value declarations, each
3494 * list of Eqns is converted to a list of Bindings. As part of this
3496 * - The ordering of the list of Bindings produced is the same as in the
3498 * - When a variable (function) is defined over a number of lines, all
3499 * of the definitions should appear together and each should give the
3500 * same arity to the variable being defined.
3501 * - No variable can have more than one definition.
3502 * - For pattern bindings:
3503 * - Each lhs is a valid pattern/function lhs, all constructor functions
3504 * have been defined and are used with the correct number of arguments.
3505 * - Each lhs contains no repeated pattern variables.
3506 * - Each equation defines at least one variable (e.g. True = False is
3508 * - Types appearing in type signatures are well formed:
3509 * - Type constructors used are defined and used with correct number
3511 * - type variables are replaced by offsets, type constructor names
3513 * - Every variable named in a type signature declaration is defined by
3514 * one or more equations elsewhere in the script.
3515 * - No variable has more than one type declaration.
3516 * - Similar properties for fixity declarations.
3518 * ------------------------------------------------------------------------*/
3520 #define bindingAttr(b) fst(snd(b)) /* type(s)/fixity(ies) for binding */
3521 #define fbindAlts(b) snd(snd(b)) /* alternatives for function binding*/
3523 static List local extractSigdecls(es) /* Extract the SIGDECLS from list */
3524 List es; { /* of equations */
3525 List sigdecls = NIL; /* :: [(Line,[Var],Type)] */
3527 for(; nonNull(es); es=tl(es)) {
3528 if (fst(hd(es))==SIGDECL) { /* type-declaration? */
3529 Pair sig = snd(hd(es));
3530 Int line = intOf(fst3(sig));
3531 List vs = snd3(sig);
3532 for(; nonNull(vs); vs=tl(vs)) {
3533 if (isQualIdent(hd(vs))) {
3534 ERRMSG(line) "Type signature for qualified variable \"%s\" is not allowed",
3539 sigdecls = cons(sig,sigdecls); /* discard SIGDECL tag*/
3545 static List local extractFixdecls(es) /* Extract the FIXDECLS from list */
3546 List es; { /* of equations */
3547 List fixdecls = NIL; /* :: [(Line,SyntaxInt,[Op])] */
3549 for(; nonNull(es); es=tl(es)) {
3550 if (fst(hd(es))==FIXDECL) { /* fixity declaration?*/
3551 fixdecls = cons(snd(hd(es)),fixdecls); /* discard FIXDECL tag*/
3557 static List local extractBindings(ds) /* extract untyped bindings from */
3558 List ds; { /* given list of equations */
3559 Cell lastVar = NIL; /* = var def'd in last eqn (if any)*/
3560 Int lastArity = 0; /* = number of args in last defn */
3561 List bs = NIL; /* :: [Binding] */
3563 for(; nonNull(ds); ds=tl(ds)) {
3565 if (fst(d)==FUNBIND) { /* Function bindings */
3566 Cell rhs = snd(snd(d));
3567 Int line = rhsLine(rhs);
3568 Cell lhs = fst(snd(d));
3569 Cell v = getHead(lhs);
3570 Cell newAlt = pair(getArgs(lhs),rhs);
3572 internal("FUNBIND");
3574 if (nonNull(lastVar) && textOf(v)==textOf(lastVar)) {
3575 if (argCount!=lastArity) {
3576 ERRMSG(line) "Equations give different arities for \"%s\"",
3577 textToStr(textOf(v))
3580 fbindAlts(hd(bs)) = cons(newAlt,fbindAlts(hd(bs)));
3584 lastArity = argCount;
3585 notDefined(line,bs,v);
3586 bs = cons(pair(v,pair(NIL,singleton(newAlt))),bs);
3589 } else if (fst(d)==PATBIND) { /* Pattern bindings */
3590 Cell rhs = snd(snd(d));
3591 Int line = rhsLine(rhs);
3592 Cell pat = fst(snd(d));
3593 while (whatIs(pat)==ESIGN) {/* Move type annotations to rhs */
3594 Cell p = fst(snd(pat));
3595 fst(snd(pat)) = rhs;
3596 snd(snd(d)) = rhs = pat;
3597 fst(snd(d)) = pat = p;
3600 if (isVar(pat)) { /* Convert simple pattern bind to */
3601 notDefined(line,bs,pat);/* a function binding */
3602 bs = cons(pair(pat,pair(NIL,singleton(pair(NIL,rhs)))),bs);
3604 List vs = getPatVars(line,pat,NIL);
3606 ERRMSG(line) "No variables defined in lhs pattern"
3609 map2Proc(notDefined,line,bs,vs);
3610 bs = cons(pair(vs,pair(NIL,snd(d))),bs);
3618 static List local getPatVars(line,p,vs) /* Find list of variables bound in */
3619 Int line; /* pattern p */
3622 switch (whatIs(p)) {
3624 vs = getPatVars(line,arg(p),vs);
3627 return vs; /* Ignore head of application */
3629 case CONFLDS : { List pfs = snd(snd(p));
3630 for (; nonNull(pfs); pfs=tl(pfs)) {
3631 if (isVar(hd(pfs))) {
3632 vs = addPatVar(line,hd(pfs),vs);
3634 vs = getPatVars(line,snd(hd(pfs)),vs);
3640 case FINLIST : { List ps = snd(p);
3641 for (; nonNull(ps); ps=tl(ps)) {
3642 vs = getPatVars(line,hd(ps),vs);
3647 case ESIGN : return getPatVars(line,fst(snd(p)),vs);
3652 case INFIX : return getPatVars(line,snd(p),vs);
3654 case ASPAT : return addPatVar(line,fst(snd(p)),
3655 getPatVars(line,snd(snd(p)),vs));
3658 case VAROPCELL : return addPatVar(line,p,vs);
3668 case WILDCARD : return vs;
3670 default : internal("getPatVars");
3675 static List local addPatVar(line,v,vs) /* Add var to list of previously */
3676 Int line; /* encountered variables */
3679 if (varIsMember(textOf(v),vs)) {
3680 ERRMSG(line) "Repeated use of variable \"%s\" in pattern binding",
3681 textToStr(textOf(v))
3687 static List local eqnsToBindings(es,ts,cs,ps)
3688 List es; /* Convert list of equations to */
3689 List ts; /* list of typed bindings */
3692 List bs = extractBindings(es);
3693 map1Proc(addSigdecl,bs,extractSigdecls(es));
3694 map4Proc(addFixdecl,bs,ts,cs,ps,extractFixdecls(es));
3698 static Void local notDefined(line,bs,v)/* check if name already defined in */
3699 Int line; /* list of bindings */
3702 if (nonNull(findBinding(textOf(v),bs))) {
3703 ERRMSG(line) "\"%s\" multiply defined", textToStr(textOf(v))
3708 static Cell local findBinding(t,bs) /* look for binding for variable t */
3709 Text t; /* in list of bindings bs */
3711 for (; nonNull(bs); bs=tl(bs)) {
3712 if (isVar(fst(hd(bs)))) { /* function-binding? */
3713 if (textOf(fst(hd(bs)))==t) {
3716 } else if (nonNull(varIsMember(t,fst(hd(bs))))){/* pattern-binding?*/
3723 static Cell local getAttr(bs,v) /* Locate type/fixity attribute */
3724 List bs; /* for variable v in bindings bs */
3727 Cell b = findBinding(t,bs);
3729 if (isNull(b)) { /* No binding */
3731 } else if (isVar(fst(b))) { /* func binding? */
3732 if (isNull(bindingAttr(b))) {
3733 bindingAttr(b) = pair(NIL,NIL);
3735 return bindingAttr(b);
3736 } else { /* pat binding? */
3738 List as = bindingAttr(b);
3741 bindingAttr(b) = as = replicate(length(vs),NIL);
3744 while (nonNull(vs) && t!=textOf(hd(vs))) {
3750 internal("getAttr");
3751 } else if (isNull(hd(as))) {
3752 hd(as) = pair(NIL,NIL);
3758 static Void local addSigdecl(bs,sigdecl)/* add type information to bindings*/
3759 List bs; /* :: [Binding] */
3760 Cell sigdecl; { /* :: (Line,[Var],Type) */
3761 Int l = intOf(fst3(sigdecl));
3762 List vs = snd3(sigdecl);
3763 Type type = checkSigType(l,"type declaration",hd(vs),thd3(sigdecl));
3765 for (; nonNull(vs); vs=tl(vs)) {
3767 Pair attr = getAttr(bs,v);
3769 ERRMSG(l) "Missing binding for variable \"%s\" in type signature",
3770 textToStr(textOf(v))
3772 } else if (nonNull(fst(attr))) {
3773 ERRMSG(l) "Repeated type signature for \"%s\"",
3774 textToStr(textOf(v))
3781 static Void local addFixdecl(bs,ts,cs,ps,fixdecl)
3787 Int line = intOf(fst3(fixdecl));
3788 List ops = snd3(fixdecl);
3789 Cell sy = thd3(fixdecl);
3791 for (; nonNull(ops); ops=tl(ops)) {
3793 Text t = textOf(op);
3794 Cell attr = getAttr(bs,op);
3795 if (nonNull(attr)) { /* Found name in binding? */
3796 if (nonNull(snd(attr))) {
3800 } else { /* Look in tycons, classes, prims */
3805 for (; isNull(n) && nonNull(ts1); ts1=tl(ts1)) { /* tycons */
3807 if (tycon(tc).what==DATATYPE || tycon(tc).what==NEWTYPE) {
3808 n = nameIsMember(t,tycon(tc).defn);
3811 for (; isNull(n) && nonNull(cs1); cs1=tl(cs1)) { /* classes */
3812 n = nameIsMember(t,cclass(hd(cs1)).members);
3814 for (; isNull(n) && nonNull(ps1); ps1=tl(ps1)) { /* prims */
3815 n = nameIsMember(t,hd(ps1));
3820 } else if (name(n).syntax!=NO_SYNTAX) {
3823 name(n).syntax = intOf(sy);
3828 static Void local dupFixity(line,t) /* Report repeated fixity decl */
3832 "Repeated fixity declaration for operator \"%s\"", textToStr(t)
3836 static Void local missFixity(line,t) /* Report missing op for fixity */
3840 "Cannot find binding for operator \"%s\" in fixity declaration",
3845 /* --------------------------------------------------------------------------
3846 * Dealing with infix operators:
3848 * Expressions involving infix operators or unary minus are parsed as
3849 * elements of the following type:
3851 * data InfixExp = Only Exp | Neg InfixExp | Infix InfixExp Op Exp
3853 * (The algorithms here do not assume that negation can be applied only once,
3854 * i.e., that - - x is a syntax error, as required by the Haskell report.
3855 * Instead, that restriction is captured by the grammar itself, given above.)
3857 * There are rules of precedence and grouping, expressed by two functions:
3859 * prec :: Op -> Int; assoc :: Op -> Assoc (Assoc = {L, N, R})
3861 * InfixExp values are rearranged accordingly when a complete expression
3862 * has been read using a simple shift-reduce parser whose result may be taken
3863 * to be a value of the following type:
3865 * data Exp = Atom Int | Negate Exp | Apply Op Exp Exp | Error String
3867 * The machine on which this parser is based can be defined as follows:
3869 * tidy :: InfixExp -> [(Op,Exp)] -> Exp
3870 * tidy (Only a) [] = a
3871 * tidy (Only a) ((o,b):ss) = tidy (Only (Apply o a b)) ss
3872 * tidy (Infix a o b) [] = tidy a [(o,b)]
3873 * tidy (Infix a o b) ((p,c):ss)
3874 * | shift o p = tidy a ((o,b):(p,c):ss)
3875 * | red o p = tidy (Infix a o (Apply p b c)) ss
3876 * | ambig o p = Error "ambiguous use of operators"
3877 * tidy (Neg e) [] = tidy (tidyNeg e) []
3878 * tidy (Neg e) ((o,b):ss)
3879 * | nshift o = tidy (Neg (underNeg o b e)) ss
3880 * | nred o = tidy (tidyNeg e) ((o,b):ss)
3881 * | nambig o = Error "illegal use of negation"
3883 * At each stage, the parser can either shift, reduce, accept, or error.
3884 * The transitions when dealing with juxtaposed operators o and p are
3885 * determined by the following rules:
3887 * shift o p = (prec o > prec p)
3888 * || (prec o == prec p && assoc o == L && assoc p == L)
3890 * red o p = (prec o < prec p)
3891 * || (prec o == prec p && assoc o == R && assoc p == R)
3893 * ambig o p = (prec o == prec p)
3894 * && (assoc o == N || assoc p == N || assoc o /= assoc p)
3896 * The transitions when dealing with juxtaposed unary minus and infix
3897 * operators are as follows. The precedence of unary minus (infixl 6) is
3898 * hardwired in to these definitions, as it is to the definitions of the
3899 * Haskell grammar in the official report.
3901 * nshift o = (prec o > 6)
3902 * nred o = (prec o < 6) || (prec o == 6 && assoc o == L)
3903 * nambig o = prec o == 6 && (assoc o == R || assoc o == N)
3905 * An InfixExp of the form (Neg e) means negate the last thing in
3906 * the InfixExp e; we can force this negation using:
3908 * tidyNeg :: OpExp -> OpExp
3909 * tidyNeg (Only e) = Only (Negate e)
3910 * tidyNeg (Infix a o b) = Infix a o (Negate b)
3911 * tidyNeg (Neg e) = tidyNeg (tidyNeg e)
3913 * On the other hand, if we want to sneak application of an infix operator
3914 * under a negation, then we use:
3916 * underNeg :: Op -> Exp -> OpExp -> OpExp
3917 * underNeg o b (Only e) = Only (Apply o e b)
3918 * underNeg o b (Neg e) = Neg (underNeg o b e)
3919 * underNeg o b (Infix e p f) = Infix e p (Apply o f b)
3921 * As a concession to efficiency, we lower the number of calls to syntaxOf
3922 * by keeping track of the values of sye, sys throughout the process. The
3923 * value APPLIC is used to indicate that the syntax value is unknown.
3924 * ------------------------------------------------------------------------*/
3926 static Cell local tidyInfix(line,e) /* Convert infixExp to Exp */
3928 Cell e; { /* :: OpExp */
3929 Cell s = NIL; /* :: [(Op,Exp)] */
3930 Syntax sye = APPLIC; /* Syntax of op in e (init unknown)*/
3931 Syntax sys = APPLIC; /* Syntax of op in s (init unknown)*/
3934 while (fst(d)!=ONLY) { /* Attach fixities to operators */
3938 fun(fun(d)) = attachFixity(line,fun(fun(d)));
3944 switch (whatIs(e)) {
3945 case ONLY : e = snd(e);
3946 while (nonNull(s)) {
3947 Cell next = arg(fun(s));
3949 fun(fun(s)) = snd(fun(fun(s)));
3955 case NEG : if (nonNull(s)) {
3956 if (sys==APPLIC) { /* calculate sys */
3957 sys = intOf(fst(fun(fun(s))));
3960 if (precOf(sys)==UMINUS_PREC && /* nambig */
3961 assocOf(sys)!=UMINUS_ASSOC) {
3963 "Ambiguous use of unary minus with \""
3964 ETHEN ERREXPR(snd(fun(fun(s))));
3969 if (precOf(sys)>UMINUS_PREC) { /* nshift */
3973 while (whatIs(e1)==NEG)
3975 arg(fun(t)) = arg(e1);
3976 fun(fun(t)) = snd(fun(fun(t)));
3983 /* Intentional fall-thru for nreduce and isNull(s) */
3985 { Cell prev = e; /* e := tidyNeg e */
3986 Cell temp = arg(prev);
3988 for (; whatIs(temp)==NEG; nneg++) {
3989 fun(prev) = nameNegate;
3993 if (isInt(arg(temp))) { /* special cases */
3994 if (nneg&1) /* for literals */
3995 arg(temp) = mkInt(-intOf(arg(temp)));
3997 else if (isFloat(arg(temp))) {
3999 arg(temp) = floatNegate(arg(temp));
4000 //mkFloat(-floatOf(arg(temp)));
4003 fun(prev) = nameNegate;
4004 arg(prev) = arg(temp);
4011 default : if (isNull(s)) {/* Move operation onto empty stack */
4012 Cell next = arg(fun(e));
4019 else { /* deal with pair of operators */
4021 if (sye==APPLIC) { /* calculate sys and sye */
4022 sye = intOf(fst(fun(fun(e))));
4025 sys = intOf(fst(fun(fun(s))));
4028 if (precOf(sye)==precOf(sys) && /* ambig */
4029 (assocOf(sye)!=assocOf(sys) ||
4030 assocOf(sye)==NON_ASS)) {
4031 ERRMSG(line) "Ambiguous use of operator \""
4032 ETHEN ERREXPR(snd(fun(fun(e))));
4033 ERRTEXT "\" with \""
4034 ETHEN ERREXPR(snd(fun(fun(s))));
4039 if (precOf(sye)>precOf(sys) || /* shift */
4040 (precOf(sye)==precOf(sys) &&
4041 assocOf(sye)==LEFT_ASS &&
4042 assocOf(sys)==LEFT_ASS)) {
4043 Cell next = arg(fun(e));
4051 Cell next = arg(fun(s));
4052 arg(fun(s)) = arg(e);
4053 fun(fun(s)) = snd(fun(fun(s)));
4064 static Pair local attachFixity(line,op) /* Attach fixity to operator in an */
4065 Int line; /* infix expression */
4067 Syntax sy = DEF_OPSYNTAX;
4069 switch (whatIs(op)) {
4071 case VARIDCELL : if ((sy=lookupSyntax(textOf(op)))==NO_SYNTAX) {
4072 Name n = findName(textOf(op));
4074 ERRMSG(line) "Undefined variable \"%s\"",
4075 textToStr(textOf(op))
4084 case CONIDCELL : sy = syntaxOf(op = conDefined(line,op));
4087 case QUALIDENT : { Name n = findQualName(op);
4093 "Undefined qualified variable \"%s\"",
4103 return pair(mkInt(sy),op); /* Pair fixity with (possibly) */
4104 /* translated operator */
4107 static Syntax local lookupSyntax(t) /* Try to find fixity for var in */
4108 Text t; { /* enclosing bindings */
4109 List bounds1 = bounds;
4110 List bindings1 = bindings;
4112 while (nonNull(bindings1)) {
4113 if (nonNull(varIsMember(t,hd(bounds1)))) {
4114 return DEF_OPSYNTAX;
4116 Cell b = findBinding(t,hd(bindings1));
4118 Cell a = fst(snd(b));
4119 if (isVar(fst(b))) { /* Function binding */
4120 if (nonNull(a) && nonNull(snd(a))) {
4121 return intOf(snd(a));
4123 } else { /* Pattern binding */
4125 while (nonNull(vs) && nonNull(a)) {
4126 if (t==textOf(hd(vs))) {
4127 if (nonNull(hd(a)) && isInt(snd(hd(a)))) {
4128 return intOf(snd(hd(a)));
4136 return DEF_OPSYNTAX;
4139 bounds1 = tl(bounds1);
4140 bindings1 = tl(bindings1);
4145 /* --------------------------------------------------------------------------
4146 * To facilitate dependency analysis, lists of bindings are temporarily
4147 * augmented with an additional field, which is used in two ways:
4148 * - to build the `adjacency lists' for the dependency graph. Represented by
4149 * a list of pointers to other bindings in the same list of bindings.
4150 * - to hold strictly positive integer values (depth first search numbers) of
4151 * elements `on the stack' during the strongly connected components search
4152 * algorithm, or a special value mkInt(0), once the binding has been added
4153 * to a particular strongly connected component.
4155 * Using this extra field, the type of each list of declarations during
4156 * dependency analysis is [Binding'] where:
4158 * Binding' ::= (Var, (Attr, (Dep, [Alt]))) -- function binding
4159 * | ([Var], ([Attr], (Dep, (Pat,Rhs)))) -- pattern binding
4161 * ------------------------------------------------------------------------*/
4163 #define depVal(d) (fst(snd(snd(d)))) /* Access to dependency information*/
4165 static List local dependencyAnal(bs) /* Separate lists of bindings into */
4166 List bs; { /* mutually recursive groups in */
4167 /* order of dependency */
4168 mapProc(addDepField,bs); /* add extra field for dependents */
4169 mapProc(depBinding,bs); /* find dependents of each binding */
4170 bs = bscc(bs); /* sort to strongly connected comps*/
4171 mapProc(remDepField,bs); /* remove dependency info field */
4175 static List local topDependAnal(bs) /* Like dependencyAnal(), but at */
4176 List bs; { /* top level, reporting on progress*/
4180 setGoal("Dependency analysis",(Target)(length(bs)));
4182 mapProc(addDepField,bs); /* add extra field for dependents */
4183 for (xs=bs; nonNull(xs); xs=tl(xs)) {
4184 emptySubstitution();
4186 soFar((Target)(i++));
4188 bs = bscc(bs); /* sort to strongly connected comps */
4189 mapProc(remDepField,bs); /* remove dependency info field */
4194 static Void local addDepField(b) /* add extra field to binding to */
4195 Cell b; { /* hold list of dependents */
4196 snd(snd(b)) = pair(NIL,snd(snd(b)));
4199 static Void local remDepField(bs) /* remove dependency field from */
4200 List bs; { /* list of bindings */
4201 mapProc(remDepField1,bs);
4204 static Void local remDepField1(b) /* remove dependency field from */
4205 Cell b; { /* single binding */
4206 snd(snd(b)) = snd(snd(snd(b)));
4209 static Void local clearScope() { /* initialise dependency scoping */
4215 static Void local withinScope(bs) /* Enter scope of bindings bs */
4217 bounds = cons(NIL,bounds);
4218 bindings = cons(bs,bindings);
4219 depends = cons(NIL,depends);
4222 static Void local leaveScope() { /* Leave scope of last withinScope */
4223 List bs = hd(bindings); /* Remove fixity info from binds */
4224 Bool toplevel = isNull(tl(bindings));
4225 for (; nonNull(bs); bs=tl(bs)) {
4227 if (isVar(fst(b))) { /* Variable binding */
4228 Cell a = fst(snd(b));
4231 saveSyntax(fst(b),snd(a));
4233 fst(snd(b)) = fst(a);
4235 } else { /* Pattern binding */
4237 List as = fst(snd(b));
4238 while (nonNull(vs) && nonNull(as)) {
4239 if (isPair(hd(as))) {
4241 saveSyntax(hd(vs),snd(hd(as)));
4243 hd(as) = fst(hd(as));
4250 bounds = tl(bounds);
4251 bindings = tl(bindings);
4252 depends = tl(depends);
4255 static Void local saveSyntax(v,sy) /* Save syntax of top-level var */
4256 Cell v; /* in corresponding Name */
4258 Name n = findName(textOf(v));
4259 if (isNull(n) || name(n).syntax!=NO_SYNTAX) {
4260 internal("saveSyntax");
4263 name(n).syntax = intOf(sy);
4267 /* --------------------------------------------------------------------------
4268 * As a side effect of the dependency analysis we also make the following
4270 * - Each lhs is a valid pattern/function lhs, all constructor functions
4271 * have been defined and are used with the correct number of arguments.
4272 * - No lhs contains repeated pattern variables.
4273 * - Expressions used on the rhs of an eqn should be well formed. This
4275 * - Checking for valid patterns (including repeated vars) in lambda,
4276 * case, and list comprehension expressions.
4277 * - Recursively checking local lists of equations.
4278 * - No free (i.e. unbound) variables are used in the declaration list.
4279 * ------------------------------------------------------------------------*/
4281 static Void local depBinding(b) /* find dependents of binding */
4283 Cell defpart = snd(snd(snd(b))); /* definition part of binding */
4287 if (isVar(fst(b))) { /* function-binding? */
4288 mapProc(depAlt,defpart);
4289 if (isNull(fst(snd(b)))) { /* Save dep info if no type sig */
4290 fst(snd(b)) = pair(ap(IMPDEPS,hd(depends)),NIL);
4291 } else if (isNull(fst(fst(snd(b))))) {
4292 fst(fst(snd(b))) = ap(IMPDEPS,hd(depends));
4294 } else { /* pattern-binding? */
4295 Int line = rhsLine(snd(defpart));
4298 fst(defpart) = checkPat(line,fst(defpart));
4299 depRhs(snd(defpart));
4301 if (nonNull(hd(btyvars))) {
4303 "Sorry, no type variables are allowed in pattern binding type annotations"
4307 fst(defpart) = applyBtyvs(fst(defpart));
4309 depVal(b) = hd(depends);
4312 static Void local depDefaults(c) /* dependency analysis on defaults */
4313 Class c; { /* from class definition */
4314 depClassBindings(cclass(c).defaults);
4317 static Void local depInsts(in) /* dependency analysis on instance */
4318 Inst in; { /* bindings */
4319 depClassBindings(inst(in).implements);
4322 static Void local depClassBindings(bs) /* dependency analysis on list of */
4323 List bs; { /* bindings, possibly containing */
4324 for (; nonNull(bs); bs=tl(bs)) { /* NIL bindings ... */
4325 if (nonNull(hd(bs))) { /* No need to add extra field for */
4326 mapProc(depAlt,snd(hd(bs)));/* dependency information... */
4331 static Void local depAlt(a) /* Find dependents of alternative */
4333 List obvs = saveBvars(); /* Save list of bound variables */
4335 bindPats(rhsLine(snd(a)),fst(a)); /* add new bound vars for patterns */
4336 depRhs(snd(a)); /* find dependents of rhs */
4337 fst(a) = applyBtyvs(fst(a));
4338 restoreBvars(obvs); /* restore original list of bvars */
4341 static Void local depRhs(r) /* Find dependents of rhs */
4343 switch (whatIs(r)) {
4344 case GUARDED : mapProc(depGuard,snd(r));
4347 case LETREC : fst(snd(r)) = eqnsToBindings(fst(snd(r)),NIL,NIL,NIL);
4348 withinScope(fst(snd(r)));
4349 fst(snd(r)) = dependencyAnal(fst(snd(r)));
4350 hd(depends) = fst(snd(r));
4351 depRhs(snd(snd(r)));
4355 case RSIGN : snd(snd(r)) = checkPatType(rhsLine(fst(snd(r))),
4357 rhsExpr(fst(snd(r))),
4359 depRhs(fst(snd(r)));
4362 default : snd(r) = depExpr(intOf(fst(r)),snd(r));
4367 static Void local depGuard(g) /* find dependents of single guarded*/
4368 Cell g; { /* expression */
4369 depPair(intOf(fst(g)),snd(g));
4372 static Cell local depExpr(line,e) /* find dependents of expression */
4375 // Printf( "\n\n"); print(e,100); Printf("\n");
4376 //printExp(stdout,e);
4377 switch (whatIs(e)) {
4380 case VAROPCELL : return depVar(line,e);
4383 case CONOPCELL : return conDefined(line,e);
4385 case QUALIDENT : if (isQVar(e)) {
4386 return depQVar(line,e);
4387 } else { /* QConOrConOp */
4388 return conDefined(line,e);
4391 case INFIX : return depExpr(line,tidyInfix(line,snd(e)));
4394 case RECSEL : break;
4396 case AP : if (isAp(e) && isAp(fun(e)) && isExt(fun(fun(e)))) {
4397 return depRecord(line,e);
4403 arg(a) = depExpr(line,arg(a));
4406 fun(a) = depExpr(line,fun(a));
4410 case AP : depPair(line,e);
4424 case INTCELL : break;
4426 case COND : depTriple(line,snd(e));
4429 case FINLIST : map1Over(depExpr,line,snd(e));
4432 case LETREC : fst(snd(e)) = eqnsToBindings(fst(snd(e)),NIL,NIL,NIL);
4433 withinScope(fst(snd(e)));
4434 fst(snd(e)) = dependencyAnal(fst(snd(e)));
4435 hd(depends) = fst(snd(e));
4436 snd(snd(e)) = depExpr(line,snd(snd(e)));
4440 case LAMBDA : depAlt(snd(e));
4443 case DOCOMP : /* fall-thru */
4444 case COMP : depComp(line,snd(e),snd(snd(e)));
4447 case ESIGN : fst(snd(e)) = depExpr(line,fst(snd(e)));
4448 snd(snd(e)) = checkSigType(line,
4454 case CASE : fst(snd(e)) = depExpr(line,fst(snd(e)));
4455 map1Proc(depCaseAlt,line,snd(snd(e)));
4458 case CONFLDS : depConFlds(line,e,FALSE);
4461 case UPDFLDS : depUpdFlds(line,e);
4465 case WITHEXP : depWith(line,e);
4469 case ASPAT : ERRMSG(line) "Illegal `@' in expression"
4472 case LAZYPAT : ERRMSG(line) "Illegal `~' in expression"
4475 case WILDCARD : ERRMSG(line) "Illegal `_' in expression"
4479 case EXT : ERRMSG(line) "Illegal application of record"
4483 default : internal("depExpr");
4488 static Void local depPair(line,e) /* find dependents of pair of exprs*/
4491 fst(e) = depExpr(line,fst(e));
4492 snd(e) = depExpr(line,snd(e));
4495 static Void local depTriple(line,e) /* find dependents of triple exprs */
4498 fst3(e) = depExpr(line,fst3(e));
4499 snd3(e) = depExpr(line,snd3(e));
4500 thd3(e) = depExpr(line,thd3(e));
4503 static Void local depComp(l,e,qs) /* find dependents of comprehension*/
4508 fst(e) = depExpr(l,fst(e));
4512 switch (whatIs(q)) {
4513 case FROMQUAL : { List obvs = saveBvars();
4514 snd(snd(q)) = depExpr(l,snd(snd(q)));
4516 fst(snd(q)) = bindPat(l,fst(snd(q)));
4518 fst(snd(q)) = applyBtyvs(fst(snd(q)));
4523 case QWHERE : snd(q) = eqnsToBindings(snd(q),NIL,NIL,NIL);
4524 withinScope(snd(q));
4525 snd(q) = dependencyAnal(snd(q));
4526 hd(depends) = snd(q);
4531 case DOQUAL : /* fall-thru */
4532 case BOOLQUAL : snd(q) = depExpr(l,snd(q));
4539 static Void local depCaseAlt(line,a) /* Find dependents of case altern. */
4542 List obvs = saveBvars(); /* Save list of bound variables */
4544 fst(a) = bindPat(line,fst(a)); /* Add new bound vars for pats */
4545 depRhs(snd(a)); /* Find dependents of rhs */
4546 fst(a) = applyBtyvs(fst(a));
4547 restoreBvars(obvs); /* Restore original list of bvars */
4550 static Cell local depVar(line,e) /* Register occurrence of variable */
4553 List bounds1 = bounds;
4554 List bindings1 = bindings;
4555 List depends1 = depends;
4559 while (nonNull(bindings1)) {
4560 n = varIsMember(t,hd(bounds1)); /* look for t in bound variables */
4564 n = findBinding(t,hd(bindings1)); /* look for t in var bindings */
4566 if (!cellIsMember(n,hd(depends1))) {
4567 hd(depends1) = cons(n,hd(depends1));
4569 return (isVar(fst(n)) ? fst(n) : e);
4572 bounds1 = tl(bounds1);
4573 bindings1 = tl(bindings1);
4574 depends1 = tl(depends1);
4577 if (isNull(n=findName(t))) { /* check global definitions */
4578 ERRMSG(line) "Undefined variable \"%s\"", textToStr(t)
4582 if (!moduleThisScript(name(n).mod)) {
4585 /* Later phases of the system cannot cope if we resolve references
4586 * to unprocessed objects too early. This is the main reason that
4587 * we cannot cope with recursive modules at the moment.
4592 static Cell local depQVar(line,e)/* register occurrence of qualified variable */
4595 Name n = findQualName(e);
4596 if (isNull(n)) { /* check global definitions */
4597 ERRMSG(line) "Undefined qualified variable \"%s\"", identToStr(e)
4600 if (name(n).mod != currentModule) {
4603 if (fst(e) == VARIDCELL) {
4604 e = mkVar(qtextOf(e));
4606 e = mkVarop(qtextOf(e));
4608 return depVar(line,e);
4611 static Void local depConFlds(line,e,isP)/* check construction using fields */
4615 Name c = conDefined(line,fst(snd(e)));
4616 if (isNull(snd(snd(e))) ||
4617 nonNull(cellIsMember(c,depFields(line,e,snd(snd(e)),isP)))) {
4620 ERRMSG(line) "Constructor \"%s\" does not have selected fields in ",
4621 textToStr(name(c).text)
4626 if (!isP && isPair(name(c).defn)) { /* Check that banged fields defined*/
4627 List scs = fst(name(c).defn); /* List of strict components */
4628 Type t = name(c).type;
4629 Int a = userArity(c);
4630 List fs = snd(snd(e));
4632 if (isPolyType(t)) { /* Find tycon that c belongs to */
4635 if (isQualType(t)) {
4638 if (whatIs(t)==CDICTS) {
4647 for (ss=tycon(t).defn; hasCfun(ss); ss=tl(ss)) {
4649 /* Now we know the tycon t that c belongs to, and the corresponding
4650 * list of selectors for that type, ss. Now we have to check that
4651 * each of the fields identified by scs appears in fs, using ss to
4652 * cross reference, and convert integers to selector names.
4654 for (; nonNull(scs); scs=tl(scs)) {
4655 Int i = intOf(hd(scs));
4657 for (; nonNull(ss1); ss1=tl(ss1)) {
4658 List cns = name(hd(ss1)).defn;
4659 for (; nonNull(cns); cns=tl(cns)) {
4660 if (fst(hd(cns))==c) {
4664 if (nonNull(cns) && intOf(snd(hd(cns)))==i) {
4669 internal("depConFlds");
4673 for (; nonNull(fs1) && s!=fst(hd(fs1)); fs1=tl(fs1)) {
4676 ERRMSG(line) "Construction does not define strict field"
4678 ERRTEXT "\nExpression : " ETHEN ERREXPR(e);
4679 ERRTEXT "\nField : " ETHEN ERREXPR(s);
4688 static Void local depUpdFlds(line,e) /* check update using fields */
4691 if (isNull(thd3(snd(e)))) {
4692 ERRMSG(line) "Empty field list in update"
4695 fst3(snd(e)) = depExpr(line,fst3(snd(e)));
4696 snd3(snd(e)) = depFields(line,e,thd3(snd(e)),FALSE);
4699 static List local depFields(l,e,fs,isP) /* check field binding list */
4707 for (; nonNull(fs); fs=tl(fs)) { /* for each field binding */
4711 if (isVar(fb)) { /* expand var to var = var */
4712 h98DoesntSupport(l,"missing field bindings");
4713 fb = hd(fs) = pair(fb,fb);
4716 s = findQualName(fst(fb)); /* check for selector */
4717 if (nonNull(s) && isSfun(s)) {
4720 ERRMSG(l) "\"%s\" is not a selector function/field name",
4721 textToStr(textOf(fst(fb)))
4725 if (isNull(ss)) { /* for first named selector */
4726 List scs = name(s).defn; /* calculate list of constructors */
4727 for (; nonNull(scs); scs=tl(scs)) {
4728 cs = cons(fst(hd(scs)),cs);
4730 ss = singleton(s); /* initialize selector list */
4731 } else { /* for subsequent selectors */
4732 List ds = cs; /* intersect constructor lists */
4733 for (cs=NIL; nonNull(ds); ) {
4734 List scs = name(s).defn;
4735 while (nonNull(scs) && fst(hd(scs))!=hd(ds)) {
4748 if (cellIsMember(s,ss)) { /* check for repeated uses */
4749 ERRMSG(l) "Repeated field name \"%s\" in field list",
4750 textToStr(name(s).text)
4756 if (isNull(cs)) { /* Are there any matching constrs? */
4757 ERRMSG(l) "No constructor has all of the fields specified in "
4763 snd(fb) = (isP ? checkPat(l,snd(fb)) : depExpr(l,snd(fb)));
4769 static Void local depWith(line,e) /* check with using fields */
4772 fst(snd(e)) = depExpr(line,fst(snd(e)));
4773 snd(snd(e)) = depDwFlds(line,e,snd(snd(e)));
4776 static List local depDwFlds(l,e,fs)/* check field binding list */
4782 for (; nonNull(c); c=tl(c)) { /* for each field binding */
4783 snd(hd(c)) = depExpr(l,snd(hd(c)));
4790 static Cell local depRecord(line,e) /* find dependents of record and */
4791 Int line; /* sort fields into approp. order */
4792 Cell e; { /* to make construction and update */
4793 List exts = NIL; /* more efficient. */
4796 h98DoesntSupport(line,"extensible records");
4797 do { /* build up list of extensions */
4798 Text t = extText(fun(fun(r)));
4799 String s = textToStr(t);
4802 while (nonNull(nx) && strcmp(textToStr(extText(fun(fun(nx)))),s)>0) {
4806 if (nonNull(nx) && t==extText(fun(fun(nx)))) {
4807 ERRMSG(line) "Repeated label \"%s\" in record ", s
4813 exts = cons(fun(r),exts);
4815 tl(prev) = cons(fun(r),nx);
4817 extField(r) = depExpr(line,extField(r));
4819 } while (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r))));
4820 r = depExpr(line,r);
4821 return revOnto(exts,r);
4826 /* --------------------------------------------------------------------------
4827 * Several parts of this program require an algorithm for sorting a list
4828 * of values (with some added dependency information) into a list of strongly
4829 * connected components in which each value appears before its dependents.
4831 * Each of these algorithms is obtained by parameterising a standard
4832 * algorithm in "scc.c" as shown below.
4833 * ------------------------------------------------------------------------*/
4835 #define SCC2 tcscc /* make scc algorithm for Tycons */
4836 #define LOWLINK tclowlink
4837 #define DEPENDS(c) (isTycon(c) ? tycon(c).kind : cclass(c).kinds)
4838 #define SETDEPENDS(c,v) if(isTycon(c)) tycon(c).kind=v; else cclass(c).kinds=v
4845 #define SCC bscc /* make scc algorithm for Bindings */
4846 #define LOWLINK blowlink
4847 #define DEPENDS(t) depVal(t)
4848 #define SETDEPENDS(c,v) depVal(c)=v
4855 /* --------------------------------------------------------------------------
4856 * Main static analysis:
4857 * ------------------------------------------------------------------------*/
4859 Void checkExp() { /* Top level static check on Expr */
4860 staticAnalysis(RESET);
4861 clearScope(); /* Analyse expression in the scope */
4862 withinScope(NIL); /* of no local bindings */
4863 inputExpr = depExpr(0,inputExpr);
4865 staticAnalysis(RESET);
4868 Void checkContext() { /* Top level static check on Expr */
4871 staticAnalysis(RESET);
4872 clearScope(); /* Analyse expression in the scope */
4873 withinScope(NIL); /* of no local bindings */
4875 for (vs = NIL; nonNull(qs); qs=tl(qs)) {
4876 vs = typeVarsIn(hd(qs),NIL,NIL,vs);
4878 map2Proc(depPredExp,0,vs,inputContext);
4880 staticAnalysis(RESET);
4883 Void checkDefns() { /* Top level static analysis */
4884 Module thisModule = lastModule();
4885 staticAnalysis(RESET);
4887 setCurrModule(thisModule);
4889 /* Resolve module references */
4890 mapProc(checkQualImport, module(thisModule).qualImports);
4891 mapProc(checkUnqualImport,unqualImports);
4892 /* Add "import Prelude" if there`s no explicit import */
4893 if (thisModule!=modulePrelude
4894 && isNull(cellAssoc(modulePrelude,unqualImports))
4895 && isNull(cellRevAssoc(modulePrelude,module(thisModule).qualImports))) {
4896 unqualImports = cons(pair(modulePrelude,DOTDOT),unqualImports);
4898 /* Every module (including the Prelude) implicitly contains
4899 * "import qualified Prelude"
4901 module(thisModule).qualImports=cons(pair(mkCon(textPrelude),modulePrelude),
4902 module(thisModule).qualImports);
4904 mapProc(checkImportList, unqualImports);
4906 linkPreludeTC(); /* Get prelude tycons and classes */
4907 mapProc(checkTyconDefn,tyconDefns); /* validate tycon definitions */
4908 checkSynonyms(tyconDefns); /* check synonym definitions */
4909 mapProc(checkClassDefn,classDefns); /* process class definitions */
4910 mapProc(kindTCGroup,tcscc(tyconDefns,classDefns)); /* attach kinds */
4911 mapProc(addMembers,classDefns); /* add definitions for member funs */
4912 mapProc(visitClass,classDefns); /* check class hierarchy */
4913 linkPreludeCM(); /* Get prelude cfuns and mfuns */
4915 instDefns = rev(instDefns); /* process instance definitions */
4916 mapProc(checkInstDefn,instDefns);
4918 setCurrModule(thisModule);
4919 mapProc(addRSsigdecls,typeInDefns); /* add sigdecls for RESTRICTSYN */
4920 valDefns = eqnsToBindings(valDefns,tyconDefns,classDefns,/*primDefns*/NIL);
4921 mapProc(allNoPrevDef,valDefns); /* check against previous defns */
4922 mapProc(addDerivImp,derivedInsts); /* Add impls for derived instances */
4923 deriveContexts(derivedInsts); /* Calculate derived inst contexts */
4924 instDefns = appendOnto(instDefns,derivedInsts);
4925 checkDefaultDefns(); /* validate default definitions */
4927 mapProc(allNoPrevDef,valDefns); /* check against previous defns */
4931 mapProc(checkForeignImport,foreignImports); /* check foreign imports */
4932 mapProc(checkForeignExport,foreignExports); /* check foreign exports */
4933 foreignImports = NIL;
4934 foreignExports = NIL;
4936 /* Every top-level name has now been created - so we can build the */
4937 /* export list. Note that this has to happen before dependency */
4938 /* analysis so that references to Prelude.foo will be resolved */
4939 /* when compiling the prelude. */
4940 module(thisModule).exports = checkExports(module(thisModule).exports);
4942 mapProc(checkTypeIn,typeInDefns); /* check restricted synonym defns */
4945 withinScope(valDefns);
4946 valDefns = topDependAnal(valDefns); /* top level dependency ordering */
4947 mapProc(depDefaults,classDefns); /* dep. analysis on class defaults */
4948 mapProc(depInsts,instDefns); /* dep. analysis on inst defns */
4951 /* ToDo: evalDefaults should match current evaluation module */
4952 evalDefaults = defaultDefns; /* Set defaults for evaluator */
4954 staticAnalysis(RESET);
4960 static Void local addRSsigdecls(pr) /* add sigdecls from TYPE ... IN ..*/
4962 List vs = snd(pr); /* get list of variables */
4963 for (; nonNull(vs); vs=tl(vs)) {
4964 if (fst(hd(vs))==SIGDECL) { /* find a sigdecl */
4965 valDefns = cons(hd(vs),valDefns); /* add to valDefns */
4966 hd(vs) = hd(snd3(snd(hd(vs)))); /* and replace with var */
4971 static Void local allNoPrevDef(b) /* ensure no previous bindings for*/
4972 Cell b; { /* variables in new binding */
4973 if (isVar(fst(b))) {
4974 noPrevDef(rhsLine(snd(hd(snd(snd(b))))),fst(b));
4976 Int line = rhsLine(snd(snd(snd(b))));
4977 map1Proc(noPrevDef,line,fst(b));
4981 static Void local noPrevDef(line,v) /* ensure no previous binding for */
4982 Int line; /* new variable */
4984 Name n = findName(textOf(v));
4987 n = newName(textOf(v),NIL);
4988 name(n).defn = PREDEFINED;
4989 } else if (name(n).defn!=PREDEFINED) {
4990 duplicateError(line,name(n).mod,name(n).text,"variable");
4992 name(n).line = line;
4995 static Void local duplicateErrorAux(line,mod,t,kind)/* report duplicate defn */
5000 if (mod == currentModule) {
5001 ERRMSG(line) "Repeated definition for %s \"%s\"", kind,
5005 ERRMSG(line) "Definition of %s \"%s\" clashes with import", kind,
5011 static Void local checkTypeIn(cvs) /* Check that vars in restricted */
5012 Pair cvs; { /* synonym are defined */
5016 for (; nonNull(vs); vs=tl(vs)) {
5017 if (isNull(findName(textOf(hd(vs))))) {
5018 ERRMSG(tycon(c).line)
5019 "No top level binding of \"%s\" for restricted synonym \"%s\"",
5020 textToStr(textOf(hd(vs))), textToStr(tycon(c).text)
5026 /* --------------------------------------------------------------------------
5027 * Haskell 98 compatibility tests:
5028 * ------------------------------------------------------------------------*/
5030 Bool h98Pred(allowArgs,pi) /* Check syntax of Hask98 predicate*/
5033 return isClass(getHead(pi)) && argCount==1 &&
5034 isOffset(getHead(arg(pi))) && (argCount==0 || allowArgs);
5037 Cell h98Context(allowArgs,ps) /* Check syntax of Hask98 context */
5040 for (; nonNull(ps); ps=tl(ps)) {
5041 if (!h98Pred(allowArgs,hd(ps))) {
5048 Void h98CheckCtxt(line,wh,allowArgs,ps,in)
5049 Int line; /* Report illegal context/predicate*/
5055 Cell pi = h98Context(allowArgs,ps);
5057 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh ETHEN
5059 ERRTEXT "\n*** Instance : " ETHEN ERRPRED(inst(in).head);
5061 ERRTEXT "\n*** Constraint : " ETHEN ERRPRED(pi);
5062 if (nonNull(ps) && nonNull(tl(ps))) {
5063 ERRTEXT "\n*** Context : " ETHEN ERRCONTEXT(ps);
5071 Void h98CheckType(line,wh,e,t) /* Check for Haskell 98 type */
5080 if (isQualType(t)) {
5081 Cell pi = h98Context(TRUE,fst(snd(t)));
5083 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh
5085 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
5086 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(ty);
5094 Void h98DoesntSupport(line,wh) /* Report feature missing in H98 */
5098 ERRMSG(line) "Haskell 98 does not support %s", wh
5103 /* --------------------------------------------------------------------------
5104 * Static Analysis control:
5105 * ------------------------------------------------------------------------*/
5107 Void staticAnalysis(what)
5110 case RESET : cfunSfuns = NIL;
5123 case MARK : mark(daSccs);
5138 case INSTALL : staticAnalysis(RESET);
5140 extKind = pair(STAR,pair(ROW,ROW));
5146 /*-------------------------------------------------------------------------*/