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/07/06 15:24:41 $
13 * ------------------------------------------------------------------------*/
23 /* --------------------------------------------------------------------------
24 * local function prototypes:
25 * ------------------------------------------------------------------------*/
27 static Void local kindError Args((Int,Constr,Constr,String,Kind,Int));
28 static Void local checkQualImport Args((Pair));
29 static Void local checkUnqualImport Args((Triple));
31 static Name local lookupName Args((Text,List));
32 static List local checkSubentities Args((List,List,List,String,Text));
33 static List local checkExportTycon Args((List,Text,Cell,Tycon));
34 static List local checkExportClass Args((List,Text,Cell,Class));
35 static List local checkExport Args((List,Text,Cell));
36 static List local checkImportEntity Args((List,Module,Cell));
37 static List local resolveImportList Args((Module,Cell));
38 static Void local checkImportList Args((Pair));
40 static Void local importEntity Args((Module,Cell));
41 static Void local importName Args((Module,Name));
42 static Void local importTycon Args((Module,Tycon));
43 static Void local importClass Args((Module,Class));
44 static List local checkExports Args((List));
46 static Void local checkTyconDefn Args((Tycon));
47 static Void local depConstrs Args((Tycon,List,Cell));
48 static List local addSels Args((Int,Name,List,List));
49 static List local selectCtxt Args((List,List));
50 static Void local checkSynonyms Args((List));
51 static List local visitSyn Args((List,Tycon,List));
52 static Type local instantiateSyn Args((Type,Type));
54 static Void local checkClassDefn Args((Class));
55 static Void local depPredExp Args((Int,List,Cell));
56 static Void local checkMems Args((Class,List,Cell));
57 static Void local addMembers Args((Class));
58 static Name local newMember Args((Int,Int,Cell,Type,Class));
59 static Name local newDSel Args((Class,Int));
60 static Name local newDBuild Args((Class));
61 static Text local generateText Args((String,Class));
62 static Int local visitClass Args((Class));
64 static List local classBindings Args((String,Class,List));
65 static Name local memberName Args((Class,Text));
66 static List local numInsert Args((Int,Cell,List));
68 static List local maybeAppendVar Args((Cell,List));
70 static Type local checkSigType Args((Int,String,Cell,Type));
71 static Type local depTopType Args((Int,List,Type));
72 static Type local depCompType Args((Int,List,Type));
73 static Type local depTypeExp Args((Int,List,Type));
74 static Type local depTypeVar Args((Int,List,Text));
75 static List local checkQuantVars Args((Int,List,List,Cell));
76 static Void local kindConstr Args((Int,Int,Int,Constr));
77 static Kind local kindAtom Args((Int,Constr));
78 static Void local kindPred Args((Int,Int,Int,Cell));
79 static Void local kindType Args((Int,String,Type));
80 static Void local fixKinds Args((Void));
82 static Void local kindTCGroup Args((List));
83 static Void local initTCKind Args((Cell));
84 static Void local kindTC Args((Cell));
85 static Void local genTC Args((Cell));
87 static Void local checkInstDefn Args((Inst));
88 static Void local insertInst Args((Inst));
89 static Bool local instCompare Args((Inst,Inst));
90 static Name local newInstImp Args((Inst));
91 static Void local kindInst Args((Inst,Int));
92 static Void local checkDerive Args((Tycon,List,List,Cell));
93 static Void local addDerInst Args((Int,Class,List,List,Type,Int));
94 static Void local deriveContexts Args((List));
95 static Void local initDerInst Args((Inst));
96 static Void local calcInstPreds Args((Inst));
97 static Void local maybeAddPred Args((Cell,Int,Int,List));
98 static Cell local copyAdj Args((Cell,Int,Int));
99 static Void local tidyDerInst Args((Inst));
101 static Void local addDerivImp Args((Inst));
103 static Void local checkDefaultDefns Args((Void));
105 static Void local checkForeignImport Args((Name));
106 static Void local checkForeignExport Args((Name));
108 static Cell local tidyInfix Args((Int,Cell));
109 static Pair local attachFixity Args((Int,Cell));
110 static Syntax local lookupSyntax Args((Text));
112 static Cell local checkPat Args((Int,Cell));
113 static Cell local checkMaybeCnkPat Args((Int,Cell));
114 static Cell local checkApPat Args((Int,Int,Cell));
115 static Void local addToPatVars Args((Int,Cell));
116 static Name local conDefined Args((Int,Cell));
117 static Void local checkIsCfun Args((Int,Name));
118 static Void local checkCfunArgs Args((Int,Cell,Int));
119 static Cell local checkPatType Args((Int,String,Cell,Type));
120 static Cell local applyBtyvs Args((Cell));
121 static Cell local bindPat Args((Int,Cell));
122 static Void local bindPats Args((Int,List));
124 static List local extractSigdecls Args((List));
125 static List local extractFixdecls Args((List));
126 static List local extractBindings Args((List));
127 static List local getPatVars Args((Int,Cell,List));
128 static List local addPatVar Args((Int,Cell,List));
129 static List local eqnsToBindings Args((List,List,List,List));
130 static Void local notDefined Args((Int,List,Cell));
131 static Cell local findBinding Args((Text,List));
132 static Cell local getAttr Args((List,Cell));
133 static Void local addSigdecl Args((List,Cell));
134 static Void local addFixdecl Args((List,List,List,List,Triple));
135 static Void local dupFixity Args((Int,Text));
136 static Void local missFixity Args((Int,Text));
138 static List local dependencyAnal Args((List));
139 static List local topDependAnal Args((List));
140 static Void local addDepField Args((Cell));
141 static Void local remDepField Args((List));
142 static Void local remDepField1 Args((Cell));
143 static Void local clearScope Args((Void));
144 static Void local withinScope Args((List));
145 static Void local leaveScope Args((Void));
146 static Void local saveSyntax Args((Cell,Cell));
148 static Void local depBinding Args((Cell));
149 static Void local depDefaults Args((Class));
150 static Void local depInsts Args((Inst));
151 static Void local depClassBindings Args((List));
152 static Void local depAlt Args((Cell));
153 static Void local depRhs Args((Cell));
154 static Void local depGuard Args((Cell));
155 static Cell local depExpr Args((Int,Cell));
156 static Void local depPair Args((Int,Cell));
157 static Void local depTriple Args((Int,Cell));
158 static Void local depComp Args((Int,Cell,List));
159 static Void local depCaseAlt Args((Int,Cell));
160 static Cell local depVar Args((Int,Cell));
161 static Cell local depQVar Args((Int,Cell));
162 static Void local depConFlds Args((Int,Cell,Bool));
163 static Void local depUpdFlds Args((Int,Cell));
164 static List local depFields Args((Int,Cell,List,Bool));
166 static Cell local depRecord Args((Int,Cell));
169 static List local tcscc Args((List,List));
170 static List local bscc Args((List));
172 static Void local addRSsigdecls Args((Pair));
173 static Void local allNoPrevDef Args((Cell));
174 static Void local noPrevDef Args((Int,Cell));
175 static Void local duplicateErrorAux Args((Int,Module,Text,String));
176 #define duplicateError(l,m,t,k) duplicateErrorAux(l,m,t,k)
177 static Void local checkTypeIn Args((Pair));
179 /* --------------------------------------------------------------------------
180 * The code in this file is arranged in roughly the following order:
181 * - Kind inference preliminaries
182 * - Module declarations
183 * - Type declarations (data, type, newtype, type in)
184 * - Class declarations
186 * - Instance declarations
187 * - Default declarations
188 * - Primitive definitions
190 * - Infix expressions
191 * - Value definitions
192 * - Top-level static analysis and control
193 * - Haskell 98 compatibility tests
194 * ------------------------------------------------------------------------*/
196 /* --------------------------------------------------------------------------
197 * Kind checking preliminaries:
198 * ------------------------------------------------------------------------*/
200 Bool kindExpert = FALSE; /* TRUE => display kind errors in */
203 static Void local kindError(l,c,in,wh,k,o)
204 Int l; /* line number near constuctor exp */
205 Constr c; /* constructor */
206 Constr in; /* context (if any) */
207 String wh; /* place in which error occurs */
208 Kind k; /* expected kind (k,o) */
209 Int o; { /* inferred kind (typeIs,typeOff) */
212 if (!kindExpert) { /* for those with a fear of kinds */
213 ERRMSG(l) "Illegal type" ETHEN
215 ERRTEXT " \"" ETHEN ERRTYPE(in);
218 ERRTEXT " in %s\n", wh
222 ERRMSG(l) "Kind error in %s", wh ETHEN
224 ERRTEXT "\n*** expression : " ETHEN ERRTYPE(in);
226 ERRTEXT "\n*** constructor : " ETHEN ERRTYPE(c);
227 ERRTEXT "\n*** kind : " ETHEN ERRKIND(copyType(typeIs,typeOff));
228 ERRTEXT "\n*** does not match : " ETHEN ERRKIND(copyType(k,o));
230 ERRTEXT "\n*** because : %s", unifyFails ETHEN
236 #define shouldKind(l,c,in,wh,k,o) if (!kunify(typeIs,typeOff,k,o)) \
237 kindError(l,c,in,wh,k,o)
238 #define checkKind(l,a,m,c,in,wh,k,o) kindConstr(l,a,m,c); \
239 shouldKind(l,c,in,wh,k,o)
240 #define inferKind(k,o) typeIs=k; typeOff=o
242 static List unkindTypes; /* types in need of kind annotation*/
244 Kind extKind; /* Kind of extension, *->row->row */
247 /* --------------------------------------------------------------------------
248 * Static analysis of modules:
249 * ------------------------------------------------------------------------*/
255 Void startModule(nm) /* switch to a new module */
258 if (!isCon(nm)) internal("startModule");
259 if (isNull(m = findModule(textOf(nm))))
260 m = newModule(textOf(nm));
261 else if (!isPreludeScript()) {
262 /* You're allowed to break the rules in the Prelude! */
264 reloadModule = textToStr(textOf(nm));
266 ERRMSG(0) "Module \"%s\" already loaded", textToStr(textOf(nm))
272 Void setExportList(exps) /* Add export list to current module */
274 module(currentModule).exports = exps;
277 Void addQualImport(orig,new) /* Add to qualified import list */
278 Cell orig; /* Original name of module */
279 Cell new; { /* Name module is called within this module (or NIL) */
280 module(currentModule).qualImports =
281 cons(pair(isNull(new)?orig:new,orig),module(currentModule).qualImports);
284 Void addUnqualImport(mod,entities) /* Add to unqualified import list */
285 Cell mod; /* Name of module */
286 List entities; { /* List of entity names */
287 unqualImports = cons(pair(mod,entities),unqualImports);
290 static Void local checkQualImport(i) /* Process qualified import */
292 Module m = findModid(snd(i));
294 ERRMSG(0) "Module \"%s\" not previously loaded",
295 textToStr(textOf(snd(i)))
301 static Void local checkUnqualImport(i) /* Process unqualified import */
303 Module m = findModid(fst(i));
305 ERRMSG(0) "Module \"%s\" not previously loaded",
306 textToStr(textOf(fst(i)))
312 static Name local lookupName(t,nms) /* find text t in list of Names */
314 List nms; { /* :: [Name] */
315 for(; nonNull(nms); nms=tl(nms)) {
316 if (t == name(hd(nms)).text)
322 static List local checkSubentities(imports,named,wanted,description,textParent)
324 List named; /* :: [ Q?(Var|Con)(Id|Op) ] */
325 List wanted; /* :: [Name] */
326 String description; /* "<constructor>|<member> of <type>|<class>" */
328 for(; nonNull(named); named=tl(named)) {
330 /* ToDo: ignores qualifier; doesn't check that entity is in scope */
331 Text t = isPair(snd(x)) ? qtextOf(x) : textOf(x);
332 Name n = lookupName(t,wanted);
334 ERRMSG(0) "Entity \"%s\" is not a %s \"%s\"",
337 textToStr(textParent)
340 imports = cons(n,imports);
345 static List local checkImportEntity(imports,exporter,entity)
346 List imports; /* Accumulated list of things to import */
348 Cell entity; { /* Entry from import list */
349 List oldImports = imports;
350 Text t = isIdent(entity) ? textOf(entity) : textOf(fst(entity));
351 List es = module(exporter).exports;
352 for(; nonNull(es); es=tl(es)) {
353 Cell e = hd(es); /* :: Entity | (Entity, NIL|DOTDOT) */
357 if (tycon(f).text == t) {
358 imports = cons(f,imports);
359 if (!isIdent(entity)) {
360 switch (tycon(f).what) {
363 if (DOTDOT == snd(entity)) {
364 imports=dupOnto(tycon(f).defn,imports);
366 imports=checkSubentities(imports,snd(entity),tycon(f).defn,
367 "constructor of type",t);
371 /* deliberate fall thru */
375 } else if (isClass(f)) {
376 if (cclass(f).text == t) {
377 imports = cons(f,imports);
378 if (!isIdent(entity)) {
379 if (DOTDOT == snd(entity)) {
380 return dupOnto(cclass(f).members,imports);
382 return checkSubentities(imports,snd(entity),cclass(f).members,
383 "member of class",t);
388 internal("checkImportEntity2");
390 } else if (isName(e)) {
391 if (isIdent(entity) && name(e).text == t) {
392 imports = cons(e,imports);
395 internal("checkImportEntity3");
398 if (imports == oldImports) {
399 ERRMSG(0) "Unknown entity \"%s\" imported from module \"%s\"",
401 textToStr(module(exporter ).text)
407 static List local resolveImportList(m,impList)
408 Module m; /* exporting module */
411 if (DOTDOT == impList) {
412 List es = module(m).exports;
413 for(; nonNull(es); es=tl(es)) {
416 imports = cons(e,imports);
419 List subentities = NIL;
420 imports = cons(c,imports);
422 && (tycon(c).what == DATATYPE
423 || tycon(c).what == NEWTYPE))
424 subentities = tycon(c).defn;
426 subentities = cclass(c).members;
427 if (DOTDOT == snd(e)) {
428 imports = dupOnto(subentities,imports);
433 map1Accum(checkImportEntity,imports,m,impList);
438 static Void local checkImportList(importSpec) /*Import a module unqualified*/
440 Module m = fst(importSpec);
441 Cell impList = snd(importSpec);
443 List imports = NIL; /* entities we want to import */
444 List hidden = NIL; /* entities we want to hide */
446 if (moduleThisScript(m)) {
447 ERRMSG(0) "Module \"%s\" recursively imports itself",
448 textToStr(module(m).text)
451 if (isPair(impList) && HIDDEN == fst(impList)) {
452 /* Somewhat inefficient - but obviously correct:
453 * imports = importsOf("module Foo") `setDifference` hidden;
455 hidden = resolveImportList(m, snd(impList));
456 imports = resolveImportList(m, DOTDOT);
458 imports = resolveImportList(m, impList);
460 for(; nonNull(imports); imports=tl(imports)) {
461 Cell e = hd(imports);
462 if (!cellIsMember(e,hidden))
465 /* ToDo: hang onto the imports list for processing export list entries
466 * of the form "module Foo"
470 static Void local importEntity(source,e)
474 case NAME : importName(source,e);
476 case TYCON : importTycon(source,e);
478 case CLASS : importClass(source,e);
480 default: internal("importEntity");
484 static Void local importName(source,n)
487 Name clash = addName(n);
488 if (nonNull(clash) && clash!=n) {
489 ERRMSG(0) "Entity \"%s\" imported from module \"%s\" already defined in module \"%s\"",
490 textToStr(name(n).text),
491 textToStr(module(source).text),
492 textToStr(module(name(clash).mod).text)
497 static Void local importTycon(source,tc)
500 Tycon clash=addTycon(tc);
501 if (nonNull(clash) && clash!=tc) {
502 ERRMSG(0) "Tycon \"%s\" imported from \"%s\" already defined in module \"%s\"",
503 textToStr(tycon(tc).text),
504 textToStr(module(source).text),
505 textToStr(module(tycon(clash).mod).text)
508 if (nonNull(findClass(tycon(tc).text))) {
509 ERRMSG(0) "Import of type constructor \"%s\" clashes with class in module \"%s\"",
510 textToStr(tycon(tc).text),
511 textToStr(module(tycon(tc).mod).text)
516 static Void local importClass(source,c)
519 Class clash=addClass(c);
520 if (nonNull(clash) && clash!=c) {
521 ERRMSG(0) "Class \"%s\" imported from \"%s\" already defined in module \"%s\"",
522 textToStr(cclass(c).text),
523 textToStr(module(source).text),
524 textToStr(module(cclass(clash).mod).text)
527 if (nonNull(findTycon(cclass(c).text))) {
528 ERRMSG(0) "Import of class \"%s\" clashes with type constructor in module \"%s\"",
529 textToStr(cclass(c).text),
530 textToStr(module(source).text)
535 static List local checkExportTycon(exports,mt,spec,tc)
540 if (DOTDOT == spec || SYNONYM == tycon(tc).what) {
541 return cons(pair(tc,DOTDOT), exports);
543 return cons(pair(tc,NIL), exports);
547 static List local checkExportClass(exports,mt,spec,cl)
552 if (DOTDOT == spec) {
553 return cons(pair(cl,DOTDOT), exports);
555 return cons(pair(cl,NIL), exports);
559 static List local checkExport(exports,mt,e) /* Process entry in export list*/
565 List origExports = exports;
566 if (nonNull(export=findQualName(e))) {
567 exports=cons(export,exports);
569 if (isQCon(e) && nonNull(export=findQualTycon(e))) {
570 exports = checkExportTycon(exports,mt,NIL,export);
572 if (isQCon(e) && nonNull(export=findQualClass(e))) {
573 /* opaque class export */
574 exports = checkExportClass(exports,mt,NIL,export);
576 if (exports == origExports) {
577 ERRMSG(0) "Unknown entity \"%s\" exported from module \"%s\"",
583 } else if (MODULEENT == fst(e)) {
584 Module m = findModid(snd(e));
585 /* ToDo: shouldn't allow export of module we didn't import */
587 ERRMSG(0) "Unknown module \"%s\" exported from module \"%s\"",
588 textToStr(textOf(snd(e))),
592 if (m == currentModule) {
593 /* Exporting the current module exports local definitions */
595 for(xs=module(m).classes; nonNull(xs); xs=tl(xs)) {
596 if (cclass(hd(xs)).mod==m)
597 exports = checkExportClass(exports,mt,DOTDOT,hd(xs));
599 for(xs=module(m).tycons; nonNull(xs); xs=tl(xs)) {
600 if (tycon(hd(xs)).mod==m)
601 exports = checkExportTycon(exports,mt,DOTDOT,hd(xs));
603 for(xs=module(m).names; nonNull(xs); xs=tl(xs)) {
604 if (name(hd(xs)).mod==m)
605 exports = cons(hd(xs),exports);
608 /* Exporting other modules imports all things imported
609 * unqualified from it.
610 * ToDo: we reexport everything exported by a module -
611 * whether we imported it or not. This gives the wrong
612 * result for "module M(module N) where import N(x)"
614 exports = dupOnto(module(m).exports,exports);
618 Cell ident = fst(e); /* class name or type name */
619 Cell parts = snd(e); /* members or constructors */
621 if (isQCon(ident) && nonNull(nm=findQualTycon(ident))) {
622 switch (tycon(nm).what) {
625 ERRMSG(0) "Explicit constructor list given for type synonym"
626 " \"%s\" in export list of module \"%s\"",
631 return cons(pair(nm,DOTDOT),exports);
633 ERRMSG(0) "Transparent export of restricted type synonym"
634 " \"%s\" in export list of module \"%s\"",
638 return exports; /* Not reached */
642 return cons(pair(nm,DOTDOT),exports);
644 exports = checkSubentities(exports,parts,tycon(nm).defn,
645 "constructor of type",
647 return cons(pair(nm,DOTDOT), exports);
650 internal("checkExport1");
652 } else if (isQCon(ident) && nonNull(nm=findQualClass(ident))) {
653 if (DOTDOT == parts) {
654 return cons(pair(nm,DOTDOT),exports);
656 exports = checkSubentities(exports,parts,cclass(nm).members,
657 "member of class",cclass(nm).text);
658 return cons(pair(nm,DOTDOT), exports);
661 ERRMSG(0) "Explicit export list given for non-class/datatype \"%s\" in export list of module \"%s\"",
667 return 0; /* NOTREACHED */
670 static List local checkExports(exports)
672 Module m = lastModule();
673 Text mt = module(m).text;
676 map1Accum(checkExport,es,mt,exports);
679 for(xs=es; nonNull(xs); xs=tl(xs)) {
680 Printf(" %s", textToStr(textOfEntity(hd(xs))));
687 /* --------------------------------------------------------------------------
688 * Static analysis of type declarations:
690 * Type declarations come in two forms:
691 * - data declarations - define new constructed data types
692 * - type declarations - define new type synonyms
694 * A certain amount of work is carried out as the declarations are
695 * read during parsing. In particular, for each type constructor
696 * definition encountered:
697 * - check that there is no previous definition of constructor
698 * - ensure type constructor not previously used as a class name
699 * - make a new entry in the type constructor table
700 * - record line number of declaration
701 * - Build separate lists of newly defined constructors for later use.
702 * ------------------------------------------------------------------------*/
704 Void tyconDefn(line,lhs,rhs,what) /* process new type definition */
705 Int line; /* definition line number */
706 Cell lhs; /* left hand side of definition */
707 Cell rhs; /* right hand side of definition */
708 Cell what; { /* SYNONYM/DATATYPE/etc... */
709 Text t = textOf(getHead(lhs));
711 if (nonNull(findTycon(t))) {
712 ERRMSG(line) "Repeated definition of type constructor \"%s\"",
716 else if (nonNull(findClass(t))) {
717 ERRMSG(line) "\"%s\" used as both class and type constructor",
722 Tycon nw = newTycon(t);
723 tyconDefns = cons(nw,tyconDefns);
724 tycon(nw).line = line;
725 tycon(nw).arity = argCount;
726 tycon(nw).what = what;
727 if (what==RESTRICTSYN) {
728 h98DoesntSupport(line,"restricted type synonyms");
729 typeInDefns = cons(pair(nw,snd(rhs)),typeInDefns);
732 tycon(nw).defn = pair(lhs,rhs);
736 Void setTypeIns(bs) /* set local synonyms for given */
737 List bs; { /* binding group */
738 List cvs = typeInDefns;
739 for (; nonNull(cvs); cvs=tl(cvs)) {
740 Tycon c = fst(hd(cvs));
741 List vs = snd(hd(cvs));
742 for (tycon(c).what = RESTRICTSYN; nonNull(vs); vs=tl(vs)) {
743 if (nonNull(findBinding(textOf(hd(vs)),bs))) {
744 tycon(c).what = SYNONYM;
751 Void clearTypeIns() { /* clear list of local synonyms */
752 for (; nonNull(typeInDefns); typeInDefns=tl(typeInDefns))
753 tycon(fst(hd(typeInDefns))).what = RESTRICTSYN;
756 /* --------------------------------------------------------------------------
757 * Further analysis of Type declarations:
759 * In order to allow the definition of mutually recursive families of
760 * data types, the static analysis of the right hand sides of type
761 * declarations cannot be performed until all of the type declarations
764 * Once parsing is complete, we carry out the following:
766 * - check format of lhs, extracting list of bound vars and ensuring that
767 * there are no repeated variables and no Skolem variables.
768 * - run dependency analysis on rhs to check that only bound type vars
769 * appear in type and that all constructors are defined.
770 * Replace type variables by offsets, constructors by Tycons.
771 * - use list of dependents to sort into strongly connected components.
772 * - ensure that there is not more than one synonym in each group.
773 * - kind-check each group of type definitions.
775 * - check that there are no previous definitions for constructor
776 * functions in data type definitions.
777 * - install synonym expansions and constructor definitions.
778 * ------------------------------------------------------------------------*/
780 static List tcDeps = NIL; /* list of dependent tycons/classes*/
782 static Void local checkTyconDefn(d) /* validate type constructor defn */
784 Cell lhs = fst(tycon(d).defn);
785 Cell rhs = snd(tycon(d).defn);
786 Int line = tycon(d).line;
787 List tyvars = getArgs(lhs);
789 /* check for repeated tyvars on lhs*/
790 for (temp=tyvars; nonNull(temp); temp=tl(temp))
791 if (nonNull(varIsMember(textOf(hd(temp)),tl(temp)))) {
792 ERRMSG(line) "Repeated type variable \"%s\" on left hand side",
793 textToStr(textOf(hd(temp)))
797 tcDeps = NIL; /* find dependents */
798 switch (whatIs(tycon(d).what)) {
800 case SYNONYM : rhs = depTypeExp(line,tyvars,rhs);
801 if (cellIsMember(d,tcDeps)) {
802 ERRMSG(line) "Recursive type synonym \"%s\"",
803 textToStr(tycon(d).text)
809 case NEWTYPE : depConstrs(d,tyvars,rhs);
813 default : internal("checkTyconDefn");
818 tycon(d).kind = tcDeps;
822 static Void local depConstrs(t,tyvars,cd)
823 Tycon t; /* Define constructor functions and*/
824 List tyvars; /* do dependency analysis for data */
825 Cell cd; { /* definitions (w or w/o deriving) */
826 Int line = tycon(t).line;
831 List derivs = snd(cd);
832 List compTypes = NIL;
836 for (i=0; i<tycon(t).arity; ++i) /* build representation for tycon */
837 lhs = ap(lhs,mkOffset(i)); /* applied to full comp. of args */
839 if (whatIs(cs)==QUAL) { /* allow for possible context */
842 map2Proc(depPredExp,line,tyvars,ctxt);
843 h98CheckCtxt(line,"context",TRUE,ctxt,NIL);
846 if (nonNull(cs) && isNull(tl(cs))) /* Single constructor datatype? */
849 for (; nonNull(cs); cs=tl(cs)) { /* For each constructor function: */
851 List sig = dupList(tyvars);
852 List evs = NIL; /* locally quantified vars */
853 List lps = NIL; /* locally bound predicates */
854 List ctxt1 = ctxt; /* constructor function context */
855 List scs = NIL; /* strict components */
856 List fs = NONE; /* selector names */
857 Type type = lhs; /* constructor function type */
858 Int arity = 0; /* arity of constructor function */
859 Int nr2 = 0; /* Number of rank 2 args */
860 Name n; /* name for constructor function */
862 if (whatIs(con)==POLYTYPE) { /* Locally quantified vars */
865 sig = checkQuantVars(line,evs,sig,con);
868 if (whatIs(con)==QUAL) { /* Local predicates */
871 for (us = typeVarsIn(lps,NIL,NIL); nonNull(us); us=tl(us))
872 if (!varIsMember(textOf(hd(us)),evs)) {
874 "Variable \"%s\" in constraint is not locally bound",
875 textToStr(textOf(hd(us)))
878 map2Proc(depPredExp,line,sig,lps);
883 if (whatIs(con)==LABC) { /* Skeletize constr components */
884 Cell fls = snd(snd(con)); /* get field specifications */
887 for (; nonNull(fls); fls=tl(fls)) { /* for each field spec: */
888 List vs = fst(hd(fls));
889 Type t = snd(hd(fls)); /* - scrutinize type */
890 Bool banged = whatIs(t)==BANG;
891 t = depCompType(line,sig,(banged ? arg(t) : t));
892 while (nonNull(vs)) { /* - add named components */
900 scs = cons(mkInt(arity),scs);
904 scs = rev(scs); /* put strict comps in ascend ord */
906 else { /* Non-labelled constructor */
909 for (; isAp(c); c=fun(c))
911 for (compNo=arity, c=con; isAp(c); c=fun(c)) {
913 if (whatIs(t)==BANG) {
914 scs = cons(mkInt(compNo),scs);
918 arg(c) = depCompType(line,sig,t);
922 if (nonNull(ctxt1)) /* Extract relevant part of context*/
923 ctxt1 = selectCtxt(ctxt1,offsetTyvarsIn(con,NIL));
925 for (i=arity; isAp(con); i--) { /* Calculate type of constructor */
928 fun(con) = typeArrow;
929 if (isPolyType(cmp)) {
930 if (nonNull(derivs)) {
931 ERRMSG(line) "Cannot derive instances for types" ETHEN
932 ERRTEXT " with polymorphic components"
938 if (nonNull(derivs)) /* and build list of components */
939 compTypes = cons(cmp,compTypes);
944 if (nr2>0) /* Add rank 2 annotation */
945 type = ap(RANK2,pair(mkInt(nr2),type));
947 if (nonNull(evs)) { /* Add existential annotation */
948 if (nonNull(derivs)) {
949 ERRMSG(line) "Cannot derive instances for types" ETHEN
950 ERRTEXT " with existentially typed components"
955 "Cannot use selectors with existentially typed components"
958 type = ap(EXIST,pair(mkInt(length(evs)),type));
961 if (nonNull(lps)) { /* Add local preds part to type */
962 type = ap(CDICTS,pair(lps,type));
965 if (nonNull(ctxt1)) { /* Add context part to type */
966 type = ap(QUAL,pair(ctxt1,type));
969 if (nonNull(sig)) { /* Add quantifiers to type */
971 for (; nonNull(ts1); ts1=tl(ts1)) {
974 type = mkPolyType(sig,type);
977 n = findName(textOf(con)); /* Allocate constructor fun name */
979 n = newName(textOf(con),NIL);
980 } else if (name(n).defn!=PREDEFINED) {
981 duplicateError(line,name(n).mod,name(n).text,
982 "constructor function");
984 name(n).arity = arity; /* Save constructor fun details */
987 name(n).number = cfunNo(conNo++);
989 if (tycon(t).what==NEWTYPE) {
992 "A newtype constructor cannot have class constraints"
997 "A newtype constructor must have exactly one argument"
1002 "Illegal strictess annotation for newtype constructor"
1005 name(n).defn = nameId;
1007 implementCfun(n,scs);
1012 sels = addSels(line,n,fs,sels);
1016 if (nonNull(sels)) {
1018 fst(cd) = appendOnto(fst(cd),sels);
1019 selDefns = cons(sels,selDefns);
1022 if (nonNull(derivs)) { /* Generate derived instances */
1023 map3Proc(checkDerive,t,ctxt,compTypes,derivs);
1027 Int userArity(c) /* Find arity for cfun, ignoring */
1028 Name c; { /* CDICTS parameters */
1029 Int a = name(c).arity;
1030 Type t = name(c).type;
1032 if (isPolyType(t)) {
1035 if ((w=whatIs(t))==QUAL) {
1036 w = whatIs(t=snd(snd(t)));
1039 a -= length(fst(snd(t)));
1045 static List local addSels(line,c,fs,ss) /* Add fields to selector list */
1046 Int line; /* line number of constructor */
1047 Name c; /* corresponding constr function */
1048 List fs; /* list of fields (varids) */
1049 List ss; { /* list of existing selectors */
1051 cfunSfuns = cons(pair(c,fs),cfunSfuns);
1052 for (; nonNull(fs); fs=tl(fs), ++sn) {
1054 Text t = textOf(hd(fs));
1056 if (nonNull(varIsMember(t,tl(fs)))) {
1057 ERRMSG(line) "Repeated field name \"%s\" for constructor \"%s\"",
1058 textToStr(t), textToStr(name(c).text)
1062 while (nonNull(ns) && t!=name(hd(ns)).text) {
1067 name(hd(ns)).defn = cons(pair(c,mkInt(sn)),name(hd(ns)).defn);
1069 Name n = findName(t);
1071 ERRMSG(line) "Repeated definition for selector \"%s\"",
1076 name(n).line = line;
1077 name(n).number = SELNAME;
1078 name(n).defn = singleton(pair(c,mkInt(sn)));
1085 static List local selectCtxt(ctxt,vs) /* calculate subset of context */
1092 for (; nonNull(ctxt); ctxt=tl(ctxt)) {
1093 List us = offsetTyvarsIn(hd(ctxt),NIL);
1094 for (; nonNull(us) && cellIsMember(hd(us),vs); us=tl(us)) {
1097 ps = cons(hd(ctxt),ps);
1104 static Void local checkSynonyms(ts) /* Check for mutually recursive */
1105 List ts; { /* synonyms */
1107 for (; nonNull(ts); ts=tl(ts)) { /* build list of all synonyms */
1109 switch (whatIs(tycon(t).what)) {
1111 case RESTRICTSYN : syns = cons(t,syns);
1115 while (nonNull(syns)) { /* then visit each synonym */
1116 syns = visitSyn(NIL,hd(syns),syns);
1120 static List local visitSyn(path,t,syns) /* visit synonym definition to look*/
1121 List path; /* for cycles */
1124 if (cellIsMember(t,path)) { /* every elt in path depends on t */
1125 ERRMSG(tycon(t).line)
1126 "Type synonyms \"%s\" and \"%s\" are mutually recursive",
1127 textToStr(tycon(t).text), textToStr(tycon(hd(path)).text)
1130 List ds = tycon(t).kind;
1132 for (; nonNull(ds); ds=tl(ds)) {
1133 if (cellIsMember(hd(ds),syns)) {
1134 if (isNull(path1)) {
1135 path1 = cons(t,path);
1137 syns = visitSyn(path1,hd(ds),syns);
1141 tycon(t).defn = fullExpand(tycon(t).defn);
1142 return removeCell(t,syns);
1145 /* --------------------------------------------------------------------------
1146 * Expanding out all type synonyms in a type expression:
1147 * ------------------------------------------------------------------------*/
1149 Type fullExpand(t) /* find full expansion of type exp */
1150 Type t; { /* assuming that all relevant */
1151 Cell h = t; /* synonym defns of lower rank have*/
1152 Int n = 0; /* already been fully expanded */
1154 for (args=NIL; isAp(h); h=fun(h), n++) {
1155 args = cons(fullExpand(arg(h)),args);
1157 t = applyToArgs(h,args);
1158 if (isSynonym(h) && n>=tycon(h).arity) {
1159 if (n==tycon(h).arity) {
1160 t = instantiateSyn(tycon(h).defn,t);
1163 while (--n > tycon(h).arity) {
1166 fun(p) = instantiateSyn(tycon(h).defn,fun(p));
1172 static Type local instantiateSyn(t,env) /* instantiate type according using*/
1173 Type t; /* env to determine appropriate */
1174 Type env; { /* values for OFFSET type vars */
1175 switch (whatIs(t)) {
1176 case AP : return ap(instantiateSyn(fun(t),env),
1177 instantiateSyn(arg(t),env));
1179 case OFFSET : return nthArg(offsetOf(t),env);
1185 /* --------------------------------------------------------------------------
1186 * Static analysis of class declarations:
1188 * Performed in a similar manner to that used for type declarations.
1190 * The first part of the static analysis is performed as the declarations
1191 * are read during parsing. The parser ensures that:
1192 * - the class header and all superclass predicates are of the form
1195 * The classDefn() function:
1196 * - ensures that there is no previous definition for class
1197 * - checks that class name has not previously been used as a type constr.
1198 * - make new entry in class table
1199 * - record line number of declaration
1200 * - build list of classes defined in current script for use in later
1201 * stages of static analysis.
1202 * ------------------------------------------------------------------------*/
1204 Void classDefn(line,head,ms) /* process new class definition */
1205 Int line; /* definition line number */
1206 Cell head; /* class header :: ([Supers],Class) */
1207 List ms; { /* class definition body */
1208 Text ct = textOf(getHead(snd(head)));
1209 Int arity = argCount;
1211 if (nonNull(findClass(ct))) {
1212 ERRMSG(line) "Repeated definition of class \"%s\"",
1215 } else if (nonNull(findTycon(ct))) {
1216 ERRMSG(line) "\"%s\" used as both class and type constructor",
1220 Class nw = newClass(ct);
1221 cclass(nw).line = line;
1222 cclass(nw).arity = arity;
1223 cclass(nw).head = snd(head);
1224 cclass(nw).supers = fst(head);
1225 cclass(nw).members = ms;
1226 cclass(nw).level = 0;
1227 classDefns = cons(nw,classDefns);
1229 h98DoesntSupport(line,"multiple parameter classes");
1233 /* --------------------------------------------------------------------------
1234 * Further analysis of class declarations:
1236 * Full static analysis of class definitions must be postponed until the
1237 * complete script has been read and all static analysis on type definitions
1238 * has been completed.
1240 * Once this has been achieved, we carry out the following checks on each
1242 * - check that variables in header are distinct
1243 * - replace head by skeleton
1244 * - check superclass declarations, replace by skeletons
1245 * - split body of class into members and declarations
1246 * - make new name entry for each member function
1247 * - record member function number (eventually an offset into dictionary!)
1248 * - no member function has a previous definition ...
1249 * - no member function is mentioned more than once in the list of members
1250 * - each member function type is valid, replace vars by offsets
1251 * - qualify each member function type by class header
1252 * - only bindings for members appear in defaults
1253 * - only function bindings appear in defaults
1254 * - check that extended class hierarchy does not contain any cycles
1255 * ------------------------------------------------------------------------*/
1257 static Void local checkClassDefn(c) /* validate class definition */
1260 Int args = cclass(c).arity - 1;
1261 Cell temp = cclass(c).head;
1265 for (; isAp(temp); temp=fun(temp)) {
1266 if (!isVar(arg(temp))) {
1267 ERRMSG(cclass(c).line) "Type variable required in class head"
1270 if (nonNull(varIsMember(textOf(arg(temp)),tyvars))) {
1271 ERRMSG(cclass(c).line)
1272 "Repeated type variable \"%s\" in class head",
1273 textToStr(textOf(arg(temp)))
1276 tyvars = cons(arg(temp),tyvars);
1279 for (temp=cclass(c).head; args>0; temp=fun(temp), args--) {
1280 arg(temp) = mkOffset(args);
1282 arg(temp) = mkOffset(0);
1285 tcDeps = NIL; /* find dependents */
1286 map2Proc(depPredExp,cclass(c).line,tyvars,cclass(c).supers);
1287 h98CheckCtxt(cclass(c).line,"class definition",FALSE,cclass(c).supers,NIL);
1288 cclass(c).numSupers = length(cclass(c).supers);
1289 cclass(c).defaults = extractBindings(cclass(c).members); /* defaults*/
1290 ss = extractSigdecls(cclass(c).members);
1291 fs = extractFixdecls(cclass(c).members);
1292 cclass(c).members = pair(ss,fs);
1293 map2Proc(checkMems,c,tyvars,ss);
1295 cclass(c).kinds = tcDeps;
1299 static Void local depPredExp(line,tyvars,pred)
1303 Int args = 1; /* parser guarantees >=1 args */
1305 for (; isAp(h); args++) {
1306 arg(pred) = depTypeExp(line,tyvars,arg(pred));
1310 arg(pred) = depTypeExp(line,tyvars,arg(pred));
1312 h98DoesntSupport(line,"multiple parameter classes");
1314 if (isQCon(h)) { /* standard class constraint */
1315 Class c = findQualClass(h);
1317 ERRMSG(line) "Undefined class \"%s\"", identToStr(h)
1321 if (args!=cclass(c).arity) {
1322 ERRMSG(line) "Wrong number of arguments for class \"%s\"",
1323 textToStr(cclass(c).text)
1326 if (cellIsMember(c,classDefns) && !cellIsMember(c,tcDeps)) {
1327 tcDeps = cons(c,tcDeps);
1331 else if (isExt(h)) { /* Lacks predicate */
1332 if (args!=1) { /* parser shouldn't let this happen*/
1333 ERRMSG(line) "Wrong number of arguments for lacks predicate"
1338 else { /* check for other kinds of pred */
1339 internal("depPredExp"); /* ... but there aren't any! */
1343 static Void local checkMems(c,tyvars,m) /* check member function details */
1347 Int line = intOf(fst3(m));
1353 tyvars = typeVarsIn(t,NIL,tyvars);/* Look for extra type vars. */
1355 if (whatIs(t)==QUAL) { /* Overloaded member signatures? */
1356 map2Proc(depPredExp,line,tyvars,fst(snd(t)));
1358 t = ap(QUAL,pair(NIL,t));
1361 fst(snd(t)) = cons(cclass(c).head,fst(snd(t)));/* Add main predicate */
1362 snd(snd(t)) = depTopType(line,tyvars,snd(snd(t)));
1364 for (tvs=tyvars; nonNull(tvs); tvs=tl(tvs)){/* Quantify */
1367 t = mkPolyType(sig,t);
1368 thd3(m) = t; /* Save type */
1369 take(cclass(c).arity,tyvars); /* Delete extra type vars */
1371 if (isAmbiguous(t)) {
1372 ambigError(line,"class declaration",hd(vs),t);
1374 h98CheckType(line,"member type",hd(vs),t);
1377 static Void local addMembers(c) /* Add definitions of member funs */
1378 Class c; { /* and other parts of class struct.*/
1379 List ms = fst(cclass(c).members);
1380 List fs = snd(cclass(c).members);
1381 List ns = NIL; /* List of names */
1382 Int mno; /* Member function number */
1384 for (mno=0; mno<cclass(c).numSupers; mno++) {
1385 ns = cons(newDSel(c,mno),ns);
1387 cclass(c).dsels = rev(ns); /* Save dictionary selectors */
1389 for (mno=1, ns=NIL; nonNull(ms); ms=tl(ms)) {
1390 Int line = intOf(fst3(hd(ms)));
1391 List vs = rev(snd3(hd(ms)));
1392 Type t = thd3(hd(ms));
1393 for (; nonNull(vs); vs=tl(vs)) {
1394 ns = cons(newMember(line,mno++,hd(vs),t,c),ns);
1397 cclass(c).members = rev(ns); /* Save list of members */
1398 cclass(c).numMembers = length(cclass(c).members);
1400 for (; nonNull(fs); fs=tl(fs)) { /* fixity declarations */
1401 Int line = intOf(fst3(hd(fs)));
1402 List ops = snd3(hd(fs));
1403 Syntax s = intOf(thd3(hd(fs)));
1404 for (; nonNull(ops); ops=tl(ops)) {
1405 Name n = nameIsMember(textOf(hd(ops)),cclass(c).members);
1407 missFixity(line,textOf(hd(ops)));
1408 } else if (name(n).syntax!=NO_SYNTAX) {
1409 dupFixity(line,textOf(hd(ops)));
1415 /* Not actually needed just yet; for the time being, dictionary code will
1416 not be passed through the type checker.
1418 cclass(c).dtycon = addPrimTycon(generateText("Dict.%s",c),
1425 mno = cclass(c).numSupers + cclass(c).numMembers;
1426 cclass(c).dcon = addPrimCfun(generateText("Make.%s",c),mno,0,NIL);
1427 implementCfun(cclass(c).dcon,NIL); /* ADR addition */
1429 if (mno==1) { /* Single entry dicts use newtype */
1430 name(cclass(c).dcon).defn = nameId;
1431 name(hd(cclass(c).members)).number = mfunNo(0);
1433 cclass(c).dbuild = newDBuild(c);
1434 cclass(c).defaults = classBindings("class",c,cclass(c).defaults);
1437 static Name local newMember(l,no,v,t,parent)
1438 Int l; /* Make definition for member fn */
1443 Name m = findName(textOf(v));
1446 m = newName(textOf(v),parent);
1447 } else if (name(m).defn!=PREDEFINED) {
1448 ERRMSG(l) "Repeated definition for member function \"%s\"",
1449 textToStr(name(m).text)
1455 name(m).number = mfunNo(no);
1457 name(m).inlineMe = TRUE;
1461 static Name local newDSel(c,no) /* Make definition for dict selectr*/
1467 sprintf(buf,"sc%d.%s",no,"%s");
1468 s = newName(generateText(buf,c),c);
1469 name(s).line = cclass(c).line;
1471 name(s).number = DFUNNAME;
1475 static Name local newDBuild(c) /* Make definition for builder */
1477 Name b = newName(generateText("class.%s",c),c);
1478 name(b).line = cclass(c).line;
1479 name(b).arity = cclass(c).numSupers+1;
1485 static Text local generateText(sk,c) /* We need to generate names for */
1486 String sk; /* certain objects corresponding */
1487 Class c; { /* to each class. */
1488 String cname = textToStr(cclass(c).text);
1489 char buffer[MAX_GEN+1];
1491 if ((strlen(sk)+strlen(cname))>=MAX_GEN) {
1492 ERRMSG(0) "Please use a shorter name for class \"%s\"", cname
1495 sprintf(buffer,sk,cname);
1496 return findText(buffer);
1499 static Int local visitClass(c) /* visit class defn to check that */
1500 Class c; { /* class hierarchy is acyclic */
1502 if (isExt(c)) { /* special case for lacks preds */
1506 if (cclass(c).level < 0) { /* already visiting this class? */
1507 ERRMSG(cclass(c).line) "Class hierarchy for \"%s\" is not acyclic",
1508 textToStr(cclass(c).text)
1510 } else if (cclass(c).level == 0) { /* visiting class for first time */
1511 List scs = cclass(c).supers;
1513 cclass(c).level = (-1);
1514 for (; nonNull(scs); scs=tl(scs)) {
1515 Int l = visitClass(getHead(hd(scs)));
1518 cclass(c).level = 1+lev; /* level = 1 + max level of supers */
1520 return cclass(c).level;
1523 /* --------------------------------------------------------------------------
1524 * Process class and instance declaration binding groups:
1525 * ------------------------------------------------------------------------*/
1527 static List local classBindings(where,c,bs)
1528 String where; /* Check validity of bindings bs */
1529 Class c; /* for class c (or an inst of c) */
1530 List bs; { /* sort into approp. member order */
1533 for (; nonNull(bs); bs=tl(bs)) {
1535 Cell body = snd(snd(b));
1538 if (!isVar(fst(b))) { /* Only allow function bindings */
1539 ERRMSG(rhsLine(snd(body)))
1540 "Pattern binding illegal in %s declaration", where
1544 if (isNull(mnm=memberName(c,textOf(fst(b))))) {
1545 ERRMSG(rhsLine(snd(hd(body))))
1546 "No member \"%s\" in class \"%s\"",
1547 textToStr(textOf(fst(b))), textToStr(cclass(c).text)
1551 nbs = numInsert(mfunOf(mnm)-1,b,nbs);
1556 static Name local memberName(c,t) /* return name of member function */
1557 Class c; /* with name t in class c */
1558 Text t; { /* return NIL if not a member */
1559 List ms = cclass(c).members;
1560 for (; nonNull(ms); ms=tl(ms)) {
1561 if (t==name(hd(ms)).text) {
1568 static List local numInsert(n,x,xs) /* insert x at nth position in xs, */
1569 Int n; /* filling gaps with NIL */
1572 List start = isNull(xs) ? cons(NIL,NIL) : xs;
1574 for (xs=start; 0<n--; xs=tl(xs)) {
1575 if (isNull(tl(xs))) {
1576 tl(xs) = cons(NIL,NIL);
1583 /* --------------------------------------------------------------------------
1584 * Calculate set of variables appearing in a given type expression (possibly
1585 * qualified) as a list of distinct values. The order in which variables
1586 * appear in the list is the same as the order in which those variables
1587 * occur in the type expression when read from left to right.
1588 * ------------------------------------------------------------------------*/
1590 List typeVarsIn(ty,us,vs) /* Calculate list of type variables*/
1591 Cell ty; /* used in type expression, reading*/
1592 List us; /* from left to right ignoring any */
1593 List vs; { /* listed in us. */
1594 switch (whatIs(ty)) {
1595 case AP : return typeVarsIn(snd(ty),us,
1596 typeVarsIn(fst(ty),us,vs));
1599 case VAROPCELL : if (nonNull(findBtyvs(textOf(ty)))
1600 || varIsMember(textOf(ty),us)) {
1603 return maybeAppendVar(ty,vs);
1606 case POLYTYPE : return typeVarsIn(monotypeOf(ty),polySigOf(ty),vs);
1608 case QUAL : { List qs = fst(snd(ty));
1609 for (; nonNull(qs); qs=tl(qs)) {
1610 vs = typeVarsIn(hd(qs),us,vs);
1612 return typeVarsIn(snd(snd(ty)),us,vs);
1615 case BANG : return typeVarsIn(snd(ty),us,vs);
1617 case LABC : { List fs = snd(snd(ty));
1618 for (; nonNull(fs); fs=tl(fs)) {
1619 vs = typeVarsIn(snd(hd(fs)),us,vs);
1627 static List local maybeAppendVar(v,vs) /* append variable to list if not */
1628 Cell v; /* already included */
1634 while (nonNull(c)) {
1635 if (textOf(hd(c))==t) {
1643 tl(p) = cons(v,NIL);
1651 /* --------------------------------------------------------------------------
1652 * Static analysis for type expressions is required to:
1653 * - ensure that each type constructor or class used has been defined.
1654 * - replace type variables by offsets, constructor names by Tycons.
1655 * - ensure that the type is well-kinded.
1656 * ------------------------------------------------------------------------*/
1658 static Type local checkSigType(line,where,e,type)
1659 Int line; /* Check validity of type expr in */
1660 String where; /* explicit type signature */
1663 List tvs = typeVarsIn(type,NIL,NIL);
1664 Int n = length(tvs);
1665 List sunk = unkindTypes;
1667 if (whatIs(type)==QUAL) {
1668 map2Proc(depPredExp,line,tvs,fst(snd(type)));
1669 snd(snd(type)) = depTopType(line,tvs,snd(snd(type)));
1671 if (isAmbiguous(type)) {
1672 ambigError(line,where,e,type);
1675 type = depTopType(line,tvs,type);
1679 if (n>=NUM_OFFSETS) {
1680 ERRMSG(line) "Too many type variables in %s\n", where
1684 for (; nonNull(ts); ts=tl(ts)) {
1687 type = mkPolyType(tvs,type);
1692 kindType(line,"type expression",type);
1696 h98CheckType(line,where,e,type);
1700 static Type local depTopType(l,tvs,t) /* Check top-level of type sig */
1708 for (; getHead(t1)==typeArrow && argCount==2; ++i) {
1709 arg(fun(t1)) = depCompType(l,tvs,arg(fun(t1)));
1710 if (isPolyType(arg(fun(t1)))) {
1716 if (nonNull(prev)) {
1717 arg(prev) = depTypeExp(l,tvs,t1);
1719 t = depTypeExp(l,tvs,t1);
1722 t = ap(RANK2,pair(mkInt(nr2),t));
1727 static Type local depCompType(l,tvs,t) /* Check component type for constr */
1731 if (isPolyType(t)) {
1732 Int ntvs = length(tvs);
1734 if (isPolyType(t)) {
1735 List vs = fst(snd(t));
1737 tvs = checkQuantVars(l,vs,tvs,t);
1738 nfr = replicate(length(vs),NIL);
1740 if (whatIs(t)==QUAL) {
1741 map2Proc(depPredExp,l,tvs,fst(snd(t)));
1742 snd(snd(t)) = depTypeExp(l,tvs,snd(snd(t)));
1743 if (isAmbiguous(t)) {
1744 ambigError(l,"type component",NIL,t);
1747 t = depTypeExp(l,tvs,t);
1753 return mkPolyType(nfr,t);
1755 return depTypeExp(l,tvs,t);
1759 static Type local depTypeExp(line,tyvars,type)
1763 switch (whatIs(type)) {
1764 case AP : fst(type) = depTypeExp(line,tyvars,fst(type));
1765 snd(type) = depTypeExp(line,tyvars,snd(type));
1768 case VARIDCELL : return depTypeVar(line,tyvars,textOf(type));
1770 case QUALIDENT : if (isQVar(type)) {
1771 ERRMSG(line) "Qualified type variables not allowed"
1774 /* deliberate fall through */
1775 case CONIDCELL : { Tycon tc = findQualTycon(type);
1778 "Undefined type constructor \"%s\"",
1782 if (cellIsMember(tc,tyconDefns) &&
1783 !cellIsMember(tc,tcDeps)) {
1784 tcDeps = cons(tc,tcDeps);
1790 case EXT : h98DoesntSupport(line,"extensible records");
1795 default : internal("depTypeExp");
1800 static Type local depTypeVar(line,tyvars,tv)
1805 Cell vt = findBtyvs(tv);
1810 for (; nonNull(tyvars) && tv!=textOf(hd(tyvars)); offset++) {
1811 tyvars = tl(tyvars);
1813 if (isNull(tyvars)) {
1814 ERRMSG(line) "Undefined type variable \"%s\"", textToStr(tv)
1817 return mkOffset(offset);
1820 static List local checkQuantVars(line,vs,tvs,body)
1822 List vs; /* variables to quantify over */
1823 List tvs; /* variables already in scope */
1824 Cell body; { /* type/constr for scope of vars */
1826 List bvs = typeVarsIn(body,NIL,NIL);
1828 for (; nonNull(us); us=tl(us)) {
1829 Text u = textOf(hd(us));
1830 if (varIsMember(u,tl(us))) {
1831 ERRMSG(line) "Duplicated quantified variable %s",
1835 if (varIsMember(u,tvs)) {
1836 ERRMSG(line) "Local quantifier for %s hides an outer use",
1840 if (!varIsMember(u,bvs)) {
1841 ERRMSG(line) "Locally quantified variable %s is not used",
1846 tvs = appendOnto(tvs,vs);
1851 /* --------------------------------------------------------------------------
1852 * Check for ambiguous types:
1853 * A type Preds => type is ambiguous if not (TV(P) `subset` TV(type))
1854 * ------------------------------------------------------------------------*/
1856 List offsetTyvarsIn(t,vs) /* add list of offset tyvars in t */
1857 Type t; /* to list vs */
1859 switch (whatIs(t)) {
1860 case AP : return offsetTyvarsIn(fun(t),
1861 offsetTyvarsIn(arg(t),vs));
1863 case OFFSET : if (cellIsMember(t,vs))
1868 case QUAL : return offsetTyvarsIn(snd(t),vs);
1870 case POLYTYPE : return offsetTyvarsIn(monotypeOf(t),vs);
1871 /* slightly inaccurate, but won't matter here */
1874 case RANK2 : return offsetTyvarsIn(snd(snd(t)),vs);
1876 default : return vs;
1880 Bool isAmbiguous(type) /* Determine whether type is */
1881 Type type; { /* ambiguous */
1882 if (isPolyType(type)) {
1883 type = monotypeOf(type);
1885 if (whatIs(type)==QUAL) { /* only qualified types can be */
1886 List tvps = offsetTyvarsIn(fst(snd(type)),NIL); /* ambiguous */
1887 List tvts = offsetTyvarsIn(snd(snd(type)),NIL);
1888 while (nonNull(tvps) && cellIsMember(hd(tvps),tvts)) {
1891 return nonNull(tvps);
1896 Void ambigError(line,where,e,type) /* produce error message for */
1897 Int line; /* ambiguity */
1901 ERRMSG(line) "Ambiguous type signature in %s", where ETHEN
1902 ERRTEXT "\n*** ambiguous type : " ETHEN ERRTYPE(type);
1904 ERRTEXT "\n*** assigned to : " ETHEN ERREXPR(e);
1910 /* --------------------------------------------------------------------------
1911 * Kind inference for simple types:
1912 * ------------------------------------------------------------------------*/
1914 static Void local kindConstr(line,alpha,m,c)
1915 Int line; /* Determine kind of constructor */
1919 Cell h = getHead(c);
1923 Printf("kindConstr: alpha=%d, m=%d, c=",alpha,m);
1924 printType(stdout,c);
1928 switch (whatIs(h)) {
1929 case POLYTYPE : if (n!=0) {
1930 internal("kindConstr1");
1932 static String pt = "polymorphic type";
1933 Type t = dropRank1(c,alpha,m);
1934 Kinds ks = polySigOf(t);
1937 for (; isAp(ks); ks=tl(ks)) {
1940 beta = newKindvars(m1);
1941 unkindTypes = cons(pair(mkInt(beta),t),unkindTypes);
1942 checkKind(line,beta,m1,monotypeOf(t),NIL,pt,STAR,0);
1947 case QUAL : if (n!=0) {
1948 internal("kindConstr2");
1950 map3Proc(kindPred,line,alpha,m,fst(snd(c)));
1951 kindConstr(line,alpha,m,snd(snd(c)));
1955 case RANK2 : kindConstr(line,alpha,m,snd(snd(c)));
1959 case EXT : if (n!=2) {
1961 "Illegal use of row in " ETHEN ERRTYPE(c);
1968 case TYCON : if (isSynonym(h) && n<tycon(h).arity) {
1970 "Not enough arguments for type synonym \"%s\"",
1971 textToStr(tycon(h).text)
1977 if (n==0) { /* trivial case, no arguments */
1978 typeIs = kindAtom(alpha,c);
1979 } else { /* non-trivial application */
1980 static String app = "constructor application";
1990 typeIs = kindAtom(alpha,h); /* h :: v1 -> ... -> vn -> w */
1991 shouldKind(line,h,c,app,k,beta);
1993 for (i=n; i>0; --i) { /* ci :: vi for each 1 <- 1..n */
1994 checkKind(line,alpha,m,arg(a),c,app,aVar,beta+i-1);
1997 tyvarType(beta+n); /* inferred kind is w */
2001 static Kind local kindAtom(alpha,c) /* Find kind of atomic constructor */
2004 switch (whatIs(c)) {
2005 case TUPLE : return simpleKind(tupleOf(c)); /*(,)::* -> * -> * */
2006 case OFFSET : return mkInt(alpha+offsetOf(c));
2007 case TYCON : return tycon(c).kind;
2008 case INTCELL : return c;
2010 case VAROPCELL : { Cell vt = findBtyvs(textOf(c));
2016 case EXT : return extKind;
2020 Printf("kindAtom(%d,whatIs(%d)) on ",alpha,whatIs(c));
2021 printType(stdout,c);
2024 internal("kindAtom");
2025 return STAR;/* not reached */
2028 static Void local kindPred(l,alpha,m,pi)/* Check kinds of arguments in pred*/
2034 if (isExt(fun(pi))) {
2035 static String lackspred = "lacks predicate";
2036 checkKind(l,alpha,m,arg(pi),NIL,lackspred,ROW,0);
2040 { static String predicate = "class constraint";
2041 Class c = getHead(pi);
2042 List as = getArgs(pi);
2043 Kinds ks = cclass(c).kinds;
2045 while (nonNull(ks)) {
2046 checkKind(l,alpha,m,hd(as),NIL,predicate,hd(ks),0);
2053 static Void local kindType(line,wh,type)/* check that (poss qualified) type*/
2054 Int line; /* is well-kinded */
2057 checkKind(line,0,0,type,NIL,wh,STAR,0);
2060 static Void local fixKinds() { /* add kind annotations to types */
2061 for (; nonNull(unkindTypes); unkindTypes=tl(unkindTypes)) {
2062 Pair pr = hd(unkindTypes);
2063 Int beta = intOf(fst(pr));
2064 Cell qts = polySigOf(snd(pr));
2066 if (isNull(hd(qts))) {
2067 hd(qts) = copyKindvar(beta++);
2069 internal("fixKinds");
2071 if (nonNull(tl(qts))) {
2079 Printf("Type expression: ");
2080 printType(stdout,snd(pr));
2082 printKind(stdout,polySigOf(snd(pr)));
2088 /* --------------------------------------------------------------------------
2089 * Kind checking of groups of type constructors and classes:
2090 * ------------------------------------------------------------------------*/
2092 static Void local kindTCGroup(tcs) /* find kinds for mutually rec. gp */
2093 List tcs; { /* of tycons and classes */
2094 emptySubstitution();
2096 mapProc(initTCKind,tcs);
2097 mapProc(kindTC,tcs);
2100 emptySubstitution();
2103 static Void local initTCKind(c) /* build initial kind/arity for c */
2105 if (isTycon(c)) { /* Initial kind of tycon is: */
2106 Int beta = newKindvars(1); /* v1 -> ... -> vn -> vn+1 */
2107 varKind(tycon(c).arity); /* where n is the arity of c. */
2108 bindTv(beta,typeIs,typeOff); /* For data definitions, vn+1 == * */
2109 switch (whatIs(tycon(c).what)) {
2111 case DATATYPE : bindTv(typeOff+tycon(c).arity,STAR,0);
2113 tycon(c).kind = mkInt(beta);
2115 Int n = cclass(c).arity;
2116 Int beta = newKindvars(n);
2117 cclass(c).kinds = NIL;
2120 cclass(c).kinds = pair(mkInt(beta+n),cclass(c).kinds);
2125 static Void local kindTC(c) /* check each part of a tycon/class*/
2126 Cell c; { /* is well-kinded */
2128 static String cfun = "constructor function";
2129 static String tsyn = "synonym definition";
2130 Int line = tycon(c).line;
2131 Int beta = tyvar(intOf(tycon(c).kind))->offs;
2132 Int m = tycon(c).arity;
2133 switch (whatIs(tycon(c).what)) {
2135 case DATATYPE : { List cs = tycon(c).defn;
2136 if (whatIs(cs)==QUAL) {
2137 map3Proc(kindPred,line,beta,m,
2139 tycon(c).defn = cs = snd(snd(cs));
2141 for (; hasCfun(cs); cs=tl(cs)) {
2142 kindType(line,cfun,name(hd(cs)).type);
2147 default : checkKind(line,beta,m,tycon(c).defn,NIL,
2151 else { /* scan type exprs in class defn to*/
2152 List ms = fst(cclass(c).members);
2153 Int m = cclass(c).arity; /* determine the class signature */
2154 Int beta = newKindvars(m);
2155 kindPred(cclass(c).line,beta,m,cclass(c).head);
2156 map3Proc(kindPred,cclass(c).line,beta,m,cclass(c).supers);
2157 for (; nonNull(ms); ms=tl(ms)) {
2158 Int line = intOf(fst3(hd(ms)));
2159 Type type = thd3(hd(ms));
2160 kindType(line,"member function type signature",type);
2165 static Void local genTC(c) /* generalise kind inferred for */
2166 Cell c; { /* given tycon/class */
2168 tycon(c).kind = copyKindvar(intOf(tycon(c).kind));
2170 Printf("%s :: ",textToStr(tycon(c).text));
2171 printKind(stdout,tycon(c).kind);
2175 Kinds ks = cclass(c).kinds;
2176 for (; nonNull(ks); ks=tl(ks)) {
2177 hd(ks) = copyKindvar(intOf(hd(ks)));
2180 Printf("%s :: ",textToStr(cclass(c).text));
2181 printKinds(stdout,cclass(c).kinds);
2187 /* --------------------------------------------------------------------------
2188 * Static analysis of instance declarations:
2190 * The first part of the static analysis is performed as the declarations
2191 * are read during parsing:
2192 * - make new entry in instance table
2193 * - record line number of declaration
2194 * - build list of instances defined in current script for use in later
2195 * stages of static analysis.
2196 * ------------------------------------------------------------------------*/
2198 Void instDefn(line,head,ms) /* process new instance definition */
2199 Int line; /* definition line number */
2200 Cell head; /* inst header :: (context,Class) */
2201 List ms; { /* instance members */
2202 Inst nw = newInst();
2203 inst(nw).line = line;
2204 inst(nw).specifics = fst(head);
2205 inst(nw).head = snd(head);
2206 inst(nw).implements = ms;
2207 instDefns = cons(nw,instDefns);
2210 /* --------------------------------------------------------------------------
2211 * Further static analysis of instance declarations:
2213 * Makes the following checks:
2214 * - Class part of header has form C (T a1 ... an) where C is a known
2215 * class, and T is a known datatype constructor (or restricted synonym),
2216 * and there is no previous C-T instance, and (T a1 ... an) has a kind
2217 * appropriate for the class C.
2218 * - Each element of context is a valid class expression, with type vars
2219 * drawn from a1, ..., an.
2220 * - All bindings are function bindings
2221 * - All bindings define member functions for class C
2222 * - Arrange bindings into appropriate order for member list
2223 * - No top level type signature declarations
2224 * ------------------------------------------------------------------------*/
2226 Bool allowOverlap = FALSE; /* TRUE => allow overlapping insts */
2227 Name nameListMonad = NIL; /* builder function for List Monad */
2229 static Void local checkInstDefn(in) /* Validate instance declaration */
2231 Int line = inst(in).line;
2232 List tyvars = typeVarsIn(inst(in).head,NIL,NIL);
2234 if (haskell98) { /* Check for `simple' type */
2236 Cell t = arg(inst(in).head);
2237 for (; isAp(t); t=fun(t)) {
2238 if (!isVar(arg(t))) {
2240 "syntax error in instance head (variable expected)"
2243 if (varIsMember(textOf(arg(t)),tvs)) {
2244 ERRMSG(line) "repeated type variable \"%s\" in instance head",
2245 textToStr(textOf(arg(t)))
2248 tvs = cons(arg(t),tvs);
2252 "syntax error in instance head (constructor expected)"
2257 depPredExp(line,tyvars,inst(in).head);
2260 Type h = getHead(arg(inst(in).head));
2262 ERRMSG(line) "Cannot use type synonym in instance head"
2267 map2Proc(depPredExp,line,tyvars,inst(in).specifics);
2268 h98CheckCtxt(line,"instance definition",FALSE,inst(in).specifics,NIL);
2269 inst(in).numSpecifics = length(inst(in).specifics);
2270 inst(in).c = getHead(inst(in).head);
2271 if (!isClass(inst(in).c)) {
2272 ERRMSG(line) "Illegal predicate in instance declaration"
2275 kindInst(in,length(tyvars));
2278 if (nonNull(extractSigdecls(inst(in).implements))) {
2280 "Type signature declarations not permitted in instance declaration"
2283 if (nonNull(extractFixdecls(inst(in).implements))) {
2285 "Fixity declarations not permitted in instance declaration"
2288 inst(in).implements = classBindings("instance",
2290 extractBindings(inst(in).implements));
2291 inst(in).builder = newInstImp(in);
2292 if (!preludeLoaded && isNull(nameListMonad) && isAp(inst(in).head)
2293 && fun(inst(in).head)==classMonad && arg(inst(in).head)==typeList) {
2294 nameListMonad = inst(in).builder;
2298 static Void local insertInst(in) /* Insert instance into class */
2300 Class c = inst(in).c;
2301 List ins = cclass(c).instances;
2304 substitution(RESET);
2305 while (nonNull(ins)) { /* Look for overlap w/ other insts */
2306 Int alpha = newKindedVars(inst(in).kinds);
2307 Int beta = newKindedVars(inst(hd(ins)).kinds);
2308 if (unifyPred(inst(in).head,alpha,inst(hd(ins)).head,beta)) {
2309 Cell pi = copyPred(inst(in).head,alpha);
2310 if (allowOverlap && !haskell98) {
2311 Bool bef = instCompare(in,hd(ins));
2312 Bool aft = instCompare(hd(ins),in);
2313 if (bef && !aft) { /* in comes strictly before hd(ins)*/
2316 if (aft && !bef) { /* in comes strictly after hd(ins) */
2322 ERRMSG(inst(in).line) "Overlapping instances for class \"%s\"",
2323 textToStr(cclass(c).text)
2325 ERRTEXT "\n*** This instance : " ETHEN ERRPRED(inst(in).head);
2326 ERRTEXT "\n*** Overlaps with : " ETHEN
2327 ERRPRED(inst(hd(ins)).head);
2328 ERRTEXT "\n*** Common instance : " ETHEN
2333 prev = ins; /* No overlap detected, so move on */
2334 ins = tl(ins); /* to next instance */
2336 substitution(RESET);
2338 if (nonNull(prev)) { /* Insert instance at this point */
2339 tl(prev) = cons(in,ins);
2341 cclass(c).instances = cons(in,ins);
2345 static Bool local instCompare(ia,ib) /* See if ia is an instance of ib */
2347 Int alpha = newKindedVars(inst(ia).kinds);
2348 Int beta = newKindedVars(inst(ib).kinds);
2349 return matchPred(inst(ia).head,alpha,inst(ib).head,beta);
2352 static Name local newInstImp(in) /* Make definition for inst builder*/
2354 Name b = newName(inventText(),in);
2355 name(b).line = inst(in).line;
2356 name(b).arity = inst(in).numSpecifics;
2357 name(b).number = DFUNNAME;
2361 /* --------------------------------------------------------------------------
2362 * Kind checking of instance declaration headers:
2363 * ------------------------------------------------------------------------*/
2365 static Void local kindInst(in,freedom) /* check predicates in instance */
2370 emptySubstitution();
2371 beta = newKindvars(freedom);
2372 kindPred(inst(in).line,beta,freedom,inst(in).head);
2373 if (whatIs(inst(in).specifics)!=DERIVE) {
2374 map3Proc(kindPred,inst(in).line,beta,freedom,inst(in).specifics);
2376 for (inst(in).kinds = NIL; 0<freedom--; ) {
2377 inst(in).kinds = cons(copyKindvar(beta+freedom),inst(in).kinds);
2380 Printf("instance ");
2381 printPred(stdout,inst(in).head);
2383 printKinds(stdout,inst(in).kinds);
2386 emptySubstitution();
2389 /* --------------------------------------------------------------------------
2390 * Process derived instance requests:
2391 * ------------------------------------------------------------------------*/
2393 static List derivedInsts; /* list of derived instances */
2395 static Void local checkDerive(t,p,ts,ct)/* verify derived instance request */
2396 Tycon t; /* for tycon t, with explicit */
2397 List p; /* context p, component types ts */
2398 List ts; /* and named class ct */
2400 Int line = tycon(t).line;
2401 Class c = findClass(textOf(ct));
2403 ERRMSG(line) "Unknown class \"%s\" in derived instance",
2404 textToStr(textOf(ct))
2407 addDerInst(line,c,p,dupList(ts),t,tycon(t).arity);
2410 static Void local addDerInst(line,c,p,cts,t,a) /* Add a derived instance */
2417 Cell head = t; /* Build instance head */
2421 head = ap(head,mkOffset(i));
2427 inst(in).line = line;
2428 inst(in).head = head;
2429 inst(in).specifics = ap(DERIVE,pair(dupList(p),cts));
2430 inst(in).implements = NIL;
2431 inst(in).kinds = mkInt(a);
2432 derivedInsts = cons(in,derivedInsts);
2435 Void addTupInst(c,n) /* Request derived instance of c */
2436 Class c; /* for mkTuple(n) constructor */
2441 cts = cons(mkOffset(m),cts);
2444 addDerInst(0,c,NIL,cts,mkTuple(n),n);
2448 Inst addRecShowInst(c,e) /* Generate instance for ShowRecRow*/
2449 Class c; /* c *must* be ShowRecRow */
2451 Inst in = newInst();
2453 inst(in).head = ap(c,ap2(e,aVar,bVar));
2454 inst(in).kinds = extKind;
2455 inst(in).specifics = cons(ap(classShow,aVar),
2457 cons(ap(c,bVar),NIL)));
2458 inst(in).numSpecifics = 3;
2459 inst(in).builder = implementRecShw(extText(e),in);
2460 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2464 Inst addRecEqInst(c,e) /* Generate instance for EqRecRow */
2465 Class c; /* c *must* be EqRecRow */
2467 Inst in = newInst();
2469 inst(in).head = ap(c,ap2(e,aVar,bVar));
2470 inst(in).kinds = extKind;
2471 inst(in).specifics = cons(ap(classEq,aVar),
2473 cons(ap(c,bVar),NIL)));
2474 inst(in).numSpecifics = 3;
2475 inst(in).builder = implementRecEq(extText(e),in);
2476 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2481 /* --------------------------------------------------------------------------
2482 * Calculation of contexts for derived instances:
2484 * Allowing arbitrary types to appear in contexts makes it rather harder
2485 * to decide what the context for a derived instance should be. For
2488 * data T a = MkT [a] deriving Show,
2490 * we could have either of the following:
2492 * instance (Show [a]) => Show (T a) where ...
2493 * instance (Show a) => Show (T a) where ...
2495 * (assuming, of course, that instance (Show a) => Show [a]). For now, we
2496 * choose to reduce contexts in the hope of detecting errors at an earlier
2497 * stage---in contrast with value definitions, there is no way for a user
2498 * to provide something analogous to a `type signature' by which they might
2499 * be able to control this behaviour themselves. We eliminate tautological
2500 * predicates, but only allow predicates to appear in the final result if
2501 * they have at least one argument with a variable at its head.
2503 * In general, we have to deal with mutually recursive instance declarations.
2504 * We find a solution in the obvious way by iterating to find a fixed point.
2505 * Of course, without restrictions on the form of instance declarations, we
2506 * cannot be sure that this will always terminate!
2508 * For each instance we maintain a pair of the form DERIVE (ctxt,ps).
2509 * Ctxt is a list giving the parts of the context that have been produced
2510 * so far in the form of predicate skeletons. During the calculation of
2511 * derived instances, we attach a dummy NIL value to the end of the list
2512 * which acts as a kind of `variable': other parts of the system maintain
2513 * pointers to this variable, and use it to detect when the context has
2514 * been extended with new elements. Meanwhile, ps is a list containing
2515 * predicates (pi,o) together with (delayed) substitutions of the form
2516 * (o,xs) where o is an offset and xs is one of the context variables
2517 * described above, which may have been partially instantiated.
2518 * ------------------------------------------------------------------------*/
2520 static Bool instsChanged;
2522 static Void local deriveContexts(is) /* Calc contexts for derived insts */
2524 emptySubstitution();
2525 mapProc(initDerInst,is); /* Prepare derived instances */
2527 do { /* Main calculation of contexts */
2528 instsChanged = FALSE;
2529 mapProc(calcInstPreds,is);
2530 } while (instsChanged);
2532 mapProc(tidyDerInst,is); /* Tidy up results */
2535 static Void local initDerInst(in) /* Prepare instance for calculation*/
2536 Inst in; { /* of derived instance context */
2537 Cell spcs = inst(in).specifics;
2538 Int beta = newKindedVars(inst(in).kinds);
2539 if (whatIs(spcs)!=DERIVE) {
2540 internal("initDerInst");
2542 fst(snd(spcs)) = appendOnto(fst(snd(spcs)),singleton(NIL));
2543 for (spcs=snd(snd(spcs)); nonNull(spcs); spcs=tl(spcs)) {
2544 hd(spcs) = ap2(inst(in).c,hd(spcs),mkInt(beta));
2546 inst(in).numSpecifics = beta;
2548 #ifdef DEBUG_DERIVING
2549 Printf("initDerInst: ");
2550 printPred(stdout,inst(in).head);
2552 printContext(stdout,snd(snd(inst(in).specifics)));
2557 static Void local calcInstPreds(in) /* Calculate next approximation */
2558 Inst in; { /* of the context for a derived */
2559 List retain = NIL; /* instance */
2560 List ps = snd(snd(inst(in).specifics));
2561 List spcs = fst(snd(inst(in).specifics));
2562 Int beta = inst(in).numSpecifics;
2564 #ifdef DEBUG_DERIVING
2565 Printf("calcInstPreds: ");
2566 printPred(stdout,inst(in).head);
2570 while (nonNull(ps)) {
2573 if (isInt(fst(p))) { /* Delayed substitution? */
2575 for (; nonNull(hd(qs)); qs=tl(qs)) {
2576 ps = cons(pair(hd(qs),fst(p)),ps);
2578 retain = cons(pair(fst(p),qs),retain);
2581 else if (isExt(fun(fst(p)))) { /* Lacks predicate */
2582 Text l = extText(fun(fst(p)));
2583 Type t = arg(fst(p));
2584 Int o = intOf(snd(p));
2589 h = getDerefHead(t,o);
2590 while (isExt(h) && argCount==2 && l!=extText(h)) {
2593 h = getDerefHead(t,o);
2595 if (argCount==0 && isOffset(h)) {
2596 maybeAddPred(ap(fun(fun(p)),h),o,beta,spcs);
2597 } else if (argCount!=0 || h!=typeNoRow) {
2598 Cell bpi = inst(in).head;
2599 Cell pi = copyPred(fun(p),intOf(snd(p)));
2600 ERRMSG(inst(in).line) "Cannot derive " ETHEN ERRPRED(bpi);
2601 ERRTEXT " because predicate " ETHEN ERRPRED(pi);
2602 ERRTEXT " does not hold\n"
2607 else { /* Class predicate */
2609 Int o = intOf(snd(p));
2610 Inst in1 = findInstFor(pi,o);
2612 List qs = inst(in1).specifics;
2613 Int off = mkInt(typeOff);
2614 if (whatIs(qs)==DERIVE) { /* Still being derived */
2615 for (qs=fst(snd(qs)); nonNull(hd(qs)); qs=tl(qs)) {
2616 ps = cons(pair(hd(qs),off),ps);
2618 retain = cons(pair(off,qs),retain);
2619 } else { /* Previously def'd inst */
2620 for (; nonNull(qs); qs=tl(qs)) {
2621 ps = cons(pair(hd(qs),off),ps);
2624 } else { /* No matching instance */
2626 while (isAp(qi) && isOffset(getDerefHead(arg(qi),o))) {
2630 Cell bpi = inst(in).head;
2631 pi = copyPred(pi,o);
2632 ERRMSG(inst(in).line) "An instance of " ETHEN ERRPRED(pi);
2633 ERRTEXT " is required to derive " ETHEN ERRPRED(bpi);
2637 maybeAddPred(pi,o,beta,spcs);
2642 snd(snd(inst(in).specifics)) = retain;
2645 static Void local maybeAddPred(pi,o,beta,ps)
2646 Cell pi; /* Add predicate pi to the list ps,*/
2647 Int o; /* setting the instsChanged flag if*/
2648 Int beta; /* pi is not already a member and */
2649 List ps; { /* using beta to adjust vars */
2650 Cell c = getHead(pi);
2651 for (; nonNull(ps); ps=tl(ps)) {
2652 if (isNull(hd(ps))) { /* reached the `dummy' end of list?*/
2653 hd(ps) = copyAdj(pi,o,beta);
2654 tl(ps) = pair(NIL,NIL);
2655 instsChanged = TRUE;
2657 } else if (c==getHead(hd(ps)) && samePred(pi,o,hd(ps),beta)) {
2663 static Cell local copyAdj(c,o,beta) /* Copy (c,o), replacing vars with */
2664 Cell c; /* offsets relative to beta. */
2667 switch (whatIs(c)) {
2668 case AP : { Cell l = copyAdj(fst(c),o,beta);
2669 Cell r = copyAdj(snd(c),o,beta);
2673 case OFFSET : { Int vn = o+offsetOf(c);
2674 Tyvar *tyv = tyvar(vn);
2676 return copyAdj(tyv->bound,tyv->offs,beta);
2679 if (vn<0 || vn>=NUM_OFFSETS) {
2680 internal("copyAdj");
2682 return mkOffset(vn);
2688 static Void local tidyDerInst(in) /* Tidy up results of derived inst */
2689 Inst in; { /* calculations */
2690 Int o = inst(in).numSpecifics;
2691 List ps = tl(rev(fst(snd(inst(in).specifics))));
2693 copyPred(inst(in).head,o);
2694 inst(in).specifics = simpleContext(ps,o);
2695 h98CheckCtxt(inst(in).line,"derived instance",FALSE,inst(in).specifics,in);
2696 inst(in).numSpecifics = length(inst(in).specifics);
2698 #ifdef DEBUG_DERIVING
2699 Printf("Derived instance: ");
2700 printContext(stdout,inst(in).specifics);
2702 printPred(stdout,inst(in).head);
2707 /* --------------------------------------------------------------------------
2708 * Generate code for derived instances:
2709 * ------------------------------------------------------------------------*/
2711 static Void local addDerivImp(in)
2714 Type t = getHead(arg(inst(in).head));
2715 Class c = inst(in).c;
2718 } else if (c==classOrd) {
2720 } else if (c==classEnum) {
2721 imp = deriveEnum(t);
2722 } else if (c==classIx) {
2724 } else if (c==classShow) {
2725 imp = deriveShow(t);
2726 } else if (c==classRead) {
2727 imp = deriveRead(t);
2728 } else if (c==classBounded) {
2729 imp = deriveBounded(t);
2731 ERRMSG(inst(in).line) "Cannot derive instances of class \"%s\"",
2732 textToStr(cclass(inst(in).c).text)
2736 kindInst(in,intOf(inst(in).kinds));
2738 inst(in).builder = newInstImp(in);
2739 inst(in).implements = classBindings("derived instance",
2745 /* --------------------------------------------------------------------------
2746 * Default definitions; only one default definition is permitted in a
2747 * given script file. If no default is supplied, then a standard system
2748 * default will be used where necessary.
2749 * ------------------------------------------------------------------------*/
2751 Void defaultDefn(line,defs) /* Handle default types definition */
2754 if (defaultLine!=0) {
2755 ERRMSG(line) "Multiple default declarations are not permitted in" ETHEN
2756 ERRTEXT "a single script file.\n"
2759 defaultDefns = defs;
2763 static Void local checkDefaultDefns() { /* check that default types are */
2764 List ds = NIL; /* well-kinded instances of Num */
2766 if (defaultLine!=0) {
2767 map2Over(depTypeExp,defaultLine,NIL,defaultDefns);
2768 emptySubstitution();
2770 map2Proc(kindType,defaultLine,"default type",defaultDefns);
2772 emptySubstitution();
2773 mapOver(fullExpand,defaultDefns);
2775 defaultDefns = stdDefaults;
2778 if (isNull(classNum)) {
2779 classNum = findClass(findText("Num"));
2782 for (ds=defaultDefns; nonNull(ds); ds=tl(ds)) {
2783 if (isNull(provePred(NIL,NIL,ap(classNum,hd(ds))))) {
2785 "Default types must be instances of the Num class"
2793 /* --------------------------------------------------------------------------
2794 * Foreign import declarations are Hugs' equivalent of GHC's ccall mechanism.
2795 * They are used to "import" C functions into a module.
2796 * They are usually not written by hand but, rather, generated automatically
2797 * by GreenCard, IDL compilers or whatever.
2799 * Foreign export declarations generate C wrappers for Hugs functions.
2800 * Hugs only provides "foreign export dynamic" because it's not obvious
2801 * what "foreign export static" would mean in an interactive setting.
2802 * ------------------------------------------------------------------------*/
2804 Void foreignImport(line,extName,intName,type) /* Handle foreign imports */
2809 Text t = textOf(intName);
2810 Name n = findName(t);
2811 Int l = intOf(line);
2815 } else if (name(n).defn!=PREDEFINED) {
2816 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
2820 name(n).defn = extName;
2821 name(n).type = type;
2822 foreignImports = cons(n,foreignImports);
2825 static Void local checkForeignImport(p) /* Check foreign import */
2827 emptySubstitution();
2828 name(p).type = checkSigType(name(p).line,
2829 "foreign import declaration",
2832 /* We don't expand synonyms here because we don't want the IO
2833 * part to be expanded.
2834 * name(p).type = fullExpand(name(p).type);
2836 implementForeignImport(p);
2839 Void foreignExport(line,extName,intName,type)/* Handle foreign exports */
2844 Text t = textOf(intName);
2845 Name n = findName(t);
2846 Int l = intOf(line);
2850 } else if (name(n).defn!=PREDEFINED) {
2851 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
2855 name(n).defn = NIL; /* nothing to say */
2856 name(n).type = type;
2857 foreignExports = cons(n,foreignExports);
2860 static Void local checkForeignExport(p) /* Check foreign export */
2862 emptySubstitution();
2863 name(p).type = checkSigType(name(p).line,
2864 "foreign export declaration",
2867 implementForeignExport(p);
2875 /* --------------------------------------------------------------------------
2876 * Primitive definitions are usually only included in the first script
2877 * file read - the prelude. A primitive definition associates a variable
2878 * name with a string (which identifies a built-in primitive) and a type.
2879 * ------------------------------------------------------------------------*/
2881 Void primDefn(line,prims,type) /* Handle primitive definitions */
2885 primDefns = cons(triple(line,prims,type),primDefns);
2888 static List local checkPrimDefn(pd) /* Check primitive definition */
2890 Int line = intOf(fst3(pd));
2891 List prims = snd3(pd);
2892 Type type = thd3(pd);
2893 emptySubstitution();
2894 type = checkSigType(line,"primitive definition",fst(hd(prims)),type);
2895 for (; nonNull(prims); prims=tl(prims)) {
2897 Bool same = isVar(p);
2898 Text pt = textOf(same ? p : fst(p));
2899 String pr = textToStr(textOf(same ? p : snd(p)));
2900 hd(prims) = addNewPrim(line,pt,pr,type);
2905 static Name local addNewPrim(l,vn,s,t) /* make binding of variable vn to */
2906 Int l; /* primitive function referred */
2907 Text vn; /* to by s, with given type t */
2910 Name n = findName(vn);
2913 n = newName(vn,NIL);
2914 } else if (name(n).defn!=PREDEFINED) {
2915 duplicateError(l,name(n).mod,vn,"primitive");
2927 /* --------------------------------------------------------------------------
2928 * Static analysis of patterns:
2930 * Patterns are parsed as ordinary (atomic) expressions. Static analysis
2931 * makes the following checks:
2932 * - Patterns are well formed (according to pattern syntax), including the
2933 * special case of (n+k) patterns.
2934 * - All constructor functions have been defined and are used with the
2935 * correct number of arguments.
2936 * - No variable name is used more than once in a pattern.
2938 * The list of pattern variables occuring in each pattern is accumulated in
2939 * a global list `patVars', which must be initialised to NIL at appropriate
2940 * points before using these routines to check for valid patterns. This
2941 * mechanism enables the pattern checking routine to be mapped over a list
2942 * of patterns, ensuring that no variable occurs more than once in the
2943 * complete pattern list (as is required on the lhs of a function defn).
2944 * ------------------------------------------------------------------------*/
2946 static List patVars; /* List of vars bound in pattern */
2948 static Cell local checkPat(line,p) /* Check valid pattern syntax */
2951 switch (whatIs(p)) {
2953 case VAROPCELL : addToPatVars(line,p);
2956 case INFIX : return checkPat(line,tidyInfix(line,snd(p)));
2958 case AP : return checkMaybeCnkPat(line,p);
2963 case CONOPCELL : return checkApPat(line,0,p);
2968 case FLOATCELL : break;
2969 case INTCELL : break;
2971 case ASPAT : addToPatVars(line,fst(snd(p)));
2972 snd(snd(p)) = checkPat(line,snd(snd(p)));
2975 case LAZYPAT : snd(p) = checkPat(line,snd(p));
2978 case FINLIST : map1Over(checkPat,line,snd(p));
2981 case CONFLDS : depConFlds(line,p,TRUE);
2984 case ESIGN : snd(snd(p)) = checkPatType(line,
2988 fst(snd(p)) = checkPat(line,fst(snd(p)));
2991 default : ERRMSG(line) "Illegal pattern syntax"
2997 static Cell local checkMaybeCnkPat(l,p)/* Check applicative pattern with */
2998 Int l; /* the possibility of n+k pattern */
3001 Cell h = getHead(p);
3003 if (argCount==2 && isVar(h) && textOf(h)==textPlus) { /* n+k */
3004 Cell v = arg(fun(p));
3005 if (!isInt(arg(p))) {
3006 ERRMSG(l) "Second argument in (n+k) pattern must be an integer"
3009 if (intOf(arg(p))<=0) {
3010 ERRMSG(l) "Integer k in (n+k) pattern must be > 0"
3013 fst(fun(p)) = ADDPAT;
3014 intValOf(fun(p)) = intOf(arg(p));
3015 arg(p) = checkPat(l,v);
3019 return checkApPat(l,0,p);
3022 static Cell local checkApPat(line,args,p)
3023 Int line; /* check validity of application */
3024 Int args; /* of constructor to arguments */
3026 switch (whatIs(p)) {
3027 case AP : fun(p) = checkApPat(line,args+1,fun(p));
3028 arg(p) = checkPat(line,arg(p));
3031 case TUPLE : if (tupleOf(p)!=args) {
3032 ERRMSG(line) "Illegal tuple pattern"
3038 case EXT : h98DoesntSupport(line,"extensible records");
3040 ERRMSG(line) "Illegal record pattern"
3046 case QUALIDENT : if (!isQCon(p)) {
3048 "Illegal use of qualified variable in pattern"
3051 /* deliberate fall through */
3053 case CONOPCELL : p = conDefined(line,p);
3054 checkCfunArgs(line,p,args);
3057 case NAME : checkIsCfun(line,p);
3058 checkCfunArgs(line,p,args);
3061 default : ERRMSG(line) "Illegal pattern syntax"
3067 static Void local addToPatVars(line,v) /* Add variable v to list of vars */
3068 Int line; /* in current pattern, checking */
3069 Cell v; { /* for repeated variables. */
3074 for (; nonNull(n); p=n, n=tl(n)) {
3075 if (textOf(hd(n))==t) {
3076 ERRMSG(line) "Repeated variable \"%s\" in pattern",
3083 patVars = cons(v,NIL);
3085 tl(p) = cons(v,NIL);
3089 static Name local conDefined(line,nm) /* check that nm is the name of a */
3090 Int line; /* previously defined constructor */
3091 Cell nm; { /* function. */
3092 Name n = findQualName(nm);
3094 ERRMSG(line) "Undefined constructor function \"%s\"", identToStr(nm)
3097 checkIsCfun(line,n);
3101 static Void local checkIsCfun(line,c) /* Check that c is a constructor fn */
3105 ERRMSG(line) "\"%s\" is not a constructor function",
3106 textToStr(name(c).text)
3111 static Void local checkCfunArgs(line,c,args)
3112 Int line; /* Check constructor applied with */
3113 Cell c; /* correct number of arguments */
3115 Int a = userArity(c);
3118 "Constructor \"%s\" must have exactly %d argument%s in pattern",
3119 textToStr(name(c).text), a, ((a==1)?"":"s")
3124 static Cell local checkPatType(l,wh,e,t)/* Check type appearing in pattern */
3129 List tvs = typeVarsIn(t,NIL,NIL);
3130 h98DoesntSupport(l,"pattern type annotations");
3131 for (; nonNull(tvs); tvs=tl(tvs)) {
3132 Int beta = newKindvars(1);
3133 hd(btyvars) = cons(pair(hd(tvs),mkInt(beta)), hd(btyvars));
3135 t = checkSigType(l,"pattern type",e,t);
3136 if (isPolyType(t) || whatIs(t)==QUAL || whatIs(t)==RANK2) {
3137 ERRMSG(l) "Illegal syntax in %s type annotation", wh
3143 static Cell local applyBtyvs(pat) /* Record bound type vars in pat */
3145 List bts = hd(btyvars);
3148 pat = ap(BIGLAM,pair(bts,pat));
3149 for (; nonNull(bts); bts=tl(bts)) {
3150 snd(hd(bts)) = copyKindvar(intOf(snd(hd(bts))));
3156 /* --------------------------------------------------------------------------
3157 * Maintaining lists of bound variables and local definitions, for
3158 * dependency and scope analysis.
3159 * ------------------------------------------------------------------------*/
3161 static List bounds; /* list of lists of bound vars */
3162 static List bindings; /* list of lists of binds in scope */
3163 static List depends; /* list of lists of dependents */
3165 /* bounds :: [[Var]] -- var equality used on Vars */
3166 /* bindings :: [[([Var],?)]] -- var equality used on Vars */
3167 /* depends :: [[Var]] -- pointer equality used on Vars */
3169 #define saveBvars() hd(bounds) /* list of bvars in current scope */
3170 #define restoreBvars(bs) hd(bounds)=bs /* restore list of bound variables */
3172 static Cell local bindPat(line,p) /* add new bound vars for pattern */
3176 p = checkPat(line,p);
3177 hd(bounds) = revOnto(patVars,hd(bounds));
3181 static Void local bindPats(line,ps) /* add new bound vars for patterns */
3185 map1Over(checkPat,line,ps);
3186 hd(bounds) = revOnto(patVars,hd(bounds));
3189 /* --------------------------------------------------------------------------
3190 * Before processing value and type signature declarations, all data and
3191 * type definitions have been processed so that:
3192 * - all valid type constructors (with their arities) are known.
3193 * - all valid constructor functions (with their arities and types) are
3196 * The result of parsing a list of value declarations is a list of Eqns:
3197 * Eqn ::= (SIGDECL,(Line,[Var],type))
3198 * | (FIXDECL,(Line,[Op],SyntaxInt))
3200 * The ordering of the equations in this list is the reverse of the original
3201 * ordering in the script parsed. This is a consequence of the structure of
3202 * the parser ... but also turns out to be most convenient for the static
3205 * As the first stage of the static analysis of value declarations, each
3206 * list of Eqns is converted to a list of Bindings. As part of this
3208 * - The ordering of the list of Bindings produced is the same as in the
3210 * - When a variable (function) is defined over a number of lines, all
3211 * of the definitions should appear together and each should give the
3212 * same arity to the variable being defined.
3213 * - No variable can have more than one definition.
3214 * - For pattern bindings:
3215 * - Each lhs is a valid pattern/function lhs, all constructor functions
3216 * have been defined and are used with the correct number of arguments.
3217 * - Each lhs contains no repeated pattern variables.
3218 * - Each equation defines at least one variable (e.g. True = False is
3220 * - Types appearing in type signatures are well formed:
3221 * - Type constructors used are defined and used with correct number
3223 * - type variables are replaced by offsets, type constructor names
3225 * - Every variable named in a type signature declaration is defined by
3226 * one or more equations elsewhere in the script.
3227 * - No variable has more than one type declaration.
3228 * - Similar properties for fixity declarations.
3230 * ------------------------------------------------------------------------*/
3232 #define bindingAttr(b) fst(snd(b)) /* type(s)/fixity(ies) for binding */
3233 #define fbindAlts(b) snd(snd(b)) /* alternatives for function binding*/
3235 static List local extractSigdecls(es) /* Extract the SIGDECLS from list */
3236 List es; { /* of equations */
3237 List sigdecls = NIL; /* :: [(Line,[Var],Type)] */
3239 for(; nonNull(es); es=tl(es)) {
3240 if (fst(hd(es))==SIGDECL) { /* type-declaration? */
3241 Pair sig = snd(hd(es));
3242 Int line = intOf(fst3(sig));
3243 List vs = snd3(sig);
3244 for(; nonNull(vs); vs=tl(vs)) {
3245 if (isQualIdent(hd(vs))) {
3246 ERRMSG(line) "Type signature for qualified variable \"%s\" is not allowed",
3251 sigdecls = cons(sig,sigdecls); /* discard SIGDECL tag*/
3257 static List local extractFixdecls(es) /* Extract the FIXDECLS from list */
3258 List es; { /* of equations */
3259 List fixdecls = NIL; /* :: [(Line,SyntaxInt,[Op])] */
3261 for(; nonNull(es); es=tl(es)) {
3262 if (fst(hd(es))==FIXDECL) { /* fixity declaration?*/
3263 fixdecls = cons(snd(hd(es)),fixdecls); /* discard FIXDECL tag*/
3269 static List local extractBindings(ds) /* extract untyped bindings from */
3270 List ds; { /* given list of equations */
3271 Cell lastVar = NIL; /* = var def'd in last eqn (if any)*/
3272 Int lastArity = 0; /* = number of args in last defn */
3273 List bs = NIL; /* :: [Binding] */
3275 for(; nonNull(ds); ds=tl(ds)) {
3277 if (fst(d)==FUNBIND) { /* Function bindings */
3278 Cell rhs = snd(snd(d));
3279 Int line = rhsLine(rhs);
3280 Cell lhs = fst(snd(d));
3281 Cell v = getHead(lhs);
3282 Cell newAlt = pair(getArgs(lhs),rhs);
3284 internal("FUNBIND");
3286 if (nonNull(lastVar) && textOf(v)==textOf(lastVar)) {
3287 if (argCount!=lastArity) {
3288 ERRMSG(line) "Equations give different arities for \"%s\"",
3289 textToStr(textOf(v))
3292 fbindAlts(hd(bs)) = cons(newAlt,fbindAlts(hd(bs)));
3296 lastArity = argCount;
3297 notDefined(line,bs,v);
3298 bs = cons(pair(v,pair(NIL,singleton(newAlt))),bs);
3301 } else if (fst(d)==PATBIND) { /* Pattern bindings */
3302 Cell rhs = snd(snd(d));
3303 Int line = rhsLine(rhs);
3304 Cell pat = fst(snd(d));
3305 while (whatIs(pat)==ESIGN) {/* Move type annotations to rhs */
3306 Cell p = fst(snd(pat));
3307 fst(snd(pat)) = rhs;
3308 snd(snd(d)) = rhs = pat;
3309 fst(snd(d)) = pat = p;
3312 if (isVar(pat)) { /* Convert simple pattern bind to */
3313 notDefined(line,bs,pat);/* a function binding */
3314 bs = cons(pair(pat,pair(NIL,singleton(pair(NIL,rhs)))),bs);
3316 List vs = getPatVars(line,pat,NIL);
3318 ERRMSG(line) "No variables defined in lhs pattern"
3321 map2Proc(notDefined,line,bs,vs);
3322 bs = cons(pair(vs,pair(NIL,snd(d))),bs);
3330 static List local getPatVars(line,p,vs) /* Find list of variables bound in */
3331 Int line; /* pattern p */
3334 switch (whatIs(p)) {
3336 vs = getPatVars(line,arg(p),vs);
3339 return vs; /* Ignore head of application */
3341 case CONFLDS : { List pfs = snd(snd(p));
3342 for (; nonNull(pfs); pfs=tl(pfs)) {
3343 if (isVar(hd(pfs))) {
3344 vs = addPatVar(line,hd(pfs),vs);
3346 vs = getPatVars(line,snd(hd(pfs)),vs);
3352 case FINLIST : { List ps = snd(p);
3353 for (; nonNull(ps); ps=tl(ps)) {
3354 vs = getPatVars(line,hd(ps),vs);
3359 case ESIGN : return getPatVars(line,fst(snd(p)),vs);
3364 case INFIX : return getPatVars(line,snd(p),vs);
3366 case ASPAT : return addPatVar(line,fst(snd(p)),
3367 getPatVars(line,snd(snd(p)),vs));
3370 case VAROPCELL : return addPatVar(line,p,vs);
3380 case WILDCARD : return vs;
3382 default : internal("getPatVars");
3387 static List local addPatVar(line,v,vs) /* Add var to list of previously */
3388 Int line; /* encountered variables */
3391 if (varIsMember(textOf(v),vs)) {
3392 ERRMSG(line) "Repeated use of variable \"%s\" in pattern binding",
3393 textToStr(textOf(v))
3399 static List local eqnsToBindings(es,ts,cs,ps)
3400 List es; /* Convert list of equations to */
3401 List ts; /* list of typed bindings */
3404 List bs = extractBindings(es);
3405 map1Proc(addSigdecl,bs,extractSigdecls(es));
3406 map4Proc(addFixdecl,bs,ts,cs,ps,extractFixdecls(es));
3410 static Void local notDefined(line,bs,v)/* check if name already defined in */
3411 Int line; /* list of bindings */
3414 if (nonNull(findBinding(textOf(v),bs))) {
3415 ERRMSG(line) "\"%s\" multiply defined", textToStr(textOf(v))
3420 static Cell local findBinding(t,bs) /* look for binding for variable t */
3421 Text t; /* in list of bindings bs */
3423 for (; nonNull(bs); bs=tl(bs)) {
3424 if (isVar(fst(hd(bs)))) { /* function-binding? */
3425 if (textOf(fst(hd(bs)))==t) {
3428 } else if (nonNull(varIsMember(t,fst(hd(bs))))){/* pattern-binding?*/
3435 static Cell local getAttr(bs,v) /* Locate type/fixity attribute */
3436 List bs; /* for variable v in bindings bs */
3439 Cell b = findBinding(t,bs);
3441 if (isNull(b)) { /* No binding */
3443 } else if (isVar(fst(b))) { /* func binding? */
3444 if (isNull(bindingAttr(b))) {
3445 bindingAttr(b) = pair(NIL,NIL);
3447 return bindingAttr(b);
3448 } else { /* pat binding? */
3450 List as = bindingAttr(b);
3453 bindingAttr(b) = as = replicate(length(vs),NIL);
3456 while (nonNull(vs) && t!=textOf(hd(vs))) {
3462 internal("getAttr");
3463 } else if (isNull(hd(as))) {
3464 hd(as) = pair(NIL,NIL);
3470 static Void local addSigdecl(bs,sigdecl)/* add type information to bindings*/
3471 List bs; /* :: [Binding] */
3472 Cell sigdecl; { /* :: (Line,[Var],Type) */
3473 Int l = intOf(fst3(sigdecl));
3474 List vs = snd3(sigdecl);
3475 Type type = checkSigType(l,"type declaration",hd(vs),thd3(sigdecl));
3477 for (; nonNull(vs); vs=tl(vs)) {
3479 Pair attr = getAttr(bs,v);
3481 ERRMSG(l) "Missing binding for variable \"%s\" in type signature",
3482 textToStr(textOf(v))
3484 } else if (nonNull(fst(attr))) {
3485 ERRMSG(l) "Repeated type signature for \"%s\"",
3486 textToStr(textOf(v))
3493 static Void local addFixdecl(bs,ts,cs,ps,fixdecl)
3499 Int line = intOf(fst3(fixdecl));
3500 List ops = snd3(fixdecl);
3501 Cell sy = thd3(fixdecl);
3503 for (; nonNull(ops); ops=tl(ops)) {
3505 Text t = textOf(op);
3506 Cell attr = getAttr(bs,op);
3507 if (nonNull(attr)) { /* Found name in binding? */
3508 if (nonNull(snd(attr))) {
3512 } else { /* Look in tycons, classes, prims */
3517 for (; isNull(n) && nonNull(ts1); ts1=tl(ts1)) { /* tycons */
3519 if (tycon(tc).what==DATATYPE || tycon(tc).what==NEWTYPE) {
3520 n = nameIsMember(t,tycon(tc).defn);
3523 for (; isNull(n) && nonNull(cs1); cs1=tl(cs1)) { /* classes */
3524 n = nameIsMember(t,cclass(hd(cs1)).members);
3526 for (; isNull(n) && nonNull(ps1); ps1=tl(ps1)) { /* prims */
3527 n = nameIsMember(t,hd(ps1));
3532 } else if (name(n).syntax!=NO_SYNTAX) {
3535 name(n).syntax = intOf(sy);
3540 static Void local dupFixity(line,t) /* Report repeated fixity decl */
3544 "Repeated fixity declaration for operator \"%s\"", textToStr(t)
3548 static Void local missFixity(line,t) /* Report missing op for fixity */
3552 "Cannot find binding for operator \"%s\" in fixity declaration",
3557 /* --------------------------------------------------------------------------
3558 * Dealing with infix operators:
3560 * Expressions involving infix operators or unary minus are parsed as
3561 * elements of the following type:
3563 * data InfixExp = Only Exp | Neg InfixExp | Infix InfixExp Op Exp
3565 * (The algorithms here do not assume that negation can be applied only once,
3566 * i.e., that - - x is a syntax error, as required by the Haskell report.
3567 * Instead, that restriction is captured by the grammar itself, given above.)
3569 * There are rules of precedence and grouping, expressed by two functions:
3571 * prec :: Op -> Int; assoc :: Op -> Assoc (Assoc = {L, N, R})
3573 * InfixExp values are rearranged accordingly when a complete expression
3574 * has been read using a simple shift-reduce parser whose result may be taken
3575 * to be a value of the following type:
3577 * data Exp = Atom Int | Negate Exp | Apply Op Exp Exp | Error String
3579 * The machine on which this parser is based can be defined as follows:
3581 * tidy :: InfixExp -> [(Op,Exp)] -> Exp
3582 * tidy (Only a) [] = a
3583 * tidy (Only a) ((o,b):ss) = tidy (Only (Apply o a b)) ss
3584 * tidy (Infix a o b) [] = tidy a [(o,b)]
3585 * tidy (Infix a o b) ((p,c):ss)
3586 * | shift o p = tidy a ((o,b):(p,c):ss)
3587 * | red o p = tidy (Infix a o (Apply p b c)) ss
3588 * | ambig o p = Error "ambiguous use of operators"
3589 * tidy (Neg e) [] = tidy (tidyNeg e) []
3590 * tidy (Neg e) ((o,b):ss)
3591 * | nshift o = tidy (Neg (underNeg o b e)) ss
3592 * | nred o = tidy (tidyNeg e) ((o,b):ss)
3593 * | nambig o = Error "illegal use of negation"
3595 * At each stage, the parser can either shift, reduce, accept, or error.
3596 * The transitions when dealing with juxtaposed operators o and p are
3597 * determined by the following rules:
3599 * shift o p = (prec o > prec p)
3600 * || (prec o == prec p && assoc o == L && assoc p == L)
3602 * red o p = (prec o < prec p)
3603 * || (prec o == prec p && assoc o == R && assoc p == R)
3605 * ambig o p = (prec o == prec p)
3606 * && (assoc o == N || assoc p == N || assoc o /= assoc p)
3608 * The transitions when dealing with juxtaposed unary minus and infix
3609 * operators are as follows. The precedence of unary minus (infixl 6) is
3610 * hardwired in to these definitions, as it is to the definitions of the
3611 * Haskell grammar in the official report.
3613 * nshift o = (prec o > 6)
3614 * nred o = (prec o < 6) || (prec o == 6 && assoc o == L)
3615 * nambig o = prec o == 6 && (assoc o == R || assoc o == N)
3617 * An InfixExp of the form (Neg e) means negate the last thing in
3618 * the InfixExp e; we can force this negation using:
3620 * tidyNeg :: OpExp -> OpExp
3621 * tidyNeg (Only e) = Only (Negate e)
3622 * tidyNeg (Infix a o b) = Infix a o (Negate b)
3623 * tidyNeg (Neg e) = tidyNeg (tidyNeg e)
3625 * On the other hand, if we want to sneak application of an infix operator
3626 * under a negation, then we use:
3628 * underNeg :: Op -> Exp -> OpExp -> OpExp
3629 * underNeg o b (Only e) = Only (Apply o e b)
3630 * underNeg o b (Neg e) = Neg (underNeg o b e)
3631 * underNeg o b (Infix e p f) = Infix e p (Apply o f b)
3633 * As a concession to efficiency, we lower the number of calls to syntaxOf
3634 * by keeping track of the values of sye, sys throughout the process. The
3635 * value APPLIC is used to indicate that the syntax value is unknown.
3636 * ------------------------------------------------------------------------*/
3638 static Cell local tidyInfix(line,e) /* Convert infixExp to Exp */
3640 Cell e; { /* :: OpExp */
3641 Cell s = NIL; /* :: [(Op,Exp)] */
3642 Syntax sye = APPLIC; /* Syntax of op in e (init unknown)*/
3643 Syntax sys = APPLIC; /* Syntax of op in s (init unknown)*/
3646 while (fst(d)!=ONLY) { /* Attach fixities to operators */
3650 fun(fun(d)) = attachFixity(line,fun(fun(d)));
3656 switch (whatIs(e)) {
3657 case ONLY : e = snd(e);
3658 while (nonNull(s)) {
3659 Cell next = arg(fun(s));
3661 fun(fun(s)) = snd(fun(fun(s)));
3667 case NEG : if (nonNull(s)) {
3668 if (sys==APPLIC) { /* calculate sys */
3669 sys = intOf(fst(fun(fun(s))));
3672 if (precOf(sys)==UMINUS_PREC && /* nambig */
3673 assocOf(sys)!=UMINUS_ASSOC) {
3675 "Ambiguous use of unary minus with \""
3676 ETHEN ERREXPR(snd(fun(fun(s))));
3681 if (precOf(sys)>UMINUS_PREC) { /* nshift */
3685 while (whatIs(e1)==NEG)
3687 arg(fun(t)) = arg(e1);
3688 fun(fun(t)) = snd(fun(fun(t)));
3695 /* Intentional fall-thru for nreduce and isNull(s) */
3697 { Cell prev = e; /* e := tidyNeg e */
3698 Cell temp = arg(prev);
3700 for (; whatIs(temp)==NEG; nneg++) {
3701 fun(prev) = nameNegate;
3705 if (isInt(arg(temp))) { /* special cases */
3706 if (nneg&1) /* for literals */
3707 arg(temp) = mkInt(-intOf(arg(temp)));
3709 else if (isFloat(arg(temp))) {
3711 arg(temp) = floatNegate(arg(temp));
3712 //mkFloat(-floatOf(arg(temp)));
3715 fun(prev) = nameNegate;
3716 arg(prev) = arg(temp);
3723 default : if (isNull(s)) {/* Move operation onto empty stack */
3724 Cell next = arg(fun(e));
3731 else { /* deal with pair of operators */
3733 if (sye==APPLIC) { /* calculate sys and sye */
3734 sye = intOf(fst(fun(fun(e))));
3737 sys = intOf(fst(fun(fun(s))));
3740 if (precOf(sye)==precOf(sys) && /* ambig */
3741 (assocOf(sye)!=assocOf(sys) ||
3742 assocOf(sye)==NON_ASS)) {
3743 ERRMSG(line) "Ambiguous use of operator \""
3744 ETHEN ERREXPR(snd(fun(fun(e))));
3745 ERRTEXT "\" with \""
3746 ETHEN ERREXPR(snd(fun(fun(s))));
3751 if (precOf(sye)>precOf(sys) || /* shift */
3752 (precOf(sye)==precOf(sys) &&
3753 assocOf(sye)==LEFT_ASS &&
3754 assocOf(sys)==LEFT_ASS)) {
3755 Cell next = arg(fun(e));
3763 Cell next = arg(fun(s));
3764 arg(fun(s)) = arg(e);
3765 fun(fun(s)) = snd(fun(fun(s)));
3776 static Pair local attachFixity(line,op) /* Attach fixity to operator in an */
3777 Int line; /* infix expression */
3779 Syntax sy = DEF_OPSYNTAX;
3781 switch (whatIs(op)) {
3783 case VARIDCELL : if ((sy=lookupSyntax(textOf(op)))==NO_SYNTAX) {
3784 Name n = findName(textOf(op));
3786 ERRMSG(line) "Undefined variable \"%s\"",
3787 textToStr(textOf(op))
3796 case CONIDCELL : sy = syntaxOf(op = conDefined(line,op));
3799 case QUALIDENT : { Name n = findQualName(op);
3805 "Undefined qualified variable \"%s\"",
3815 return pair(mkInt(sy),op); /* Pair fixity with (possibly) */
3816 /* translated operator */
3819 static Syntax local lookupSyntax(t) /* Try to find fixity for var in */
3820 Text t; { /* enclosing bindings */
3821 List bounds1 = bounds;
3822 List bindings1 = bindings;
3824 while (nonNull(bindings1)) {
3825 if (nonNull(varIsMember(t,hd(bounds1)))) {
3826 return DEF_OPSYNTAX;
3828 Cell b = findBinding(t,hd(bindings1));
3830 Cell a = fst(snd(b));
3831 if (isVar(fst(b))) { /* Function binding */
3832 if (nonNull(a) && nonNull(snd(a))) {
3833 return intOf(snd(a));
3835 } else { /* Pattern binding */
3837 while (nonNull(vs) && nonNull(a)) {
3838 if (t==textOf(hd(vs))) {
3839 if (nonNull(hd(a)) && isInt(snd(hd(a)))) {
3840 return intOf(snd(hd(a)));
3848 return DEF_OPSYNTAX;
3851 bounds1 = tl(bounds1);
3852 bindings1 = tl(bindings1);
3857 /* --------------------------------------------------------------------------
3858 * To facilitate dependency analysis, lists of bindings are temporarily
3859 * augmented with an additional field, which is used in two ways:
3860 * - to build the `adjacency lists' for the dependency graph. Represented by
3861 * a list of pointers to other bindings in the same list of bindings.
3862 * - to hold strictly positive integer values (depth first search numbers) of
3863 * elements `on the stack' during the strongly connected components search
3864 * algorithm, or a special value mkInt(0), once the binding has been added
3865 * to a particular strongly connected component.
3867 * Using this extra field, the type of each list of declarations during
3868 * dependency analysis is [Binding'] where:
3870 * Binding' ::= (Var, (Attr, (Dep, [Alt]))) -- function binding
3871 * | ([Var], ([Attr], (Dep, (Pat,Rhs)))) -- pattern binding
3873 * ------------------------------------------------------------------------*/
3875 #define depVal(d) (fst(snd(snd(d)))) /* Access to dependency information*/
3877 static List local dependencyAnal(bs) /* Separate lists of bindings into */
3878 List bs; { /* mutually recursive groups in */
3879 /* order of dependency */
3880 mapProc(addDepField,bs); /* add extra field for dependents */
3881 mapProc(depBinding,bs); /* find dependents of each binding */
3882 bs = bscc(bs); /* sort to strongly connected comps*/
3883 mapProc(remDepField,bs); /* remove dependency info field */
3887 static List local topDependAnal(bs) /* Like dependencyAnal(), but at */
3888 List bs; { /* top level, reporting on progress*/
3892 setGoal("Dependency analysis",(Target)(length(bs)));
3894 mapProc(addDepField,bs); /* add extra field for dependents */
3895 for (xs=bs; nonNull(xs); xs=tl(xs)) {
3896 emptySubstitution();
3898 soFar((Target)(i++));
3900 bs = bscc(bs); /* sort to strongly connected comps */
3901 mapProc(remDepField,bs); /* remove dependency info field */
3906 static Void local addDepField(b) /* add extra field to binding to */
3907 Cell b; { /* hold list of dependents */
3908 snd(snd(b)) = pair(NIL,snd(snd(b)));
3911 static Void local remDepField(bs) /* remove dependency field from */
3912 List bs; { /* list of bindings */
3913 mapProc(remDepField1,bs);
3916 static Void local remDepField1(b) /* remove dependency field from */
3917 Cell b; { /* single binding */
3918 snd(snd(b)) = snd(snd(snd(b)));
3921 static Void local clearScope() { /* initialise dependency scoping */
3927 static Void local withinScope(bs) /* Enter scope of bindings bs */
3929 bounds = cons(NIL,bounds);
3930 bindings = cons(bs,bindings);
3931 depends = cons(NIL,depends);
3934 static Void local leaveScope() { /* Leave scope of last withinScope */
3935 List bs = hd(bindings); /* Remove fixity info from binds */
3936 Bool toplevel = isNull(tl(bindings));
3937 for (; nonNull(bs); bs=tl(bs)) {
3939 if (isVar(fst(b))) { /* Variable binding */
3940 Cell a = fst(snd(b));
3943 saveSyntax(fst(b),snd(a));
3945 fst(snd(b)) = fst(a);
3947 } else { /* Pattern binding */
3949 List as = fst(snd(b));
3950 while (nonNull(vs) && nonNull(as)) {
3951 if (isPair(hd(as))) {
3953 saveSyntax(hd(vs),snd(hd(as)));
3955 hd(as) = fst(hd(as));
3962 bounds = tl(bounds);
3963 bindings = tl(bindings);
3964 depends = tl(depends);
3967 static Void local saveSyntax(v,sy) /* Save syntax of top-level var */
3968 Cell v; /* in corresponding Name */
3970 Name n = findName(textOf(v));
3971 if (isNull(n) || name(n).syntax!=NO_SYNTAX) {
3972 internal("saveSyntax");
3975 name(n).syntax = intOf(sy);
3979 /* --------------------------------------------------------------------------
3980 * As a side effect of the dependency analysis we also make the following
3982 * - Each lhs is a valid pattern/function lhs, all constructor functions
3983 * have been defined and are used with the correct number of arguments.
3984 * - No lhs contains repeated pattern variables.
3985 * - Expressions used on the rhs of an eqn should be well formed. This
3987 * - Checking for valid patterns (including repeated vars) in lambda,
3988 * case, and list comprehension expressions.
3989 * - Recursively checking local lists of equations.
3990 * - No free (i.e. unbound) variables are used in the declaration list.
3991 * ------------------------------------------------------------------------*/
3993 static Void local depBinding(b) /* find dependents of binding */
3995 Cell defpart = snd(snd(snd(b))); /* definition part of binding */
3999 if (isVar(fst(b))) { /* function-binding? */
4000 mapProc(depAlt,defpart);
4001 if (isNull(fst(snd(b)))) { /* Save dep info if no type sig */
4002 fst(snd(b)) = pair(ap(IMPDEPS,hd(depends)),NIL);
4003 } else if (isNull(fst(fst(snd(b))))) {
4004 fst(fst(snd(b))) = ap(IMPDEPS,hd(depends));
4006 } else { /* pattern-binding? */
4007 Int line = rhsLine(snd(defpart));
4010 fst(defpart) = checkPat(line,fst(defpart));
4011 depRhs(snd(defpart));
4013 if (nonNull(hd(btyvars))) {
4015 "Sorry, no type variables are allowed in pattern binding type annotations"
4019 fst(defpart) = applyBtyvs(fst(defpart));
4021 depVal(b) = hd(depends);
4024 static Void local depDefaults(c) /* dependency analysis on defaults */
4025 Class c; { /* from class definition */
4026 depClassBindings(cclass(c).defaults);
4029 static Void local depInsts(in) /* dependency analysis on instance */
4030 Inst in; { /* bindings */
4031 depClassBindings(inst(in).implements);
4034 static Void local depClassBindings(bs) /* dependency analysis on list of */
4035 List bs; { /* bindings, possibly containing */
4036 for (; nonNull(bs); bs=tl(bs)) { /* NIL bindings ... */
4037 if (nonNull(hd(bs))) { /* No need to add extra field for */
4038 mapProc(depAlt,snd(hd(bs)));/* dependency information... */
4043 static Void local depAlt(a) /* Find dependents of alternative */
4045 List obvs = saveBvars(); /* Save list of bound variables */
4047 bindPats(rhsLine(snd(a)),fst(a)); /* add new bound vars for patterns */
4048 depRhs(snd(a)); /* find dependents of rhs */
4049 fst(a) = applyBtyvs(fst(a));
4050 restoreBvars(obvs); /* restore original list of bvars */
4053 static Void local depRhs(r) /* Find dependents of rhs */
4055 switch (whatIs(r)) {
4056 case GUARDED : mapProc(depGuard,snd(r));
4059 case LETREC : fst(snd(r)) = eqnsToBindings(fst(snd(r)),NIL,NIL,NIL);
4060 withinScope(fst(snd(r)));
4061 fst(snd(r)) = dependencyAnal(fst(snd(r)));
4062 hd(depends) = fst(snd(r));
4063 depRhs(snd(snd(r)));
4067 case RSIGN : snd(snd(r)) = checkPatType(rhsLine(fst(snd(r))),
4069 rhsExpr(fst(snd(r))),
4071 depRhs(fst(snd(r)));
4074 default : snd(r) = depExpr(intOf(fst(r)),snd(r));
4079 static Void local depGuard(g) /* find dependents of single guarded*/
4080 Cell g; { /* expression */
4081 depPair(intOf(fst(g)),snd(g));
4084 static Cell local depExpr(line,e) /* find dependents of expression */
4087 // Printf( "\n\n"); print(e,100); Printf("\n");
4088 //printExp(stdout,e);
4089 switch (whatIs(e)) {
4092 case VAROPCELL : return depVar(line,e);
4095 case CONOPCELL : return conDefined(line,e);
4097 case QUALIDENT : if (isQVar(e)) {
4098 return depQVar(line,e);
4099 } else { /* QConOrConOp */
4100 return conDefined(line,e);
4103 case INFIX : return depExpr(line,tidyInfix(line,snd(e)));
4106 case RECSEL : break;
4108 case AP : if (isAp(e) && isAp(fun(e)) && isExt(fun(fun(e)))) {
4109 return depRecord(line,e);
4115 arg(a) = depExpr(line,arg(a));
4118 fun(a) = depExpr(line,fun(a));
4122 case AP : depPair(line,e);
4132 case INTCELL : break;
4134 case COND : depTriple(line,snd(e));
4137 case FINLIST : map1Over(depExpr,line,snd(e));
4140 case LETREC : fst(snd(e)) = eqnsToBindings(fst(snd(e)),NIL,NIL,NIL);
4141 withinScope(fst(snd(e)));
4142 fst(snd(e)) = dependencyAnal(fst(snd(e)));
4143 hd(depends) = fst(snd(e));
4144 snd(snd(e)) = depExpr(line,snd(snd(e)));
4148 case LAMBDA : depAlt(snd(e));
4151 case DOCOMP : /* fall-thru */
4152 case COMP : depComp(line,snd(e),snd(snd(e)));
4155 case ESIGN : fst(snd(e)) = depExpr(line,fst(snd(e)));
4156 snd(snd(e)) = checkSigType(line,
4162 case CASE : fst(snd(e)) = depExpr(line,fst(snd(e)));
4163 map1Proc(depCaseAlt,line,snd(snd(e)));
4166 case CONFLDS : depConFlds(line,e,FALSE);
4169 case UPDFLDS : depUpdFlds(line,e);
4172 case ASPAT : ERRMSG(line) "Illegal `@' in expression"
4175 case LAZYPAT : ERRMSG(line) "Illegal `~' in expression"
4178 case WILDCARD : ERRMSG(line) "Illegal `_' in expression"
4182 case EXT : ERRMSG(line) "Illegal application of record"
4186 default : internal("depExpr");
4191 static Void local depPair(line,e) /* find dependents of pair of exprs*/
4194 fst(e) = depExpr(line,fst(e));
4195 snd(e) = depExpr(line,snd(e));
4198 static Void local depTriple(line,e) /* find dependents of triple exprs */
4201 fst3(e) = depExpr(line,fst3(e));
4202 snd3(e) = depExpr(line,snd3(e));
4203 thd3(e) = depExpr(line,thd3(e));
4206 static Void local depComp(l,e,qs) /* find dependents of comprehension*/
4211 fst(e) = depExpr(l,fst(e));
4215 switch (whatIs(q)) {
4216 case FROMQUAL : { List obvs = saveBvars();
4217 snd(snd(q)) = depExpr(l,snd(snd(q)));
4219 fst(snd(q)) = bindPat(l,fst(snd(q)));
4221 fst(snd(q)) = applyBtyvs(fst(snd(q)));
4226 case QWHERE : snd(q) = eqnsToBindings(snd(q),NIL,NIL,NIL);
4227 withinScope(snd(q));
4228 snd(q) = dependencyAnal(snd(q));
4229 hd(depends) = snd(q);
4234 case DOQUAL : /* fall-thru */
4235 case BOOLQUAL : snd(q) = depExpr(l,snd(q));
4242 static Void local depCaseAlt(line,a) /* Find dependents of case altern. */
4245 List obvs = saveBvars(); /* Save list of bound variables */
4247 fst(a) = bindPat(line,fst(a)); /* Add new bound vars for pats */
4248 depRhs(snd(a)); /* Find dependents of rhs */
4249 fst(a) = applyBtyvs(fst(a));
4250 restoreBvars(obvs); /* Restore original list of bvars */
4253 static Cell local depVar(line,e) /* Register occurrence of variable */
4256 List bounds1 = bounds;
4257 List bindings1 = bindings;
4258 List depends1 = depends;
4262 while (nonNull(bindings1)) {
4263 n = varIsMember(t,hd(bounds1)); /* look for t in bound variables */
4267 n = findBinding(t,hd(bindings1)); /* look for t in var bindings */
4269 if (!cellIsMember(n,hd(depends1))) {
4270 hd(depends1) = cons(n,hd(depends1));
4272 return (isVar(fst(n)) ? fst(n) : e);
4275 bounds1 = tl(bounds1);
4276 bindings1 = tl(bindings1);
4277 depends1 = tl(depends1);
4280 if (isNull(n=findName(t))) { /* check global definitions */
4281 ERRMSG(line) "Undefined variable \"%s\"", textToStr(t)
4285 if (!moduleThisScript(name(n).mod)) {
4288 /* Later phases of the system cannot cope if we resolve references
4289 * to unprocessed objects too early. This is the main reason that
4290 * we cannot cope with recursive modules at the moment.
4295 static Cell local depQVar(line,e)/* register occurrence of qualified variable */
4298 Name n = findQualName(e);
4299 if (isNull(n)) { /* check global definitions */
4300 ERRMSG(line) "Undefined qualified variable \"%s\"", identToStr(e)
4303 if (name(n).mod != currentModule) {
4306 if (fst(e) == VARIDCELL) {
4307 e = mkVar(qtextOf(e));
4309 e = mkVarop(qtextOf(e));
4311 return depVar(line,e);
4314 static Void local depConFlds(line,e,isP)/* check construction using fields */
4318 Name c = conDefined(line,fst(snd(e)));
4319 if (isNull(snd(snd(e))) ||
4320 nonNull(cellIsMember(c,depFields(line,e,snd(snd(e)),isP)))) {
4323 ERRMSG(line) "Constructor \"%s\" does not have selected fields in ",
4324 textToStr(name(c).text)
4329 if (!isP && isPair(name(c).defn)) { /* Check that banged fields defined*/
4330 List scs = fst(name(c).defn); /* List of strict components */
4331 Type t = name(c).type;
4332 Int a = userArity(c);
4333 List fs = snd(snd(e));
4335 if (isPolyType(t)) { /* Find tycon that c belongs to */
4338 if (whatIs(t)==QUAL) {
4341 if (whatIs(t)==CDICTS) {
4350 for (ss=tycon(t).defn; hasCfun(ss); ss=tl(ss)) {
4352 /* Now we know the tycon t that c belongs to, and the corresponding
4353 * list of selectors for that type, ss. Now we have to check that
4354 * each of the fields identified by scs appears in fs, using ss to
4355 * cross reference, and convert integers to selector names.
4357 for (; nonNull(scs); scs=tl(scs)) {
4358 Int i = intOf(hd(scs));
4360 for (; nonNull(ss1); ss1=tl(ss1)) {
4361 List cns = name(hd(ss1)).defn;
4362 for (; nonNull(cns); cns=tl(cns)) {
4363 if (fst(hd(cns))==c) {
4367 if (nonNull(cns) && intOf(snd(hd(cns)))==i) {
4372 internal("depConFlds");
4376 for (; nonNull(fs1) && s!=fst(hd(fs1)); fs1=tl(fs1)) {
4379 ERRMSG(line) "Construction does not define strict field"
4381 ERRTEXT "\nExpression : " ETHEN ERREXPR(e);
4382 ERRTEXT "\nField : " ETHEN ERREXPR(s);
4391 static Void local depUpdFlds(line,e) /* check update using fields */
4394 if (isNull(thd3(snd(e)))) {
4395 ERRMSG(line) "Empty field list in update"
4398 fst3(snd(e)) = depExpr(line,fst3(snd(e)));
4399 snd3(snd(e)) = depFields(line,e,thd3(snd(e)),FALSE);
4402 static List local depFields(l,e,fs,isP) /* check field binding list */
4410 for (; nonNull(fs); fs=tl(fs)) { /* for each field binding */
4414 if (isVar(fb)) { /* expand var to var = var */
4415 h98DoesntSupport(l,"missing field bindings");
4416 fb = hd(fs) = pair(fb,fb);
4419 s = findQualName(fst(fb)); /* check for selector */
4420 if (nonNull(s) && isSfun(s)) {
4423 ERRMSG(l) "\"%s\" is not a selector function/field name",
4424 textToStr(textOf(fst(fb)))
4428 if (isNull(ss)) { /* for first named selector */
4429 List scs = name(s).defn; /* calculate list of constructors */
4430 for (; nonNull(scs); scs=tl(scs)) {
4431 cs = cons(fst(hd(scs)),cs);
4433 ss = singleton(s); /* initialize selector list */
4434 } else { /* for subsequent selectors */
4435 List ds = cs; /* intersect constructor lists */
4436 for (cs=NIL; nonNull(ds); ) {
4437 List scs = name(s).defn;
4438 while (nonNull(scs) && fst(hd(scs))!=hd(ds)) {
4451 if (cellIsMember(s,ss)) { /* check for repeated uses */
4452 ERRMSG(l) "Repeated field name \"%s\" in field list",
4453 textToStr(name(s).text)
4459 if (isNull(cs)) { /* Are there any matching constrs? */
4460 ERRMSG(l) "No constructor has all of the fields specified in "
4466 snd(fb) = (isP ? checkPat(l,snd(fb)) : depExpr(l,snd(fb)));
4472 static Cell local depRecord(line,e) /* find dependents of record and */
4473 Int line; /* sort fields into approp. order */
4474 Cell e; { /* to make construction and update */
4475 List exts = NIL; /* more efficient. */
4478 h98DoesntSupport(line,"extensible records");
4479 do { /* build up list of extensions */
4480 Text t = extText(fun(fun(r)));
4481 String s = textToStr(t);
4484 while (nonNull(nx) && strcmp(textToStr(extText(fun(fun(nx)))),s)>0) {
4488 if (nonNull(nx) && t==extText(fun(fun(nx)))) {
4489 ERRMSG(line) "Repeated label \"%s\" in record ", s
4495 exts = cons(fun(r),exts);
4497 tl(prev) = cons(fun(r),nx);
4499 extField(r) = depExpr(line,extField(r));
4501 } while (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r))));
4502 r = depExpr(line,r);
4503 return revOnto(exts,r);
4508 /* --------------------------------------------------------------------------
4509 * Several parts of this program require an algorithm for sorting a list
4510 * of values (with some added dependency information) into a list of strongly
4511 * connected components in which each value appears before its dependents.
4513 * Each of these algorithms is obtained by parameterising a standard
4514 * algorithm in "scc.c" as shown below.
4515 * ------------------------------------------------------------------------*/
4517 #define SCC2 tcscc /* make scc algorithm for Tycons */
4518 #define LOWLINK tclowlink
4519 #define DEPENDS(c) (isTycon(c) ? tycon(c).kind : cclass(c).kinds)
4520 #define SETDEPENDS(c,v) if(isTycon(c)) tycon(c).kind=v; else cclass(c).kinds=v
4527 #define SCC bscc /* make scc algorithm for Bindings */
4528 #define LOWLINK blowlink
4529 #define DEPENDS(t) depVal(t)
4530 #define SETDEPENDS(c,v) depVal(c)=v
4537 /* --------------------------------------------------------------------------
4538 * Main static analysis:
4539 * ------------------------------------------------------------------------*/
4541 Void checkExp() { /* Top level static check on Expr */
4542 staticAnalysis(RESET);
4543 clearScope(); /* Analyse expression in the scope */
4544 withinScope(NIL); /* of no local bindings */
4545 inputExpr = depExpr(0,inputExpr);
4547 staticAnalysis(RESET);
4550 Void checkDefns() { /* Top level static analysis */
4551 Module thisModule = lastModule();
4552 staticAnalysis(RESET);
4554 setCurrModule(thisModule);
4556 /* Resolve module references */
4557 mapProc(checkQualImport, module(thisModule).qualImports);
4558 mapProc(checkUnqualImport,unqualImports);
4559 /* Add "import Prelude" if there`s no explicit import */
4560 if (thisModule!=modulePrelude
4561 && isNull(cellAssoc(modulePrelude,unqualImports))
4562 && isNull(cellRevAssoc(modulePrelude,module(thisModule).qualImports))) {
4563 unqualImports = cons(pair(modulePrelude,DOTDOT),unqualImports);
4565 /* Every module (including the Prelude) implicitly contains
4566 * "import qualified Prelude"
4568 module(thisModule).qualImports=cons(pair(mkCon(textPrelude),modulePrelude),
4569 module(thisModule).qualImports);
4571 mapProc(checkImportList, unqualImports);
4573 linkPreludeTC(); /* Get prelude tycons and classes */
4574 mapProc(checkTyconDefn,tyconDefns); /* validate tycon definitions */
4575 checkSynonyms(tyconDefns); /* check synonym definitions */
4576 mapProc(checkClassDefn,classDefns); /* process class definitions */
4577 mapProc(kindTCGroup,tcscc(tyconDefns,classDefns)); /* attach kinds */
4578 mapProc(addMembers,classDefns); /* add definitions for member funs */
4579 mapProc(visitClass,classDefns); /* check class hierarchy */
4580 linkPreludeCM(); /* Get prelude cfuns and mfuns */
4582 instDefns = rev(instDefns); /* process instance definitions */
4583 mapProc(checkInstDefn,instDefns);
4585 setCurrModule(thisModule);
4586 mapProc(addDerivImp,derivedInsts); /* Add impls for derived instances */
4587 deriveContexts(derivedInsts); /* Calculate derived inst contexts */
4588 instDefns = appendOnto(instDefns,derivedInsts);
4589 checkDefaultDefns(); /* validate default definitions */
4591 mapProc(addRSsigdecls,typeInDefns); /* add sigdecls for RESTRICTSYN */
4592 valDefns = eqnsToBindings(valDefns,tyconDefns,classDefns, NIL/*primDefns*/ );
4595 mapProc(allNoPrevDef,valDefns); /* check against previous defns */
4599 mapProc(checkForeignImport,foreignImports); /* check foreign imports */
4600 mapProc(checkForeignExport,foreignExports); /* check foreign exports */
4601 foreignImports = NIL;
4602 foreignExports = NIL;
4604 /* Every top-level name has now been created - so we can build the */
4605 /* export list. Note that this has to happen before dependency */
4606 /* analysis so that references to Prelude.foo will be resolved */
4607 /* when compiling the prelude. */
4608 module(thisModule).exports = checkExports(module(thisModule).exports);
4610 mapProc(checkTypeIn,typeInDefns); /* check restricted synonym defns */
4613 withinScope(valDefns);
4614 valDefns = topDependAnal(valDefns); /* top level dependency ordering */
4615 mapProc(depDefaults,classDefns); /* dep. analysis on class defaults */
4616 mapProc(depInsts,instDefns); /* dep. analysis on inst defns */
4619 /* ToDo: evalDefaults should match current evaluation module */
4620 evalDefaults = defaultDefns; /* Set defaults for evaluator */
4622 staticAnalysis(RESET);
4625 static Void local addRSsigdecls(pr) /* add sigdecls from TYPE ... IN ..*/
4627 List vs = snd(pr); /* get list of variables */
4628 for (; nonNull(vs); vs=tl(vs)) {
4629 if (fst(hd(vs))==SIGDECL) { /* find a sigdecl */
4630 valDefns = cons(hd(vs),valDefns); /* add to valDefns */
4631 hd(vs) = hd(snd3(snd(hd(vs)))); /* and replace with var */
4636 static Void local allNoPrevDef(b) /* ensure no previous bindings for*/
4637 Cell b; { /* variables in new binding */
4638 if (isVar(fst(b))) {
4639 noPrevDef(rhsLine(snd(hd(snd(snd(b))))),fst(b));
4641 Int line = rhsLine(snd(snd(snd(b))));
4642 map1Proc(noPrevDef,line,fst(b));
4646 static Void local noPrevDef(line,v) /* ensure no previous binding for */
4647 Int line; /* new variable */
4649 Name n = findName(textOf(v));
4652 n = newName(textOf(v),NIL);
4653 name(n).defn = PREDEFINED;
4654 } else if (name(n).defn!=PREDEFINED) {
4655 duplicateError(line,name(n).mod,name(n).text,"variable");
4657 name(n).line = line;
4660 static Void local duplicateErrorAux(line,mod,t,kind)/* report duplicate defn */
4665 if (mod == currentModule) {
4666 ERRMSG(line) "Repeated definition for %s \"%s\"", kind,
4670 ERRMSG(line) "Definition of %s \"%s\" clashes with import", kind,
4676 static Void local checkTypeIn(cvs) /* Check that vars in restricted */
4677 Pair cvs; { /* synonym are defined */
4681 for (; nonNull(vs); vs=tl(vs)) {
4682 if (isNull(findName(textOf(hd(vs))))) {
4683 ERRMSG(tycon(c).line)
4684 "No top level binding of \"%s\" for restricted synonym \"%s\"",
4685 textToStr(textOf(hd(vs))), textToStr(tycon(c).text)
4691 /* --------------------------------------------------------------------------
4692 * Haskell 98 compatibility tests:
4693 * ------------------------------------------------------------------------*/
4695 Bool h98Pred(allowArgs,pi) /* Check syntax of Hask98 predicate*/
4698 return isClass(getHead(pi)) && argCount==1 &&
4699 isOffset(getHead(arg(pi))) && (argCount==0 || allowArgs);
4702 Cell h98Context(allowArgs,ps) /* Check syntax of Hask98 context */
4705 for (; nonNull(ps); ps=tl(ps)) {
4706 if (!h98Pred(allowArgs,hd(ps))) {
4713 Void h98CheckCtxt(line,wh,allowArgs,ps,in)
4714 Int line; /* Report illegal context/predicate*/
4720 Cell pi = h98Context(allowArgs,ps);
4722 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh ETHEN
4724 ERRTEXT "\n*** Instance : " ETHEN ERRPRED(inst(in).head);
4726 ERRTEXT "\n*** Constraint : " ETHEN ERRPRED(pi);
4727 if (nonNull(ps) && nonNull(tl(ps))) {
4728 ERRTEXT "\n*** Context : " ETHEN ERRCONTEXT(ps);
4736 Void h98CheckType(line,wh,e,t) /* Check for Haskell 98 type */
4745 if (whatIs(t)==QUAL) {
4746 Cell pi = h98Context(TRUE,fst(snd(t)));
4748 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh
4750 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
4751 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(ty);
4759 Void h98DoesntSupport(line,wh) /* Report feature missing in H98 */
4763 ERRMSG(line) "Haskell 98 does not support %s", wh
4768 /* --------------------------------------------------------------------------
4769 * Static Analysis control:
4770 * ------------------------------------------------------------------------*/
4772 Void staticAnalysis(what)
4775 case RESET : cfunSfuns = NIL;
4788 case MARK : mark(daSccs);
4803 case INSTALL : staticAnalysis(RESET);
4805 extKind = pair(STAR,pair(ROW,ROW));
4811 /*-------------------------------------------------------------------------*/