2 /* --------------------------------------------------------------------------
3 * Static Analysis for Hugs
5 * Hugs 98 is Copyright (c) Mark P Jones, Alastair Reid and the Yale
6 * Haskell Group 1994-99, and is distributed as Open Source software
7 * under the Artistic License; see the file "Artistic" that is included
8 * in the distribution for details.
10 * $RCSfile: static.c,v $
12 * $Date: 1999/03/09 14:51:10 $
13 * ------------------------------------------------------------------------*/
23 /* --------------------------------------------------------------------------
24 * local function prototypes:
25 * ------------------------------------------------------------------------*/
27 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));
48 static Void local checkTyconDefn Args((Tycon));
49 static Void local depConstrs Args((Tycon,List,Cell));
50 static List local addSels Args((Int,Name,List,List));
51 static List local selectCtxt Args((List,List));
52 static Void local checkSynonyms Args((List));
53 static List local visitSyn Args((List,Tycon,List));
55 static Void local deriveEval Args((List));
56 static List local calcEvalContexts Args((Tycon,List,List));
57 static Void local checkBanged Args((Name,Kinds,List,Type));
59 static Type local instantiateSyn Args((Type,Type));
61 static Void local checkClassDefn Args((Class));
62 static Void local depPredExp Args((Int,List,Cell));
63 static Void local checkMems Args((Class,List,Cell));
64 static Void local addMembers Args((Class));
65 static Name local newMember Args((Int,Int,Cell,Type,Class));
66 static Name local newDSel Args((Class,Int));
67 static Name local newDBuild Args((Class));
68 static Text local generateText Args((String,Class));
69 static Int local visitClass Args((Class));
71 static List local classBindings Args((String,Class,List));
72 static Name local memberName Args((Class,Text));
73 static List local numInsert Args((Int,Cell,List));
75 static List local typeVarsIn Args((Cell,List,List));
76 static List local maybeAppendVar Args((Cell,List));
78 static Type local checkSigType Args((Int,String,Cell,Type));
79 static Type local depTopType Args((Int,List,Type));
80 static Type local depCompType Args((Int,List,Type));
81 static Type local depTypeExp Args((Int,List,Type));
82 static Type local depTypeVar Args((Int,List,Text));
83 static List local checkQuantVars Args((Int,List,List,Cell));
84 static Void local kindConstr Args((Int,Int,Int,Constr));
85 static Kind local kindAtom Args((Int,Constr));
86 static Void local kindPred Args((Int,Int,Int,Cell));
87 static Void local kindType Args((Int,String,Type));
88 static Void local fixKinds Args((Void));
90 static Void local kindTCGroup Args((List));
91 static Void local initTCKind Args((Cell));
92 static Void local kindTC Args((Cell));
93 static Void local genTC Args((Cell));
95 static Void local checkInstDefn Args((Inst));
96 static Void local insertInst Args((Inst));
97 static Bool local instCompare Args((Inst,Inst));
98 static Name local newInstImp Args((Inst));
99 static Void local kindInst Args((Inst,Int));
100 static Void local checkDerive Args((Tycon,List,List,Cell));
101 static Void local addDerInst Args((Int,Class,List,List,Type,Int));
102 static Void local deriveContexts Args((List));
103 static Void local initDerInst Args((Inst));
104 static Void local calcInstPreds Args((Inst));
105 static Void local maybeAddPred Args((Cell,Int,Int,List));
106 static Cell local copyAdj Args((Cell,Int,Int));
107 static Void local tidyDerInst Args((Inst));
109 static Void local addDerivImp Args((Inst));
111 static Void local checkDefaultDefns Args((Void));
113 static Void local checkForeignImport Args((Name));
114 static Void local checkForeignExport Args((Name));
116 static Cell local tidyInfix Args((Int,Cell));
117 static Pair local attachFixity Args((Int,Cell));
118 static Syntax local lookupSyntax Args((Text));
120 static Cell local checkPat Args((Int,Cell));
121 static Cell local checkMaybeCnkPat Args((Int,Cell));
122 static Cell local checkApPat Args((Int,Int,Cell));
123 static Void local addToPatVars Args((Int,Cell));
124 static Name local conDefined Args((Int,Cell));
125 static Void local checkIsCfun Args((Int,Name));
126 static Void local checkCfunArgs Args((Int,Cell,Int));
127 static Cell local checkPatType Args((Int,String,Cell,Type));
128 static Cell local applyBtyvs Args((Cell));
129 static Cell local bindPat Args((Int,Cell));
130 static Void local bindPats Args((Int,List));
132 static List local extractSigdecls Args((List));
133 static List local extractFixdecls Args((List));
134 static List local extractBindings Args((List));
135 static List local getPatVars Args((Int,Cell,List));
136 static List local addPatVar Args((Int,Cell,List));
137 static List local eqnsToBindings Args((List,List,List,List));
138 static Void local notDefined Args((Int,List,Cell));
139 static Cell local findBinding Args((Text,List));
140 static Cell local getAttr Args((List,Cell));
141 static Void local addSigdecl Args((List,Cell));
142 static Void local addFixdecl Args((List,List,List,List,Triple));
143 static Void local dupFixity Args((Int,Text));
144 static Void local missFixity Args((Int,Text));
146 static List local dependencyAnal Args((List));
147 static List local topDependAnal Args((List));
148 static Void local addDepField Args((Cell));
149 static Void local remDepField Args((List));
150 static Void local remDepField1 Args((Cell));
151 static Void local clearScope Args((Void));
152 static Void local withinScope Args((List));
153 static Void local leaveScope Args((Void));
154 static Void local saveSyntax Args((Cell,Cell));
156 static Void local depBinding Args((Cell));
157 static Void local depDefaults Args((Class));
158 static Void local depInsts Args((Inst));
159 static Void local depClassBindings Args((List));
160 static Void local depAlt Args((Cell));
161 static Void local depRhs Args((Cell));
162 static Void local depGuard Args((Cell));
163 static Cell local depExpr Args((Int,Cell));
164 static Void local depPair Args((Int,Cell));
165 static Void local depTriple Args((Int,Cell));
166 static Void local depComp Args((Int,Cell,List));
167 static Void local depCaseAlt Args((Int,Cell));
168 static Cell local depVar Args((Int,Cell));
169 static Cell local depQVar Args((Int,Cell));
170 static Void local depConFlds Args((Int,Cell,Bool));
171 static Void local depUpdFlds Args((Int,Cell));
172 static List local depFields Args((Int,Cell,List,Bool));
174 static Cell local depRecord Args((Int,Cell));
177 static List local tcscc Args((List,List));
178 static List local bscc Args((List));
180 static Void local addRSsigdecls Args((Pair));
181 static Void local allNoPrevDef Args((Cell));
182 static Void local noPrevDef Args((Int,Cell));
184 static Void local duplicateErrorAux Args((Int,Text,String));
185 #define duplicateError(l,m,t,k) duplicateErrorAux(l,t,k)
187 static Void local duplicateErrorAux Args((Int,Module,Text,String));
188 #define duplicateError(l,m,t,k) duplicateErrorAux(l,m,t,k)
190 static Void local checkTypeIn Args((Pair));
192 /* --------------------------------------------------------------------------
193 * The code in this file is arranged in roughly the following order:
194 * - Kind inference preliminaries
195 * - Module declarations
196 * - Type declarations (data, type, newtype, type in)
197 * - Class declarations
199 * - Instance declarations
200 * - Default declarations
201 * - Primitive definitions
203 * - Infix expressions
204 * - Value definitions
205 * - Top-level static analysis and control
206 * - Haskell 98 compatibility tests
207 * ------------------------------------------------------------------------*/
209 /* --------------------------------------------------------------------------
210 * Kind checking preliminaries:
211 * ------------------------------------------------------------------------*/
213 Bool kindExpert = FALSE; /* TRUE => display kind errors in */
216 static Void local kindError(l,c,in,wh,k,o)
217 Int l; /* line number near constuctor exp */
218 Constr c; /* constructor */
219 Constr in; /* context (if any) */
220 String wh; /* place in which error occurs */
221 Kind k; /* expected kind (k,o) */
222 Int o; { /* inferred kind (typeIs,typeOff) */
225 if (!kindExpert) { /* for those with a fear of kinds */
226 ERRMSG(l) "Illegal type" ETHEN
228 ERRTEXT " \"" ETHEN ERRTYPE(in);
231 ERRTEXT " in %s\n", wh
235 ERRMSG(l) "Kind error in %s", wh ETHEN
237 ERRTEXT "\n*** expression : " ETHEN ERRTYPE(in);
239 ERRTEXT "\n*** constructor : " ETHEN ERRTYPE(c);
240 ERRTEXT "\n*** kind : " ETHEN ERRKIND(copyType(typeIs,typeOff));
241 ERRTEXT "\n*** does not match : " ETHEN ERRKIND(copyType(k,o));
243 ERRTEXT "\n*** because : %s", unifyFails ETHEN
249 #define shouldKind(l,c,in,wh,k,o) if (!kunify(typeIs,typeOff,k,o)) \
250 kindError(l,c,in,wh,k,o)
251 #define checkKind(l,a,m,c,in,wh,k,o) kindConstr(l,a,m,c); \
252 shouldKind(l,c,in,wh,k,o)
253 #define inferKind(k,o) typeIs=k; typeOff=o
255 static List unkindTypes; /* types in need of kind annotation*/
257 Kind extKind; /* Kind of extension, *->row->row */
260 /* --------------------------------------------------------------------------
261 * Static analysis of modules:
262 * ------------------------------------------------------------------------*/
269 Void startModule(nm) /* switch to a new module */
272 if (!isCon(nm)) internal("startModule");
273 if (isNull(m = findModule(textOf(nm))))
274 m = newModule(textOf(nm));
275 else if (!isPreludeScript()) {
276 /* You're allowed to break the rules in the Prelude! */
278 reloadModule = textToStr(textOf(nm));
280 ERRMSG(0) "Module \"%s\" already loaded", textToStr(textOf(nm))
286 Void setExportList(exps) /* Add export list to current module */
288 module(currentModule).exports = exps;
291 Void addQualImport(orig,new) /* Add to qualified import list */
292 Cell orig; /* Original name of module */
293 Cell new; { /* Name module is called within this module (or NIL) */
294 module(currentModule).qualImports =
295 cons(pair(isNull(new)?orig:new,orig),module(currentModule).qualImports);
298 Void addUnqualImport(mod,entities) /* Add to unqualified import list */
299 Cell mod; /* Name of module */
300 List entities; { /* List of entity names */
301 unqualImports = cons(pair(mod,entities),unqualImports);
304 static Void local checkQualImport(i) /* Process qualified import */
306 Module m = findModid(snd(i));
308 ERRMSG(0) "Module \"%s\" not previously loaded",
309 textToStr(textOf(snd(i)))
315 static Void local checkUnqualImport(i) /* Process unqualified import */
317 Module m = findModid(fst(i));
319 ERRMSG(0) "Module \"%s\" not previously loaded",
320 textToStr(textOf(fst(i)))
326 static Name local lookupName(t,nms) /* find text t in list of Names */
328 List nms; { /* :: [Name] */
329 for(; nonNull(nms); nms=tl(nms)) {
330 if (t == name(hd(nms)).text)
336 static List local checkSubentities(imports,named,wanted,description,textParent)
338 List named; /* :: [ Q?(Var|Con)(Id|Op) ] */
339 List wanted; /* :: [Name] */
340 String description; /* "<constructor>|<member> of <type>|<class>" */
342 for(; nonNull(named); named=tl(named)) {
344 /* ToDo: ignores qualifier; doesn't check that entity is in scope */
345 Text t = isPair(snd(x)) ? qtextOf(x) : textOf(x);
346 Name n = lookupName(t,wanted);
348 ERRMSG(0) "Entity \"%s\" is not a %s \"%s\"",
351 textToStr(textParent)
354 imports = cons(n,imports);
359 static List local checkImportEntity(imports,exporter,entity)
360 List imports; /* Accumulated list of things to import */
362 Cell entity; { /* Entry from import list */
363 List oldImports = imports;
364 Text t = isIdent(entity) ? textOf(entity) : textOf(fst(entity));
365 List es = module(exporter).exports;
366 for(; nonNull(es); es=tl(es)) {
367 Cell e = hd(es); /* :: Entity | (Entity, NIL|DOTDOT) */
371 if (tycon(f).text == t) {
372 imports = cons(f,imports);
373 if (!isIdent(entity)) {
374 switch (tycon(f).what) {
377 if (DOTDOT == snd(entity)) {
378 imports=dupOnto(tycon(f).defn,imports);
380 imports=checkSubentities(imports,snd(entity),tycon(f).defn,"constructor of type",t);
384 /* deliberate fall thru */
388 } else if (isClass(f)) {
389 if (cclass(f).text == t) {
390 imports = cons(f,imports);
391 if (!isIdent(entity)) {
392 if (DOTDOT == snd(entity)) {
393 return dupOnto(cclass(f).members,imports);
395 return checkSubentities(imports,snd(entity),cclass(f).members,"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 \"%s\" in export list of module \"%s\"",
642 return cons(pair(nm,DOTDOT),exports);
644 ERRMSG(0) "Transparent export of restricted type synonym \"%s\" in export list of module \"%s\"",
648 return exports; /* Not reached */
652 return cons(pair(nm,DOTDOT),exports);
654 exports = checkSubentities(exports,parts,tycon(nm).defn,
655 "constructor of type",
657 return cons(pair(nm,DOTDOT), exports);
660 internal("checkExport1");
662 } else if (isQCon(ident) && nonNull(nm=findQualClass(ident))) {
663 if (DOTDOT == parts) {
664 return cons(pair(nm,DOTDOT),exports);
666 exports = checkSubentities(exports,parts,cclass(nm).members,
667 "member of class",cclass(nm).text);
668 return cons(pair(nm,DOTDOT), exports);
671 ERRMSG(0) "Explicit export list given for non-class/datatype \"%s\" in export list of module \"%s\"",
677 return 0; /* NOTREACHED */
680 static List local checkExports(exports)
682 Module m = lastModule();
683 Text mt = module(m).text;
686 map1Accum(checkExport,es,mt,exports);
689 for(xs=es; nonNull(xs); xs=tl(xs)) {
690 Printf(" %s", textToStr(textOfEntity(hd(xs))));
697 /* --------------------------------------------------------------------------
698 * Static analysis of type declarations:
700 * Type declarations come in two forms:
701 * - data declarations - define new constructed data types
702 * - type declarations - define new type synonyms
704 * A certain amount of work is carried out as the declarations are
705 * read during parsing. In particular, for each type constructor
706 * definition encountered:
707 * - check that there is no previous definition of constructor
708 * - ensure type constructor not previously used as a class name
709 * - make a new entry in the type constructor table
710 * - record line number of declaration
711 * - Build separate lists of newly defined constructors for later use.
712 * ------------------------------------------------------------------------*/
714 Void tyconDefn(line,lhs,rhs,what) /* process new type definition */
715 Int line; /* definition line number */
716 Cell lhs; /* left hand side of definition */
717 Cell rhs; /* right hand side of definition */
718 Cell what; { /* SYNONYM/DATATYPE/etc... */
719 Text t = textOf(getHead(lhs));
721 if (nonNull(findTycon(t))) {
722 ERRMSG(line) "Repeated definition of type constructor \"%s\"",
726 else if (nonNull(findClass(t))) {
727 ERRMSG(line) "\"%s\" used as both class and type constructor",
732 Tycon nw = newTycon(t);
733 tyconDefns = cons(nw,tyconDefns);
734 tycon(nw).line = line;
735 tycon(nw).arity = argCount;
736 tycon(nw).what = what;
737 if (what==RESTRICTSYN) {
738 h98DoesntSupport(line,"restricted type synonyms");
739 typeInDefns = cons(pair(nw,snd(rhs)),typeInDefns);
742 tycon(nw).defn = pair(lhs,rhs);
746 Void setTypeIns(bs) /* set local synonyms for given */
747 List bs; { /* binding group */
748 List cvs = typeInDefns;
749 for (; nonNull(cvs); cvs=tl(cvs)) {
750 Tycon c = fst(hd(cvs));
751 List vs = snd(hd(cvs));
752 for (tycon(c).what = RESTRICTSYN; nonNull(vs); vs=tl(vs)) {
753 if (nonNull(findBinding(textOf(hd(vs)),bs))) {
754 tycon(c).what = SYNONYM;
761 Void clearTypeIns() { /* clear list of local synonyms */
762 for (; nonNull(typeInDefns); typeInDefns=tl(typeInDefns))
763 tycon(fst(hd(typeInDefns))).what = RESTRICTSYN;
766 /* --------------------------------------------------------------------------
767 * Further analysis of Type declarations:
769 * In order to allow the definition of mutually recursive families of
770 * data types, the static analysis of the right hand sides of type
771 * declarations cannot be performed until all of the type declarations
774 * Once parsing is complete, we carry out the following:
776 * - check format of lhs, extracting list of bound vars and ensuring that
777 * there are no repeated variables and no Skolem variables.
778 * - run dependency analysis on rhs to check that only bound type vars
779 * appear in type and that all constructors are defined.
780 * Replace type variables by offsets, constructors by Tycons.
781 * - use list of dependents to sort into strongly connected components.
782 * - ensure that there is not more than one synonym in each group.
783 * - kind-check each group of type definitions.
785 * - check that there are no previous definitions for constructor
786 * functions in data type definitions.
787 * - install synonym expansions and constructor definitions.
788 * ------------------------------------------------------------------------*/
790 static List tcDeps = NIL; /* list of dependent tycons/classes*/
792 static Void local checkTyconDefn(d) /* validate type constructor defn */
794 Cell lhs = fst(tycon(d).defn);
795 Cell rhs = snd(tycon(d).defn);
796 Int line = tycon(d).line;
797 List tyvars = getArgs(lhs);
799 /* check for repeated tyvars on lhs*/
800 for (temp=tyvars; nonNull(temp); temp=tl(temp))
801 if (nonNull(varIsMember(textOf(hd(temp)),tl(temp)))) {
802 ERRMSG(line) "Repeated type variable \"%s\" on left hand side",
803 textToStr(textOf(hd(temp)))
807 tcDeps = NIL; /* find dependents */
808 switch (whatIs(tycon(d).what)) {
810 case SYNONYM : rhs = depTypeExp(line,tyvars,rhs);
811 if (cellIsMember(d,tcDeps)) {
812 ERRMSG(line) "Recursive type synonym \"%s\"",
813 textToStr(tycon(d).text)
819 case NEWTYPE : depConstrs(d,tyvars,rhs);
823 default : internal("checkTyconDefn");
828 tycon(d).kind = tcDeps;
832 static Void local depConstrs(t,tyvars,cd)
833 Tycon t; /* Define constructor functions and*/
834 List tyvars; /* do dependency analysis for data */
835 Cell cd; { /* definitions (w or w/o deriving) */
836 Int line = tycon(t).line;
841 List derivs = snd(cd);
842 List compTypes = NIL;
846 for (i=0; i<tycon(t).arity; ++i) /* build representation for tycon */
847 lhs = ap(lhs,mkOffset(i)); /* applied to full comp. of args */
849 if (whatIs(cs)==QUAL) { /* allow for possible context */
852 map2Proc(depPredExp,line,tyvars,ctxt);
853 h98CheckCtxt(line,"context",TRUE,ctxt,NIL);
856 if (nonNull(cs) && isNull(tl(cs))) /* Single constructor datatype? */
859 for (; nonNull(cs); cs=tl(cs)) { /* For each constructor function: */
861 List sig = dupList(tyvars);
862 List evs = NIL; /* locally quantified vars */
863 List lps = NIL; /* locally bound predicates */
864 List ctxt1 = ctxt; /* constructor function context */
865 List scs = NIL; /* strict components */
866 List fs = NONE; /* selector names */
867 Type type = lhs; /* constructor function type */
868 Int arity = 0; /* arity of constructor function */
869 Int nr2 = 0; /* Number of rank 2 args */
870 Name n; /* name for constructor function */
872 if (whatIs(con)==POLYTYPE) { /* Locally quantified vars */
875 sig = checkQuantVars(line,evs,sig,con);
878 if (whatIs(con)==QUAL) { /* Local predicates */
881 for (us = typeVarsIn(lps,NIL,NIL); nonNull(us); us=tl(us))
882 if (!varIsMember(textOf(hd(us)),evs)) {
884 "Variable \"%s\" in constraint is not locally bound",
885 textToStr(textOf(hd(us)))
888 map2Proc(depPredExp,line,sig,lps);
893 if (whatIs(con)==LABC) { /* Skeletize constr components */
894 Cell fls = snd(snd(con)); /* get field specifications */
897 for (; nonNull(fls); fls=tl(fls)) { /* for each field spec: */
898 List vs = fst(hd(fls));
899 Type t = snd(hd(fls)); /* - scrutinize type */
900 Bool banged = whatIs(t)==BANG;
901 t = depCompType(line,sig,(banged ? arg(t) : t));
902 while (nonNull(vs)) { /* - add named components */
910 scs = cons(mkInt(arity),scs);
914 scs = rev(scs); /* put strict comps in ascend ord */
916 else { /* Non-labelled constructor */
919 for (; isAp(c); c=fun(c))
921 for (compNo=arity, c=con; isAp(c); c=fun(c)) {
923 if (whatIs(t)==BANG) {
924 scs = cons(mkInt(compNo),scs);
928 arg(c) = depCompType(line,sig,t);
932 if (nonNull(ctxt1)) /* Extract relevant part of context*/
933 ctxt1 = selectCtxt(ctxt1,offsetTyvarsIn(con,NIL));
935 for (i=arity; isAp(con); i--) { /* Calculate type of constructor */
938 fun(con) = typeArrow;
939 if (isPolyType(cmp)) {
940 if (nonNull(derivs)) {
941 ERRMSG(line) "Cannot derive instances for types" ETHEN
942 ERRTEXT " with polymorphic components"
948 if (nonNull(derivs)) /* and build list of components */
949 compTypes = cons(cmp,compTypes);
954 if (nr2>0) /* Add rank 2 annotation */
955 type = ap(RANK2,pair(mkInt(nr2),type));
957 if (nonNull(evs)) { /* Add existential annotation */
958 if (nonNull(derivs)) {
959 ERRMSG(line) "Cannot derive instances for types" ETHEN
960 ERRTEXT " with existentially typed components"
965 "Cannot use selectors with existentially typed components"
968 type = ap(EXIST,pair(mkInt(length(evs)),type));
971 if (nonNull(lps)) { /* Add local preds part to type */
972 type = ap(CDICTS,pair(lps,type));
975 if (nonNull(ctxt1)) { /* Add context part to type */
976 type = ap(QUAL,pair(ctxt1,type));
979 if (nonNull(sig)) { /* Add quantifiers to type */
981 for (; nonNull(ts1); ts1=tl(ts1)) {
984 type = mkPolyType(sig,type);
987 n = findName(textOf(con)); /* Allocate constructor fun name */
989 n = newName(textOf(con),NIL);
990 } else if (name(n).defn!=PREDEFINED) {
991 duplicateError(line,name(n).mod,name(n).text,
992 "constructor function");
994 name(n).arity = arity; /* Save constructor fun details */
997 name(n).number = cfunNo(conNo++);
999 if (tycon(t).what==NEWTYPE) {
1002 "A newtype constructor cannot have class constraints"
1007 "A newtype constructor must have exactly one argument"
1012 "Illegal strictess annotation for newtype constructor"
1015 name(n).defn = nameId;
1017 implementCfun(n,scs);
1022 sels = addSels(line,n,fs,sels);
1026 if (nonNull(sels)) {
1028 fst(cd) = appendOnto(fst(cd),sels);
1029 selDefns = cons(sels,selDefns);
1032 if (nonNull(derivs)) { /* Generate derived instances */
1033 map3Proc(checkDerive,t,ctxt,compTypes,derivs);
1037 Int userArity(c) /* Find arity for cfun, ignoring */
1038 Name c; { /* CDICTS parameters */
1039 Int a = name(c).arity;
1040 Type t = name(c).type;
1042 if (isPolyType(t)) {
1045 if ((w=whatIs(t))==QUAL) {
1046 w = whatIs(t=snd(snd(t)));
1049 a -= length(fst(snd(t)));
1055 static List local addSels(line,c,fs,ss) /* Add fields to selector list */
1056 Int line; /* line number of constructor */
1057 Name c; /* corresponding constr function */
1058 List fs; /* list of fields (varids) */
1059 List ss; { /* list of existing selectors */
1061 cfunSfuns = cons(pair(c,fs),cfunSfuns);
1062 for (; nonNull(fs); fs=tl(fs), ++sn) {
1064 Text t = textOf(hd(fs));
1066 if (nonNull(varIsMember(t,tl(fs)))) {
1067 ERRMSG(line) "Repeated field name \"%s\" for constructor \"%s\"",
1068 textToStr(t), textToStr(name(c).text)
1072 while (nonNull(ns) && t!=name(hd(ns)).text) {
1077 name(hd(ns)).defn = cons(pair(c,mkInt(sn)),name(hd(ns)).defn);
1079 Name n = findName(t);
1081 ERRMSG(line) "Repeated definition for selector \"%s\"",
1086 name(n).line = line;
1087 name(n).number = SELNAME;
1088 name(n).defn = singleton(pair(c,mkInt(sn)));
1095 static List local selectCtxt(ctxt,vs) /* calculate subset of context */
1102 for (; nonNull(ctxt); ctxt=tl(ctxt)) {
1103 List us = offsetTyvarsIn(hd(ctxt),NIL);
1104 for (; nonNull(us) && cellIsMember(hd(us),vs); us=tl(us)) {
1107 ps = cons(hd(ctxt),ps);
1114 static Void local checkSynonyms(ts) /* Check for mutually recursive */
1115 List ts; { /* synonyms */
1117 for (; nonNull(ts); ts=tl(ts)) { /* build list of all synonyms */
1119 switch (whatIs(tycon(t).what)) {
1121 case RESTRICTSYN : syns = cons(t,syns);
1125 while (nonNull(syns)) { /* then visit each synonym */
1126 syns = visitSyn(NIL,hd(syns),syns);
1130 static List local visitSyn(path,t,syns) /* visit synonym definition to look*/
1131 List path; /* for cycles */
1134 if (cellIsMember(t,path)) { /* every elt in path depends on t */
1135 ERRMSG(tycon(t).line)
1136 "Type synonyms \"%s\" and \"%s\" are mutually recursive",
1137 textToStr(tycon(t).text), textToStr(tycon(hd(path)).text)
1140 List ds = tycon(t).kind;
1142 for (; nonNull(ds); ds=tl(ds)) {
1143 if (cellIsMember(hd(ds),syns)) {
1144 if (isNull(path1)) {
1145 path1 = cons(t,path);
1147 syns = visitSyn(path1,hd(ds),syns);
1151 tycon(t).defn = fullExpand(tycon(t).defn);
1152 return removeCell(t,syns);
1156 /* --------------------------------------------------------------------------
1157 * The following code is used in calculating contexts for the automatically
1158 * derived Eval instances for newtype and restricted type synonyms. This is
1159 * ugly code, resulting from an ugly feature in the language, and I hope that
1160 * the feature, and hence the code, will be removed in the not too distant
1162 * ------------------------------------------------------------------------*/
1164 static Void local deriveEval(tcs) /* Derive instances of Eval */
1168 for (; nonNull(ts1); ts1=tl(ts1)) { /* Build list of rsyns and newtypes*/
1169 Tycon t = hd(ts1); /* and derive instances for data */
1170 switch (whatIs(tycon(t).what)) {
1171 case DATATYPE : addEvalInst(tycon(t).line,t,tycon(t).arity,NIL);
1174 case RESTRICTSYN : ts = cons(t,ts);
1178 emptySubstitution(); /* then derive other instances */
1179 while (nonNull(ts)) {
1180 ts = calcEvalContexts(hd(ts),tl(ts),NIL);
1182 emptySubstitution();
1184 for (; nonNull(tcs); tcs=tl(tcs)) { /* Check any banged components */
1186 if (whatIs(tycon(t).what)==DATATYPE) {
1187 List cs = tycon(t).defn;
1188 for (; hasCfun(cs); cs=tl(cs)) {
1190 if (isPair(name(c).defn)) {
1191 Type t = name(c).type;
1192 List scs = fst(name(c).defn);
1196 if (isPolyType(t)) {
1200 if (whatIs(t)==QUAL) {
1204 for (; nonNull(scs); scs=tl(scs)) {
1205 Int i = intOf(hd(scs));
1209 checkBanged(c,ks,ctxt,arg(fun(t)));
1217 static List local calcEvalContexts(tc,ts,ps)
1218 Tycon tc; /* Worker code for deriveEval */
1219 List ts; /* ts = not visited, ps = visiting */
1222 Int o = newKindedVars(tycon(tc).kind);
1223 Type t = tycon(tc).defn;
1226 if (whatIs(tycon(tc).what)==NEWTYPE) {
1227 t = name(hd(t)).type;
1228 if (isPolyType(t)) {
1231 if (whatIs(t)==QUAL) {
1234 if (whatIs(t)==EXIST) { /* No instance if existentials used*/
1237 if (whatIs(t)==RANK2) { /* No instance if arg is poly/qual */
1243 clearMarks(); /* Make sure generics are marked */
1244 for (i=0; i<tycon(tc).arity; i++) { /* in the correct order. */
1249 Type h = getDerefHead(t,o);
1250 if (isSynonym(h) && argCount>=tycon(h).arity) {
1251 expandSyn(h,argCount,&t,&o);
1252 } else if (isOffset(h)) { /* Stop if var at head */
1253 ctxt = singleton(ap(classEval,copyType(t,o)));
1255 } else if (isTuple(h) /* Check for tuples ... */
1256 || h==tc /* ... direct recursion */
1257 || cellIsMember(h,ps) /* ... mutual recursion */
1258 || tycon(h).what==DATATYPE) {/* ... or datatype. */
1259 break; /* => empty context */
1261 Cell pi = ap(classEval,t);
1264 if (cellIsMember(h,ts)) { /* Not yet visited? */
1265 ts = calcEvalContexts(h,removeCell(h,ts),cons(h,ts));
1267 <<<<<<<<<<<<<< variant A
1268 >>>>>>>>>>>>>> variant B
1270 ======= end of combination
1271 if (nonNull(in=findInstFor(pi,o))) {/* Look for Eval instance */
1272 List qs = inst(in).specifics;
1274 if (isNull(qs)) { /* No context there */
1275 break; /* => empty context here */
1277 if (isNull(tl(qs)) && classEval==fun(hd(qs))) {
1283 return ts; /* No instance, so give up */
1286 addEvalInst(tycon(tc).line,tc,tycon(tc).arity,ctxt);
1290 static Void local checkBanged(c,ks,ps,ty)
1291 Name c; /* Check that banged component of c */
1292 Kinds ks; /* with type ty is an instance of */
1293 List ps; /* Eval under the predicates in ps. */
1294 Type ty; { /* (All types using ks) */
1295 Cell pi = ap(classEval,ty);
1296 if (isNull(provePred(ks,ps,pi))) {
1297 ERRMSG(name(c).line) "Illegal datatype strictness annotation:" ETHEN
1298 ERRTEXT "\n*** Constructor : " ETHEN ERREXPR(c);
1299 ERRTEXT "\n*** Context : " ETHEN ERRCONTEXT(ps);
1300 ERRTEXT "\n*** Required : " ETHEN ERRPRED(pi);
1307 /* --------------------------------------------------------------------------
1308 * Expanding out all type synonyms in a type expression:
1309 * ------------------------------------------------------------------------*/
1311 Type fullExpand(t) /* find full expansion of type exp */
1312 Type t; { /* assuming that all relevant */
1313 Cell h = t; /* synonym defns of lower rank have*/
1314 Int n = 0; /* already been fully expanded */
1316 for (args=NIL; isAp(h); h=fun(h), n++) {
1317 args = cons(fullExpand(arg(h)),args);
1319 t = applyToArgs(h,args);
1320 if (isSynonym(h) && n>=tycon(h).arity) {
1321 if (n==tycon(h).arity) {
1322 t = instantiateSyn(tycon(h).defn,t);
1325 while (--n > tycon(h).arity) {
1328 fun(p) = instantiateSyn(tycon(h).defn,fun(p));
1334 static Type local instantiateSyn(t,env) /* instantiate type according using*/
1335 Type t; /* env to determine appropriate */
1336 Type env; { /* values for OFFSET type vars */
1337 switch (whatIs(t)) {
1338 case AP : return ap(instantiateSyn(fun(t),env),
1339 instantiateSyn(arg(t),env));
1341 case OFFSET : return nthArg(offsetOf(t),env);
1347 /* --------------------------------------------------------------------------
1348 * Static analysis of class declarations:
1350 * Performed in a similar manner to that used for type declarations.
1352 * The first part of the static analysis is performed as the declarations
1353 * are read during parsing. The parser ensures that:
1354 * - the class header and all superclass predicates are of the form
1357 * The classDefn() function:
1358 * - ensures that there is no previous definition for class
1359 * - checks that class name has not previously been used as a type constr.
1360 * - make new entry in class table
1361 * - record line number of declaration
1362 * - build list of classes defined in current script for use in later
1363 * stages of static analysis.
1364 * ------------------------------------------------------------------------*/
1366 Void classDefn(line,head,ms) /* process new class definition */
1367 Int line; /* definition line number */
1368 Cell head; /* class header :: ([Supers],Class) */
1369 List ms; { /* class definition body */
1370 Text ct = textOf(getHead(snd(head)));
1371 Int arity = argCount;
1373 if (nonNull(findClass(ct))) {
1374 ERRMSG(line) "Repeated definition of class \"%s\"",
1377 } else if (nonNull(findTycon(ct))) {
1378 ERRMSG(line) "\"%s\" used as both class and type constructor",
1382 Class nw = newClass(ct);
1383 cclass(nw).line = line;
1384 cclass(nw).arity = arity;
1385 cclass(nw).head = snd(head);
1386 cclass(nw).supers = fst(head);
1387 cclass(nw).members = ms;
1388 cclass(nw).level = 0;
1389 classDefns = cons(nw,classDefns);
1391 h98DoesntSupport(line,"multiple parameter classes");
1395 /* --------------------------------------------------------------------------
1396 * Further analysis of class declarations:
1398 * Full static analysis of class definitions must be postponed until the
1399 * complete script has been read and all static analysis on type definitions
1400 * has been completed.
1402 * Once this has been achieved, we carry out the following checks on each
1404 * - check that variables in header are distinct
1405 * - replace head by skeleton
1406 * - check superclass declarations, replace by skeletons
1407 * - split body of class into members and declarations
1408 * - make new name entry for each member function
1409 * - record member function number (eventually an offset into dictionary!)
1410 * - no member function has a previous definition ...
1411 * - no member function is mentioned more than once in the list of members
1412 * - each member function type is valid, replace vars by offsets
1413 * - qualify each member function type by class header
1414 * - only bindings for members appear in defaults
1415 * - only function bindings appear in defaults
1416 * - check that extended class hierarchy does not contain any cycles
1417 * ------------------------------------------------------------------------*/
1419 static Void local checkClassDefn(c) /* validate class definition */
1422 Int args = cclass(c).arity - 1;
1423 Cell temp = cclass(c).head;
1427 for (; isAp(temp); temp=fun(temp)) {
1428 if (!isVar(arg(temp))) {
1429 ERRMSG(cclass(c).line) "Type variable required in class head"
1432 if (nonNull(varIsMember(textOf(arg(temp)),tyvars))) {
1433 ERRMSG(cclass(c).line)
1434 "Repeated type variable \"%s\" in class head",
1435 textToStr(textOf(arg(temp)))
1438 tyvars = cons(arg(temp),tyvars);
1441 for (temp=cclass(c).head; args>0; temp=fun(temp), args--) {
1442 arg(temp) = mkOffset(args);
1444 arg(temp) = mkOffset(0);
1447 tcDeps = NIL; /* find dependents */
1448 map2Proc(depPredExp,cclass(c).line,tyvars,cclass(c).supers);
1449 h98CheckCtxt(cclass(c).line,"class definition",FALSE,cclass(c).supers,NIL);
1450 cclass(c).numSupers = length(cclass(c).supers);
1451 cclass(c).defaults = extractBindings(cclass(c).members); /* defaults*/
1452 ss = extractSigdecls(cclass(c).members);
1453 fs = extractFixdecls(cclass(c).members);
1454 cclass(c).members = pair(ss,fs);
1455 map2Proc(checkMems,c,tyvars,ss);
1457 cclass(c).kinds = tcDeps;
1461 static Void local depPredExp(line,tyvars,pred)
1465 Int args = 1; /* parser guarantees >=1 args */
1467 for (; isAp(h); args++) {
1468 arg(pred) = depTypeExp(line,tyvars,arg(pred));
1472 arg(pred) = depTypeExp(line,tyvars,arg(pred));
1474 h98DoesntSupport(line,"multiple parameter classes");
1476 if (isQCon(h)) { /* standard class constraint */
1477 Class c = findQualClass(h);
1479 ERRMSG(line) "Undefined class \"%s\"", identToStr(h)
1483 if (args!=cclass(c).arity) {
1484 ERRMSG(line) "Wrong number of arguments for class \"%s\"",
1485 textToStr(cclass(c).text)
1488 if (cellIsMember(c,classDefns) && !cellIsMember(c,tcDeps)) {
1489 tcDeps = cons(c,tcDeps);
1493 else if (isExt(h)) { /* Lacks predicate */
1494 if (args!=1) { /* parser shouldn't let this happen*/
1495 ERRMSG(line) "Wrong number of arguments for lacks predicate"
1500 else { /* check for other kinds of pred */
1501 internal("depPredExp"); /* ... but there aren't any! */
1505 static Void local checkMems(c,tyvars,m) /* check member function details */
1509 Int line = intOf(fst3(m));
1515 tyvars = typeVarsIn(t,NIL,tyvars);/* Look for extra type vars. */
1517 if (whatIs(t)==QUAL) { /* Overloaded member signatures? */
1518 map2Proc(depPredExp,line,tyvars,fst(snd(t)));
1520 t = ap(QUAL,pair(NIL,t));
1523 fst(snd(t)) = cons(cclass(c).head,fst(snd(t)));/* Add main predicate */
1524 snd(snd(t)) = depTopType(line,tyvars,snd(snd(t)));
1526 for (tvs=tyvars; nonNull(tvs); tvs=tl(tvs)){/* Quantify */
1529 t = mkPolyType(sig,t);
1530 thd3(m) = t; /* Save type */
1531 take(cclass(c).arity,tyvars); /* Delete extra type vars */
1533 if (isAmbiguous(t)) {
1534 ambigError(line,"class declaration",hd(vs),t);
1536 h98CheckType(line,"member type",hd(vs),t);
1539 static Void local addMembers(c) /* Add definitions of member funs */
1540 Class c; { /* and other parts of class struct.*/
1541 List ms = fst(cclass(c).members);
1542 List fs = snd(cclass(c).members);
1543 List ns = NIL; /* List of names */
1544 Int mno; /* Member function number */
1546 //printf ( "\naddMembers: class = %s\n", textToStr ( cclass(c).text ) );
1547 for (mno=0; mno<cclass(c).numSupers; mno++) {
1548 ns = cons(newDSel(c,mno),ns);
1550 cclass(c).dsels = rev(ns); /* Save dictionary selectors */
1552 for (mno=1, ns=NIL; nonNull(ms); ms=tl(ms)) {
1553 Int line = intOf(fst3(hd(ms)));
1554 List vs = rev(snd3(hd(ms)));
1555 Type t = thd3(hd(ms));
1556 for (; nonNull(vs); vs=tl(vs)) {
1557 ns = cons(newMember(line,mno++,hd(vs),t,c),ns);
1560 cclass(c).members = rev(ns); /* Save list of members */
1561 cclass(c).numMembers = length(cclass(c).members);
1563 for (; nonNull(fs); fs=tl(fs)) { /* fixity declarations */
1564 Int line = intOf(fst3(hd(fs)));
1565 List ops = snd3(hd(fs));
1566 Syntax s = intOf(thd3(hd(fs)));
1567 for (; nonNull(ops); ops=tl(ops)) {
1568 Name n = nameIsMember(textOf(hd(ops)),cclass(c).members);
1570 missFixity(line,textOf(hd(ops)));
1571 } else if (name(n).syntax!=NO_SYNTAX) {
1572 dupFixity(line,textOf(hd(ops)));
1578 /* Not actually needed just yet; for the time being, dictionary code will
1579 not be passed through the type checker.
1581 cclass(c).dtycon = addPrimTycon(generateText("Dict.%s",c),
1588 mno = cclass(c).numSupers + cclass(c).numMembers;
1589 cclass(c).dcon = addPrimCfun(generateText("Make.%s",c),mno,0,NIL);
1590 implementCfun(cclass(c).dcon,NIL); /* ADR addition */
1592 if (mno==1) { /* Single entry dicts use newtype */
1593 name(cclass(c).dcon).defn = nameId;
1594 name(hd(cclass(c).members)).number = mfunNo(0);
1596 cclass(c).dbuild = newDBuild(c);
1597 cclass(c).defaults = classBindings("class",c,cclass(c).defaults);
1600 static Name local newMember(l,no,v,t,parent)
1601 Int l; /* Make definition for member fn */
1606 Name m = findName(textOf(v));
1609 m = newName(textOf(v),parent);
1610 } else if (name(m).defn!=PREDEFINED) {
1611 ERRMSG(l) "Repeated definition for member function \"%s\"",
1612 textToStr(name(m).text)
1618 name(m).number = mfunNo(no);
1620 //printf ( " [%d %d] %s :: ", m, m-NAMEMIN, textToStr ( name(m).text ) );
1621 //printType(stdout, t );
1626 static Name local newDSel(c,no) /* Make definition for dict selectr*/
1632 sprintf(buf,"sc%d.%s",no,"%s");
1633 s = newName(generateText(buf,c),c);
1634 name(s).line = cclass(c).line;
1636 name(s).number = DFUNNAME;
1640 static Name local newDBuild(c) /* Make definition for builder */
1642 Name b = newName(generateText("class.%s",c),c);
1643 name(b).line = cclass(c).line;
1644 name(b).arity = cclass(c).numSupers+1;
1650 static Text local generateText(sk,c) /* We need to generate names for */
1651 String sk; /* certain objects corresponding */
1652 Class c; { /* to each class. */
1653 String cname = textToStr(cclass(c).text);
1654 char buffer[MAX_GEN+1];
1656 if ((strlen(sk)+strlen(cname))>=MAX_GEN) {
1657 ERRMSG(0) "Please use a shorter name for class \"%s\"", cname
1660 sprintf(buffer,sk,cname);
1661 return findText(buffer);
1664 static Int local visitClass(c) /* visit class defn to check that */
1665 Class c; { /* class hierarchy is acyclic */
1667 if (isExt(c)) { /* special case for lacks preds */
1671 if (cclass(c).level < 0) { /* already visiting this class? */
1672 ERRMSG(cclass(c).line) "Class hierarchy for \"%s\" is not acyclic",
1673 textToStr(cclass(c).text)
1675 } else if (cclass(c).level == 0) { /* visiting class for first time */
1676 List scs = cclass(c).supers;
1678 cclass(c).level = (-1);
1679 for (; nonNull(scs); scs=tl(scs)) {
1680 Int l = visitClass(getHead(hd(scs)));
1683 cclass(c).level = 1+lev; /* level = 1 + max level of supers */
1685 return cclass(c).level;
1688 /* --------------------------------------------------------------------------
1689 * Process class and instance declaration binding groups:
1690 * ------------------------------------------------------------------------*/
1692 static List local classBindings(where,c,bs)
1693 String where; /* Check validity of bindings bs */
1694 Class c; /* for class c (or an inst of c) */
1695 List bs; { /* sort into approp. member order */
1698 for (; nonNull(bs); bs=tl(bs)) {
1700 Cell body = snd(snd(b));
1703 if (!isVar(fst(b))) { /* Only allow function bindings */
1704 ERRMSG(rhsLine(snd(body)))
1705 "Pattern binding illegal in %s declaration", where
1709 if (isNull(mnm=memberName(c,textOf(fst(b))))) {
1710 ERRMSG(rhsLine(snd(hd(body))))
1711 "No member \"%s\" in class \"%s\"",
1712 textToStr(textOf(fst(b))), textToStr(cclass(c).text)
1716 nbs = numInsert(mfunOf(mnm)-1,b,nbs);
1721 static Name local memberName(c,t) /* return name of member function */
1722 Class c; /* with name t in class c */
1723 Text t; { /* return NIL if not a member */
1724 List ms = cclass(c).members;
1725 for (; nonNull(ms); ms=tl(ms)) {
1726 if (t==name(hd(ms)).text) {
1733 static List local numInsert(n,x,xs) /* insert x at nth position in xs, */
1734 Int n; /* filling gaps with NIL */
1737 List start = isNull(xs) ? cons(NIL,NIL) : xs;
1739 for (xs=start; 0<n--; xs=tl(xs)) {
1740 if (isNull(tl(xs))) {
1741 tl(xs) = cons(NIL,NIL);
1748 /* --------------------------------------------------------------------------
1749 * Calculate set of variables appearing in a given type expression (possibly
1750 * qualified) as a list of distinct values. The order in which variables
1751 * appear in the list is the same as the order in which those variables
1752 * occur in the type expression when read from left to right.
1753 * ------------------------------------------------------------------------*/
1755 static List local typeVarsIn(ty,us,vs) /* Calculate list of type variables*/
1756 Cell ty; /* used in type expression, reading*/
1757 List us; /* from left to right ignoring any */
1758 List vs; { /* listed in us. */
1759 switch (whatIs(ty)) {
1760 case AP : return typeVarsIn(snd(ty),us,
1761 typeVarsIn(fst(ty),us,vs));
1764 case VAROPCELL : if (nonNull(findBtyvs(textOf(ty)))
1765 || varIsMember(textOf(ty),us)) {
1768 return maybeAppendVar(ty,vs);
1771 case POLYTYPE : return typeVarsIn(monotypeOf(ty),polySigOf(ty),vs);
1773 case QUAL : { List qs = fst(snd(ty));
1774 for (; nonNull(qs); qs=tl(qs)) {
1775 vs = typeVarsIn(hd(qs),us,vs);
1777 return typeVarsIn(snd(snd(ty)),us,vs);
1780 case BANG : return typeVarsIn(snd(ty),us,vs);
1782 case LABC : { List fs = snd(snd(ty));
1783 for (; nonNull(fs); fs=tl(fs)) {
1784 vs = typeVarsIn(snd(hd(fs)),us,vs);
1792 static List local maybeAppendVar(v,vs) /* append variable to list if not */
1793 Cell v; /* already included */
1799 while (nonNull(c)) {
1800 if (textOf(hd(c))==t) {
1808 tl(p) = cons(v,NIL);
1816 /* --------------------------------------------------------------------------
1817 * Static analysis for type expressions is required to:
1818 * - ensure that each type constructor or class used has been defined.
1819 * - replace type variables by offsets, constructor names by Tycons.
1820 * - ensure that the type is well-kinded.
1821 * ------------------------------------------------------------------------*/
1823 static Type local checkSigType(line,where,e,type)
1824 Int line; /* Check validity of type expr in */
1825 String where; /* explicit type signature */
1828 List tvs = typeVarsIn(type,NIL,NIL);
1829 Int n = length(tvs);
1830 List sunk = unkindTypes;
1832 if (whatIs(type)==QUAL) {
1833 map2Proc(depPredExp,line,tvs,fst(snd(type)));
1834 snd(snd(type)) = depTopType(line,tvs,snd(snd(type)));
1836 if (isAmbiguous(type)) {
1837 ambigError(line,where,e,type);
1840 type = depTopType(line,tvs,type);
1844 if (n>=NUM_OFFSETS) {
1845 ERRMSG(line) "Too many type variables in %s\n", where
1849 for (; nonNull(ts); ts=tl(ts)) {
1852 type = mkPolyType(tvs,type);
1857 kindType(line,"type expression",type);
1861 h98CheckType(line,where,e,type);
1865 static Type local depTopType(l,tvs,t) /* Check top-level of type sig */
1873 for (; getHead(t1)==typeArrow && argCount==2; ++i) {
1874 arg(fun(t1)) = depCompType(l,tvs,arg(fun(t1)));
1875 if (isPolyType(arg(fun(t1)))) {
1881 if (nonNull(prev)) {
1882 arg(prev) = depTypeExp(l,tvs,t1);
1884 t = depTypeExp(l,tvs,t1);
1887 t = ap(RANK2,pair(mkInt(nr2),t));
1892 static Type local depCompType(l,tvs,t) /* Check component type for constr */
1896 if (isPolyType(t)) {
1897 Int ntvs = length(tvs);
1899 if (isPolyType(t)) {
1900 List vs = fst(snd(t));
1902 tvs = checkQuantVars(l,vs,tvs,t);
1903 nfr = replicate(length(vs),NIL);
1905 if (whatIs(t)==QUAL) {
1906 map2Proc(depPredExp,l,tvs,fst(snd(t)));
1907 snd(snd(t)) = depTypeExp(l,tvs,snd(snd(t)));
1908 if (isAmbiguous(t)) {
1909 ambigError(l,"type component",NIL,t);
1912 t = depTypeExp(l,tvs,t);
1918 return mkPolyType(nfr,t);
1920 return depTypeExp(l,tvs,t);
1924 static Type local depTypeExp(line,tyvars,type)
1928 switch (whatIs(type)) {
1929 case AP : fst(type) = depTypeExp(line,tyvars,fst(type));
1930 snd(type) = depTypeExp(line,tyvars,snd(type));
1933 case VARIDCELL : return depTypeVar(line,tyvars,textOf(type));
1935 case QUALIDENT : if (isQVar(type)) {
1936 ERRMSG(line) "Qualified type variables not allowed"
1939 /* deliberate fall through */
1940 case CONIDCELL : { Tycon tc = findQualTycon(type);
1943 "Undefined type constructor \"%s\"",
1947 if (cellIsMember(tc,tyconDefns) &&
1948 !cellIsMember(tc,tcDeps)) {
1949 tcDeps = cons(tc,tcDeps);
1955 case EXT : h98DoesntSupport(line,"extensible records");
1960 default : internal("depTypeExp");
1965 static Type local depTypeVar(line,tyvars,tv)
1970 Cell vt = findBtyvs(tv);
1975 for (; nonNull(tyvars) && tv!=textOf(hd(tyvars)); offset++) {
1976 tyvars = tl(tyvars);
1978 if (isNull(tyvars)) {
1979 ERRMSG(line) "Undefined type variable \"%s\"", textToStr(tv)
1982 return mkOffset(offset);
1985 static List local checkQuantVars(line,vs,tvs,body)
1987 List vs; /* variables to quantify over */
1988 List tvs; /* variables already in scope */
1989 Cell body; { /* type/constr for scope of vars */
1991 List bvs = typeVarsIn(body,NIL,NIL);
1993 for (; nonNull(us); us=tl(us)) {
1994 Text u = textOf(hd(us));
1995 if (varIsMember(u,tl(us))) {
1996 ERRMSG(line) "Duplicated quantified variable %s",
2000 if (varIsMember(u,tvs)) {
2001 ERRMSG(line) "Local quantifier for %s hides an outer use",
2005 if (!varIsMember(u,bvs)) {
2006 ERRMSG(line) "Locally quantified variable %s is not used",
2011 tvs = appendOnto(tvs,vs);
2016 /* --------------------------------------------------------------------------
2017 * Check for ambiguous types:
2018 * A type Preds => type is ambiguous if not (TV(P) `subset` TV(type))
2019 * ------------------------------------------------------------------------*/
2021 List offsetTyvarsIn(t,vs) /* add list of offset tyvars in t */
2022 Type t; /* to list vs */
2024 switch (whatIs(t)) {
2025 case AP : return offsetTyvarsIn(fun(t),
2026 offsetTyvarsIn(arg(t),vs));
2028 case OFFSET : if (cellIsMember(t,vs))
2033 case QUAL : return offsetTyvarsIn(snd(t),vs);
2035 case POLYTYPE : return offsetTyvarsIn(monotypeOf(t),vs);
2036 /* slightly inaccurate, but won't matter here */
2039 case RANK2 : return offsetTyvarsIn(snd(snd(t)),vs);
2041 default : return vs;
2045 Bool isAmbiguous(type) /* Determine whether type is */
2046 Type type; { /* ambiguous */
2047 if (isPolyType(type)) {
2048 type = monotypeOf(type);
2050 if (whatIs(type)==QUAL) { /* only qualified types can be */
2051 List tvps = offsetTyvarsIn(fst(snd(type)),NIL); /* ambiguous */
2052 List tvts = offsetTyvarsIn(snd(snd(type)),NIL);
2053 while (nonNull(tvps) && cellIsMember(hd(tvps),tvts)) {
2056 return nonNull(tvps);
2061 Void ambigError(line,where,e,type) /* produce error message for */
2062 Int line; /* ambiguity */
2066 ERRMSG(line) "Ambiguous type signature in %s", where ETHEN
2067 ERRTEXT "\n*** ambiguous type : " ETHEN ERRTYPE(type);
2069 ERRTEXT "\n*** assigned to : " ETHEN ERREXPR(e);
2075 /* --------------------------------------------------------------------------
2076 * Kind inference for simple types:
2077 * ------------------------------------------------------------------------*/
2079 static Void local kindConstr(line,alpha,m,c)
2080 Int line; /* Determine kind of constructor */
2084 Cell h = getHead(c);
2088 Printf("kindConstr: alpha=%d, m=%d, c=",alpha,m);
2089 printType(stdout,c);
2093 switch (whatIs(h)) {
2094 case POLYTYPE : if (n!=0) {
2095 internal("kindConstr1");
2097 static String pt = "polymorphic type";
2098 Type t = dropRank1(c,alpha,m);
2099 Kinds ks = polySigOf(t);
2102 for (; isAp(ks); ks=tl(ks)) {
2105 beta = newKindvars(m1);
2106 unkindTypes = cons(pair(mkInt(beta),t),unkindTypes);
2107 checkKind(line,beta,m1,monotypeOf(t),NIL,pt,STAR,0);
2112 case QUAL : if (n!=0) {
2113 internal("kindConstr2");
2115 map3Proc(kindPred,line,alpha,m,fst(snd(c)));
2116 kindConstr(line,alpha,m,snd(snd(c)));
2120 case RANK2 : kindConstr(line,alpha,m,snd(snd(c)));
2124 case EXT : if (n!=2) {
2126 "Illegal use of row in " ETHEN ERRTYPE(c);
2133 case TYCON : if (isSynonym(h) && n<tycon(h).arity) {
2135 "Not enough arguments for type synonym \"%s\"",
2136 textToStr(tycon(h).text)
2142 if (n==0) { /* trivial case, no arguments */
2143 typeIs = kindAtom(alpha,c);
2144 } else { /* non-trivial application */
2145 static String app = "constructor application";
2155 typeIs = kindAtom(alpha,h); /* h :: v1 -> ... -> vn -> w */
2156 shouldKind(line,h,c,app,k,beta);
2158 for (i=n; i>0; --i) { /* ci :: vi for each 1 <- 1..n */
2159 checkKind(line,alpha,m,arg(a),c,app,aVar,beta+i-1);
2162 tyvarType(beta+n); /* inferred kind is w */
2166 static Kind local kindAtom(alpha,c) /* Find kind of atomic constructor */
2169 switch (whatIs(c)) {
2170 case TUPLE : return simpleKind(tupleOf(c)); /*(,)::* -> * -> * */
2171 case OFFSET : return mkInt(alpha+offsetOf(c));
2172 case TYCON : return tycon(c).kind;
2173 case INTCELL : return c;
2175 case VAROPCELL : { Cell vt = findBtyvs(textOf(c));
2181 case EXT : return extKind;
2185 Printf("kindAtom(%d,whatIs(%d)) on ",alpha,whatIs(c));
2186 printType(stdout,c);
2189 internal("kindAtom");
2190 return STAR;/* not reached */
2193 static Void local kindPred(l,alpha,m,pi)/* Check kinds of arguments in pred*/
2199 if (isExt(fun(pi))) {
2200 static String lackspred = "lacks predicate";
2201 checkKind(l,alpha,m,arg(pi),NIL,lackspred,ROW,0);
2205 { static String predicate = "class constraint";
2206 Class c = getHead(pi);
2207 List as = getArgs(pi);
2208 Kinds ks = cclass(c).kinds;
2210 while (nonNull(ks)) {
2211 checkKind(l,alpha,m,hd(as),NIL,predicate,hd(ks),0);
2218 static Void local kindType(line,wh,type)/* check that (poss qualified) type*/
2219 Int line; /* is well-kinded */
2222 checkKind(line,0,0,type,NIL,wh,STAR,0);
2225 static Void local fixKinds() { /* add kind annotations to types */
2226 for (; nonNull(unkindTypes); unkindTypes=tl(unkindTypes)) {
2227 Pair pr = hd(unkindTypes);
2228 Int beta = intOf(fst(pr));
2229 Cell qts = polySigOf(snd(pr));
2231 if (isNull(hd(qts))) {
2232 hd(qts) = copyKindvar(beta++);
2234 internal("fixKinds");
2236 if (nonNull(tl(qts))) {
2244 Printf("Type expression: ");
2245 printType(stdout,snd(pr));
2247 printKind(stdout,polySigOf(snd(pr)));
2253 /* --------------------------------------------------------------------------
2254 * Kind checking of groups of type constructors and classes:
2255 * ------------------------------------------------------------------------*/
2257 static Void local kindTCGroup(tcs) /* find kinds for mutually rec. gp */
2258 List tcs; { /* of tycons and classes */
2259 emptySubstitution();
2261 mapProc(initTCKind,tcs);
2262 mapProc(kindTC,tcs);
2265 emptySubstitution();
2268 static Void local initTCKind(c) /* build initial kind/arity for c */
2270 if (isTycon(c)) { /* Initial kind of tycon is: */
2271 Int beta = newKindvars(1); /* v1 -> ... -> vn -> vn+1 */
2272 varKind(tycon(c).arity); /* where n is the arity of c. */
2273 bindTv(beta,typeIs,typeOff); /* For data definitions, vn+1 == * */
2274 switch (whatIs(tycon(c).what)) {
2276 case DATATYPE : bindTv(typeOff+tycon(c).arity,STAR,0);
2278 tycon(c).kind = mkInt(beta);
2280 Int n = cclass(c).arity;
2281 Int beta = newKindvars(n);
2282 cclass(c).kinds = NIL;
2285 cclass(c).kinds = pair(mkInt(beta+n),cclass(c).kinds);
2290 static Void local kindTC(c) /* check each part of a tycon/class*/
2291 Cell c; { /* is well-kinded */
2293 static String cfun = "constructor function";
2294 static String tsyn = "synonym definition";
2295 Int line = tycon(c).line;
2296 Int beta = tyvar(intOf(tycon(c).kind))->offs;
2297 Int m = tycon(c).arity;
2298 switch (whatIs(tycon(c).what)) {
2300 case DATATYPE : { List cs = tycon(c).defn;
2301 if (whatIs(cs)==QUAL) {
2302 map3Proc(kindPred,line,beta,m,
2304 tycon(c).defn = cs = snd(snd(cs));
2306 for (; hasCfun(cs); cs=tl(cs)) {
2307 kindType(line,cfun,name(hd(cs)).type);
2312 default : checkKind(line,beta,m,tycon(c).defn,NIL,
2316 else { /* scan type exprs in class defn to*/
2317 List ms = fst(cclass(c).members);
2318 Int m = cclass(c).arity; /* determine the class signature */
2319 Int beta = newKindvars(m);
2320 kindPred(cclass(c).line,beta,m,cclass(c).head);
2321 map3Proc(kindPred,cclass(c).line,beta,m,cclass(c).supers);
2322 for (; nonNull(ms); ms=tl(ms)) {
2323 Int line = intOf(fst3(hd(ms)));
2324 Type type = thd3(hd(ms));
2325 kindType(line,"member function type signature",type);
2330 static Void local genTC(c) /* generalise kind inferred for */
2331 Cell c; { /* given tycon/class */
2333 tycon(c).kind = copyKindvar(intOf(tycon(c).kind));
2335 Printf("%s :: ",textToStr(tycon(c).text));
2336 printKind(stdout,tycon(c).kind);
2340 Kinds ks = cclass(c).kinds;
2341 for (; nonNull(ks); ks=tl(ks)) {
2342 hd(ks) = copyKindvar(intOf(hd(ks)));
2345 Printf("%s :: ",textToStr(cclass(c).text));
2346 printKinds(stdout,cclass(c).kinds);
2352 /* --------------------------------------------------------------------------
2353 * Static analysis of instance declarations:
2355 * The first part of the static analysis is performed as the declarations
2356 * are read during parsing:
2357 * - make new entry in instance table
2358 * - record line number of declaration
2359 * - build list of instances defined in current script for use in later
2360 * stages of static analysis.
2361 * ------------------------------------------------------------------------*/
2363 Void instDefn(line,head,ms) /* process new instance definition */
2364 Int line; /* definition line number */
2365 Cell head; /* inst header :: (context,Class) */
2366 List ms; { /* instance members */
2367 Inst nw = newInst();
2368 inst(nw).line = line;
2369 inst(nw).specifics = fst(head);
2370 inst(nw).head = snd(head);
2371 inst(nw).implements = ms;
2372 instDefns = cons(nw,instDefns);
2375 /* --------------------------------------------------------------------------
2376 * Further static analysis of instance declarations:
2378 * Makes the following checks:
2379 * - Class part of header has form C (T a1 ... an) where C is a known
2380 * class, and T is a known datatype constructor (or restricted synonym),
2381 * and there is no previous C-T instance, and (T a1 ... an) has a kind
2382 * appropriate for the class C.
2383 * - Each element of context is a valid class expression, with type vars
2384 * drawn from a1, ..., an.
2385 * - All bindings are function bindings
2386 * - All bindings define member functions for class C
2387 * - Arrange bindings into appropriate order for member list
2388 * - No top level type signature declarations
2389 * ------------------------------------------------------------------------*/
2391 Bool allowOverlap = FALSE; /* TRUE => allow overlapping insts */
2392 Name nameListMonad = NIL; /* builder function for List Monad */
2394 static Void local checkInstDefn(in) /* Validate instance declaration */
2396 Int line = inst(in).line;
2397 List tyvars = typeVarsIn(inst(in).head,NIL,NIL);
2399 if (haskell98) { /* Check for `simple' type */
2401 Cell t = arg(inst(in).head);
2402 for (; isAp(t); t=fun(t)) {
2403 if (!isVar(arg(t))) {
2405 "syntax error in instance head (variable expected)"
2408 if (varIsMember(textOf(arg(t)),tvs)) {
2409 ERRMSG(line) "repeated type variable \"%s\" in instance head",
2410 textToStr(textOf(arg(t)))
2413 tvs = cons(arg(t),tvs);
2417 "syntax error in instance head (constructor expected)"
2422 depPredExp(line,tyvars,inst(in).head);
2425 Type h = getHead(arg(inst(in).head));
2427 ERRMSG(line) "Cannot use type synonym in instance head"
2432 map2Proc(depPredExp,line,tyvars,inst(in).specifics);
2433 h98CheckCtxt(line,"instance definition",FALSE,inst(in).specifics,NIL);
2434 inst(in).numSpecifics = length(inst(in).specifics);
2435 inst(in).c = getHead(inst(in).head);
2436 if (!isClass(inst(in).c)) {
2437 ERRMSG(line) "Illegal predicate in instance declaration"
2441 if (inst(in).c==classEval) {
2442 ERRMSG(line) "Instances of class \"%s\" are generated automatically",
2443 textToStr(cclass(inst(in).c).text)
2447 kindInst(in,length(tyvars));
2450 if (nonNull(extractSigdecls(inst(in).implements))) {
2452 "Type signature declarations not permitted in instance declaration"
2455 if (nonNull(extractFixdecls(inst(in).implements))) {
2457 "Fixity declarations not permitted in instance declaration"
2460 inst(in).implements = classBindings("instance",
2462 extractBindings(inst(in).implements));
2463 inst(in).builder = newInstImp(in);
2464 if (!preludeLoaded && isNull(nameListMonad) && isAp(inst(in).head)
2465 && fun(inst(in).head)==classMonad && arg(inst(in).head)==typeList) {
2466 nameListMonad = inst(in).builder;
2470 static Void local insertInst(in) /* Insert instance into class */
2472 Class c = inst(in).c;
2473 List ins = cclass(c).instances;
2476 substitution(RESET);
2477 while (nonNull(ins)) { /* Look for overlap w/ other insts */
2478 Int alpha = newKindedVars(inst(in).kinds);
2479 Int beta = newKindedVars(inst(hd(ins)).kinds);
2480 if (unifyPred(inst(in).head,alpha,inst(hd(ins)).head,beta)) {
2481 Cell pi = copyPred(inst(in).head,alpha);
2482 if (allowOverlap && !haskell98) {
2483 Bool bef = instCompare(in,hd(ins));
2484 Bool aft = instCompare(hd(ins),in);
2485 if (bef && !aft) { /* in comes strictly before hd(ins)*/
2488 if (aft && !bef) { /* in comes strictly after hd(ins) */
2494 ERRMSG(inst(in).line) "Overlapping instances for class \"%s\"",
2495 textToStr(cclass(c).text)
2497 ERRTEXT "\n*** This instance : " ETHEN ERRPRED(inst(in).head);
2498 ERRTEXT "\n*** Overlaps with : " ETHEN
2499 ERRPRED(inst(hd(ins)).head);
2500 ERRTEXT "\n*** Common instance : " ETHEN
2505 prev = ins; /* No overlap detected, so move on */
2506 ins = tl(ins); /* to next instance */
2508 substitution(RESET);
2510 if (nonNull(prev)) { /* Insert instance at this point */
2511 tl(prev) = cons(in,ins);
2513 cclass(c).instances = cons(in,ins);
2517 static Bool local instCompare(ia,ib) /* See if ia is an instance of ib */
2519 Int alpha = newKindedVars(inst(ia).kinds);
2520 Int beta = newKindedVars(inst(ib).kinds);
2521 return matchPred(inst(ia).head,alpha,inst(ib).head,beta);
2524 static Name local newInstImp(in) /* Make definition for inst builder*/
2526 Name b = newName(inventText(),in);
2527 name(b).line = inst(in).line;
2528 name(b).arity = inst(in).numSpecifics;
2529 name(b).number = DFUNNAME;
2533 /* --------------------------------------------------------------------------
2534 * Kind checking of instance declaration headers:
2535 * ------------------------------------------------------------------------*/
2537 static Void local kindInst(in,freedom) /* check predicates in instance */
2542 emptySubstitution();
2543 beta = newKindvars(freedom);
2544 kindPred(inst(in).line,beta,freedom,inst(in).head);
2545 if (whatIs(inst(in).specifics)!=DERIVE) {
2546 map3Proc(kindPred,inst(in).line,beta,freedom,inst(in).specifics);
2548 for (inst(in).kinds = NIL; 0<freedom--; ) {
2549 inst(in).kinds = cons(copyKindvar(beta+freedom),inst(in).kinds);
2552 Printf("instance ");
2553 printPred(stdout,inst(in).head);
2555 printKinds(stdout,inst(in).kinds);
2558 emptySubstitution();
2561 /* --------------------------------------------------------------------------
2562 * Process derived instance requests:
2563 * ------------------------------------------------------------------------*/
2565 static List derivedInsts; /* list of derived instances */
2567 static Void local checkDerive(t,p,ts,ct)/* verify derived instance request */
2568 Tycon t; /* for tycon t, with explicit */
2569 List p; /* context p, component types ts */
2570 List ts; /* and named class ct */
2572 Int line = tycon(t).line;
2573 Class c = findClass(textOf(ct));
2575 ERRMSG(line) "Unknown class \"%s\" in derived instance",
2576 textToStr(textOf(ct))
2579 addDerInst(line,c,p,dupList(ts),t,tycon(t).arity);
2582 static Void local addDerInst(line,c,p,cts,t,a) /* Add a derived instance */
2589 Cell head = t; /* Build instance head */
2593 head = ap(head,mkOffset(i));
2599 inst(in).line = line;
2600 inst(in).head = head;
2601 inst(in).specifics = ap(DERIVE,pair(dupList(p),cts));
2602 inst(in).implements = NIL;
2603 inst(in).kinds = mkInt(a);
2604 derivedInsts = cons(in,derivedInsts);
2607 Void addTupInst(c,n) /* Request derived instance of c */
2608 Class c; /* for mkTuple(n) constructor */
2613 cts = cons(mkOffset(m),cts);
2616 addDerInst(0,c,NIL,cts,mkTuple(n),n);
2620 Void addEvalInst(line,t,arity,ctxt) /* Add dummy instance for Eval */
2625 Inst in = newInst();
2628 for (i=0; i<arity; i++) {
2629 head = ap(head,mkOffset(i));
2631 inst(in).line = line;
2632 inst(in).c = classEval;
2633 inst(in).head = ap(classEval,head);
2634 inst(in).specifics = ctxt;
2635 inst(in).builder = newInstImp(in);
2636 inst(in).numSpecifics = length(ctxt);
2638 cclass(classEval).instances
2639 = appendOnto(cclass(classEval).instances,singleton(in));
2644 Inst addRecShowInst(c,e) /* Generate instance for ShowRecRow*/
2645 Class c; /* c *must* be ShowRecRow */
2647 Inst in = newInst();
2649 inst(in).head = ap(c,ap2(e,aVar,bVar));
2650 inst(in).kinds = extKind;
2651 inst(in).specifics = cons(ap(classShow,aVar),
2653 cons(ap(c,bVar),NIL)));
2654 inst(in).numSpecifics = 3;
2655 inst(in).builder = implementRecShw(extText(e),in);
2656 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2660 Inst addRecEqInst(c,e) /* Generate instance for EqRecRow */
2661 Class c; /* c *must* be EqRecRow */
2663 Inst in = newInst();
2665 inst(in).head = ap(c,ap2(e,aVar,bVar));
2666 inst(in).kinds = extKind;
2667 inst(in).specifics = cons(ap(classEq,aVar),
2669 cons(ap(c,bVar),NIL)));
2670 inst(in).numSpecifics = 3;
2671 inst(in).builder = implementRecEq(extText(e),in);
2672 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2677 /* --------------------------------------------------------------------------
2678 * Calculation of contexts for derived instances:
2680 * Allowing arbitrary types to appear in contexts makes it rather harder
2681 * to decide what the context for a derived instance should be. For
2684 * data T a = MkT [a] deriving Show,
2686 * we could have either of the following:
2688 * instance (Show [a]) => Show (T a) where ...
2689 * instance (Show a) => Show (T a) where ...
2691 * (assuming, of course, that instance (Show a) => Show [a]). For now, we
2692 * choose to reduce contexts in the hope of detecting errors at an earlier
2693 * stage---in contrast with value definitions, there is no way for a user
2694 * to provide something analogous to a `type signature' by which they might
2695 * be able to control this behaviour themselves. We eliminate tautological
2696 * predicates, but only allow predicates to appear in the final result if
2697 * they have at least one argument with a variable at its head.
2699 * In general, we have to deal with mutually recursive instance declarations.
2700 * We find a solution in the obvious way by iterating to find a fixed point.
2701 * Of course, without restrictions on the form of instance declarations, we
2702 * cannot be sure that this will always terminate!
2704 * For each instance we maintain a pair of the form DERIVE (ctxt,ps).
2705 * Ctxt is a list giving the parts of the context that have been produced
2706 * so far in the form of predicate skeletons. During the calculation of
2707 * derived instances, we attach a dummy NIL value to the end of the list
2708 * which acts as a kind of `variable': other parts of the system maintain
2709 * pointers to this variable, and use it to detect when the context has
2710 * been extended with new elements. Meanwhile, ps is a list containing
2711 * predicates (pi,o) together with (delayed) substitutions of the form
2712 * (o,xs) where o is an offset and xs is one of the context variables
2713 * described above, which may have been partially instantiated.
2714 * ------------------------------------------------------------------------*/
2716 static Bool instsChanged;
2718 static Void local deriveContexts(is) /* Calc contexts for derived insts */
2720 emptySubstitution();
2721 mapProc(initDerInst,is); /* Prepare derived instances */
2723 do { /* Main calculation of contexts */
2724 instsChanged = FALSE;
2725 mapProc(calcInstPreds,is);
2726 } while (instsChanged);
2728 mapProc(tidyDerInst,is); /* Tidy up results */
2731 static Void local initDerInst(in) /* Prepare instance for calculation*/
2732 Inst in; { /* of derived instance context */
2733 Cell spcs = inst(in).specifics;
2734 Int beta = newKindedVars(inst(in).kinds);
2735 if (whatIs(spcs)!=DERIVE) {
2736 internal("initDerInst");
2738 fst(snd(spcs)) = appendOnto(fst(snd(spcs)),singleton(NIL));
2739 for (spcs=snd(snd(spcs)); nonNull(spcs); spcs=tl(spcs)) {
2740 hd(spcs) = ap2(inst(in).c,hd(spcs),mkInt(beta));
2742 inst(in).numSpecifics = beta;
2744 #ifdef DEBUG_DERIVING
2745 Printf("initDerInst: ");
2746 printPred(stdout,inst(in).head);
2748 printContext(stdout,snd(snd(inst(in).specifics)));
2753 static Void local calcInstPreds(in) /* Calculate next approximation */
2754 Inst in; { /* of the context for a derived */
2755 List retain = NIL; /* instance */
2756 List ps = snd(snd(inst(in).specifics));
2757 List spcs = fst(snd(inst(in).specifics));
2758 Int beta = inst(in).numSpecifics;
2760 #ifdef DEBUG_DERIVING
2761 Printf("calcInstPreds: ");
2762 printPred(stdout,inst(in).head);
2766 while (nonNull(ps)) {
2769 if (isInt(fst(p))) { /* Delayed substitution? */
2771 for (; nonNull(hd(qs)); qs=tl(qs)) {
2772 ps = cons(pair(hd(qs),fst(p)),ps);
2774 retain = cons(pair(fst(p),qs),retain);
2777 else if (isExt(fun(fst(p)))) { /* Lacks predicate */
2778 Text l = extText(fun(fst(p)));
2779 Type t = arg(fst(p));
2780 Int o = intOf(snd(p));
2785 h = getDerefHead(t,o);
2786 while (isExt(h) && argCount==2 && l!=extText(h)) {
2789 h = getDerefHead(t,o);
2791 if (argCount==0 && isOffset(h)) {
2792 maybeAddPred(ap(fun(fun(p)),h),o,beta,spcs);
2793 } else if (argCount!=0 || h!=typeNoRow) {
2794 Cell bpi = inst(in).head;
2795 Cell pi = copyPred(fun(p),intOf(snd(p)));
2796 ERRMSG(inst(in).line) "Cannot derive " ETHEN ERRPRED(bpi);
2797 ERRTEXT " because predicate " ETHEN ERRPRED(pi);
2798 ERRTEXT " does not hold\n"
2803 else { /* Class predicate */
2805 Int o = intOf(snd(p));
2806 Inst in1 = findInstFor(pi,o);
2808 List qs = inst(in1).specifics;
2809 Int off = mkInt(typeOff);
2810 if (whatIs(qs)==DERIVE) { /* Still being derived */
2811 for (qs=fst(snd(qs)); nonNull(hd(qs)); qs=tl(qs)) {
2812 ps = cons(pair(hd(qs),off),ps);
2814 retain = cons(pair(off,qs),retain);
2815 } else { /* Previously def'd inst */
2816 for (; nonNull(qs); qs=tl(qs)) {
2817 ps = cons(pair(hd(qs),off),ps);
2820 } else { /* No matching instance */
2822 while (isAp(qi) && isOffset(getDerefHead(arg(qi),o))) {
2826 Cell bpi = inst(in).head;
2827 pi = copyPred(pi,o);
2828 ERRMSG(inst(in).line) "An instance of " ETHEN ERRPRED(pi);
2829 ERRTEXT " is required to derive " ETHEN ERRPRED(bpi);
2833 maybeAddPred(pi,o,beta,spcs);
2838 snd(snd(inst(in).specifics)) = retain;
2841 static Void local maybeAddPred(pi,o,beta,ps)
2842 Cell pi; /* Add predicate pi to the list ps,*/
2843 Int o; /* setting the instsChanged flag if*/
2844 Int beta; /* pi is not already a member and */
2845 List ps; { /* using beta to adjust vars */
2846 Cell c = getHead(pi);
2847 for (; nonNull(ps); ps=tl(ps)) {
2848 if (isNull(hd(ps))) { /* reached the `dummy' end of list?*/
2849 hd(ps) = copyAdj(pi,o,beta);
2850 tl(ps) = pair(NIL,NIL);
2851 instsChanged = TRUE;
2853 } else if (c==getHead(hd(ps)) && samePred(pi,o,hd(ps),beta)) {
2859 static Cell local copyAdj(c,o,beta) /* Copy (c,o), replacing vars with */
2860 Cell c; /* offsets relative to beta. */
2863 switch (whatIs(c)) {
2864 case AP : { Cell l = copyAdj(fst(c),o,beta);
2865 Cell r = copyAdj(snd(c),o,beta);
2869 case OFFSET : { Int vn = o+offsetOf(c);
2870 Tyvar *tyv = tyvar(vn);
2872 return copyAdj(tyv->bound,tyv->offs,beta);
2875 if (vn<0 || vn>=NUM_OFFSETS) {
2876 internal("copyAdj");
2878 return mkOffset(vn);
2884 static Void local tidyDerInst(in) /* Tidy up results of derived inst */
2885 Inst in; { /* calculations */
2886 Int o = inst(in).numSpecifics;
2887 List ps = tl(rev(fst(snd(inst(in).specifics))));
2889 copyPred(inst(in).head,o);
2890 inst(in).specifics = simpleContext(ps,o);
2891 h98CheckCtxt(inst(in).line,"derived instance",FALSE,inst(in).specifics,in);
2892 inst(in).numSpecifics = length(inst(in).specifics);
2894 #ifdef DEBUG_DERIVING
2895 Printf("Derived instance: ");
2896 printContext(stdout,inst(in).specifics);
2898 printPred(stdout,inst(in).head);
2903 /* --------------------------------------------------------------------------
2904 * Generate code for derived instances:
2905 * ------------------------------------------------------------------------*/
2907 static Void local addDerivImp(in)
2910 Type t = getHead(arg(inst(in).head));
2911 Class c = inst(in).c;
2914 } else if (c==classOrd) {
2916 } else if (c==classEnum) {
2917 imp = deriveEnum(t);
2918 } else if (c==classIx) {
2920 } else if (c==classShow) {
2921 imp = deriveShow(t);
2922 } else if (c==classRead) {
2923 imp = deriveRead(t);
2924 } else if (c==classBounded) {
2925 imp = deriveBounded(t);
2927 ERRMSG(inst(in).line) "Cannot derive instances of class \"%s\"",
2928 textToStr(cclass(inst(in).c).text)
2932 kindInst(in,intOf(inst(in).kinds));
2934 inst(in).builder = newInstImp(in);
2935 inst(in).implements = classBindings("derived instance",
2941 /* --------------------------------------------------------------------------
2942 * Default definitions; only one default definition is permitted in a
2943 * given script file. If no default is supplied, then a standard system
2944 * default will be used where necessary.
2945 * ------------------------------------------------------------------------*/
2947 Void defaultDefn(line,defs) /* Handle default types definition */
2950 if (defaultLine!=0) {
2951 ERRMSG(line) "Multiple default declarations are not permitted in" ETHEN
2952 ERRTEXT "a single script file.\n"
2955 defaultDefns = defs;
2959 static Void local checkDefaultDefns() { /* check that default types are */
2960 List ds = NIL; /* well-kinded instances of Num */
2962 if (defaultLine!=0) {
2963 map2Over(depTypeExp,defaultLine,NIL,defaultDefns);
2964 emptySubstitution();
2966 map2Proc(kindType,defaultLine,"default type",defaultDefns);
2968 emptySubstitution();
2969 mapOver(fullExpand,defaultDefns);
2971 defaultDefns = stdDefaults;
2974 if (isNull(classNum)) {
2975 classNum = findClass(findText("Num"));
2978 for (ds=defaultDefns; nonNull(ds); ds=tl(ds)) {
2979 if (isNull(provePred(NIL,NIL,ap(classNum,hd(ds))))) {
2981 "Default types must be instances of the Num class"
2989 /* --------------------------------------------------------------------------
2990 * Foreign import declarations are Hugs' equivalent of GHC's ccall mechanism.
2991 * They are used to "import" C functions into a module.
2992 * They are usually not written by hand but, rather, generated automatically
2993 * by GreenCard, IDL compilers or whatever.
2995 * Foreign export declarations generate C wrappers for Hugs functions.
2996 * Hugs only provides "foreign export dynamic" because it's not obvious
2997 * what "foreign export static" would mean in an interactive setting.
2998 * ------------------------------------------------------------------------*/
3000 Void foreignImport(line,extName,intName,type) /* Handle foreign imports */
3005 Text t = textOf(intName);
3006 Name n = findName(t);
3007 Int l = intOf(line);
3011 } else if (name(n).defn!=PREDEFINED) {
3012 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
3016 name(n).defn = extName;
3017 name(n).type = type;
3018 foreignImports = cons(n,foreignImports);
3021 static Void local checkForeignImport(p) /* Check foreign import */
3023 emptySubstitution();
3024 name(p).type = checkSigType(name(p).line,
3025 "foreign import declaration",
3028 /* We don't expand synonyms here because we don't want the IO
3029 * part to be expanded.
3030 * name(p).type = fullExpand(name(p).type);
3032 implementForeignImport(p);
3035 Void foreignExport(line,extName,intName,type)/* Handle foreign exports */
3040 Text t = textOf(intName);
3041 Name n = findName(t);
3042 Int l = intOf(line);
3046 } else if (name(n).defn!=PREDEFINED) {
3047 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
3051 name(n).defn = NIL; /* nothing to say */
3052 name(n).type = type;
3053 foreignExports = cons(n,foreignExports);
3056 static Void local checkForeignExport(p) /* Check foreign export */
3058 emptySubstitution();
3059 name(p).type = checkSigType(name(p).line,
3060 "foreign export declaration",
3063 implementForeignExport(p);
3071 /* --------------------------------------------------------------------------
3072 * Primitive definitions are usually only included in the first script
3073 * file read - the prelude. A primitive definition associates a variable
3074 * name with a string (which identifies a built-in primitive) and a type.
3075 * ------------------------------------------------------------------------*/
3077 Void primDefn(line,prims,type) /* Handle primitive definitions */
3081 primDefns = cons(triple(line,prims,type),primDefns);
3084 static List local checkPrimDefn(pd) /* Check primitive definition */
3086 Int line = intOf(fst3(pd));
3087 List prims = snd3(pd);
3088 Type type = thd3(pd);
3089 emptySubstitution();
3090 type = checkSigType(line,"primitive definition",fst(hd(prims)),type);
3091 for (; nonNull(prims); prims=tl(prims)) {
3093 Bool same = isVar(p);
3094 Text pt = textOf(same ? p : fst(p));
3095 String pr = textToStr(textOf(same ? p : snd(p)));
3096 hd(prims) = addNewPrim(line,pt,pr,type);
3101 static Name local addNewPrim(l,vn,s,t) /* make binding of variable vn to */
3102 Int l; /* primitive function referred */
3103 Text vn; /* to by s, with given type t */
3106 Name n = findName(vn);
3109 n = newName(vn,NIL);
3110 } else if (name(n).defn!=PREDEFINED) {
3111 duplicateError(l,name(n).mod,vn,"primitive");
3123 /* --------------------------------------------------------------------------
3124 * Static analysis of patterns:
3126 * Patterns are parsed as ordinary (atomic) expressions. Static analysis
3127 * makes the following checks:
3128 * - Patterns are well formed (according to pattern syntax), including the
3129 * special case of (n+k) patterns.
3130 * - All constructor functions have been defined and are used with the
3131 * correct number of arguments.
3132 * - No variable name is used more than once in a pattern.
3134 * The list of pattern variables occuring in each pattern is accumulated in
3135 * a global list `patVars', which must be initialised to NIL at appropriate
3136 * points before using these routines to check for valid patterns. This
3137 * mechanism enables the pattern checking routine to be mapped over a list
3138 * of patterns, ensuring that no variable occurs more than once in the
3139 * complete pattern list (as is required on the lhs of a function defn).
3140 * ------------------------------------------------------------------------*/
3142 static List patVars; /* List of vars bound in pattern */
3144 static Cell local checkPat(line,p) /* Check valid pattern syntax */
3147 switch (whatIs(p)) {
3149 case VAROPCELL : addToPatVars(line,p);
3152 case INFIX : return checkPat(line,tidyInfix(line,snd(p)));
3154 case AP : return checkMaybeCnkPat(line,p);
3159 case CONOPCELL : return checkApPat(line,0,p);
3169 case FLOATCELL : break;
3170 case INTCELL : break;
3172 case ASPAT : addToPatVars(line,fst(snd(p)));
3173 snd(snd(p)) = checkPat(line,snd(snd(p)));
3176 case LAZYPAT : snd(p) = checkPat(line,snd(p));
3179 case FINLIST : map1Over(checkPat,line,snd(p));
3182 case CONFLDS : depConFlds(line,p,TRUE);
3185 case ESIGN : snd(snd(p)) = checkPatType(line,
3189 fst(snd(p)) = checkPat(line,fst(snd(p)));
3192 default : ERRMSG(line) "Illegal pattern syntax"
3198 static Cell local checkMaybeCnkPat(l,p)/* Check applicative pattern with */
3199 Int l; /* the possibility of n+k pattern */
3202 Cell h = getHead(p);
3204 if (argCount==2 && isVar(h) && textOf(h)==textPlus) { /* n+k */
3205 Cell v = arg(fun(p));
3206 if (!isInt(arg(p))) {
3207 ERRMSG(l) "Second argument in (n+k) pattern must be an integer"
3210 if (intOf(arg(p))<=0) {
3211 ERRMSG(l) "Integer k in (n+k) pattern must be > 0"
3214 fst(fun(p)) = ADDPAT;
3215 intValOf(fun(p)) = intOf(arg(p));
3216 arg(p) = checkPat(l,v);
3220 return checkApPat(l,0,p);
3223 static Cell local checkApPat(line,args,p)
3224 Int line; /* check validity of application */
3225 Int args; /* of constructor to arguments */
3227 switch (whatIs(p)) {
3228 case AP : fun(p) = checkApPat(line,args+1,fun(p));
3229 arg(p) = checkPat(line,arg(p));
3232 case TUPLE : if (tupleOf(p)!=args) {
3233 ERRMSG(line) "Illegal tuple pattern"
3239 case EXT : h98DoesntSupport(line,"extensible records");
3241 ERRMSG(line) "Illegal record pattern"
3247 case QUALIDENT : if (!isQCon(p)) {
3249 "Illegal use of qualified variable in pattern"
3252 /* deliberate fall through */
3254 case CONOPCELL : p = conDefined(line,p);
3255 checkCfunArgs(line,p,args);
3258 case NAME : checkIsCfun(line,p);
3259 checkCfunArgs(line,p,args);
3262 default : ERRMSG(line) "Illegal pattern syntax"
3268 static Void local addToPatVars(line,v) /* Add variable v to list of vars */
3269 Int line; /* in current pattern, checking */
3270 Cell v; { /* for repeated variables. */
3275 for (; nonNull(n); p=n, n=tl(n)) {
3276 if (textOf(hd(n))==t) {
3277 ERRMSG(line) "Repeated variable \"%s\" in pattern",
3284 patVars = cons(v,NIL);
3286 tl(p) = cons(v,NIL);
3290 static Name local conDefined(line,nm) /* check that nm is the name of a */
3291 Int line; /* previously defined constructor */
3292 Cell nm; { /* function. */
3293 Name n = findQualName(nm);
3295 ERRMSG(line) "Undefined constructor function \"%s\"", identToStr(nm)
3298 checkIsCfun(line,n);
3302 static Void local checkIsCfun(line,c) /* Check that c is a constructor fn */
3306 ERRMSG(line) "\"%s\" is not a constructor function",
3307 textToStr(name(c).text)
3312 static Void local checkCfunArgs(line,c,args)
3313 Int line; /* Check constructor applied with */
3314 Cell c; /* correct number of arguments */
3316 Int a = userArity(c);
3319 "Constructor \"%s\" must have exactly %d argument%s in pattern",
3320 textToStr(name(c).text), a, ((a==1)?"":"s")
3325 static Cell local checkPatType(l,wh,e,t)/* Check type appearing in pattern */
3330 List tvs = typeVarsIn(t,NIL,NIL);
3331 h98DoesntSupport(l,"pattern type annotations");
3332 for (; nonNull(tvs); tvs=tl(tvs)) {
3333 Int beta = newKindvars(1);
3334 hd(btyvars) = cons(pair(hd(tvs),mkInt(beta)), hd(btyvars));
3336 t = checkSigType(l,"pattern type",e,t);
3337 if (isPolyType(t) || whatIs(t)==QUAL || whatIs(t)==RANK2) {
3338 ERRMSG(l) "Illegal syntax in %s type annotation", wh
3344 static Cell local applyBtyvs(pat) /* Record bound type vars in pat */
3346 List bts = hd(btyvars);
3349 pat = ap(BIGLAM,pair(bts,pat));
3350 for (; nonNull(bts); bts=tl(bts)) {
3351 snd(hd(bts)) = copyKindvar(intOf(snd(hd(bts))));
3357 /* --------------------------------------------------------------------------
3358 * Maintaining lists of bound variables and local definitions, for
3359 * dependency and scope analysis.
3360 * ------------------------------------------------------------------------*/
3362 static List bounds; /* list of lists of bound vars */
3363 static List bindings; /* list of lists of binds in scope */
3364 static List depends; /* list of lists of dependents */
3366 /* bounds :: [[Var]] -- var equality used on Vars */
3367 /* bindings :: [[([Var],?)]] -- var equality used on Vars */
3368 /* depends :: [[Var]] -- pointer equality used on Vars */
3370 #define saveBvars() hd(bounds) /* list of bvars in current scope */
3371 #define restoreBvars(bs) hd(bounds)=bs /* restore list of bound variables */
3373 static Cell local bindPat(line,p) /* add new bound vars for pattern */
3377 p = checkPat(line,p);
3378 hd(bounds) = revOnto(patVars,hd(bounds));
3382 static Void local bindPats(line,ps) /* add new bound vars for patterns */
3386 map1Over(checkPat,line,ps);
3387 hd(bounds) = revOnto(patVars,hd(bounds));
3390 /* --------------------------------------------------------------------------
3391 * Before processing value and type signature declarations, all data and
3392 * type definitions have been processed so that:
3393 * - all valid type constructors (with their arities) are known.
3394 * - all valid constructor functions (with their arities and types) are
3397 * The result of parsing a list of value declarations is a list of Eqns:
3398 * Eqn ::= (SIGDECL,(Line,[Var],type))
3399 * | (FIXDECL,(Line,[Op],SyntaxInt))
3401 * The ordering of the equations in this list is the reverse of the original
3402 * ordering in the script parsed. This is a consequence of the structure of
3403 * the parser ... but also turns out to be most convenient for the static
3406 * As the first stage of the static analysis of value declarations, each
3407 * list of Eqns is converted to a list of Bindings. As part of this
3409 * - The ordering of the list of Bindings produced is the same as in the
3411 * - When a variable (function) is defined over a number of lines, all
3412 * of the definitions should appear together and each should give the
3413 * same arity to the variable being defined.
3414 * - No variable can have more than one definition.
3415 * - For pattern bindings:
3416 * - Each lhs is a valid pattern/function lhs, all constructor functions
3417 * have been defined and are used with the correct number of arguments.
3418 * - Each lhs contains no repeated pattern variables.
3419 * - Each equation defines at least one variable (e.g. True = False is
3421 * - Types appearing in type signatures are well formed:
3422 * - Type constructors used are defined and used with correct number
3424 * - type variables are replaced by offsets, type constructor names
3426 * - Every variable named in a type signature declaration is defined by
3427 * one or more equations elsewhere in the script.
3428 * - No variable has more than one type declaration.
3429 * - Similar properties for fixity declarations.
3431 * ------------------------------------------------------------------------*/
3433 #define bindingAttr(b) fst(snd(b)) /* type(s)/fixity(ies) for binding */
3434 #define fbindAlts(b) snd(snd(b)) /* alternatives for function binding*/
3436 static List local extractSigdecls(es) /* Extract the SIGDECLS from list */
3437 List es; { /* of equations */
3438 List sigdecls = NIL; /* :: [(Line,[Var],Type)] */
3440 for(; nonNull(es); es=tl(es)) {
3441 if (fst(hd(es))==SIGDECL) { /* type-declaration? */
3442 Pair sig = snd(hd(es));
3443 Int line = intOf(fst3(sig));
3444 List vs = snd3(sig);
3445 for(; nonNull(vs); vs=tl(vs)) {
3446 if (isQualIdent(hd(vs))) {
3447 ERRMSG(line) "Type signature for qualified variable \"%s\" is not allowed",
3452 sigdecls = cons(sig,sigdecls); /* discard SIGDECL tag*/
3458 static List local extractFixdecls(es) /* Extract the FIXDECLS from list */
3459 List es; { /* of equations */
3460 List fixdecls = NIL; /* :: [(Line,SyntaxInt,[Op])] */
3462 for(; nonNull(es); es=tl(es)) {
3463 if (fst(hd(es))==FIXDECL) { /* fixity declaration?*/
3464 fixdecls = cons(snd(hd(es)),fixdecls); /* discard FIXDECL tag*/
3470 static List local extractBindings(ds) /* extract untyped bindings from */
3471 List ds; { /* given list of equations */
3472 Cell lastVar = NIL; /* = var def'd in last eqn (if any)*/
3473 Int lastArity = 0; /* = number of args in last defn */
3474 List bs = NIL; /* :: [Binding] */
3476 for(; nonNull(ds); ds=tl(ds)) {
3478 if (fst(d)==FUNBIND) { /* Function bindings */
3479 Cell rhs = snd(snd(d));
3480 Int line = rhsLine(rhs);
3481 Cell lhs = fst(snd(d));
3482 Cell v = getHead(lhs);
3483 Cell newAlt = pair(getArgs(lhs),rhs);
3485 internal("FUNBIND");
3487 if (nonNull(lastVar) && textOf(v)==textOf(lastVar)) {
3488 if (argCount!=lastArity) {
3489 ERRMSG(line) "Equations give different arities for \"%s\"",
3490 textToStr(textOf(v))
3493 fbindAlts(hd(bs)) = cons(newAlt,fbindAlts(hd(bs)));
3497 lastArity = argCount;
3498 notDefined(line,bs,v);
3499 bs = cons(pair(v,pair(NIL,singleton(newAlt))),bs);
3502 } else if (fst(d)==PATBIND) { /* Pattern bindings */
3503 Cell rhs = snd(snd(d));
3504 Int line = rhsLine(rhs);
3505 Cell pat = fst(snd(d));
3506 while (whatIs(pat)==ESIGN) {/* Move type annotations to rhs */
3507 Cell p = fst(snd(pat));
3508 fst(snd(pat)) = rhs;
3509 snd(snd(d)) = rhs = pat;
3510 fst(snd(d)) = pat = p;
3513 if (isVar(pat)) { /* Convert simple pattern bind to */
3514 notDefined(line,bs,pat);/* a function binding */
3515 bs = cons(pair(pat,pair(NIL,singleton(pair(NIL,rhs)))),bs);
3517 List vs = getPatVars(line,pat,NIL);
3519 ERRMSG(line) "No variables defined in lhs pattern"
3522 map2Proc(notDefined,line,bs,vs);
3523 bs = cons(pair(vs,pair(NIL,snd(d))),bs);
3531 static List local getPatVars(line,p,vs) /* Find list of variables bound in */
3532 Int line; /* pattern p */
3535 switch (whatIs(p)) {
3537 vs = getPatVars(line,arg(p),vs);
3540 return vs; /* Ignore head of application */
3542 case CONFLDS : { List pfs = snd(snd(p));
3543 for (; nonNull(pfs); pfs=tl(pfs)) {
3544 if (isVar(hd(pfs))) {
3545 vs = addPatVar(line,hd(pfs),vs);
3547 vs = getPatVars(line,snd(hd(pfs)),vs);
3553 case FINLIST : { List ps = snd(p);
3554 for (; nonNull(ps); ps=tl(ps)) {
3555 vs = getPatVars(line,hd(ps),vs);
3560 case ESIGN : return getPatVars(line,fst(snd(p)),vs);
3565 case INFIX : return getPatVars(line,snd(p),vs);
3567 case ASPAT : return addPatVar(line,fst(snd(p)),
3568 getPatVars(line,snd(snd(p)),vs));
3571 case VAROPCELL : return addPatVar(line,p,vs);
3581 case WILDCARD : return vs;
3583 default : internal("getPatVars");
3588 static List local addPatVar(line,v,vs) /* Add var to list of previously */
3589 Int line; /* encountered variables */
3592 if (varIsMember(textOf(v),vs)) {
3593 ERRMSG(line) "Repeated use of variable \"%s\" in pattern binding",
3594 textToStr(textOf(v))
3600 static List local eqnsToBindings(es,ts,cs,ps)
3601 List es; /* Convert list of equations to */
3602 List ts; /* list of typed bindings */
3605 List bs = extractBindings(es);
3606 map1Proc(addSigdecl,bs,extractSigdecls(es));
3607 map4Proc(addFixdecl,bs,ts,cs,ps,extractFixdecls(es));
3611 static Void local notDefined(line,bs,v)/* check if name already defined in */
3612 Int line; /* list of bindings */
3615 if (nonNull(findBinding(textOf(v),bs))) {
3616 ERRMSG(line) "\"%s\" multiply defined", textToStr(textOf(v))
3621 static Cell local findBinding(t,bs) /* look for binding for variable t */
3622 Text t; /* in list of bindings bs */
3624 for (; nonNull(bs); bs=tl(bs)) {
3625 if (isVar(fst(hd(bs)))) { /* function-binding? */
3626 if (textOf(fst(hd(bs)))==t) {
3629 } else if (nonNull(varIsMember(t,fst(hd(bs))))){/* pattern-binding?*/
3636 static Cell local getAttr(bs,v) /* Locate type/fixity attribute */
3637 List bs; /* for variable v in bindings bs */
3640 Cell b = findBinding(t,bs);
3642 if (isNull(b)) { /* No binding */
3644 } else if (isVar(fst(b))) { /* func binding? */
3645 if (isNull(bindingAttr(b))) {
3646 bindingAttr(b) = pair(NIL,NIL);
3648 return bindingAttr(b);
3649 } else { /* pat binding? */
3651 List as = bindingAttr(b);
3654 bindingAttr(b) = as = replicate(length(vs),NIL);
3657 while (nonNull(vs) && t!=textOf(hd(vs))) {
3663 internal("getAttr");
3664 } else if (isNull(hd(as))) {
3665 hd(as) = pair(NIL,NIL);
3671 static Void local addSigdecl(bs,sigdecl)/* add type information to bindings*/
3672 List bs; /* :: [Binding] */
3673 Cell sigdecl; { /* :: (Line,[Var],Type) */
3674 Int l = intOf(fst3(sigdecl));
3675 List vs = snd3(sigdecl);
3676 Type type = checkSigType(l,"type declaration",hd(vs),thd3(sigdecl));
3678 for (; nonNull(vs); vs=tl(vs)) {
3680 Pair attr = getAttr(bs,v);
3682 ERRMSG(l) "Missing binding for variable \"%s\" in type signature",
3683 textToStr(textOf(v))
3685 } else if (nonNull(fst(attr))) {
3686 ERRMSG(l) "Repeated type signature for \"%s\"",
3687 textToStr(textOf(v))
3694 static Void local addFixdecl(bs,ts,cs,ps,fixdecl)
3700 Int line = intOf(fst3(fixdecl));
3701 List ops = snd3(fixdecl);
3702 Cell sy = thd3(fixdecl);
3704 for (; nonNull(ops); ops=tl(ops)) {
3706 Text t = textOf(op);
3707 Cell attr = getAttr(bs,op);
3708 if (nonNull(attr)) { /* Found name in binding? */
3709 if (nonNull(snd(attr))) {
3713 } else { /* Look in tycons, classes, prims */
3718 for (; isNull(n) && nonNull(ts1); ts1=tl(ts1)) { /* tycons */
3720 if (tycon(tc).what==DATATYPE || tycon(tc).what==NEWTYPE) {
3721 n = nameIsMember(t,tycon(tc).defn);
3724 for (; isNull(n) && nonNull(cs1); cs1=tl(cs1)) { /* classes */
3725 n = nameIsMember(t,cclass(hd(cs1)).members);
3727 for (; isNull(n) && nonNull(ps1); ps1=tl(ps1)) { /* prims */
3728 n = nameIsMember(t,hd(ps1));
3733 } else if (name(n).syntax!=NO_SYNTAX) {
3736 name(n).syntax = intOf(sy);
3741 static Void local dupFixity(line,t) /* Report repeated fixity decl */
3745 "Repeated fixity declaration for operator \"%s\"", textToStr(t)
3749 static Void local missFixity(line,t) /* Report missing op for fixity */
3753 "Cannot find binding for operator \"%s\" in fixity declaration",
3758 /* --------------------------------------------------------------------------
3759 * Dealing with infix operators:
3761 * Expressions involving infix operators or unary minus are parsed as
3762 * elements of the following type:
3764 * data InfixExp = Only Exp | Neg InfixExp | Infix InfixExp Op Exp
3766 * (The algorithms here do not assume that negation can be applied only once,
3767 * i.e., that - - x is a syntax error, as required by the Haskell report.
3768 * Instead, that restriction is captured by the grammar itself, given above.)
3770 * There are rules of precedence and grouping, expressed by two functions:
3772 * prec :: Op -> Int; assoc :: Op -> Assoc (Assoc = {L, N, R})
3774 * InfixExp values are rearranged accordingly when a complete expression
3775 * has been read using a simple shift-reduce parser whose result may be taken
3776 * to be a value of the following type:
3778 * data Exp = Atom Int | Negate Exp | Apply Op Exp Exp | Error String
3780 * The machine on which this parser is based can be defined as follows:
3782 * tidy :: InfixExp -> [(Op,Exp)] -> Exp
3783 * tidy (Only a) [] = a
3784 * tidy (Only a) ((o,b):ss) = tidy (Only (Apply o a b)) ss
3785 * tidy (Infix a o b) [] = tidy a [(o,b)]
3786 * tidy (Infix a o b) ((p,c):ss)
3787 * | shift o p = tidy a ((o,b):(p,c):ss)
3788 * | red o p = tidy (Infix a o (Apply p b c)) ss
3789 * | ambig o p = Error "ambiguous use of operators"
3790 * tidy (Neg e) [] = tidy (tidyNeg e) []
3791 * tidy (Neg e) ((o,b):ss)
3792 * | nshift o = tidy (Neg (underNeg o b e)) ss
3793 * | nred o = tidy (tidyNeg e) ((o,b):ss)
3794 * | nambig o = Error "illegal use of negation"
3796 * At each stage, the parser can either shift, reduce, accept, or error.
3797 * The transitions when dealing with juxtaposed operators o and p are
3798 * determined by the following rules:
3800 * shift o p = (prec o > prec p)
3801 * || (prec o == prec p && assoc o == L && assoc p == L)
3803 * red o p = (prec o < prec p)
3804 * || (prec o == prec p && assoc o == R && assoc p == R)
3806 * ambig o p = (prec o == prec p)
3807 * && (assoc o == N || assoc p == N || assoc o /= assoc p)
3809 * The transitions when dealing with juxtaposed unary minus and infix
3810 * operators are as follows. The precedence of unary minus (infixl 6) is
3811 * hardwired in to these definitions, as it is to the definitions of the
3812 * Haskell grammar in the official report.
3814 * nshift o = (prec o > 6)
3815 * nred o = (prec o < 6) || (prec o == 6 && assoc o == L)
3816 * nambig o = prec o == 6 && (assoc o == R || assoc o == N)
3818 * An InfixExp of the form (Neg e) means negate the last thing in
3819 * the InfixExp e; we can force this negation using:
3821 * tidyNeg :: OpExp -> OpExp
3822 * tidyNeg (Only e) = Only (Negate e)
3823 * tidyNeg (Infix a o b) = Infix a o (Negate b)
3824 * tidyNeg (Neg e) = tidyNeg (tidyNeg e)
3826 * On the other hand, if we want to sneak application of an infix operator
3827 * under a negation, then we use:
3829 * underNeg :: Op -> Exp -> OpExp -> OpExp
3830 * underNeg o b (Only e) = Only (Apply o e b)
3831 * underNeg o b (Neg e) = Neg (underNeg o b e)
3832 * underNeg o b (Infix e p f) = Infix e p (Apply o f b)
3834 * As a concession to efficiency, we lower the number of calls to syntaxOf
3835 * by keeping track of the values of sye, sys throughout the process. The
3836 * value APPLIC is used to indicate that the syntax value is unknown.
3837 * ------------------------------------------------------------------------*/
3839 static Cell local tidyInfix(line,e) /* Convert infixExp to Exp */
3841 Cell e; { /* :: OpExp */
3842 Cell s = NIL; /* :: [(Op,Exp)] */
3843 Syntax sye = APPLIC; /* Syntax of op in e (init unknown)*/
3844 Syntax sys = APPLIC; /* Syntax of op in s (init unknown)*/
3847 while (fst(d)!=ONLY) { /* Attach fixities to operators */
3851 fun(fun(d)) = attachFixity(line,fun(fun(d)));
3857 switch (whatIs(e)) {
3858 case ONLY : e = snd(e);
3859 while (nonNull(s)) {
3860 Cell next = arg(fun(s));
3862 fun(fun(s)) = snd(fun(fun(s)));
3868 case NEG : if (nonNull(s)) {
3869 if (sys==APPLIC) { /* calculate sys */
3870 sys = intOf(fst(fun(fun(s))));
3873 if (precOf(sys)==UMINUS_PREC && /* nambig */
3874 assocOf(sys)!=UMINUS_ASSOC) {
3876 "Ambiguous use of unary minus with \""
3877 ETHEN ERREXPR(snd(fun(fun(s))));
3882 if (precOf(sys)>UMINUS_PREC) { /* nshift */
3886 while (whatIs(e1)==NEG)
3888 arg(fun(t)) = arg(e1);
3889 fun(fun(t)) = snd(fun(fun(t)));
3896 /* Intentional fall-thru for nreduce and isNull(s) */
3898 { Cell prev = e; /* e := tidyNeg e */
3899 Cell temp = arg(prev);
3901 for (; whatIs(temp)==NEG; nneg++) {
3902 fun(prev) = nameNegate;
3906 if (isInt(arg(temp))) { /* special cases */
3907 if (nneg&1) /* for literals */
3908 arg(temp) = mkInt(-intOf(arg(temp)));
3911 else if (isBignum(arg(temp))) {
3913 arg(temp) = bigNeg(arg(temp));
3916 else if (isFloat(arg(temp))) {
3918 arg(temp) = floatNegate(arg(temp));
3919 //mkFloat(-floatOf(arg(temp)));
3922 fun(prev) = nameNegate;
3923 arg(prev) = arg(temp);
3930 default : if (isNull(s)) {/* Move operation onto empty stack */
3931 Cell next = arg(fun(e));
3938 else { /* deal with pair of operators */
3940 if (sye==APPLIC) { /* calculate sys and sye */
3941 sye = intOf(fst(fun(fun(e))));
3944 sys = intOf(fst(fun(fun(s))));
3947 if (precOf(sye)==precOf(sys) && /* ambig */
3948 (assocOf(sye)!=assocOf(sys) ||
3949 assocOf(sye)==NON_ASS)) {
3950 ERRMSG(line) "Ambiguous use of operator \""
3951 ETHEN ERREXPR(snd(fun(fun(e))));
3952 ERRTEXT "\" with \""
3953 ETHEN ERREXPR(snd(fun(fun(s))));
3958 if (precOf(sye)>precOf(sys) || /* shift */
3959 (precOf(sye)==precOf(sys) &&
3960 assocOf(sye)==LEFT_ASS &&
3961 assocOf(sys)==LEFT_ASS)) {
3962 Cell next = arg(fun(e));
3970 Cell next = arg(fun(s));
3971 arg(fun(s)) = arg(e);
3972 fun(fun(s)) = snd(fun(fun(s)));
3983 static Pair local attachFixity(line,op) /* Attach fixity to operator in an */
3984 Int line; /* infix expression */
3986 Syntax sy = DEF_OPSYNTAX;
3988 switch (whatIs(op)) {
3990 case VARIDCELL : if ((sy=lookupSyntax(textOf(op)))==NO_SYNTAX) {
3991 Name n = findName(textOf(op));
3993 ERRMSG(line) "Undefined variable \"%s\"",
3994 textToStr(textOf(op))
4003 case CONIDCELL : sy = syntaxOf(op = conDefined(line,op));
4006 case QUALIDENT : { Name n = findQualName(op);
4012 "Undefined qualified variable \"%s\"",
4022 return pair(mkInt(sy),op); /* Pair fixity with (possibly) */
4023 /* translated operator */
4026 static Syntax local lookupSyntax(t) /* Try to find fixity for var in */
4027 Text t; { /* enclosing bindings */
4028 List bounds1 = bounds;
4029 List bindings1 = bindings;
4031 while (nonNull(bindings1)) {
4032 if (nonNull(varIsMember(t,hd(bounds1)))) {
4033 return DEF_OPSYNTAX;
4035 Cell b = findBinding(t,hd(bindings1));
4037 Cell a = fst(snd(b));
4038 if (isVar(fst(b))) { /* Function binding */
4039 if (nonNull(a) && nonNull(snd(a))) {
4040 return intOf(snd(a));
4042 } else { /* Pattern binding */
4044 while (nonNull(vs) && nonNull(a)) {
4045 if (t==textOf(hd(vs))) {
4046 if (nonNull(hd(a)) && isInt(snd(hd(a)))) {
4047 return intOf(snd(hd(a)));
4055 return DEF_OPSYNTAX;
4058 bounds1 = tl(bounds1);
4059 bindings1 = tl(bindings1);
4064 /* --------------------------------------------------------------------------
4065 * To facilitate dependency analysis, lists of bindings are temporarily
4066 * augmented with an additional field, which is used in two ways:
4067 * - to build the `adjacency lists' for the dependency graph. Represented by
4068 * a list of pointers to other bindings in the same list of bindings.
4069 * - to hold strictly positive integer values (depth first search numbers) of
4070 * elements `on the stack' during the strongly connected components search
4071 * algorithm, or a special value mkInt(0), once the binding has been added
4072 * to a particular strongly connected component.
4074 * Using this extra field, the type of each list of declarations during
4075 * dependency analysis is [Binding'] where:
4077 * Binding' ::= (Var, (Attr, (Dep, [Alt]))) -- function binding
4078 * | ([Var], ([Attr], (Dep, (Pat,Rhs)))) -- pattern binding
4080 * ------------------------------------------------------------------------*/
4082 #define depVal(d) (fst(snd(snd(d)))) /* Access to dependency information*/
4084 static List local dependencyAnal(bs) /* Separate lists of bindings into */
4085 List bs; { /* mutually recursive groups in */
4086 /* order of dependency */
4087 mapProc(addDepField,bs); /* add extra field for dependents */
4088 mapProc(depBinding,bs); /* find dependents of each binding */
4089 bs = bscc(bs); /* sort to strongly connected comps*/
4090 mapProc(remDepField,bs); /* remove dependency info field */
4094 static List local topDependAnal(bs) /* Like dependencyAnal(), but at */
4095 List bs; { /* top level, reporting on progress*/
4099 setGoal("Dependency analysis",(Target)(length(bs)));
4101 mapProc(addDepField,bs); /* add extra field for dependents */
4102 for (xs=bs; nonNull(xs); xs=tl(xs)) {
4104 //Printf("\n-----------------------------------------\n" ); print(hd(xs),1000); Printf("\n");
4106 emptySubstitution();
4108 soFar((Target)(i++));
4110 bs = bscc(bs); /* sort to strongly connected comps */
4111 mapProc(remDepField,bs); /* remove dependency info field */
4116 static Void local addDepField(b) /* add extra field to binding to */
4117 Cell b; { /* hold list of dependents */
4118 snd(snd(b)) = pair(NIL,snd(snd(b)));
4121 static Void local remDepField(bs) /* remove dependency field from */
4122 List bs; { /* list of bindings */
4123 mapProc(remDepField1,bs);
4126 static Void local remDepField1(b) /* remove dependency field from */
4127 Cell b; { /* single binding */
4128 snd(snd(b)) = snd(snd(snd(b)));
4131 static Void local clearScope() { /* initialise dependency scoping */
4137 static Void local withinScope(bs) /* Enter scope of bindings bs */
4139 bounds = cons(NIL,bounds);
4140 bindings = cons(bs,bindings);
4141 depends = cons(NIL,depends);
4144 static Void local leaveScope() { /* Leave scope of last withinScope */
4145 List bs = hd(bindings); /* Remove fixity info from binds */
4146 Bool toplevel = isNull(tl(bindings));
4147 for (; nonNull(bs); bs=tl(bs)) {
4149 if (isVar(fst(b))) { /* Variable binding */
4150 Cell a = fst(snd(b));
4153 saveSyntax(fst(b),snd(a));
4155 fst(snd(b)) = fst(a);
4157 } else { /* Pattern binding */
4159 List as = fst(snd(b));
4160 while (nonNull(vs) && nonNull(as)) {
4161 if (isPair(hd(as))) {
4163 saveSyntax(hd(vs),snd(hd(as)));
4165 hd(as) = fst(hd(as));
4172 bounds = tl(bounds);
4173 bindings = tl(bindings);
4174 depends = tl(depends);
4177 static Void local saveSyntax(v,sy) /* Save syntax of top-level var */
4178 Cell v; /* in corresponding Name */
4180 Name n = findName(textOf(v));
4181 if (isNull(n) || name(n).syntax!=NO_SYNTAX) {
4182 internal("saveSyntax");
4185 name(n).syntax = intOf(sy);
4189 /* --------------------------------------------------------------------------
4190 * As a side effect of the dependency analysis we also make the following
4192 * - Each lhs is a valid pattern/function lhs, all constructor functions
4193 * have been defined and are used with the correct number of arguments.
4194 * - No lhs contains repeated pattern variables.
4195 * - Expressions used on the rhs of an eqn should be well formed. This
4197 * - Checking for valid patterns (including repeated vars) in lambda,
4198 * case, and list comprehension expressions.
4199 * - Recursively checking local lists of equations.
4200 * - No free (i.e. unbound) variables are used in the declaration list.
4201 * ------------------------------------------------------------------------*/
4203 static Void local depBinding(b) /* find dependents of binding */
4205 Cell defpart = snd(snd(snd(b))); /* definition part of binding */
4209 if (isVar(fst(b))) { /* function-binding? */
4210 mapProc(depAlt,defpart);
4211 if (isNull(fst(snd(b)))) { /* Save dep info if no type sig */
4212 fst(snd(b)) = pair(ap(IMPDEPS,hd(depends)),NIL);
4213 } else if (isNull(fst(fst(snd(b))))) {
4214 fst(fst(snd(b))) = ap(IMPDEPS,hd(depends));
4216 } else { /* pattern-binding? */
4217 Int line = rhsLine(snd(defpart));
4220 fst(defpart) = checkPat(line,fst(defpart));
4221 depRhs(snd(defpart));
4223 if (nonNull(hd(btyvars))) {
4225 "Sorry, no type variables are allowed in pattern binding type annotations"
4229 fst(defpart) = applyBtyvs(fst(defpart));
4231 depVal(b) = hd(depends);
4234 static Void local depDefaults(c) /* dependency analysis on defaults */
4235 Class c; { /* from class definition */
4236 depClassBindings(cclass(c).defaults);
4239 static Void local depInsts(in) /* dependency analysis on instance */
4240 Inst in; { /* bindings */
4241 depClassBindings(inst(in).implements);
4244 static Void local depClassBindings(bs) /* dependency analysis on list of */
4245 List bs; { /* bindings, possibly containing */
4246 for (; nonNull(bs); bs=tl(bs)) { /* NIL bindings ... */
4247 if (nonNull(hd(bs))) { /* No need to add extra field for */
4248 mapProc(depAlt,snd(hd(bs)));/* dependency information... */
4253 static Void local depAlt(a) /* Find dependents of alternative */
4255 List obvs = saveBvars(); /* Save list of bound variables */
4257 bindPats(rhsLine(snd(a)),fst(a)); /* add new bound vars for patterns */
4258 depRhs(snd(a)); /* find dependents of rhs */
4259 fst(a) = applyBtyvs(fst(a));
4260 restoreBvars(obvs); /* restore original list of bvars */
4263 static Void local depRhs(r) /* Find dependents of rhs */
4265 switch (whatIs(r)) {
4266 case GUARDED : mapProc(depGuard,snd(r));
4269 case LETREC : fst(snd(r)) = eqnsToBindings(fst(snd(r)),NIL,NIL,NIL);
4270 withinScope(fst(snd(r)));
4271 fst(snd(r)) = dependencyAnal(fst(snd(r)));
4272 hd(depends) = fst(snd(r));
4273 depRhs(snd(snd(r)));
4277 case RSIGN : snd(snd(r)) = checkPatType(rhsLine(fst(snd(r))),
4279 rhsExpr(fst(snd(r))),
4281 depRhs(fst(snd(r)));
4284 default : snd(r) = depExpr(intOf(fst(r)),snd(r));
4289 static Void local depGuard(g) /* find dependents of single guarded*/
4290 Cell g; { /* expression */
4291 depPair(intOf(fst(g)),snd(g));
4294 static Cell local depExpr(line,e) /* find dependents of expression */
4297 // Printf( "\n\n"); print(e,100); Printf("\n");
4298 //printExp(stdout,e);
4299 switch (whatIs(e)) {
4302 case VAROPCELL : return depVar(line,e);
4305 case CONOPCELL : return conDefined(line,e);
4307 case QUALIDENT : if (isQVar(e)) {
4308 return depQVar(line,e);
4309 } else { /* QConOrConOp */
4310 return conDefined(line,e);
4313 case INFIX : return depExpr(line,tidyInfix(line,snd(e)));
4316 case RECSEL : break;
4318 case AP : if (isAp(e) && isAp(fun(e)) && isExt(fun(fun(e)))) {
4319 return depRecord(line,e);
4325 arg(a) = depExpr(line,arg(a));
4328 fun(a) = depExpr(line,fun(a));
4332 case AP : depPair(line,e);
4346 case INTCELL : break;
4348 case COND : depTriple(line,snd(e));
4351 case FINLIST : map1Over(depExpr,line,snd(e));
4354 case LETREC : fst(snd(e)) = eqnsToBindings(fst(snd(e)),NIL,NIL,NIL);
4355 withinScope(fst(snd(e)));
4356 fst(snd(e)) = dependencyAnal(fst(snd(e)));
4357 hd(depends) = fst(snd(e));
4358 snd(snd(e)) = depExpr(line,snd(snd(e)));
4362 case LAMBDA : depAlt(snd(e));
4365 case DOCOMP : /* fall-thru */
4366 case COMP : depComp(line,snd(e),snd(snd(e)));
4369 case ESIGN : fst(snd(e)) = depExpr(line,fst(snd(e)));
4370 snd(snd(e)) = checkSigType(line,
4376 case CASE : fst(snd(e)) = depExpr(line,fst(snd(e)));
4377 map1Proc(depCaseAlt,line,snd(snd(e)));
4380 case CONFLDS : depConFlds(line,e,FALSE);
4383 case UPDFLDS : depUpdFlds(line,e);
4386 case ASPAT : ERRMSG(line) "Illegal `@' in expression"
4389 case LAZYPAT : ERRMSG(line) "Illegal `~' in expression"
4392 case WILDCARD : ERRMSG(line) "Illegal `_' in expression"
4396 case EXT : ERRMSG(line) "Illegal application of record"
4400 default : fprintf(stderr,"whatIs(e) == %d\n",whatIs(e));internal("depExpr");
4405 static Void local depPair(line,e) /* find dependents of pair of exprs*/
4408 fst(e) = depExpr(line,fst(e));
4409 snd(e) = depExpr(line,snd(e));
4412 static Void local depTriple(line,e) /* find dependents of triple exprs */
4415 fst3(e) = depExpr(line,fst3(e));
4416 snd3(e) = depExpr(line,snd3(e));
4417 thd3(e) = depExpr(line,thd3(e));
4420 static Void local depComp(l,e,qs) /* find dependents of comprehension*/
4425 fst(e) = depExpr(l,fst(e));
4429 switch (whatIs(q)) {
4430 case FROMQUAL : { List obvs = saveBvars();
4431 snd(snd(q)) = depExpr(l,snd(snd(q)));
4433 fst(snd(q)) = bindPat(l,fst(snd(q)));
4435 fst(snd(q)) = applyBtyvs(fst(snd(q)));
4440 case QWHERE : snd(q) = eqnsToBindings(snd(q),NIL,NIL,NIL);
4441 withinScope(snd(q));
4442 snd(q) = dependencyAnal(snd(q));
4443 hd(depends) = snd(q);
4448 case DOQUAL : /* fall-thru */
4449 case BOOLQUAL : snd(q) = depExpr(l,snd(q));
4456 static Void local depCaseAlt(line,a) /* Find dependents of case altern. */
4459 List obvs = saveBvars(); /* Save list of bound variables */
4461 fst(a) = bindPat(line,fst(a)); /* Add new bound vars for pats */
4462 depRhs(snd(a)); /* Find dependents of rhs */
4463 fst(a) = applyBtyvs(fst(a));
4464 restoreBvars(obvs); /* Restore original list of bvars */
4467 static Cell local depVar(line,e) /* Register occurrence of variable */
4470 List bounds1 = bounds;
4471 List bindings1 = bindings;
4472 List depends1 = depends;
4476 while (nonNull(bindings1)) {
4477 n = varIsMember(t,hd(bounds1)); /* look for t in bound variables */
4481 n = findBinding(t,hd(bindings1)); /* look for t in var bindings */
4483 if (!cellIsMember(n,hd(depends1))) {
4484 hd(depends1) = cons(n,hd(depends1));
4486 return (isVar(fst(n)) ? fst(n) : e);
4489 bounds1 = tl(bounds1);
4490 bindings1 = tl(bindings1);
4491 depends1 = tl(depends1);
4494 if (isNull(n=findName(t))) { /* check global definitions */
4495 ERRMSG(line) "Undefined variable \"%s\"", textToStr(t)
4500 if (!moduleThisScript(name(n).mod)) {
4504 /* Later phases of the system cannot cope if we resolve references
4505 * to unprocessed objects too early. This is the main reason that
4506 * we cannot cope with recursive modules at the moment.
4511 static Cell local depQVar(line,e)/* register occurrence of qualified variable */
4514 Name n = findQualName(e);
4515 if (isNull(n)) { /* check global definitions */
4516 ERRMSG(line) "Undefined qualified variable \"%s\"", identToStr(e)
4520 if (name(n).mod != currentModule) {
4524 if (fst(e) == VARIDCELL) {
4525 e = mkVar(qtextOf(e));
4527 e = mkVarop(qtextOf(e));
4529 return depVar(line,e);
4532 static Void local depConFlds(line,e,isP)/* check construction using fields */
4536 Name c = conDefined(line,fst(snd(e)));
4537 if (isNull(snd(snd(e))) ||
4538 nonNull(cellIsMember(c,depFields(line,e,snd(snd(e)),isP)))) {
4541 ERRMSG(line) "Constructor \"%s\" does not have selected fields in ",
4542 textToStr(name(c).text)
4547 if (!isP && isPair(name(c).defn)) { /* Check that banged fields defined*/
4548 List scs = fst(name(c).defn); /* List of strict components */
4549 Type t = name(c).type;
4550 Int a = userArity(c);
4551 List fs = snd(snd(e));
4553 if (isPolyType(t)) { /* Find tycon that c belongs to */
4556 if (whatIs(t)==QUAL) {
4559 if (whatIs(t)==CDICTS) {
4568 for (ss=tycon(t).defn; hasCfun(ss); ss=tl(ss)) {
4570 /* Now we know the tycon t that c belongs to, and the corresponding
4571 * list of selectors for that type, ss. Now we have to check that
4572 * each of the fields identified by scs appears in fs, using ss to
4573 * cross reference, and convert integers to selector names.
4575 for (; nonNull(scs); scs=tl(scs)) {
4576 Int i = intOf(hd(scs));
4578 for (; nonNull(ss1); ss1=tl(ss1)) {
4579 List cns = name(hd(ss1)).defn;
4580 for (; nonNull(cns); cns=tl(cns)) {
4581 if (fst(hd(cns))==c) {
4585 if (nonNull(cns) && intOf(snd(hd(cns)))==i) {
4590 internal("depConFlds");
4594 for (; nonNull(fs1) && s!=fst(hd(fs1)); fs1=tl(fs1)) {
4597 ERRMSG(line) "Construction does not define strict field"
4599 ERRTEXT "\nExpression : " ETHEN ERREXPR(e);
4600 ERRTEXT "\nField : " ETHEN ERREXPR(s);
4609 static Void local depUpdFlds(line,e) /* check update using fields */
4612 if (isNull(thd3(snd(e)))) {
4613 ERRMSG(line) "Empty field list in update"
4616 fst3(snd(e)) = depExpr(line,fst3(snd(e)));
4617 snd3(snd(e)) = depFields(line,e,thd3(snd(e)),FALSE);
4620 static List local depFields(l,e,fs,isP) /* check field binding list */
4628 for (; nonNull(fs); fs=tl(fs)) { /* for each field binding */
4632 if (isVar(fb)) { /* expand var to var = var */
4633 h98DoesntSupport(l,"missing field bindings");
4634 fb = hd(fs) = pair(fb,fb);
4637 s = findQualName(fst(fb)); /* check for selector */
4638 if (nonNull(s) && isSfun(s)) {
4641 ERRMSG(l) "\"%s\" is not a selector function/field name",
4642 textToStr(textOf(fst(fb)))
4646 if (isNull(ss)) { /* for first named selector */
4647 List scs = name(s).defn; /* calculate list of constructors */
4648 for (; nonNull(scs); scs=tl(scs)) {
4649 cs = cons(fst(hd(scs)),cs);
4651 ss = singleton(s); /* initialize selector list */
4652 } else { /* for subsequent selectors */
4653 List ds = cs; /* intersect constructor lists */
4654 for (cs=NIL; nonNull(ds); ) {
4655 List scs = name(s).defn;
4656 while (nonNull(scs) && fst(hd(scs))!=hd(ds)) {
4669 if (cellIsMember(s,ss)) { /* check for repeated uses */
4670 ERRMSG(l) "Repeated field name \"%s\" in field list",
4671 textToStr(name(s).text)
4677 if (isNull(cs)) { /* Are there any matching constrs? */
4678 ERRMSG(l) "No constructor has all of the fields specified in "
4684 snd(fb) = (isP ? checkPat(l,snd(fb)) : depExpr(l,snd(fb)));
4690 static Cell local depRecord(line,e) /* find dependents of record and */
4691 Int line; /* sort fields into approp. order */
4692 Cell e; { /* to make construction and update */
4693 List exts = NIL; /* more efficient. */
4696 h98DoesntSupport(line,"extensible records");
4697 do { /* build up list of extensions */
4698 Text t = extText(fun(fun(r)));
4699 String s = textToStr(t);
4702 while (nonNull(nx) && strcmp(textToStr(extText(fun(fun(nx)))),s)>0) {
4706 if (nonNull(nx) && t==extText(fun(fun(nx)))) {
4707 ERRMSG(line) "Repeated label \"%s\" in record ", s
4713 exts = cons(fun(r),exts);
4715 tl(prev) = cons(fun(r),nx);
4717 extField(r) = depExpr(line,extField(r));
4719 } while (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r))));
4720 r = depExpr(line,r);
4721 return revOnto(exts,r);
4726 /* --------------------------------------------------------------------------
4727 * Several parts of this program require an algorithm for sorting a list
4728 * of values (with some added dependency information) into a list of strongly
4729 * connected components in which each value appears before its dependents.
4731 * Each of these algorithms is obtained by parameterising a standard
4732 * algorithm in "scc.c" as shown below.
4733 * ------------------------------------------------------------------------*/
4735 #define SCC2 tcscc /* make scc algorithm for Tycons */
4736 #define LOWLINK tclowlink
4737 #define DEPENDS(c) (isTycon(c) ? tycon(c).kind : cclass(c).kinds)
4738 #define SETDEPENDS(c,v) if(isTycon(c)) tycon(c).kind=v; else cclass(c).kinds=v
4745 #define SCC bscc /* make scc algorithm for Bindings */
4746 #define LOWLINK blowlink
4747 #define DEPENDS(t) depVal(t)
4748 #define SETDEPENDS(c,v) depVal(c)=v
4755 /* --------------------------------------------------------------------------
4756 * Main static analysis:
4757 * ------------------------------------------------------------------------*/
4759 Void checkExp() { /* Top level static check on Expr */
4760 staticAnalysis(RESET);
4761 clearScope(); /* Analyse expression in the scope */
4762 withinScope(NIL); /* of no local bindings */
4763 inputExpr = depExpr(0,inputExpr);
4765 staticAnalysis(RESET);
4768 Void checkDefns() { /* Top level static analysis */
4770 Module thisModule = lastModule();
4772 staticAnalysis(RESET);
4775 setCurrModule(thisModule);
4777 /* Resolve module references */
4778 mapProc(checkQualImport, module(thisModule).qualImports);
4779 mapProc(checkUnqualImport,unqualImports);
4780 /* Add "import Prelude" if there`s no explicit import */
4781 if (thisModule!=modulePrelude
4782 && isNull(cellAssoc(modulePrelude,unqualImports))
4783 && isNull(cellRevAssoc(modulePrelude,module(thisModule).qualImports))) {
4784 unqualImports = cons(pair(modulePrelude,DOTDOT),unqualImports);
4786 /* Every module (including the Prelude) implicitly contains
4787 * "import qualified Prelude"
4789 module(thisModule).qualImports=cons(pair(mkCon(textPrelude),modulePrelude),
4790 module(thisModule).qualImports);
4792 mapProc(checkImportList, unqualImports);
4795 linkPreludeTC(); /* Get prelude tycons and classes */
4796 mapProc(checkTyconDefn,tyconDefns); /* validate tycon definitions */
4797 checkSynonyms(tyconDefns); /* check synonym definitions */
4798 mapProc(checkClassDefn,classDefns); /* process class definitions */
4799 mapProc(kindTCGroup,tcscc(tyconDefns,classDefns)); /* attach kinds */
4800 mapProc(addMembers,classDefns); /* add definitions for member funs */
4801 mapProc(visitClass,classDefns); /* check class hierarchy */
4802 linkPreludeCM(); /* Get prelude cfuns and mfuns */
4804 instDefns = rev(instDefns); /* process instance definitions */
4805 mapProc(checkInstDefn,instDefns);
4807 setCurrModule(thisModule);
4808 mapProc(addDerivImp,derivedInsts); /* Add impls for derived instances */
4809 deriveContexts(derivedInsts); /* Calculate derived inst contexts */
4811 deriveEval(tyconDefns); /* Derive instances of Eval */
4813 instDefns = appendOnto(instDefns,derivedInsts);
4814 checkDefaultDefns(); /* validate default definitions */
4816 mapProc(addRSsigdecls,typeInDefns); /* add sigdecls for RESTRICTSYN */
4817 #if 0 /* from STG */
4818 valDefns = eqnsToBindings(valDefns);/* translate value equations */
4819 map1Proc(opDefined,valDefns,opDefns);/*check all declared ops bound */
4821 valDefns = eqnsToBindings(valDefns,tyconDefns,classDefns, NIL/*primDefns*/ );
4823 /* primDefns = NIL; */
4825 mapProc(allNoPrevDef,valDefns); /* check against previous defns */
4829 mapProc(checkForeignImport,foreignImports); /* check foreign imports */
4830 mapProc(checkForeignExport,foreignExports); /* check foreign exports */
4831 foreignImports = NIL;
4832 foreignExports = NIL;
4835 /* Every top-level name has now been created - so we can build the */
4836 /* export list. Note that this has to happen before dependency */
4837 /* analysis so that references to Prelude.foo will be resolved */
4838 /* when compiling the prelude. */
4839 module(thisModule).exports = checkExports(module(thisModule).exports);
4842 mapProc(checkTypeIn,typeInDefns); /* check restricted synonym defns */
4845 withinScope(valDefns);
4846 valDefns = topDependAnal(valDefns); /* top level dependency ordering */
4847 mapProc(depDefaults,classDefns); /* dep. analysis on class defaults */
4848 mapProc(depInsts,instDefns); /* dep. analysis on inst defns */
4851 /* ToDo: evalDefaults should match current evaluation module */
4852 evalDefaults = defaultDefns; /* Set defaults for evaluator */
4854 staticAnalysis(RESET);
4857 static Void local addRSsigdecls(pr) /* add sigdecls from TYPE ... IN ..*/
4859 List vs = snd(pr); /* get list of variables */
4860 for (; nonNull(vs); vs=tl(vs)) {
4861 if (fst(hd(vs))==SIGDECL) { /* find a sigdecl */
4862 valDefns = cons(hd(vs),valDefns); /* add to valDefns */
4863 hd(vs) = hd(snd3(snd(hd(vs)))); /* and replace with var */
4868 static Void local allNoPrevDef(b) /* ensure no previous bindings for*/
4869 Cell b; { /* variables in new binding */
4870 if (isVar(fst(b))) {
4871 noPrevDef(rhsLine(snd(hd(snd(snd(b))))),fst(b));
4873 Int line = rhsLine(snd(snd(snd(b))));
4874 map1Proc(noPrevDef,line,fst(b));
4878 static Void local noPrevDef(line,v) /* ensure no previous binding for */
4879 Int line; /* new variable */
4881 Name n = findName(textOf(v));
4884 n = newName(textOf(v),NIL);
4885 name(n).defn = PREDEFINED;
4886 } else if (name(n).defn!=PREDEFINED) {
4887 duplicateError(line,name(n).mod,name(n).text,"variable");
4889 name(n).line = line;
4893 static Void local duplicateErrorAux(line,t,kind) /* report duplicate defn */
4897 ERRMSG(line) "Definition of %s \"%s\" clashes with import", kind,
4901 #else /* !IGNORE_MODULES */
4902 static Void local duplicateErrorAux(line,mod,t,kind)/* report duplicate defn */
4907 if (mod == currentModule) {
4908 ERRMSG(line) "Repeated definition for %s \"%s\"", kind,
4912 ERRMSG(line) "Definition of %s \"%s\" clashes with import", kind,
4917 #endif /* !IGNORE_MODULES */
4919 static Void local checkTypeIn(cvs) /* Check that vars in restricted */
4920 Pair cvs; { /* synonym are defined */
4924 for (; nonNull(vs); vs=tl(vs)) {
4925 if (isNull(findName(textOf(hd(vs))))) {
4926 ERRMSG(tycon(c).line)
4927 "No top level binding of \"%s\" for restricted synonym \"%s\"",
4928 textToStr(textOf(hd(vs))), textToStr(tycon(c).text)
4934 /* --------------------------------------------------------------------------
4935 * Haskell 98 compatibility tests:
4936 * ------------------------------------------------------------------------*/
4938 Bool h98Pred(allowArgs,pi) /* Check syntax of Hask98 predicate*/
4941 return isClass(getHead(pi)) && argCount==1 &&
4942 isOffset(getHead(arg(pi))) && (argCount==0 || allowArgs);
4945 Cell h98Context(allowArgs,ps) /* Check syntax of Hask98 context */
4948 for (; nonNull(ps); ps=tl(ps)) {
4949 if (!h98Pred(allowArgs,hd(ps))) {
4956 Void h98CheckCtxt(line,wh,allowArgs,ps,in)
4957 Int line; /* Report illegal context/predicate*/
4963 Cell pi = h98Context(allowArgs,ps);
4965 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh ETHEN
4967 ERRTEXT "\n*** Instance : " ETHEN ERRPRED(inst(in).head);
4969 ERRTEXT "\n*** Constraint : " ETHEN ERRPRED(pi);
4970 if (nonNull(ps) && nonNull(tl(ps))) {
4971 ERRTEXT "\n*** Context : " ETHEN ERRCONTEXT(ps);
4979 Void h98CheckType(line,wh,e,t) /* Check for Haskell 98 type */
4988 if (whatIs(t)==QUAL) {
4989 Cell pi = h98Context(TRUE,fst(snd(t)));
4991 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh
4993 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
4994 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(ty);
5002 Void h98DoesntSupport(line,wh) /* Report feature missing in H98 */
5006 ERRMSG(line) "Haskell 98 does not support %s", wh
5011 /* --------------------------------------------------------------------------
5012 * Static Analysis control:
5013 * ------------------------------------------------------------------------*/
5015 Void staticAnalysis(what)
5018 case RESET : cfunSfuns = NIL;
5031 case MARK : mark(daSccs);
5046 case INSTALL : staticAnalysis(RESET);
5048 extKind = pair(STAR,pair(ROW,ROW));
5054 /*-------------------------------------------------------------------------*/