2 /* --------------------------------------------------------------------------
3 * Static Analysis for Hugs
5 * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
6 * Yale Haskell Group, and the Oregon Graduate Institute of Science and
7 * Technology, 1994-1999, All rights reserved. It is distributed as
8 * free software under the license in the file "License", which is
9 * included in the distribution.
11 * $RCSfile: static.c,v $
13 * $Date: 1999/11/12 17:32:43 $
14 * ------------------------------------------------------------------------*/
24 /* --------------------------------------------------------------------------
25 * local function prototypes:
26 * ------------------------------------------------------------------------*/
28 static Void local kindError Args((Int,Constr,Constr,String,Kind,Int));
29 static Void local checkQualImport Args((Pair));
30 static Void local checkUnqualImport Args((Triple));
32 static Name local lookupName Args((Text,List));
33 static List local checkSubentities Args((List,List,List,String,Text));
34 static List local checkExportTycon Args((List,Text,Cell,Tycon));
35 static List local checkExportClass Args((List,Text,Cell,Class));
36 static List local checkExport Args((List,Text,Cell));
37 static List local checkImportEntity Args((List,Module,Cell));
38 static List local resolveImportList Args((Module,Cell));
39 static Void local checkImportList Args((Pair));
41 static Void local importEntity Args((Module,Cell));
42 static Void local importName Args((Module,Name));
43 static Void local importTycon Args((Module,Tycon));
44 static Void local importClass Args((Module,Class));
45 static List local checkExports Args((List));
47 static Void local checkTyconDefn Args((Tycon));
48 static Void local depConstrs Args((Tycon,List,Cell));
49 static List local addSels Args((Int,Name,List,List));
50 static List local selectCtxt Args((List,List));
51 static Void local checkSynonyms Args((List));
52 static List local visitSyn Args((List,Tycon,List));
53 static Type local instantiateSyn Args((Type,Type));
55 static Void local checkClassDefn Args((Class));
56 static Cell local depPredExp Args((Int,List,Cell));
57 static Void local checkMems Args((Class,List,Cell));
58 static Void local addMembers Args((Class));
59 static Name local newMember Args((Int,Int,Cell,Type,Class));
60 static Name local newDSel Args((Class,Int));
61 static Text local generateText Args((String,Class));
62 static Int local visitClass Args((Class));
64 static List local classBindings Args((String,Class,List));
65 static Name local memberName Args((Class,Text));
66 static List local numInsert Args((Int,Cell,List));
68 static List local maybeAppendVar Args((Cell,List));
70 static Type local checkSigType Args((Int,String,Cell,Type));
71 static Void local checkOptQuantVars Args((Int,List,List));
72 static Type local depTopType Args((Int,List,Type));
73 static Type local depCompType Args((Int,List,Type));
74 static Type local depTypeExp Args((Int,List,Type));
75 static Type local depTypeVar Args((Int,List,Text));
76 static List local checkQuantVars Args((Int,List,List,Cell));
77 static List local otvars Args((Cell,List));
78 static Bool local osubset Args((List,List));
79 static Void local kindConstr Args((Int,Int,Int,Constr));
80 static Kind local kindAtom Args((Int,Constr));
81 static Void local kindPred Args((Int,Int,Int,Cell));
82 static Void local kindType Args((Int,String,Type));
83 static Void local fixKinds Args((Void));
85 static Void local kindTCGroup Args((List));
86 static Void local initTCKind Args((Cell));
87 static Void local kindTC Args((Cell));
88 static Void local genTC Args((Cell));
90 static Void local checkInstDefn Args((Inst));
91 static Void local insertInst Args((Inst));
92 static Bool local instCompare Args((Inst,Inst));
93 static Name local newInstImp Args((Inst));
94 static Void local kindInst Args((Inst,Int));
95 static Void local checkDerive Args((Tycon,List,List,Cell));
96 static Void local addDerInst Args((Int,Class,List,List,Type,Int));
97 static Void local deriveContexts Args((List));
98 static Void local initDerInst Args((Inst));
99 static Void local calcInstPreds Args((Inst));
100 static Void local maybeAddPred Args((Cell,Int,Int,List));
101 static List local calcFunDeps Args((List));
102 static Cell local copyAdj Args((Cell,Int,Int));
103 static Void local tidyDerInst Args((Inst));
104 static List local otvarsZonk Args((Cell,List,Int));
106 static Void local addDerivImp Args((Inst));
108 static Void local checkDefaultDefns Args((Void));
110 static Void local checkForeignImport Args((Name));
111 static Void local checkForeignExport Args((Name));
113 static Cell local tidyInfix Args((Int,Cell));
114 static Pair local attachFixity Args((Int,Cell));
115 static Syntax local lookupSyntax Args((Text));
117 static Cell local checkPat Args((Int,Cell));
118 static Cell local checkMaybeCnkPat Args((Int,Cell));
119 static Cell local checkApPat Args((Int,Int,Cell));
120 static Void local addToPatVars Args((Int,Cell));
121 static Name local conDefined Args((Int,Cell));
122 static Void local checkIsCfun Args((Int,Name));
123 static Void local checkCfunArgs Args((Int,Cell,Int));
124 static Cell local checkPatType Args((Int,String,Cell,Type));
125 static Cell local applyBtyvs Args((Cell));
126 static Cell local bindPat Args((Int,Cell));
127 static Void local bindPats Args((Int,List));
129 static List local extractSigdecls Args((List));
130 static List local extractFixdecls Args((List));
131 static List local extractBindings Args((List));
132 static List local getPatVars Args((Int,Cell,List));
133 static List local addPatVar Args((Int,Cell,List));
134 static List local eqnsToBindings Args((List,List,List,List));
135 static Void local notDefined Args((Int,List,Cell));
136 static Cell local findBinding Args((Text,List));
137 static Cell local getAttr Args((List,Cell));
138 static Void local addSigdecl Args((List,Cell));
139 static Void local addFixdecl Args((List,List,List,List,Triple));
140 static Void local dupFixity Args((Int,Text));
141 static Void local missFixity Args((Int,Text));
143 static List local dependencyAnal Args((List));
144 static List local topDependAnal Args((List));
145 static Void local addDepField Args((Cell));
146 static Void local remDepField Args((List));
147 static Void local remDepField1 Args((Cell));
148 static Void local clearScope Args((Void));
149 static Void local withinScope Args((List));
150 static Void local leaveScope Args((Void));
151 static Void local saveSyntax Args((Cell,Cell));
153 static Void local depBinding Args((Cell));
154 static Void local depDefaults Args((Class));
155 static Void local depInsts Args((Inst));
156 static Void local depClassBindings Args((List));
157 static Void local depAlt Args((Cell));
158 static Void local depRhs Args((Cell));
159 static Void local depGuard Args((Cell));
160 static Cell local depExpr Args((Int,Cell));
161 static Void local depPair Args((Int,Cell));
162 static Void local depTriple Args((Int,Cell));
163 static Void local depComp Args((Int,Cell,List));
164 static Void local depCaseAlt Args((Int,Cell));
165 static Cell local depVar Args((Int,Cell));
166 static Cell local depQVar Args((Int,Cell));
167 static Void local depConFlds Args((Int,Cell,Bool));
168 static Void local depUpdFlds Args((Int,Cell));
169 static List local depFields Args((Int,Cell,List,Bool));
171 static Void local depWith Args((Int,Cell));
172 static List local depDwFlds Args((Int,Cell,List));
175 static Cell local depRecord Args((Int,Cell));
178 static List local tcscc Args((List,List));
179 static List local bscc Args((List));
181 static Void local addRSsigdecls Args((Pair));
182 static Void local allNoPrevDef Args((Cell));
183 static Void local noPrevDef Args((Int,Cell));
184 static Bool local odiff Args((List,List));
186 static Void local duplicateErrorAux Args((Int,Module,Text,String));
187 #define duplicateError(l,m,t,k) duplicateErrorAux(l,m,t,k)
188 static Void local checkTypeIn Args((Pair));
190 /* --------------------------------------------------------------------------
191 * The code in this file is arranged in roughly the following order:
192 * - Kind inference preliminaries
193 * - Module declarations
194 * - Type declarations (data, type, newtype, type in)
195 * - Class declarations
197 * - Instance declarations
198 * - Default declarations
199 * - Primitive definitions
201 * - Infix expressions
202 * - Value definitions
203 * - Top-level static analysis and control
204 * - Haskell 98 compatibility tests
205 * ------------------------------------------------------------------------*/
207 /* --------------------------------------------------------------------------
208 * Kind checking preliminaries:
209 * ------------------------------------------------------------------------*/
211 Bool kindExpert = FALSE; /* TRUE => display kind errors in */
214 static Void local kindError(l,c,in,wh,k,o)
215 Int l; /* line number near constuctor exp */
216 Constr c; /* constructor */
217 Constr in; /* context (if any) */
218 String wh; /* place in which error occurs */
219 Kind k; /* expected kind (k,o) */
220 Int o; { /* inferred kind (typeIs,typeOff) */
223 if (!kindExpert) { /* for those with a fear of kinds */
224 ERRMSG(l) "Illegal type" ETHEN
226 ERRTEXT " \"" ETHEN ERRTYPE(in);
229 ERRTEXT " in %s\n", wh
233 ERRMSG(l) "Kind error in %s", wh ETHEN
235 ERRTEXT "\n*** expression : " ETHEN ERRTYPE(in);
237 ERRTEXT "\n*** constructor : " ETHEN ERRTYPE(c);
238 ERRTEXT "\n*** kind : " ETHEN ERRKIND(copyType(typeIs,typeOff));
239 ERRTEXT "\n*** does not match : " ETHEN ERRKIND(copyType(k,o));
241 ERRTEXT "\n*** because : %s", unifyFails ETHEN
247 #define shouldKind(l,c,in,wh,k,o) if (!kunify(typeIs,typeOff,k,o)) \
248 kindError(l,c,in,wh,k,o)
249 #define checkKind(l,a,m,c,in,wh,k,o) kindConstr(l,a,m,c); \
250 shouldKind(l,c,in,wh,k,o)
251 #define inferKind(k,o) typeIs=k; typeOff=o
253 static List unkindTypes; /* types in need of kind annotation*/
255 Kind extKind; /* Kind of extension, *->row->row */
258 /* --------------------------------------------------------------------------
259 * Static analysis of modules:
260 * ------------------------------------------------------------------------*/
266 Void startModule(nm) /* switch to a new module */
269 if (!isCon(nm)) internal("startModule");
270 if (isNull(m = findModule(textOf(nm))))
271 m = newModule(textOf(nm));
272 else if (!isPreludeScript()) {
273 /* You're allowed to break the rules in the Prelude! */
275 reloadModule = textToStr(textOf(nm));
277 ERRMSG(0) "Module \"%s\" already loaded", textToStr(textOf(nm))
283 Void setExportList(exps) /* Add export list to current module */
285 module(currentModule).exports = exps;
288 Void addQualImport(orig,new) /* Add to qualified import list */
289 Cell orig; /* Original name of module */
290 Cell new; { /* Name module is called within this module (or NIL) */
291 module(currentModule).qualImports =
292 cons(pair(isNull(new)?orig:new,orig),module(currentModule).qualImports);
295 Void addUnqualImport(mod,entities) /* Add to unqualified import list */
296 Cell mod; /* Name of module */
297 List entities; { /* List of entity names */
298 unqualImports = cons(pair(mod,entities),unqualImports);
301 static Void local checkQualImport(i) /* Process qualified import */
303 Module m = findModid(snd(i));
305 ERRMSG(0) "Module \"%s\" not previously loaded",
306 textToStr(textOf(snd(i)))
312 static Void local checkUnqualImport(i) /* Process unqualified import */
314 Module m = findModid(fst(i));
316 ERRMSG(0) "Module \"%s\" not previously loaded",
317 textToStr(textOf(fst(i)))
323 static Name local lookupName(t,nms) /* find text t in list of Names */
325 List nms; { /* :: [Name] */
326 for(; nonNull(nms); nms=tl(nms)) {
327 if (t == name(hd(nms)).text)
333 static List local checkSubentities(imports,named,wanted,description,textParent)
335 List named; /* :: [ Q?(Var|Con)(Id|Op) ] */
336 List wanted; /* :: [Name] */
337 String description; /* "<constructor>|<member> of <type>|<class>" */
339 for(; nonNull(named); named=tl(named)) {
341 /* ToDo: ignores qualifier; doesn't check that entity is in scope */
342 Text t = isPair(snd(x)) ? qtextOf(x) : textOf(x);
343 Name n = lookupName(t,wanted);
345 ERRMSG(0) "Entity \"%s\" is not a %s \"%s\"",
348 textToStr(textParent)
351 imports = cons(n,imports);
356 static List local checkImportEntity(imports,exporter,entity)
357 List imports; /* Accumulated list of things to import */
359 Cell entity; { /* Entry from import list */
360 List oldImports = imports;
361 Text t = isIdent(entity) ? textOf(entity) : textOf(fst(entity));
362 List es = module(exporter).exports;
363 for(; nonNull(es); es=tl(es)) {
364 Cell e = hd(es); /* :: Entity | (Entity, NIL|DOTDOT) */
368 if (tycon(f).text == t) {
369 imports = cons(f,imports);
370 if (!isIdent(entity)) {
371 switch (tycon(f).what) {
374 if (DOTDOT == snd(entity)) {
375 imports=dupOnto(tycon(f).defn,imports);
377 imports=checkSubentities(imports,snd(entity),tycon(f).defn,
378 "constructor of type",t);
382 /* deliberate fall thru */
386 } else if (isClass(f)) {
387 if (cclass(f).text == t) {
388 imports = cons(f,imports);
389 if (!isIdent(entity)) {
390 if (DOTDOT == snd(entity)) {
391 return dupOnto(cclass(f).members,imports);
393 return checkSubentities(imports,snd(entity),cclass(f).members,
394 "member of class",t);
399 internal("checkImportEntity2");
401 } else if (isName(e)) {
402 if (isIdent(entity) && name(e).text == t) {
403 imports = cons(e,imports);
406 internal("checkImportEntity3");
409 if (imports == oldImports) {
410 ERRMSG(0) "Unknown entity \"%s\" imported from module \"%s\"",
412 textToStr(module(exporter ).text)
418 static List local resolveImportList(m,impList)
419 Module m; /* exporting module */
422 if (DOTDOT == impList) {
423 List es = module(m).exports;
424 for(; nonNull(es); es=tl(es)) {
427 imports = cons(e,imports);
430 List subentities = NIL;
431 imports = cons(c,imports);
433 && (tycon(c).what == DATATYPE
434 || tycon(c).what == NEWTYPE))
435 subentities = tycon(c).defn;
437 subentities = cclass(c).members;
438 if (DOTDOT == snd(e)) {
439 imports = dupOnto(subentities,imports);
444 map1Accum(checkImportEntity,imports,m,impList);
449 static Void local checkImportList(importSpec) /*Import a module unqualified*/
451 Module m = fst(importSpec);
452 Cell impList = snd(importSpec);
454 List imports = NIL; /* entities we want to import */
455 List hidden = NIL; /* entities we want to hide */
457 if (moduleThisScript(m)) {
458 ERRMSG(0) "Module \"%s\" recursively imports itself",
459 textToStr(module(m).text)
462 if (isPair(impList) && HIDDEN == fst(impList)) {
463 /* Somewhat inefficient - but obviously correct:
464 * imports = importsOf("module Foo") `setDifference` hidden;
466 hidden = resolveImportList(m, snd(impList));
467 imports = resolveImportList(m, DOTDOT);
469 imports = resolveImportList(m, impList);
471 for(; nonNull(imports); imports=tl(imports)) {
472 Cell e = hd(imports);
473 if (!cellIsMember(e,hidden))
476 /* ToDo: hang onto the imports list for processing export list entries
477 * of the form "module Foo"
481 static Void local importEntity(source,e)
485 case NAME : importName(source,e);
487 case TYCON : importTycon(source,e);
489 case CLASS : importClass(source,e);
491 default: internal("importEntity");
495 static Void local importName(source,n)
498 Name clash = addName(n);
499 if (nonNull(clash) && clash!=n) {
500 ERRMSG(0) "Entity \"%s\" imported from module \"%s\" already defined in module \"%s\"",
501 textToStr(name(n).text),
502 textToStr(module(source).text),
503 textToStr(module(name(clash).mod).text)
508 static Void local importTycon(source,tc)
511 Tycon clash=addTycon(tc);
512 if (nonNull(clash) && clash!=tc) {
513 ERRMSG(0) "Tycon \"%s\" imported from \"%s\" already defined in module \"%s\"",
514 textToStr(tycon(tc).text),
515 textToStr(module(source).text),
516 textToStr(module(tycon(clash).mod).text)
519 if (nonNull(findClass(tycon(tc).text))) {
520 ERRMSG(0) "Import of type constructor \"%s\" clashes with class in module \"%s\"",
521 textToStr(tycon(tc).text),
522 textToStr(module(tycon(tc).mod).text)
527 static Void local importClass(source,c)
530 Class clash=addClass(c);
531 if (nonNull(clash) && clash!=c) {
532 ERRMSG(0) "Class \"%s\" imported from \"%s\" already defined in module \"%s\"",
533 textToStr(cclass(c).text),
534 textToStr(module(source).text),
535 textToStr(module(cclass(clash).mod).text)
538 if (nonNull(findTycon(cclass(c).text))) {
539 ERRMSG(0) "Import of class \"%s\" clashes with type constructor in module \"%s\"",
540 textToStr(cclass(c).text),
541 textToStr(module(source).text)
546 static List local checkExportTycon(exports,mt,spec,tc)
551 if (DOTDOT == spec || SYNONYM == tycon(tc).what) {
552 return cons(pair(tc,DOTDOT), exports);
554 return cons(pair(tc,NIL), exports);
558 static List local checkExportClass(exports,mt,spec,cl)
563 if (DOTDOT == spec) {
564 return cons(pair(cl,DOTDOT), exports);
566 return cons(pair(cl,NIL), exports);
570 static List local checkExport(exports,mt,e) /* Process entry in export list*/
576 List origExports = exports;
577 if (nonNull(export=findQualName(e))) {
578 exports=cons(export,exports);
580 if (isQCon(e) && nonNull(export=findQualTycon(e))) {
581 exports = checkExportTycon(exports,mt,NIL,export);
583 if (isQCon(e) && nonNull(export=findQualClass(e))) {
584 /* opaque class export */
585 exports = checkExportClass(exports,mt,NIL,export);
587 if (exports == origExports) {
588 ERRMSG(0) "Unknown entity \"%s\" exported from module \"%s\"",
594 } else if (MODULEENT == fst(e)) {
595 Module m = findModid(snd(e));
596 /* ToDo: shouldn't allow export of module we didn't import */
598 ERRMSG(0) "Unknown module \"%s\" exported from module \"%s\"",
599 textToStr(textOf(snd(e))),
603 if (m == currentModule) {
604 /* Exporting the current module exports local definitions */
606 for(xs=module(m).classes; nonNull(xs); xs=tl(xs)) {
607 if (cclass(hd(xs)).mod==m)
608 exports = checkExportClass(exports,mt,DOTDOT,hd(xs));
610 for(xs=module(m).tycons; nonNull(xs); xs=tl(xs)) {
611 if (tycon(hd(xs)).mod==m)
612 exports = checkExportTycon(exports,mt,DOTDOT,hd(xs));
614 for(xs=module(m).names; nonNull(xs); xs=tl(xs)) {
615 if (name(hd(xs)).mod==m)
616 exports = cons(hd(xs),exports);
619 /* Exporting other modules imports all things imported
620 * unqualified from it.
621 * ToDo: we reexport everything exported by a module -
622 * whether we imported it or not. This gives the wrong
623 * result for "module M(module N) where import N(x)"
625 exports = dupOnto(module(m).exports,exports);
629 Cell ident = fst(e); /* class name or type name */
630 Cell parts = snd(e); /* members or constructors */
632 if (isQCon(ident) && nonNull(nm=findQualTycon(ident))) {
633 switch (tycon(nm).what) {
636 ERRMSG(0) "Explicit constructor list given for type synonym"
637 " \"%s\" in export list of module \"%s\"",
642 return cons(pair(nm,DOTDOT),exports);
644 ERRMSG(0) "Transparent export of restricted type synonym"
645 " \"%s\" in export list of module \"%s\"",
649 return exports; /* Not reached */
653 return cons(pair(nm,DOTDOT),exports);
655 exports = checkSubentities(exports,parts,tycon(nm).defn,
656 "constructor of type",
658 return cons(pair(nm,DOTDOT), exports);
661 internal("checkExport1");
663 } else if (isQCon(ident) && nonNull(nm=findQualClass(ident))) {
664 if (DOTDOT == parts) {
665 return cons(pair(nm,DOTDOT),exports);
667 exports = checkSubentities(exports,parts,cclass(nm).members,
668 "member of class",cclass(nm).text);
669 return cons(pair(nm,DOTDOT), exports);
672 ERRMSG(0) "Explicit export list given for non-class/datatype \"%s\" in export list of module \"%s\"",
678 return exports; /* NOTUSED */
681 static List local checkExports(exports)
683 Module m = lastModule();
684 Text mt = module(m).text;
687 map1Accum(checkExport,es,mt,exports);
690 for(xs=es; nonNull(xs); xs=tl(xs)) {
691 Printf(" %s", textToStr(textOfEntity(hd(xs))));
698 /* --------------------------------------------------------------------------
699 * Static analysis of type declarations:
701 * Type declarations come in two forms:
702 * - data declarations - define new constructed data types
703 * - type declarations - define new type synonyms
705 * A certain amount of work is carried out as the declarations are
706 * read during parsing. In particular, for each type constructor
707 * definition encountered:
708 * - check that there is no previous definition of constructor
709 * - ensure type constructor not previously used as a class name
710 * - make a new entry in the type constructor table
711 * - record line number of declaration
712 * - Build separate lists of newly defined constructors for later use.
713 * ------------------------------------------------------------------------*/
715 Void tyconDefn(line,lhs,rhs,what) /* process new type definition */
716 Int line; /* definition line number */
717 Cell lhs; /* left hand side of definition */
718 Cell rhs; /* right hand side of definition */
719 Cell what; { /* SYNONYM/DATATYPE/etc... */
720 Text t = textOf(getHead(lhs));
722 if (nonNull(findTycon(t))) {
723 ERRMSG(line) "Repeated definition of type constructor \"%s\"",
727 else if (nonNull(findClass(t))) {
728 ERRMSG(line) "\"%s\" used as both class and type constructor",
733 Tycon nw = newTycon(t);
734 tyconDefns = cons(nw,tyconDefns);
735 tycon(nw).line = line;
736 tycon(nw).arity = argCount;
737 tycon(nw).what = what;
738 if (what==RESTRICTSYN) {
739 h98DoesntSupport(line,"restricted type synonyms");
740 typeInDefns = cons(pair(nw,snd(rhs)),typeInDefns);
743 tycon(nw).defn = pair(lhs,rhs);
747 Void setTypeIns(bs) /* set local synonyms for given */
748 List bs; { /* binding group */
749 List cvs = typeInDefns;
750 for (; nonNull(cvs); cvs=tl(cvs)) {
751 Tycon c = fst(hd(cvs));
752 List vs = snd(hd(cvs));
753 for (tycon(c).what = RESTRICTSYN; nonNull(vs); vs=tl(vs)) {
754 if (nonNull(findBinding(textOf(hd(vs)),bs))) {
755 tycon(c).what = SYNONYM;
762 Void clearTypeIns() { /* clear list of local synonyms */
763 for (; nonNull(typeInDefns); typeInDefns=tl(typeInDefns))
764 tycon(fst(hd(typeInDefns))).what = RESTRICTSYN;
767 /* --------------------------------------------------------------------------
768 * Further analysis of Type declarations:
770 * In order to allow the definition of mutually recursive families of
771 * data types, the static analysis of the right hand sides of type
772 * declarations cannot be performed until all of the type declarations
775 * Once parsing is complete, we carry out the following:
777 * - check format of lhs, extracting list of bound vars and ensuring that
778 * there are no repeated variables and no Skolem variables.
779 * - run dependency analysis on rhs to check that only bound type vars
780 * appear in type and that all constructors are defined.
781 * Replace type variables by offsets, constructors by Tycons.
782 * - use list of dependents to sort into strongly connected components.
783 * - ensure that there is not more than one synonym in each group.
784 * - kind-check each group of type definitions.
786 * - check that there are no previous definitions for constructor
787 * functions in data type definitions.
788 * - install synonym expansions and constructor definitions.
789 * ------------------------------------------------------------------------*/
791 static List tcDeps = NIL; /* list of dependent tycons/classes*/
793 static Void local checkTyconDefn(d) /* validate type constructor defn */
795 Cell lhs = fst(tycon(d).defn);
796 Cell rhs = snd(tycon(d).defn);
797 Int line = tycon(d).line;
798 List tyvars = getArgs(lhs);
800 /* check for repeated tyvars on lhs*/
801 for (temp=tyvars; nonNull(temp); temp=tl(temp))
802 if (nonNull(varIsMember(textOf(hd(temp)),tl(temp)))) {
803 ERRMSG(line) "Repeated type variable \"%s\" on left hand side",
804 textToStr(textOf(hd(temp)))
808 tcDeps = NIL; /* find dependents */
809 switch (whatIs(tycon(d).what)) {
811 case SYNONYM : rhs = depTypeExp(line,tyvars,rhs);
812 if (cellIsMember(d,tcDeps)) {
813 ERRMSG(line) "Recursive type synonym \"%s\"",
814 textToStr(tycon(d).text)
820 case NEWTYPE : depConstrs(d,tyvars,rhs);
824 default : internal("checkTyconDefn");
829 tycon(d).kind = tcDeps;
833 static Void local depConstrs(t,tyvars,cd)
834 Tycon t; /* Define constructor functions and*/
835 List tyvars; /* do dependency analysis for data */
836 Cell cd; { /* definitions (w or w/o deriving) */
837 Int line = tycon(t).line;
842 List derivs = snd(cd);
843 List compTypes = NIL;
847 for (i=0; i<tycon(t).arity; ++i) /* build representation for tycon */
848 lhs = ap(lhs,mkOffset(i)); /* applied to full comp. of args */
850 if (isQualType(cs)) { /* allow for possible context */
853 map2Over(depPredExp,line,tyvars,ctxt);
854 h98CheckCtxt(line,"context",TRUE,ctxt,NIL);
857 if (nonNull(cs) && isNull(tl(cs))) /* Single constructor datatype? */
860 for (; nonNull(cs); cs=tl(cs)) { /* For each constructor function: */
862 List sig = dupList(tyvars);
863 List evs = NIL; /* locally quantified vars */
864 List lps = NIL; /* locally bound predicates */
865 List ctxt1 = ctxt; /* constructor function context */
866 List scs = NIL; /* strict components */
867 List fs = NONE; /* selector names */
868 Type type = lhs; /* constructor function type */
869 Int arity = 0; /* arity of constructor function */
870 Int nr2 = 0; /* Number of rank 2 args */
871 Name n; /* name for constructor function */
873 if (whatIs(con)==POLYTYPE) { /* Locally quantified vars */
876 sig = checkQuantVars(line,evs,sig,con);
879 if (isQualType(con)) { /* Local predicates */
882 for (us = typeVarsIn(lps,NIL,NIL,NIL); nonNull(us); us=tl(us))
883 if (!varIsMember(textOf(hd(us)),evs)) {
885 "Variable \"%s\" in constraint is not locally bound",
886 textToStr(textOf(hd(us)))
889 map2Over(depPredExp,line,sig,lps);
894 if (whatIs(con)==LABC) { /* Skeletize constr components */
895 Cell fls = snd(snd(con)); /* get field specifications */
898 for (; nonNull(fls); fls=tl(fls)) { /* for each field spec: */
899 List vs = fst(hd(fls));
900 Type t = snd(hd(fls)); /* - scrutinize type */
901 Bool banged = whatIs(t)==BANG;
902 t = depCompType(line,sig,(banged ? arg(t) : t));
903 while (nonNull(vs)) { /* - add named components */
911 scs = cons(mkInt(arity),scs);
915 scs = rev(scs); /* put strict comps in ascend ord */
917 else { /* Non-labelled constructor */
920 for (; isAp(c); c=fun(c))
922 for (compNo=arity, c=con; isAp(c); c=fun(c)) {
924 if (whatIs(t)==BANG) {
925 scs = cons(mkInt(compNo),scs);
929 arg(c) = depCompType(line,sig,t);
933 if (nonNull(ctxt1)) /* Extract relevant part of context*/
934 ctxt1 = selectCtxt(ctxt1,offsetTyvarsIn(con,NIL));
936 for (i=arity; isAp(con); i--) { /* Calculate type of constructor */
939 fun(con) = typeArrow;
940 if (isPolyOrQualType(cmp)) {
941 if (nonNull(derivs)) {
942 ERRMSG(line) "Cannot derive instances for types" ETHEN
943 ERRTEXT " with polymorphic or qualified components"
949 if (nonNull(derivs)) /* and build list of components */
950 compTypes = cons(cmp,compTypes);
955 if (nr2>0) { /* Add rank 2 annotation */
956 type = ap(RANK2,pair(mkInt(nr2-length(lps)),type));
959 if (nonNull(evs)) { /* Add existential annotation */
960 if (nonNull(derivs)) {
961 ERRMSG(line) "Cannot derive instances for types" ETHEN
962 ERRTEXT " with existentially typed components"
967 "Cannot use selectors with existentially typed components"
970 type = ap(EXIST,pair(mkInt(length(evs)),type));
973 if (nonNull(lps)) { /* Add local preds part to type */
974 type = ap(CDICTS,pair(lps,type));
977 if (nonNull(ctxt1)) { /* Add context part to type */
978 type = ap(QUAL,pair(ctxt1,type));
981 if (nonNull(sig)) { /* Add quantifiers to type */
983 for (; nonNull(ts1); ts1=tl(ts1)) {
986 type = mkPolyType(sig,type);
989 n = findName(textOf(con)); /* Allocate constructor fun name */
991 n = newName(textOf(con),NIL);
992 } else if (name(n).defn!=PREDEFINED) {
993 duplicateError(line,name(n).mod,name(n).text,
994 "constructor function");
996 name(n).arity = arity; /* Save constructor fun details */
999 name(n).number = cfunNo(conNo++);
1000 name(n).type = type;
1001 if (tycon(t).what==NEWTYPE) {
1004 "A newtype constructor cannot have class constraints"
1009 "A newtype constructor must have exactly one argument"
1014 "Illegal strictess annotation for newtype constructor"
1017 name(n).defn = nameId;
1019 implementCfun(n,scs);
1024 sels = addSels(line,n,fs,sels);
1028 if (nonNull(sels)) {
1030 fst(cd) = appendOnto(fst(cd),sels);
1031 selDefns = cons(sels,selDefns);
1034 if (nonNull(derivs)) { /* Generate derived instances */
1035 map3Proc(checkDerive,t,ctxt,compTypes,derivs);
1039 Int userArity(c) /* Find arity for cfun, ignoring */
1040 Name c; { /* CDICTS parameters */
1041 Int a = name(c).arity;
1042 Type t = name(c).type;
1044 if (isPolyType(t)) {
1047 if ((w=whatIs(t))==QUAL) {
1048 w = whatIs(t=snd(snd(t)));
1051 a -= length(fst(snd(t)));
1057 static List local addSels(line,c,fs,ss) /* Add fields to selector list */
1058 Int line; /* line number of constructor */
1059 Name c; /* corresponding constr function */
1060 List fs; /* list of fields (varids) */
1061 List ss; { /* list of existing selectors */
1063 cfunSfuns = cons(pair(c,fs),cfunSfuns);
1064 for (; nonNull(fs); fs=tl(fs), ++sn) {
1066 Text t = textOf(hd(fs));
1068 if (nonNull(varIsMember(t,tl(fs)))) {
1069 ERRMSG(line) "Repeated field name \"%s\" for constructor \"%s\"",
1070 textToStr(t), textToStr(name(c).text)
1074 while (nonNull(ns) && t!=name(hd(ns)).text) {
1079 name(hd(ns)).defn = cons(pair(c,mkInt(sn)),name(hd(ns)).defn);
1081 Name n = findName(t);
1083 ERRMSG(line) "Repeated definition for selector \"%s\"",
1088 name(n).line = line;
1089 name(n).number = SELNAME;
1090 name(n).defn = singleton(pair(c,mkInt(sn)));
1097 static List local selectCtxt(ctxt,vs) /* calculate subset of context */
1104 for (; nonNull(ctxt); ctxt=tl(ctxt)) {
1105 List us = offsetTyvarsIn(hd(ctxt),NIL);
1106 for (; nonNull(us) && cellIsMember(hd(us),vs); us=tl(us)) {
1109 ps = cons(hd(ctxt),ps);
1116 static Void local checkSynonyms(ts) /* Check for mutually recursive */
1117 List ts; { /* synonyms */
1119 for (; nonNull(ts); ts=tl(ts)) { /* build list of all synonyms */
1121 switch (whatIs(tycon(t).what)) {
1123 case RESTRICTSYN : syns = cons(t,syns);
1127 while (nonNull(syns)) { /* then visit each synonym */
1128 syns = visitSyn(NIL,hd(syns),syns);
1132 static List local visitSyn(path,t,syns) /* visit synonym definition to look*/
1133 List path; /* for cycles */
1136 if (cellIsMember(t,path)) { /* every elt in path depends on t */
1137 ERRMSG(tycon(t).line)
1138 "Type synonyms \"%s\" and \"%s\" are mutually recursive",
1139 textToStr(tycon(t).text), textToStr(tycon(hd(path)).text)
1142 List ds = tycon(t).kind;
1144 for (; nonNull(ds); ds=tl(ds)) {
1145 if (cellIsMember(hd(ds),syns)) {
1146 if (isNull(path1)) {
1147 path1 = cons(t,path);
1149 syns = visitSyn(path1,hd(ds),syns);
1153 tycon(t).defn = fullExpand(tycon(t).defn);
1154 return removeCell(t,syns);
1157 /* --------------------------------------------------------------------------
1158 * Expanding out all type synonyms in a type expression:
1159 * ------------------------------------------------------------------------*/
1161 Type fullExpand(t) /* find full expansion of type exp */
1162 Type t; { /* assuming that all relevant */
1163 Cell h = t; /* synonym defns of lower rank have*/
1164 Int n = 0; /* already been fully expanded */
1166 for (args=NIL; isAp(h); h=fun(h), n++) {
1167 args = cons(fullExpand(arg(h)),args);
1169 t = applyToArgs(h,args);
1170 if (isSynonym(h) && n>=tycon(h).arity) {
1171 if (n==tycon(h).arity) {
1172 t = instantiateSyn(tycon(h).defn,t);
1175 while (--n > tycon(h).arity) {
1178 fun(p) = instantiateSyn(tycon(h).defn,fun(p));
1184 static Type local instantiateSyn(t,env) /* instantiate type according using*/
1185 Type t; /* env to determine appropriate */
1186 Type env; { /* values for OFFSET type vars */
1187 switch (whatIs(t)) {
1188 case AP : return ap(instantiateSyn(fun(t),env),
1189 instantiateSyn(arg(t),env));
1191 case OFFSET : return nthArg(offsetOf(t),env);
1197 /* --------------------------------------------------------------------------
1198 * Static analysis of class declarations:
1200 * Performed in a similar manner to that used for type declarations.
1202 * The first part of the static analysis is performed as the declarations
1203 * are read during parsing. The parser ensures that:
1204 * - the class header and all superclass predicates are of the form
1207 * The classDefn() function:
1208 * - ensures that there is no previous definition for class
1209 * - checks that class name has not previously been used as a type constr.
1210 * - make new entry in class table
1211 * - record line number of declaration
1212 * - build list of classes defined in current script for use in later
1213 * stages of static analysis.
1214 * ------------------------------------------------------------------------*/
1216 Void classDefn(line,head,ms,fds) /* process new class definition */
1217 Int line; /* definition line number */
1218 Cell head; /* class header :: ([Supers],Class) */
1219 List ms; /* class definition body */
1220 List fds; { /* functional dependencies */
1221 Text ct = textOf(getHead(snd(head)));
1222 Int arity = argCount;
1224 if (nonNull(findClass(ct))) {
1225 ERRMSG(line) "Repeated definition of class \"%s\"",
1228 } else if (nonNull(findTycon(ct))) {
1229 ERRMSG(line) "\"%s\" used as both class and type constructor",
1233 Class nw = newClass(ct);
1234 cclass(nw).line = line;
1235 cclass(nw).arity = arity;
1236 cclass(nw).head = snd(head);
1237 cclass(nw).supers = fst(head);
1238 cclass(nw).members = ms;
1239 cclass(nw).level = 0;
1240 cclass(nw).fds = fds;
1241 classDefns = cons(nw,classDefns);
1243 h98DoesntSupport(line,"multiple parameter classes");
1247 /* --------------------------------------------------------------------------
1248 * Further analysis of class declarations:
1250 * Full static analysis of class definitions must be postponed until the
1251 * complete script has been read and all static analysis on type definitions
1252 * has been completed.
1254 * Once this has been achieved, we carry out the following checks on each
1256 * - check that variables in header are distinct
1257 * - replace head by skeleton
1258 * - check superclass declarations, replace by skeletons
1259 * - split body of class into members and declarations
1260 * - make new name entry for each member function
1261 * - record member function number (eventually an offset into dictionary!)
1262 * - no member function has a previous definition ...
1263 * - no member function is mentioned more than once in the list of members
1264 * - each member function type is valid, replace vars by offsets
1265 * - qualify each member function type by class header
1266 * - only bindings for members appear in defaults
1267 * - only function bindings appear in defaults
1268 * - check that extended class hierarchy does not contain any cycles
1269 * ------------------------------------------------------------------------*/
1271 static Void local checkClassDefn(c) /* validate class definition */
1274 Int args = cclass(c).arity - 1;
1275 Cell temp = cclass(c).head;
1279 for (; isAp(temp); temp=fun(temp)) {
1280 if (!isVar(arg(temp))) {
1281 ERRMSG(cclass(c).line) "Type variable required in class head"
1284 if (nonNull(varIsMember(textOf(arg(temp)),tyvars))) {
1285 ERRMSG(cclass(c).line)
1286 "Repeated type variable \"%s\" in class head",
1287 textToStr(textOf(arg(temp)))
1290 tyvars = cons(arg(temp),tyvars);
1293 for (fs=cclass(c).fds; nonNull(fs); fs=tl(fs)) {
1297 /* Check for trivial dependency
1299 if (isNull(snd(fd))) {
1300 ERRMSG(cclass(c).line) "Functional dependency is trivial"
1304 /* Check for duplicated vars on right hand side, and for vars on
1305 * right that also appear on the left:
1307 for (vs=snd(fd); nonNull(vs); vs=tl(vs)) {
1308 if (varIsMember(textOf(hd(vs)),fst(fd))) {
1309 ERRMSG(cclass(c).line)
1310 "Trivial dependency for variable \"%s\"",
1311 textToStr(textOf(hd(vs)))
1314 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1315 ERRMSG(cclass(c).line)
1316 "Repeated variable \"%s\" in functional dependency",
1317 textToStr(textOf(hd(vs)))
1320 hd(vs) = depTypeVar(cclass(c).line,tyvars,textOf(hd(vs)));
1323 /* Check for duplicated vars on left hand side:
1325 for (vs=fst(fd); nonNull(vs); vs=tl(vs)) {
1326 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1327 ERRMSG(cclass(c).line)
1328 "Repeated variable \"%s\" in functional dependency",
1329 textToStr(textOf(hd(vs)))
1332 hd(vs) = depTypeVar(cclass(c).line,tyvars,textOf(hd(vs)));
1336 if (cclass(c).arity==0) {
1339 Int args = cclass(c).arity - 1;
1340 for (temp=cclass(c).head; args>0; temp=fun(temp), args--) {
1341 arg(temp) = mkOffset(args);
1343 arg(temp) = mkOffset(0);
1347 tcDeps = NIL; /* find dependents */
1348 map2Over(depPredExp,cclass(c).line,tyvars,cclass(c).supers);
1349 h98CheckCtxt(cclass(c).line,"class definition",FALSE,cclass(c).supers,NIL);
1350 cclass(c).numSupers = length(cclass(c).supers);
1351 cclass(c).defaults = extractBindings(cclass(c).members); /* defaults*/
1352 ss = extractSigdecls(cclass(c).members);
1353 fs = extractFixdecls(cclass(c).members);
1354 cclass(c).members = pair(ss,fs);
1355 map2Proc(checkMems,c,tyvars,ss);
1357 cclass(c).kinds = tcDeps;
1361 static Cell local depPredExp(line,tyvars,pred)
1368 for (; isAp(h); args++) {
1369 arg(h) = depTypeExp(line,tyvars,arg(h));
1375 h98DoesntSupport(line,"tag classes");
1376 } else if (args!=1) {
1377 h98DoesntSupport(line,"multiple parameter classes");
1380 if (isQCon(h)) { /* standard class constraint */
1381 Class c = findQualClass(h);
1383 ERRMSG(line) "Undefined class \"%s\"", identToStr(h)
1391 if (args!=cclass(c).arity) {
1392 ERRMSG(line) "Wrong number of arguments for class \"%s\"",
1393 textToStr(cclass(c).text)
1396 if (cellIsMember(c,classDefns) && !cellIsMember(c,tcDeps)) {
1397 tcDeps = cons(c,tcDeps);
1401 else if (isExt(h)) { /* Lacks predicate */
1402 if (args!=1) { /* parser shouldn't let this happen*/
1403 ERRMSG(line) "Wrong number of arguments for lacks predicate"
1410 if (whatIs(h) != IPCELL)
1413 internal("depPredExp");
1418 static Void local checkMems(c,tyvars,m) /* check member function details */
1422 Int line = intOf(fst3(m));
1429 if (isPolyType(t)) {
1435 tyvars = typeVarsIn(t,NIL,xtvs,tyvars);
1436 /* Look for extra type vars. */
1437 checkOptQuantVars(line,xtvs,tyvars);
1439 if (isQualType(t)) { /* Overloaded member signatures? */
1440 map2Over(depPredExp,line,tyvars,fst(snd(t)));
1442 t = ap(QUAL,pair(NIL,t));
1445 fst(snd(t)) = cons(cclass(c).head,fst(snd(t)));/* Add main predicate */
1446 snd(snd(t)) = depTopType(line,tyvars,snd(snd(t)));
1448 for (tvs=tyvars; nonNull(tvs); tvs=tl(tvs)){/* Quantify */
1452 t = mkPolyType(sig,t);
1454 thd3(m) = t; /* Save type */
1455 take(cclass(c).arity,tyvars); /* Delete extra type vars */
1457 if (isAmbiguous(t)) {
1458 ambigError(line,"class declaration",hd(vs),t);
1460 h98CheckType(line,"member type",hd(vs),t);
1463 static Void local addMembers(c) /* Add definitions of member funs */
1464 Class c; { /* and other parts of class struct.*/
1465 List ms = fst(cclass(c).members);
1466 List fs = snd(cclass(c).members);
1467 List ns = NIL; /* List of names */
1468 Int mno; /* Member function number */
1470 for (mno=0; mno<cclass(c).numSupers; mno++) {
1471 ns = cons(newDSel(c,mno),ns);
1473 cclass(c).dsels = rev(ns); /* Save dictionary selectors */
1475 for (mno=1, ns=NIL; nonNull(ms); ms=tl(ms)) {
1476 Int line = intOf(fst3(hd(ms)));
1477 List vs = rev(snd3(hd(ms)));
1478 Type t = thd3(hd(ms));
1479 for (; nonNull(vs); vs=tl(vs)) {
1480 ns = cons(newMember(line,mno++,hd(vs),t,c),ns);
1483 cclass(c).members = rev(ns); /* Save list of members */
1484 cclass(c).numMembers = length(cclass(c).members);
1486 for (; nonNull(fs); fs=tl(fs)) { /* fixity declarations */
1487 Int line = intOf(fst3(hd(fs)));
1488 List ops = snd3(hd(fs));
1489 Syntax s = intOf(thd3(hd(fs)));
1490 for (; nonNull(ops); ops=tl(ops)) {
1491 Name n = nameIsMember(textOf(hd(ops)),cclass(c).members);
1493 missFixity(line,textOf(hd(ops)));
1494 } else if (name(n).syntax!=NO_SYNTAX) {
1495 dupFixity(line,textOf(hd(ops)));
1501 /* Not actually needed just yet; for the time being, dictionary code will
1502 not be passed through the type checker.
1504 cclass(c).dtycon = addPrimTycon(generateText("Dict.%s",c),
1511 mno = cclass(c).numSupers + cclass(c).numMembers;
1512 cclass(c).dcon = addPrimCfun(generateText("Make.%s",c),mno,0,NIL);
1513 implementCfun(cclass(c).dcon,NIL); /* ADR addition */
1515 if (mno==1) { /* Single entry dicts use newtype */
1516 name(cclass(c).dcon).defn = nameId;
1517 if (nonNull(cclass(c).members)) {
1518 name(hd(cclass(c).members)).number = mfunNo(0);
1521 cclass(c).defaults = classBindings("class",c,cclass(c).defaults);
1524 static Name local newMember(l,no,v,t,parent)
1525 Int l; /* Make definition for member fn */
1530 Name m = findName(textOf(v));
1533 m = newName(textOf(v),parent);
1534 } else if (name(m).defn!=PREDEFINED) {
1535 ERRMSG(l) "Repeated definition for member function \"%s\"",
1536 textToStr(name(m).text)
1542 name(m).number = mfunNo(no);
1547 static Name local newDSel(c,no) /* Make definition for dict selectr*/
1553 sprintf(buf,"sc%d.%s",no,"%s");
1554 s = newName(generateText(buf,c),c);
1555 name(s).line = cclass(c).line;
1557 name(s).number = DFUNNAME;
1563 static Text local generateText(sk,c) /* We need to generate names for */
1564 String sk; /* certain objects corresponding */
1565 Class c; { /* to each class. */
1566 String cname = textToStr(cclass(c).text);
1567 char buffer[MAX_GEN+1];
1569 if ((strlen(sk)+strlen(cname))>=MAX_GEN) {
1570 ERRMSG(0) "Please use a shorter name for class \"%s\"", cname
1573 sprintf(buffer,sk,cname);
1574 return findText(buffer);
1577 static Int local visitClass(c) /* visit class defn to check that */
1578 Class c; { /* class hierarchy is acyclic */
1580 if (isExt(c)) { /* special case for lacks preds */
1584 if (cclass(c).level < 0) { /* already visiting this class? */
1585 ERRMSG(cclass(c).line) "Class hierarchy for \"%s\" is not acyclic",
1586 textToStr(cclass(c).text)
1588 } else if (cclass(c).level == 0) { /* visiting class for first time */
1589 List scs = cclass(c).supers;
1591 cclass(c).level = (-1);
1592 for (; nonNull(scs); scs=tl(scs)) {
1593 Int l = visitClass(getHead(hd(scs)));
1596 cclass(c).level = 1+lev; /* level = 1 + max level of supers */
1598 return cclass(c).level;
1601 /* --------------------------------------------------------------------------
1602 * Process class and instance declaration binding groups:
1603 * ------------------------------------------------------------------------*/
1605 static List local classBindings(where,c,bs)
1606 String where; /* Check validity of bindings bs */
1607 Class c; /* for class c (or an inst of c) */
1608 List bs; { /* sort into approp. member order */
1611 for (; nonNull(bs); bs=tl(bs)) {
1613 Cell body = snd(snd(b));
1616 if (!isVar(fst(b))) { /* Only allow function bindings */
1617 ERRMSG(rhsLine(snd(body)))
1618 "Pattern binding illegal in %s declaration", where
1622 if (isNull(mnm=memberName(c,textOf(fst(b))))) {
1623 ERRMSG(rhsLine(snd(hd(body))))
1624 "No member \"%s\" in class \"%s\"",
1625 textToStr(textOf(fst(b))), textToStr(cclass(c).text)
1629 nbs = numInsert(mfunOf(mnm)-1,b,nbs);
1634 static Name local memberName(c,t) /* return name of member function */
1635 Class c; /* with name t in class c */
1636 Text t; { /* return NIL if not a member */
1637 List ms = cclass(c).members;
1638 for (; nonNull(ms); ms=tl(ms)) {
1639 if (t==name(hd(ms)).text) {
1646 static List local numInsert(n,x,xs) /* insert x at nth position in xs, */
1647 Int n; /* filling gaps with NIL */
1650 List start = isNull(xs) ? cons(NIL,NIL) : xs;
1652 for (xs=start; 0<n--; xs=tl(xs)) {
1653 if (isNull(tl(xs))) {
1654 tl(xs) = cons(NIL,NIL);
1661 /* --------------------------------------------------------------------------
1662 * Calculate set of variables appearing in a given type expression (possibly
1663 * qualified) as a list of distinct values. The order in which variables
1664 * appear in the list is the same as the order in which those variables
1665 * occur in the type expression when read from left to right.
1666 * ------------------------------------------------------------------------*/
1668 List local typeVarsIn(ty,us,ws,vs) /*Calculate list of type variables*/
1669 Cell ty; /* used in type expression, reading*/
1670 List us; /* from left to right ignoring any */
1671 List ws; /* listed in us. */
1672 List vs; { /* ws = explicitly quantified vars */
1673 switch (whatIs(ty)) {
1674 case AP : return typeVarsIn(snd(ty),us,ws,
1675 typeVarsIn(fst(ty),us,ws,vs));
1678 case VAROPCELL : if ((nonNull(findBtyvs(textOf(ty)))
1679 && !varIsMember(textOf(ty),ws))
1680 || varIsMember(textOf(ty),us)) {
1683 return maybeAppendVar(ty,vs);
1686 case POLYTYPE : return typeVarsIn(monotypeOf(ty),polySigOf(ty),ws,vs);
1688 case QUAL : { vs = typeVarsIn(fst(snd(ty)),us,ws,vs);
1689 return typeVarsIn(snd(snd(ty)),us,ws,vs);
1692 case BANG : return typeVarsIn(snd(ty),us,ws,vs);
1694 case LABC : { List fs = snd(snd(ty));
1695 for (; nonNull(fs); fs=tl(fs)) {
1696 vs = typeVarsIn(snd(hd(fs)),us,ws,vs);
1704 static List local maybeAppendVar(v,vs) /* append variable to list if not */
1705 Cell v; /* already included */
1711 while (nonNull(c)) {
1712 if (textOf(hd(c))==t) {
1720 tl(p) = cons(v,NIL);
1728 /* --------------------------------------------------------------------------
1729 * Static analysis for type expressions is required to:
1730 * - ensure that each type constructor or class used has been defined.
1731 * - replace type variables by offsets, constructor names by Tycons.
1732 * - ensure that the type is well-kinded.
1733 * ------------------------------------------------------------------------*/
1735 static Type local checkSigType(line,where,e,type)
1736 Int line; /* Check validity of type expr in */
1737 String where; /* explicit type signature */
1744 if (isPolyType(type)) {
1745 xtvs = fst(snd(type));
1746 type = monotypeOf(type);
1748 tvs = typeVarsIn(type,NIL,xtvs,NIL);
1750 checkOptQuantVars(line,xtvs,tvs);
1752 if (isQualType(type)) {
1753 map2Over(depPredExp,line,tvs,fst(snd(type)));
1754 snd(snd(type)) = depTopType(line,tvs,snd(snd(type)));
1756 if (isAmbiguous(type)) {
1757 ambigError(line,where,e,type);
1760 type = depTopType(line,tvs,type);
1764 if (length(tvs)>=NUM_OFFSETS) {
1765 ERRMSG(line) "Too many type variables in %s\n", where
1769 for (; nonNull(ts); ts=tl(ts)) {
1772 type = mkPolyType(tvs,type);
1777 kindType(line,"type expression",type);
1781 h98CheckType(line,where,e,type);
1785 static Void local checkOptQuantVars(line,xtvs,tvs)
1787 List xtvs; /* Explicitly quantified vars */
1788 List tvs; { /* Implicitly quantified vars */
1789 if (nonNull(xtvs)) {
1791 for (; nonNull(vs); vs=tl(vs)) {
1792 if (!varIsMember(textOf(hd(vs)),xtvs)) {
1793 ERRMSG(line) "Quantifier does not mention type variable \"%s\"",
1794 textToStr(textOf(hd(vs)))
1798 for (vs=xtvs; nonNull(vs); vs=tl(vs)) {
1799 if (!varIsMember(textOf(hd(vs)),tvs)) {
1800 ERRMSG(line) "Quantified type variable \"%s\" is not used",
1801 textToStr(textOf(hd(vs)))
1804 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1805 ERRMSG(line) "Quantified type variable \"%s\" is repeated",
1806 textToStr(textOf(hd(vs)))
1813 static Type local depTopType(l,tvs,t) /* Check top-level of type sig */
1821 for (; getHead(t1)==typeArrow && argCount==2; ++i) {
1822 arg(fun(t1)) = depCompType(l,tvs,arg(fun(t1)));
1823 if (isPolyOrQualType(arg(fun(t1)))) {
1829 if (nonNull(prev)) {
1830 arg(prev) = depTypeExp(l,tvs,t1);
1832 t = depTypeExp(l,tvs,t1);
1835 t = ap(RANK2,pair(mkInt(nr2),t));
1840 static Type local depCompType(l,tvs,t) /* Check component type for constr */
1844 Int ntvs = length(tvs);
1846 if (isPolyType(t)) {
1847 List vs = fst(snd(t));
1849 tvs = checkQuantVars(l,vs,tvs,t);
1850 nfr = replicate(length(vs),NIL);
1852 if (isQualType(t)) {
1853 map2Over(depPredExp,l,tvs,fst(snd(t)));
1854 snd(snd(t)) = depTypeExp(l,tvs,snd(snd(t)));
1855 if (isAmbiguous(t)) {
1856 ambigError(l,"type component",NIL,t);
1859 t = depTypeExp(l,tvs,t);
1865 return mkPolyType(nfr,t);
1868 static Type local depTypeExp(line,tyvars,type)
1872 switch (whatIs(type)) {
1873 case AP : fst(type) = depTypeExp(line,tyvars,fst(type));
1874 snd(type) = depTypeExp(line,tyvars,snd(type));
1877 case VARIDCELL : return depTypeVar(line,tyvars,textOf(type));
1879 case QUALIDENT : if (isQVar(type)) {
1880 ERRMSG(line) "Qualified type variables not allowed"
1883 /* deliberate fall through */
1884 case CONIDCELL : { Tycon tc = findQualTycon(type);
1887 "Undefined type constructor \"%s\"",
1891 if (cellIsMember(tc,tyconDefns) &&
1892 !cellIsMember(tc,tcDeps)) {
1893 tcDeps = cons(tc,tcDeps);
1899 case EXT : h98DoesntSupport(line,"extensible records");
1904 default : internal("depTypeExp");
1909 static Type local depTypeVar(line,tyvars,tv)
1916 for (; nonNull(tyvars); offset++) {
1917 if (tv==textOf(hd(tyvars))) {
1920 tyvars = tl(tyvars);
1923 Cell vt = findBtyvs(tv);
1927 ERRMSG(line) "Undefined type variable \"%s\"", textToStr(tv)
1930 return mkOffset(found);
1933 static List local checkQuantVars(line,vs,tvs,body)
1935 List vs; /* variables to quantify over */
1936 List tvs; /* variables already in scope */
1937 Cell body; { /* type/constr for scope of vars */
1939 List bvs = typeVarsIn(body,NIL,NIL,NIL);
1941 for (; nonNull(us); us=tl(us)) {
1942 Text u = textOf(hd(us));
1943 if (varIsMember(u,tl(us))) {
1944 ERRMSG(line) "Duplicated quantified variable %s",
1949 if (varIsMember(u,tvs)) {
1950 ERRMSG(line) "Local quantifier for %s hides an outer use",
1955 if (!varIsMember(u,bvs)) {
1956 ERRMSG(line) "Locally quantified variable %s is not used",
1961 tvs = appendOnto(tvs,vs);
1966 /* --------------------------------------------------------------------------
1967 * Check for ambiguous types:
1968 * A type Preds => type is ambiguous if not (TV(P) `subset` TV(type))
1969 * ------------------------------------------------------------------------*/
1971 List offsetTyvarsIn(t,vs) /* add list of offset tyvars in t */
1972 Type t; /* to list vs */
1974 switch (whatIs(t)) {
1975 case AP : return offsetTyvarsIn(fun(t),
1976 offsetTyvarsIn(arg(t),vs));
1978 case OFFSET : if (cellIsMember(t,vs))
1983 case QUAL : return offsetTyvarsIn(snd(t),vs);
1985 case POLYTYPE : return offsetTyvarsIn(monotypeOf(t),vs);
1986 /* slightly inaccurate, but won't matter here */
1989 case RANK2 : return offsetTyvarsIn(snd(snd(t)),vs);
1991 default : return vs;
1995 List zonkTyvarsIn(t,vs)
1998 switch (whatIs(t)) {
1999 case AP : return zonkTyvarsIn(fun(t),
2000 zonkTyvarsIn(arg(t),vs));
2002 case INTCELL : if (cellIsMember(t,vs))
2007 case OFFSET : internal("zonkTyvarsIn");
2009 default : return vs;
2013 static List local otvars(pi,os) /* os is a list of offsets that */
2014 Cell pi; /* refer to the arguments of pi; */
2015 List os; { /* find list of offsets in those */
2016 List us = NIL; /* positions */
2017 for (; nonNull(os); os=tl(os)) {
2018 us = offsetTyvarsIn(nthArg(offsetOf(hd(os)),pi),us);
2023 static List local otvarsZonk(pi,os,o) /* same as above, but zonks */
2028 for (; nonNull(os); os=tl(os)) {
2029 Type t = zonkType(nthArg(offsetOf(hd(os)),pi),o);
2030 us = zonkTyvarsIn(t,us);
2035 static Bool local odiff(us,vs)
2037 while (nonNull(us) && cellIsMember(hd(us),vs)) {
2043 static Bool local osubset(us,vs) /* Determine whether us is subset */
2044 List us, vs; { /* of vs */
2045 while (nonNull(us) && cellIsMember(hd(us),vs)) {
2051 List oclose(fds,vs) /* Compute closure of vs wrt to fds*/
2054 Bool changed = TRUE;
2058 while (nonNull(fds)) {
2060 List next = tl(fds);
2061 if (osubset(fst(fd),vs)) { /* Test if fd applies */
2063 for (; nonNull(os); os=tl(os)) {
2064 if (!cellIsMember(hd(os),vs)) {
2065 vs = cons(hd(os),vs);
2069 } else { /* Didn't apply this time, so keep */
2080 Bool isAmbiguous(type) /* Determine whether type is */
2081 Type type; { /* ambiguous */
2082 if (isPolyType(type)) {
2083 type = monotypeOf(type);
2085 if (isQualType(type)) { /* only qualified types can be */
2086 List ps = fst(snd(type)); /* ambiguous */
2087 List tvps = offsetTyvarsIn(ps,NIL);
2088 List tvts = offsetTyvarsIn(snd(snd(type)),NIL);
2089 List fds = calcFunDeps(ps);
2091 tvts = oclose(fds,tvts); /* Close tvts under fds */
2092 return !osubset(tvps,tvts);
2097 List calcFunDeps(ps)
2100 for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies */
2102 Cell c = getHead(pi);
2104 List fs = cclass(c).fds;
2105 for (; nonNull(fs); fs=tl(fs)) {
2106 fds = cons(pair(otvars(pi,fst(hd(fs))),
2107 otvars(pi,snd(hd(fs)))),fds);
2112 fds = cons(pair(NIL,offsetTyvarsIn(arg(pi),NIL)),fds);
2119 List calcFunDepsPreds(ps)
2122 for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies */
2124 Cell pi = fst3(pi3);
2125 Cell c = getHead(pi);
2126 Int o = intOf(snd3(pi3));
2128 List fs = cclass(c).fds;
2129 for (; nonNull(fs); fs=tl(fs)) {
2130 fds = cons(pair(otvarsZonk(pi,fst(hd(fs)),o),
2131 otvarsZonk(pi,snd(hd(fs)),o)),fds);
2136 fds = cons(pair(NIL,zonkTyvarsIn(arg(pi),NIL)),fds);
2143 Void ambigError(line,where,e,type) /* produce error message for */
2144 Int line; /* ambiguity */
2148 ERRMSG(line) "Ambiguous type signature in %s", where ETHEN
2149 ERRTEXT "\n*** ambiguous type : " ETHEN ERRTYPE(type);
2151 ERRTEXT "\n*** assigned to : " ETHEN ERREXPR(e);
2157 /* --------------------------------------------------------------------------
2158 * Kind inference for simple types:
2159 * ------------------------------------------------------------------------*/
2161 static Void local kindConstr(line,alpha,m,c)
2162 Int line; /* Determine kind of constructor */
2166 Cell h = getHead(c);
2170 Printf("kindConstr: alpha=%d, m=%d, c=",alpha,m);
2171 printType(stdout,c);
2175 switch (whatIs(h)) {
2176 case POLYTYPE : if (n!=0) {
2177 internal("kindConstr1");
2179 static String pt = "polymorphic type";
2180 Type t = dropRank1(c,alpha,m);
2181 Kinds ks = polySigOf(t);
2184 for (; isAp(ks); ks=tl(ks)) {
2187 beta = newKindvars(m1);
2188 unkindTypes = cons(pair(mkInt(beta),t),unkindTypes);
2189 checkKind(line,beta,m1,monotypeOf(t),NIL,pt,STAR,0);
2194 case QUAL : if (n!=0) {
2195 internal("kindConstr2");
2197 map3Proc(kindPred,line,alpha,m,fst(snd(c)));
2198 kindConstr(line,alpha,m,snd(snd(c)));
2202 case RANK2 : kindConstr(line,alpha,m,snd(snd(c)));
2206 case EXT : if (n!=2) {
2208 "Illegal use of row in " ETHEN ERRTYPE(c);
2215 case TYCON : if (isSynonym(h) && n<tycon(h).arity) {
2217 "Not enough arguments for type synonym \"%s\"",
2218 textToStr(tycon(h).text)
2224 if (n==0) { /* trivial case, no arguments */
2225 typeIs = kindAtom(alpha,c);
2226 } else { /* non-trivial application */
2227 static String app = "constructor application";
2237 typeIs = kindAtom(alpha,h); /* h :: v1 -> ... -> vn -> w */
2238 shouldKind(line,h,c,app,k,beta);
2240 for (i=n; i>0; --i) { /* ci :: vi for each 1 <- 1..n */
2241 checkKind(line,alpha,m,arg(a),c,app,aVar,beta+i-1);
2244 tyvarType(beta+n); /* inferred kind is w */
2248 static Kind local kindAtom(alpha,c) /* Find kind of atomic constructor */
2251 switch (whatIs(c)) {
2252 case TUPLE : return simpleKind(tupleOf(c)); /*(,)::* -> * -> * */
2253 case OFFSET : return mkInt(alpha+offsetOf(c));
2254 case TYCON : return tycon(c).kind;
2255 case INTCELL : return c;
2257 case VAROPCELL : { Cell vt = findBtyvs(textOf(c));
2263 case EXT : return extKind;
2267 Printf("kindAtom(%d,whatIs(%d)) on ",alpha,whatIs(c));
2268 printType(stdout,c);
2271 internal("kindAtom");
2272 return STAR;/* not reached */
2275 static Void local kindPred(l,alpha,m,pi)/* Check kinds of arguments in pred*/
2281 if (isAp(pi) && isExt(fun(pi))) {
2282 static String lackspred = "lacks predicate";
2283 checkKind(l,alpha,m,arg(pi),NIL,lackspred,ROW,0);
2288 if (isAp(pi) && whatIs(fun(pi)) == IPCELL) {
2289 static String ippred = "iparam predicate";
2290 checkKind(l,alpha,m,arg(pi),NIL,ippred,STAR,0);
2294 { static String predicate = "class constraint";
2295 Class c = getHead(pi);
2296 List as = getArgs(pi);
2297 Kinds ks = cclass(c).kinds;
2299 while (nonNull(ks)) {
2300 checkKind(l,alpha,m,hd(as),NIL,predicate,hd(ks),0);
2307 static Void local kindType(line,wh,type)/* check that (poss qualified) type*/
2308 Int line; /* is well-kinded */
2311 checkKind(line,0,0,type,NIL,wh,STAR,0);
2314 static Void local fixKinds() { /* add kind annotations to types */
2315 for (; nonNull(unkindTypes); unkindTypes=tl(unkindTypes)) {
2316 Pair pr = hd(unkindTypes);
2317 Int beta = intOf(fst(pr));
2318 Cell qts = polySigOf(snd(pr));
2320 if (isNull(hd(qts))) {
2321 hd(qts) = copyKindvar(beta++);
2323 internal("fixKinds");
2325 if (nonNull(tl(qts))) {
2333 Printf("Type expression: ");
2334 printType(stdout,snd(pr));
2336 printKind(stdout,polySigOf(snd(pr)));
2342 /* --------------------------------------------------------------------------
2343 * Kind checking of groups of type constructors and classes:
2344 * ------------------------------------------------------------------------*/
2346 static Void local kindTCGroup(tcs) /* find kinds for mutually rec. gp */
2347 List tcs; { /* of tycons and classes */
2348 emptySubstitution();
2350 mapProc(initTCKind,tcs);
2351 mapProc(kindTC,tcs);
2354 emptySubstitution();
2357 static Void local initTCKind(c) /* build initial kind/arity for c */
2359 if (isTycon(c)) { /* Initial kind of tycon is: */
2360 Int beta = newKindvars(1); /* v1 -> ... -> vn -> vn+1 */
2361 varKind(tycon(c).arity); /* where n is the arity of c. */
2362 bindTv(beta,typeIs,typeOff); /* For data definitions, vn+1 == * */
2363 switch (whatIs(tycon(c).what)) {
2365 case DATATYPE : bindTv(typeOff+tycon(c).arity,STAR,0);
2367 tycon(c).kind = mkInt(beta);
2369 Int n = cclass(c).arity;
2370 Int beta = newKindvars(n);
2371 cclass(c).kinds = NIL;
2374 cclass(c).kinds = pair(mkInt(beta+n),cclass(c).kinds);
2379 static Void local kindTC(c) /* check each part of a tycon/class*/
2380 Cell c; { /* is well-kinded */
2382 static String cfun = "constructor function";
2383 static String tsyn = "synonym definition";
2384 Int line = tycon(c).line;
2385 Int beta = tyvar(intOf(tycon(c).kind))->offs;
2386 Int m = tycon(c).arity;
2387 switch (whatIs(tycon(c).what)) {
2389 case DATATYPE : { List cs = tycon(c).defn;
2390 if (isQualType(cs)) {
2391 map3Proc(kindPred,line,beta,m,
2393 tycon(c).defn = cs = snd(snd(cs));
2395 for (; hasCfun(cs); cs=tl(cs)) {
2396 kindType(line,cfun,name(hd(cs)).type);
2401 default : checkKind(line,beta,m,tycon(c).defn,NIL,
2405 else { /* scan type exprs in class defn to*/
2406 List ms = fst(cclass(c).members);
2407 Int m = cclass(c).arity; /* determine the class signature */
2408 Int beta = newKindvars(m);
2409 kindPred(cclass(c).line,beta,m,cclass(c).head);
2410 map3Proc(kindPred,cclass(c).line,beta,m,cclass(c).supers);
2411 for (; nonNull(ms); ms=tl(ms)) {
2412 Int line = intOf(fst3(hd(ms)));
2413 Type type = thd3(hd(ms));
2414 kindType(line,"member function type signature",type);
2419 static Void local genTC(c) /* generalise kind inferred for */
2420 Cell c; { /* given tycon/class */
2422 tycon(c).kind = copyKindvar(intOf(tycon(c).kind));
2424 Printf("%s :: ",textToStr(tycon(c).text));
2425 printKind(stdout,tycon(c).kind);
2429 Kinds ks = cclass(c).kinds;
2430 for (; nonNull(ks); ks=tl(ks)) {
2431 hd(ks) = copyKindvar(intOf(hd(ks)));
2434 Printf("%s :: ",textToStr(cclass(c).text));
2435 printKinds(stdout,cclass(c).kinds);
2441 /* --------------------------------------------------------------------------
2442 * Static analysis of instance declarations:
2444 * The first part of the static analysis is performed as the declarations
2445 * are read during parsing:
2446 * - make new entry in instance table
2447 * - record line number of declaration
2448 * - build list of instances defined in current script for use in later
2449 * stages of static analysis.
2450 * ------------------------------------------------------------------------*/
2452 Void instDefn(line,head,ms) /* process new instance definition */
2453 Int line; /* definition line number */
2454 Cell head; /* inst header :: (context,Class) */
2455 List ms; { /* instance members */
2456 Inst nw = newInst();
2457 inst(nw).line = line;
2458 inst(nw).specifics = fst(head);
2459 inst(nw).head = snd(head);
2460 inst(nw).implements = ms;
2461 instDefns = cons(nw,instDefns);
2464 /* --------------------------------------------------------------------------
2465 * Further static analysis of instance declarations:
2467 * Makes the following checks:
2468 * - Class part of header has form C (T a1 ... an) where C is a known
2469 * class, and T is a known datatype constructor (or restricted synonym),
2470 * and there is no previous C-T instance, and (T a1 ... an) has a kind
2471 * appropriate for the class C.
2472 * - Each element of context is a valid class expression, with type vars
2473 * drawn from a1, ..., an.
2474 * - All bindings are function bindings
2475 * - All bindings define member functions for class C
2476 * - Arrange bindings into appropriate order for member list
2477 * - No top level type signature declarations
2478 * ------------------------------------------------------------------------*/
2480 Bool allowOverlap = FALSE; /* TRUE => allow overlapping insts */
2481 Name nameListMonad = NIL; /* builder function for List Monad */
2483 static Void local checkInstDefn(in) /* Validate instance declaration */
2485 Int line = inst(in).line;
2486 List tyvars = typeVarsIn(inst(in).head,NIL,NIL,NIL);
2487 List tvps = NIL, tvts = NIL;
2490 if (haskell98) { /* Check for `simple' type */
2492 Cell t = arg(inst(in).head);
2493 for (; isAp(t); t=fun(t)) {
2494 if (!isVar(arg(t))) {
2496 "syntax error in instance head (variable expected)"
2499 if (varIsMember(textOf(arg(t)),tvs)) {
2500 ERRMSG(line) "repeated type variable \"%s\" in instance head",
2501 textToStr(textOf(arg(t)))
2504 tvs = cons(arg(t),tvs);
2508 "syntax error in instance head (constructor expected)"
2513 /* add in the tyvars from the `specifics' so that we don't
2514 prematurely complain about undefined tyvars */
2515 tyvars = typeVarsIn(inst(in).specifics,NIL,NIL,tyvars);
2516 inst(in).head = depPredExp(line,tyvars,inst(in).head);
2519 Type h = getHead(arg(inst(in).head));
2521 ERRMSG(line) "Cannot use type synonym in instance head"
2526 map2Over(depPredExp,line,tyvars,inst(in).specifics);
2528 /* OK, now we start over, and test for ambiguity */
2529 tvts = offsetTyvarsIn(inst(in).head,NIL);
2530 tvps = offsetTyvarsIn(inst(in).specifics,NIL);
2531 fds = calcFunDeps(inst(in).specifics);
2532 tvts = oclose(fds,tvts);
2533 tvts = odiff(tvps,tvts);
2534 if (!isNull(tvts)) {
2535 ERRMSG(line) "Undefined type variable \"%s\"",
2536 textToStr(textOf(nth(offsetOf(hd(tvts)),tyvars)))
2540 h98CheckCtxt(line,"instance definition",FALSE,inst(in).specifics,NIL);
2541 inst(in).numSpecifics = length(inst(in).specifics);
2542 inst(in).c = getHead(inst(in).head);
2543 if (!isClass(inst(in).c)) {
2544 ERRMSG(line) "Illegal predicate in instance declaration"
2548 if (nonNull(cclass(inst(in).c).fds)) {
2549 List fds = cclass(inst(in).c).fds;
2550 for (; nonNull(fds); fds=tl(fds)) {
2551 List as = otvars(inst(in).head, fst(hd(fds)));
2552 List bs = otvars(inst(in).head, snd(hd(fds)));
2553 if (!osubset(bs,as)) {
2554 ERRMSG(inst(in).line)
2555 "Instance is more general than a dependency allows"
2557 ERRTEXT "\n*** Instance : "
2558 ETHEN ERRPRED(inst(in).head);
2559 ERRTEXT "\n*** For class : "
2560 ETHEN ERRPRED(cclass(inst(in).c).head);
2561 ERRTEXT "\n*** Under dependency : "
2562 ETHEN ERRFD(hd(fds));
2569 kindInst(in,length(tyvars));
2572 if (nonNull(extractSigdecls(inst(in).implements))) {
2574 "Type signature declarations not permitted in instance declaration"
2577 if (nonNull(extractFixdecls(inst(in).implements))) {
2579 "Fixity declarations not permitted in instance declaration"
2582 inst(in).implements = classBindings("instance",
2584 extractBindings(inst(in).implements));
2585 inst(in).builder = newInstImp(in);
2586 if (!preludeLoaded && isNull(nameListMonad) && isAp(inst(in).head)
2587 && fun(inst(in).head)==classMonad && arg(inst(in).head)==typeList) {
2588 nameListMonad = inst(in).builder;
2592 static Void local insertInst(in) /* Insert instance into class */
2594 Class c = inst(in).c;
2595 List ins = cclass(c).instances;
2598 if (nonNull(cclass(c).fds)) { /* Check for conflicts with fds */
2599 List ins1 = cclass(c).instances;
2600 for (; nonNull(ins1); ins1=tl(ins1)) {
2601 List fds = cclass(c).fds;
2602 substitution(RESET);
2603 for (; nonNull(fds); fds=tl(fds)) {
2604 Int alpha = newKindedVars(inst(in).kinds);
2605 Int beta = newKindedVars(inst(hd(ins1)).kinds);
2606 List as = fst(hd(fds));
2608 for (; same && nonNull(as); as=tl(as)) {
2609 Int n = offsetOf(hd(as));
2610 same &= unify(nthArg(n,inst(in).head),alpha,
2611 nthArg(n,inst(hd(ins1)).head),beta);
2613 if (isNull(as) && same) {
2614 for (as=snd(hd(fds)); same && nonNull(as); as=tl(as)) {
2615 Int n = offsetOf(hd(as));
2616 same &= sameType(nthArg(n,inst(in).head),alpha,
2617 nthArg(n,inst(hd(ins1)).head),beta);
2620 ERRMSG(inst(in).line)
2621 "Instances are not consistent with dependencies"
2623 ERRTEXT "\n*** This instance : "
2624 ETHEN ERRPRED(inst(in).head);
2625 ERRTEXT "\n*** Conflicts with : "
2626 ETHEN ERRPRED(inst(hd(ins)).head);
2627 ERRTEXT "\n*** For class : "
2628 ETHEN ERRPRED(cclass(c).head);
2629 ERRTEXT "\n*** Under dependency : "
2630 ETHEN ERRFD(hd(fds));
2640 substitution(RESET);
2641 while (nonNull(ins)) { /* Look for overlap w/ other insts */
2642 Int alpha = newKindedVars(inst(in).kinds);
2643 Int beta = newKindedVars(inst(hd(ins)).kinds);
2644 if (unifyPred(inst(in).head,alpha,inst(hd(ins)).head,beta)) {
2645 Cell pi = copyPred(inst(in).head,alpha);
2646 if (allowOverlap && !haskell98) {
2647 Bool bef = instCompare(in,hd(ins));
2648 Bool aft = instCompare(hd(ins),in);
2649 if (bef && !aft) { /* in comes strictly before hd(ins)*/
2652 if (aft && !bef) { /* in comes strictly after hd(ins) */
2659 if (multiInstRes && nonNull(inst(in).specifics)) {
2663 ERRMSG(inst(in).line) "Overlapping instances for class \"%s\"",
2664 textToStr(cclass(c).text)
2666 ERRTEXT "\n*** This instance : " ETHEN ERRPRED(inst(in).head);
2667 ERRTEXT "\n*** Overlaps with : " ETHEN
2668 ERRPRED(inst(hd(ins)).head);
2669 ERRTEXT "\n*** Common instance : " ETHEN
2677 prev = ins; /* No overlap detected, so move on */
2678 ins = tl(ins); /* to next instance */
2680 substitution(RESET);
2682 if (nonNull(prev)) { /* Insert instance at this point */
2683 tl(prev) = cons(in,ins);
2685 cclass(c).instances = cons(in,ins);
2689 static Bool local instCompare(ia,ib) /* See if ia is an instance of ib */
2691 Int alpha = newKindedVars(inst(ia).kinds);
2692 Int beta = newKindedVars(inst(ib).kinds);
2693 return matchPred(inst(ia).head,alpha,inst(ib).head,beta);
2696 static Name local newInstImp(in) /* Make definition for inst builder*/
2698 Name b = newName(inventText(),in);
2699 name(b).line = inst(in).line;
2700 name(b).arity = inst(in).numSpecifics;
2701 name(b).number = DFUNNAME;
2705 /* --------------------------------------------------------------------------
2706 * Kind checking of instance declaration headers:
2707 * ------------------------------------------------------------------------*/
2709 static Void local kindInst(in,freedom) /* check predicates in instance */
2714 emptySubstitution();
2715 beta = newKindvars(freedom);
2716 kindPred(inst(in).line,beta,freedom,inst(in).head);
2717 if (whatIs(inst(in).specifics)!=DERIVE) {
2718 map3Proc(kindPred,inst(in).line,beta,freedom,inst(in).specifics);
2720 for (inst(in).kinds = NIL; 0<freedom--; ) {
2721 inst(in).kinds = cons(copyKindvar(beta+freedom),inst(in).kinds);
2724 Printf("instance ");
2725 printPred(stdout,inst(in).head);
2727 printKinds(stdout,inst(in).kinds);
2730 emptySubstitution();
2733 /* --------------------------------------------------------------------------
2734 * Process derived instance requests:
2735 * ------------------------------------------------------------------------*/
2737 static List derivedInsts; /* list of derived instances */
2739 static Void local checkDerive(t,p,ts,ct)/* verify derived instance request */
2740 Tycon t; /* for tycon t, with explicit */
2741 List p; /* context p, component types ts */
2742 List ts; /* and named class ct */
2744 Int line = tycon(t).line;
2745 Class c = findQualClass(ct);
2747 ERRMSG(line) "Unknown class \"%s\" in derived instance",
2751 addDerInst(line,c,p,dupList(ts),t,tycon(t).arity);
2754 static Void local addDerInst(line,c,p,cts,t,a) /* Add a derived instance */
2761 Cell head = t; /* Build instance head */
2765 head = ap(head,mkOffset(i));
2771 inst(in).line = line;
2772 inst(in).head = head;
2773 inst(in).specifics = ap(DERIVE,pair(dupList(p),cts));
2774 inst(in).implements = NIL;
2775 inst(in).kinds = mkInt(a);
2776 derivedInsts = cons(in,derivedInsts);
2779 Void addTupInst(c,n) /* Request derived instance of c */
2780 Class c; /* for mkTuple(n) constructor */
2785 cts = cons(mkOffset(m),cts);
2788 addDerInst(0,c,NIL,cts,mkTuple(n),n);
2792 Inst addRecShowInst(c,e) /* Generate instance for ShowRecRow*/
2793 Class c; /* c *must* be ShowRecRow */
2795 Inst in = newInst();
2797 inst(in).head = ap(c,ap2(e,aVar,bVar));
2798 inst(in).kinds = extKind;
2799 inst(in).specifics = cons(ap(classShow,aVar),
2801 cons(ap(c,bVar),NIL)));
2802 inst(in).numSpecifics = 3;
2803 inst(in).builder = implementRecShw(extText(e),in);
2804 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2808 Inst addRecEqInst(c,e) /* Generate instance for EqRecRow */
2809 Class c; /* c *must* be EqRecRow */
2811 Inst in = newInst();
2813 inst(in).head = ap(c,ap2(e,aVar,bVar));
2814 inst(in).kinds = extKind;
2815 inst(in).specifics = cons(ap(classEq,aVar),
2817 cons(ap(c,bVar),NIL)));
2818 inst(in).numSpecifics = 3;
2819 inst(in).builder = implementRecEq(extText(e),in);
2820 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2825 /* --------------------------------------------------------------------------
2826 * Calculation of contexts for derived instances:
2828 * Allowing arbitrary types to appear in contexts makes it rather harder
2829 * to decide what the context for a derived instance should be. For
2832 * data T a = MkT [a] deriving Show,
2834 * we could have either of the following:
2836 * instance (Show [a]) => Show (T a) where ...
2837 * instance (Show a) => Show (T a) where ...
2839 * (assuming, of course, that instance (Show a) => Show [a]). For now, we
2840 * choose to reduce contexts in the hope of detecting errors at an earlier
2841 * stage---in contrast with value definitions, there is no way for a user
2842 * to provide something analogous to a `type signature' by which they might
2843 * be able to control this behaviour themselves. We eliminate tautological
2844 * predicates, but only allow predicates to appear in the final result if
2845 * they have at least one argument with a variable at its head.
2847 * In general, we have to deal with mutually recursive instance declarations.
2848 * We find a solution in the obvious way by iterating to find a fixed point.
2849 * Of course, without restrictions on the form of instance declarations, we
2850 * cannot be sure that this will always terminate!
2852 * For each instance we maintain a pair of the form DERIVE (ctxt,ps).
2853 * Ctxt is a list giving the parts of the context that have been produced
2854 * so far in the form of predicate skeletons. During the calculation of
2855 * derived instances, we attach a dummy NIL value to the end of the list
2856 * which acts as a kind of `variable': other parts of the system maintain
2857 * pointers to this variable, and use it to detect when the context has
2858 * been extended with new elements. Meanwhile, ps is a list containing
2859 * predicates (pi,o) together with (delayed) substitutions of the form
2860 * (o,xs) where o is an offset and xs is one of the context variables
2861 * described above, which may have been partially instantiated.
2862 * ------------------------------------------------------------------------*/
2864 static Bool instsChanged;
2866 static Void local deriveContexts(is) /* Calc contexts for derived insts */
2868 emptySubstitution();
2869 mapProc(initDerInst,is); /* Prepare derived instances */
2871 do { /* Main calculation of contexts */
2872 instsChanged = FALSE;
2873 mapProc(calcInstPreds,is);
2874 } while (instsChanged);
2876 mapProc(tidyDerInst,is); /* Tidy up results */
2879 static Void local initDerInst(in) /* Prepare instance for calculation*/
2880 Inst in; { /* of derived instance context */
2881 Cell spcs = inst(in).specifics;
2882 Int beta = newKindedVars(inst(in).kinds);
2883 if (whatIs(spcs)!=DERIVE) {
2884 internal("initDerInst");
2886 fst(snd(spcs)) = appendOnto(fst(snd(spcs)),singleton(NIL));
2887 for (spcs=snd(snd(spcs)); nonNull(spcs); spcs=tl(spcs)) {
2888 hd(spcs) = ap2(inst(in).c,hd(spcs),mkInt(beta));
2890 inst(in).numSpecifics = beta;
2892 #ifdef DEBUG_DERIVING
2893 Printf("initDerInst: ");
2894 printPred(stdout,inst(in).head);
2896 printContext(stdout,snd(snd(inst(in).specifics)));
2901 static Void local calcInstPreds(in) /* Calculate next approximation */
2902 Inst in; { /* of the context for a derived */
2903 List retain = NIL; /* instance */
2904 List ps = snd(snd(inst(in).specifics));
2905 List spcs = fst(snd(inst(in).specifics));
2906 Int beta = inst(in).numSpecifics;
2908 Int factor = 1+length(ps);
2910 #ifdef DEBUG_DERIVING
2911 Printf("calcInstPreds: ");
2912 printPred(stdout,inst(in).head);
2916 while (nonNull(ps)) {
2919 if (its++ >= factor*cutoff) {
2920 Cell bpi = inst(in).head;
2921 Cell pi = copyPred(fun(p),intOf(snd(p)));
2922 ERRMSG(inst(in).line) "\n*** Cannot derive " ETHEN ERRPRED(bpi);
2923 ERRTEXT " after %d iterations.", its-1 ETHEN
2925 "\n*** This may indicate that the problem is undecidable. However,\n"
2927 "*** you may still try to increase the cutoff limit using the -c\n"
2929 "*** option and then try again. (The current setting is -c%d)\n",
2933 if (isInt(fst(p))) { /* Delayed substitution? */
2935 for (; nonNull(hd(qs)); qs=tl(qs)) {
2936 ps = cons(pair(hd(qs),fst(p)),ps);
2938 retain = cons(pair(fst(p),qs),retain);
2941 else if (isExt(fun(fst(p)))) { /* Lacks predicate */
2942 Text l = extText(fun(fst(p)));
2943 Type t = arg(fst(p));
2944 Int o = intOf(snd(p));
2949 h = getDerefHead(t,o);
2950 while (isExt(h) && argCount==2 && l!=extText(h)) {
2953 h = getDerefHead(t,o);
2955 if (argCount==0 && isOffset(h)) {
2956 maybeAddPred(ap(fun(fun(p)),h),o,beta,spcs);
2957 } else if (argCount!=0 || h!=typeNoRow) {
2958 Cell bpi = inst(in).head;
2959 Cell pi = copyPred(fun(p),intOf(snd(p)));
2960 ERRMSG(inst(in).line) "Cannot derive " ETHEN ERRPRED(bpi);
2961 ERRTEXT " because predicate " ETHEN ERRPRED(pi);
2962 ERRTEXT " does not hold\n"
2967 else { /* Class predicate */
2969 Int o = intOf(snd(p));
2970 Inst in1 = findInstFor(pi,o);
2972 List qs = inst(in1).specifics;
2973 Int off = mkInt(typeOff);
2974 if (whatIs(qs)==DERIVE) { /* Still being derived */
2975 for (qs=fst(snd(qs)); nonNull(hd(qs)); qs=tl(qs)) {
2976 ps = cons(pair(hd(qs),off),ps);
2978 retain = cons(pair(off,qs),retain);
2979 } else { /* Previously def'd inst */
2980 for (; nonNull(qs); qs=tl(qs)) {
2981 ps = cons(pair(hd(qs),off),ps);
2984 } else { /* No matching instance */
2986 while (isAp(qi) && isOffset(getDerefHead(arg(qi),o))) {
2990 Cell bpi = inst(in).head;
2991 pi = copyPred(pi,o);
2992 ERRMSG(inst(in).line) "An instance of " ETHEN ERRPRED(pi);
2993 ERRTEXT " is required to derive " ETHEN ERRPRED(bpi);
2997 maybeAddPred(pi,o,beta,spcs);
3002 snd(snd(inst(in).specifics)) = retain;
3005 static Void local maybeAddPred(pi,o,beta,ps)
3006 Cell pi; /* Add predicate pi to the list ps,*/
3007 Int o; /* setting the instsChanged flag if*/
3008 Int beta; /* pi is not already a member and */
3009 List ps; { /* using beta to adjust vars */
3010 Cell c = getHead(pi);
3011 for (; nonNull(ps); ps=tl(ps)) {
3012 if (isNull(hd(ps))) { /* reached the `dummy' end of list?*/
3013 hd(ps) = copyAdj(pi,o,beta);
3014 tl(ps) = pair(NIL,NIL);
3015 instsChanged = TRUE;
3017 } else if (c==getHead(hd(ps)) && samePred(pi,o,hd(ps),beta)) {
3023 static Cell local copyAdj(c,o,beta) /* Copy (c,o), replacing vars with */
3024 Cell c; /* offsets relative to beta. */
3027 switch (whatIs(c)) {
3028 case AP : { Cell l = copyAdj(fst(c),o,beta);
3029 Cell r = copyAdj(snd(c),o,beta);
3033 case OFFSET : { Int vn = o+offsetOf(c);
3034 Tyvar *tyv = tyvar(vn);
3036 return copyAdj(tyv->bound,tyv->offs,beta);
3039 if (vn<0 || vn>=NUM_OFFSETS) {
3040 internal("copyAdj");
3042 return mkOffset(vn);
3048 static Void local tidyDerInst(in) /* Tidy up results of derived inst */
3049 Inst in; { /* calculations */
3050 Int o = inst(in).numSpecifics;
3051 List ps = tl(rev(fst(snd(inst(in).specifics))));
3053 copyPred(inst(in).head,o);
3054 inst(in).specifics = simpleContext(ps,o);
3055 h98CheckCtxt(inst(in).line,"derived instance",FALSE,inst(in).specifics,in);
3056 inst(in).numSpecifics = length(inst(in).specifics);
3058 #ifdef DEBUG_DERIVING
3059 Printf("Derived instance: ");
3060 printContext(stdout,inst(in).specifics);
3062 printPred(stdout,inst(in).head);
3067 /* --------------------------------------------------------------------------
3068 * Generate code for derived instances:
3069 * ------------------------------------------------------------------------*/
3071 static Void local addDerivImp(in)
3074 Type t = getHead(arg(inst(in).head));
3075 Class c = inst(in).c;
3078 } else if (c==classOrd) {
3080 } else if (c==classEnum) {
3081 imp = deriveEnum(t);
3082 } else if (c==classIx) {
3084 } else if (c==classShow) {
3085 imp = deriveShow(t);
3086 } else if (c==classRead) {
3087 imp = deriveRead(t);
3088 } else if (c==classBounded) {
3089 imp = deriveBounded(t);
3091 ERRMSG(inst(in).line) "Cannot derive instances of class \"%s\"",
3092 textToStr(cclass(inst(in).c).text)
3096 kindInst(in,intOf(inst(in).kinds));
3098 inst(in).builder = newInstImp(in);
3099 inst(in).implements = classBindings("derived instance",
3105 /* --------------------------------------------------------------------------
3106 * Default definitions; only one default definition is permitted in a
3107 * given script file. If no default is supplied, then a standard system
3108 * default will be used where necessary.
3109 * ------------------------------------------------------------------------*/
3111 Void defaultDefn(line,defs) /* Handle default types definition */
3114 if (defaultLine!=0) {
3115 ERRMSG(line) "Multiple default declarations are not permitted in" ETHEN
3116 ERRTEXT "a single script file.\n"
3119 defaultDefns = defs;
3123 static Void local checkDefaultDefns() { /* check that default types are */
3124 List ds = NIL; /* well-kinded instances of Num */
3126 if (defaultLine!=0) {
3127 map2Over(depTypeExp,defaultLine,NIL,defaultDefns);
3128 emptySubstitution();
3130 map2Proc(kindType,defaultLine,"default type",defaultDefns);
3132 emptySubstitution();
3133 mapOver(fullExpand,defaultDefns);
3135 defaultDefns = stdDefaults;
3138 if (isNull(classNum)) {
3139 classNum = findClass(findText("Num"));
3142 for (ds=defaultDefns; nonNull(ds); ds=tl(ds)) {
3143 if (isNull(provePred(NIL,NIL,ap(classNum,hd(ds))))) {
3145 "Default types must be instances of the Num class"
3152 /* --------------------------------------------------------------------------
3153 * Foreign import declarations are Hugs' equivalent of GHC's ccall mechanism.
3154 * They are used to "import" C functions into a module.
3155 * They are usually not written by hand but, rather, generated automatically
3156 * by GreenCard, IDL compilers or whatever.
3158 * Foreign export declarations generate C wrappers for Hugs functions.
3159 * Hugs only provides "foreign export dynamic" because it's not obvious
3160 * what "foreign export static" would mean in an interactive setting.
3161 * ------------------------------------------------------------------------*/
3163 Void foreignImport(line,callconv,extName,intName,type)
3164 /* Handle foreign imports */
3170 Text t = textOf(intName);
3171 Name n = findName(t);
3172 Int l = intOf(line);
3176 } else if (name(n).defn!=PREDEFINED) {
3177 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
3181 name(n).defn = extName;
3182 name(n).type = type;
3183 name(n).callconv = callconv;
3184 foreignImports = cons(n,foreignImports);
3187 static Void local checkForeignImport(p) /* Check foreign import */
3189 emptySubstitution();
3190 name(p).type = checkSigType(name(p).line,
3191 "foreign import declaration",
3194 /* We don't expand synonyms here because we don't want the IO
3195 * part to be expanded.
3196 * name(p).type = fullExpand(name(p).type);
3198 implementForeignImport(p);
3201 Void foreignExport(line,callconv,extName,intName,type)
3202 /* Handle foreign exports */
3208 Text t = textOf(intName);
3209 Name n = findName(t);
3210 Int l = intOf(line);
3214 } else if (name(n).defn!=PREDEFINED) {
3215 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
3219 name(n).defn = NIL; /* nothing to say */
3220 name(n).type = type;
3221 name(n).callconv = callconv;
3222 foreignExports = cons(n,foreignExports);
3225 static Void local checkForeignExport(p) /* Check foreign export */
3227 emptySubstitution();
3228 name(p).type = checkSigType(name(p).line,
3229 "foreign export declaration",
3232 implementForeignExport(p);
3237 /* --------------------------------------------------------------------------
3238 * Static analysis of patterns:
3240 * Patterns are parsed as ordinary (atomic) expressions. Static analysis
3241 * makes the following checks:
3242 * - Patterns are well formed (according to pattern syntax), including the
3243 * special case of (n+k) patterns.
3244 * - All constructor functions have been defined and are used with the
3245 * correct number of arguments.
3246 * - No variable name is used more than once in a pattern.
3248 * The list of pattern variables occuring in each pattern is accumulated in
3249 * a global list `patVars', which must be initialised to NIL at appropriate
3250 * points before using these routines to check for valid patterns. This
3251 * mechanism enables the pattern checking routine to be mapped over a list
3252 * of patterns, ensuring that no variable occurs more than once in the
3253 * complete pattern list (as is required on the lhs of a function defn).
3254 * ------------------------------------------------------------------------*/
3256 static List patVars; /* List of vars bound in pattern */
3258 static Cell local checkPat(line,p) /* Check valid pattern syntax */
3261 switch (whatIs(p)) {
3263 case VAROPCELL : addToPatVars(line,p);
3266 case INFIX : return checkPat(line,tidyInfix(line,snd(p)));
3268 case AP : return checkMaybeCnkPat(line,p);
3273 case CONOPCELL : return checkApPat(line,0,p);
3278 case FLOATCELL : break;
3279 case INTCELL : break;
3281 case ASPAT : addToPatVars(line,fst(snd(p)));
3282 snd(snd(p)) = checkPat(line,snd(snd(p)));
3285 case LAZYPAT : snd(p) = checkPat(line,snd(p));
3288 case FINLIST : map1Over(checkPat,line,snd(p));
3291 case CONFLDS : depConFlds(line,p,TRUE);
3294 case ESIGN : snd(snd(p)) = checkPatType(line,
3298 fst(snd(p)) = checkPat(line,fst(snd(p)));
3301 default : ERRMSG(line) "Illegal pattern syntax"
3307 static Cell local checkMaybeCnkPat(l,p)/* Check applicative pattern with */
3308 Int l; /* the possibility of n+k pattern */
3311 Cell h = getHead(p);
3313 if (argCount==2 && isVar(h) && textOf(h)==textPlus) { /* n+k */
3314 Cell v = arg(fun(p));
3315 if (!isInt(arg(p))) {
3316 ERRMSG(l) "Second argument in (n+k) pattern must be an integer"
3319 if (intOf(arg(p))<=0) {
3320 ERRMSG(l) "Integer k in (n+k) pattern must be > 0"
3323 fst(fun(p)) = ADDPAT;
3324 intValOf(fun(p)) = intOf(arg(p));
3325 arg(p) = checkPat(l,v);
3329 return checkApPat(l,0,p);
3332 static Cell local checkApPat(line,args,p)
3333 Int line; /* check validity of application */
3334 Int args; /* of constructor to arguments */
3336 switch (whatIs(p)) {
3337 case AP : fun(p) = checkApPat(line,args+1,fun(p));
3338 arg(p) = checkPat(line,arg(p));
3341 case TUPLE : if (tupleOf(p)!=args) {
3342 ERRMSG(line) "Illegal tuple pattern"
3348 case EXT : h98DoesntSupport(line,"extensible records");
3350 ERRMSG(line) "Illegal record pattern"
3356 case QUALIDENT : if (!isQCon(p)) {
3358 "Illegal use of qualified variable in pattern"
3361 /* deliberate fall through */
3363 case CONOPCELL : p = conDefined(line,p);
3364 checkCfunArgs(line,p,args);
3367 case NAME : checkIsCfun(line,p);
3368 checkCfunArgs(line,p,args);
3371 default : ERRMSG(line) "Illegal pattern syntax"
3377 static Void local addToPatVars(line,v) /* Add variable v to list of vars */
3378 Int line; /* in current pattern, checking */
3379 Cell v; { /* for repeated variables. */
3384 for (; nonNull(n); p=n, n=tl(n)) {
3385 if (textOf(hd(n))==t) {
3386 ERRMSG(line) "Repeated variable \"%s\" in pattern",
3393 patVars = cons(v,NIL);
3395 tl(p) = cons(v,NIL);
3399 static Name local conDefined(line,nm) /* check that nm is the name of a */
3400 Int line; /* previously defined constructor */
3401 Cell nm; { /* function. */
3402 Name n = findQualName(nm);
3404 ERRMSG(line) "Undefined constructor function \"%s\"", identToStr(nm)
3407 checkIsCfun(line,n);
3411 static Void local checkIsCfun(line,c) /* Check that c is a constructor fn */
3415 ERRMSG(line) "\"%s\" is not a constructor function",
3416 textToStr(name(c).text)
3421 static Void local checkCfunArgs(line,c,args)
3422 Int line; /* Check constructor applied with */
3423 Cell c; /* correct number of arguments */
3425 Int a = userArity(c);
3428 "Constructor \"%s\" must have exactly %d argument%s in pattern",
3429 textToStr(name(c).text), a, ((a==1)?"":"s")
3434 static Cell local checkPatType(l,wh,e,t)/* Check type appearing in pattern */
3439 List tvs = typeVarsIn(t,NIL,NIL,NIL);
3440 h98DoesntSupport(l,"pattern type annotations");
3441 for (; nonNull(tvs); tvs=tl(tvs)) {
3442 Int beta = newKindvars(1);
3443 hd(btyvars) = cons(pair(hd(tvs),mkInt(beta)), hd(btyvars));
3445 t = checkSigType(l,"pattern type",e,t);
3446 if (isPolyOrQualType(t) || whatIs(t)==RANK2) {
3447 ERRMSG(l) "Illegal syntax in %s type annotation", wh
3453 static Cell local applyBtyvs(pat) /* Record bound type vars in pat */
3455 List bts = hd(btyvars);
3458 pat = ap(BIGLAM,pair(bts,pat));
3459 for (; nonNull(bts); bts=tl(bts)) {
3460 snd(hd(bts)) = copyKindvar(intOf(snd(hd(bts))));
3466 /* --------------------------------------------------------------------------
3467 * Maintaining lists of bound variables and local definitions, for
3468 * dependency and scope analysis.
3469 * ------------------------------------------------------------------------*/
3471 static List bounds; /* list of lists of bound vars */
3472 static List bindings; /* list of lists of binds in scope */
3473 static List depends; /* list of lists of dependents */
3475 /* bounds :: [[Var]] -- var equality used on Vars */
3476 /* bindings :: [[([Var],?)]] -- var equality used on Vars */
3477 /* depends :: [[Var]] -- pointer equality used on Vars */
3479 #define saveBvars() hd(bounds) /* list of bvars in current scope */
3480 #define restoreBvars(bs) hd(bounds)=bs /* restore list of bound variables */
3482 static Cell local bindPat(line,p) /* add new bound vars for pattern */
3486 p = checkPat(line,p);
3487 hd(bounds) = revOnto(patVars,hd(bounds));
3491 static Void local bindPats(line,ps) /* add new bound vars for patterns */
3495 map1Over(checkPat,line,ps);
3496 hd(bounds) = revOnto(patVars,hd(bounds));
3499 /* --------------------------------------------------------------------------
3500 * Before processing value and type signature declarations, all data and
3501 * type definitions have been processed so that:
3502 * - all valid type constructors (with their arities) are known.
3503 * - all valid constructor functions (with their arities and types) are
3506 * The result of parsing a list of value declarations is a list of Eqns:
3507 * Eqn ::= (SIGDECL,(Line,[Var],type))
3508 * | (FIXDECL,(Line,[Op],SyntaxInt))
3510 * The ordering of the equations in this list is the reverse of the original
3511 * ordering in the script parsed. This is a consequence of the structure of
3512 * the parser ... but also turns out to be most convenient for the static
3515 * As the first stage of the static analysis of value declarations, each
3516 * list of Eqns is converted to a list of Bindings. As part of this
3518 * - The ordering of the list of Bindings produced is the same as in the
3520 * - When a variable (function) is defined over a number of lines, all
3521 * of the definitions should appear together and each should give the
3522 * same arity to the variable being defined.
3523 * - No variable can have more than one definition.
3524 * - For pattern bindings:
3525 * - Each lhs is a valid pattern/function lhs, all constructor functions
3526 * have been defined and are used with the correct number of arguments.
3527 * - Each lhs contains no repeated pattern variables.
3528 * - Each equation defines at least one variable (e.g. True = False is
3530 * - Types appearing in type signatures are well formed:
3531 * - Type constructors used are defined and used with correct number
3533 * - type variables are replaced by offsets, type constructor names
3535 * - Every variable named in a type signature declaration is defined by
3536 * one or more equations elsewhere in the script.
3537 * - No variable has more than one type declaration.
3538 * - Similar properties for fixity declarations.
3540 * ------------------------------------------------------------------------*/
3542 #define bindingAttr(b) fst(snd(b)) /* type(s)/fixity(ies) for binding */
3543 #define fbindAlts(b) snd(snd(b)) /* alternatives for function binding*/
3545 static List local extractSigdecls(es) /* Extract the SIGDECLS from list */
3546 List es; { /* of equations */
3547 List sigdecls = NIL; /* :: [(Line,[Var],Type)] */
3549 for(; nonNull(es); es=tl(es)) {
3550 if (fst(hd(es))==SIGDECL) { /* type-declaration? */
3551 Pair sig = snd(hd(es));
3552 Int line = intOf(fst3(sig));
3553 List vs = snd3(sig);
3554 for(; nonNull(vs); vs=tl(vs)) {
3555 if (isQualIdent(hd(vs))) {
3556 ERRMSG(line) "Type signature for qualified variable \"%s\" is not allowed",
3561 sigdecls = cons(sig,sigdecls); /* discard SIGDECL tag*/
3567 static List local extractFixdecls(es) /* Extract the FIXDECLS from list */
3568 List es; { /* of equations */
3569 List fixdecls = NIL; /* :: [(Line,SyntaxInt,[Op])] */
3571 for(; nonNull(es); es=tl(es)) {
3572 if (fst(hd(es))==FIXDECL) { /* fixity declaration?*/
3573 fixdecls = cons(snd(hd(es)),fixdecls); /* discard FIXDECL tag*/
3579 static List local extractBindings(ds) /* extract untyped bindings from */
3580 List ds; { /* given list of equations */
3581 Cell lastVar = NIL; /* = var def'd in last eqn (if any)*/
3582 Int lastArity = 0; /* = number of args in last defn */
3583 List bs = NIL; /* :: [Binding] */
3585 for(; nonNull(ds); ds=tl(ds)) {
3587 if (fst(d)==FUNBIND) { /* Function bindings */
3588 Cell rhs = snd(snd(d));
3589 Int line = rhsLine(rhs);
3590 Cell lhs = fst(snd(d));
3591 Cell v = getHead(lhs);
3592 Cell newAlt = pair(getArgs(lhs),rhs);
3594 internal("FUNBIND");
3596 if (nonNull(lastVar) && textOf(v)==textOf(lastVar)) {
3597 if (argCount!=lastArity) {
3598 ERRMSG(line) "Equations give different arities for \"%s\"",
3599 textToStr(textOf(v))
3602 fbindAlts(hd(bs)) = cons(newAlt,fbindAlts(hd(bs)));
3606 lastArity = argCount;
3607 notDefined(line,bs,v);
3608 bs = cons(pair(v,pair(NIL,singleton(newAlt))),bs);
3611 } else if (fst(d)==PATBIND) { /* Pattern bindings */
3612 Cell rhs = snd(snd(d));
3613 Int line = rhsLine(rhs);
3614 Cell pat = fst(snd(d));
3615 while (whatIs(pat)==ESIGN) {/* Move type annotations to rhs */
3616 Cell p = fst(snd(pat));
3617 fst(snd(pat)) = rhs;
3618 snd(snd(d)) = rhs = pat;
3619 fst(snd(d)) = pat = p;
3622 if (isVar(pat)) { /* Convert simple pattern bind to */
3623 notDefined(line,bs,pat);/* a function binding */
3624 bs = cons(pair(pat,pair(NIL,singleton(pair(NIL,rhs)))),bs);
3626 List vs = getPatVars(line,pat,NIL);
3628 ERRMSG(line) "No variables defined in lhs pattern"
3631 map2Proc(notDefined,line,bs,vs);
3632 bs = cons(pair(vs,pair(NIL,snd(d))),bs);
3640 static List local getPatVars(line,p,vs) /* Find list of variables bound in */
3641 Int line; /* pattern p */
3644 switch (whatIs(p)) {
3646 vs = getPatVars(line,arg(p),vs);
3649 return vs; /* Ignore head of application */
3651 case CONFLDS : { List pfs = snd(snd(p));
3652 for (; nonNull(pfs); pfs=tl(pfs)) {
3653 if (isVar(hd(pfs))) {
3654 vs = addPatVar(line,hd(pfs),vs);
3656 vs = getPatVars(line,snd(hd(pfs)),vs);
3662 case FINLIST : { List ps = snd(p);
3663 for (; nonNull(ps); ps=tl(ps)) {
3664 vs = getPatVars(line,hd(ps),vs);
3669 case ESIGN : return getPatVars(line,fst(snd(p)),vs);
3674 case INFIX : return getPatVars(line,snd(p),vs);
3676 case ASPAT : return addPatVar(line,fst(snd(p)),
3677 getPatVars(line,snd(snd(p)),vs));
3680 case VAROPCELL : return addPatVar(line,p,vs);
3690 case WILDCARD : return vs;
3692 default : internal("getPatVars");
3697 static List local addPatVar(line,v,vs) /* Add var to list of previously */
3698 Int line; /* encountered variables */
3701 if (varIsMember(textOf(v),vs)) {
3702 ERRMSG(line) "Repeated use of variable \"%s\" in pattern binding",
3703 textToStr(textOf(v))
3709 static List local eqnsToBindings(es,ts,cs,ps)
3710 List es; /* Convert list of equations to */
3711 List ts; /* list of typed bindings */
3714 List bs = extractBindings(es);
3715 map1Proc(addSigdecl,bs,extractSigdecls(es));
3716 map4Proc(addFixdecl,bs,ts,cs,ps,extractFixdecls(es));
3720 static Void local notDefined(line,bs,v)/* check if name already defined in */
3721 Int line; /* list of bindings */
3724 if (nonNull(findBinding(textOf(v),bs))) {
3725 ERRMSG(line) "\"%s\" multiply defined", textToStr(textOf(v))
3730 static Cell local findBinding(t,bs) /* look for binding for variable t */
3731 Text t; /* in list of bindings bs */
3733 for (; nonNull(bs); bs=tl(bs)) {
3734 if (isVar(fst(hd(bs)))) { /* function-binding? */
3735 if (textOf(fst(hd(bs)))==t) {
3738 } else if (nonNull(varIsMember(t,fst(hd(bs))))){/* pattern-binding?*/
3745 static Cell local getAttr(bs,v) /* Locate type/fixity attribute */
3746 List bs; /* for variable v in bindings bs */
3749 Cell b = findBinding(t,bs);
3751 if (isNull(b)) { /* No binding */
3753 } else if (isVar(fst(b))) { /* func binding? */
3754 if (isNull(bindingAttr(b))) {
3755 bindingAttr(b) = pair(NIL,NIL);
3757 return bindingAttr(b);
3758 } else { /* pat binding? */
3760 List as = bindingAttr(b);
3763 bindingAttr(b) = as = replicate(length(vs),NIL);
3766 while (nonNull(vs) && t!=textOf(hd(vs))) {
3772 internal("getAttr");
3773 } else if (isNull(hd(as))) {
3774 hd(as) = pair(NIL,NIL);
3780 static Void local addSigdecl(bs,sigdecl)/* add type information to bindings*/
3781 List bs; /* :: [Binding] */
3782 Cell sigdecl; { /* :: (Line,[Var],Type) */
3783 Int l = intOf(fst3(sigdecl));
3784 List vs = snd3(sigdecl);
3785 Type type = checkSigType(l,"type declaration",hd(vs),thd3(sigdecl));
3787 for (; nonNull(vs); vs=tl(vs)) {
3789 Pair attr = getAttr(bs,v);
3791 ERRMSG(l) "Missing binding for variable \"%s\" in type signature",
3792 textToStr(textOf(v))
3794 } else if (nonNull(fst(attr))) {
3795 ERRMSG(l) "Repeated type signature for \"%s\"",
3796 textToStr(textOf(v))
3803 static Void local addFixdecl(bs,ts,cs,ps,fixdecl)
3809 Int line = intOf(fst3(fixdecl));
3810 List ops = snd3(fixdecl);
3811 Cell sy = thd3(fixdecl);
3813 for (; nonNull(ops); ops=tl(ops)) {
3815 Text t = textOf(op);
3816 Cell attr = getAttr(bs,op);
3817 if (nonNull(attr)) { /* Found name in binding? */
3818 if (nonNull(snd(attr))) {
3822 } else { /* Look in tycons, classes, prims */
3827 for (; isNull(n) && nonNull(ts1); ts1=tl(ts1)) { /* tycons */
3829 if (tycon(tc).what==DATATYPE || tycon(tc).what==NEWTYPE) {
3830 n = nameIsMember(t,tycon(tc).defn);
3833 for (; isNull(n) && nonNull(cs1); cs1=tl(cs1)) { /* classes */
3834 n = nameIsMember(t,cclass(hd(cs1)).members);
3836 for (; isNull(n) && nonNull(ps1); ps1=tl(ps1)) { /* prims */
3837 n = nameIsMember(t,hd(ps1));
3842 } else if (name(n).syntax!=NO_SYNTAX) {
3845 name(n).syntax = intOf(sy);
3850 static Void local dupFixity(line,t) /* Report repeated fixity decl */
3854 "Repeated fixity declaration for operator \"%s\"", textToStr(t)
3858 static Void local missFixity(line,t) /* Report missing op for fixity */
3862 "Cannot find binding for operator \"%s\" in fixity declaration",
3867 /* --------------------------------------------------------------------------
3868 * Dealing with infix operators:
3870 * Expressions involving infix operators or unary minus are parsed as
3871 * elements of the following type:
3873 * data InfixExp = Only Exp | Neg InfixExp | Infix InfixExp Op Exp
3875 * (The algorithms here do not assume that negation can be applied only once,
3876 * i.e., that - - x is a syntax error, as required by the Haskell report.
3877 * Instead, that restriction is captured by the grammar itself, given above.)
3879 * There are rules of precedence and grouping, expressed by two functions:
3881 * prec :: Op -> Int; assoc :: Op -> Assoc (Assoc = {L, N, R})
3883 * InfixExp values are rearranged accordingly when a complete expression
3884 * has been read using a simple shift-reduce parser whose result may be taken
3885 * to be a value of the following type:
3887 * data Exp = Atom Int | Negate Exp | Apply Op Exp Exp | Error String
3889 * The machine on which this parser is based can be defined as follows:
3891 * tidy :: InfixExp -> [(Op,Exp)] -> Exp
3892 * tidy (Only a) [] = a
3893 * tidy (Only a) ((o,b):ss) = tidy (Only (Apply o a b)) ss
3894 * tidy (Infix a o b) [] = tidy a [(o,b)]
3895 * tidy (Infix a o b) ((p,c):ss)
3896 * | shift o p = tidy a ((o,b):(p,c):ss)
3897 * | red o p = tidy (Infix a o (Apply p b c)) ss
3898 * | ambig o p = Error "ambiguous use of operators"
3899 * tidy (Neg e) [] = tidy (tidyNeg e) []
3900 * tidy (Neg e) ((o,b):ss)
3901 * | nshift o = tidy (Neg (underNeg o b e)) ss
3902 * | nred o = tidy (tidyNeg e) ((o,b):ss)
3903 * | nambig o = Error "illegal use of negation"
3905 * At each stage, the parser can either shift, reduce, accept, or error.
3906 * The transitions when dealing with juxtaposed operators o and p are
3907 * determined by the following rules:
3909 * shift o p = (prec o > prec p)
3910 * || (prec o == prec p && assoc o == L && assoc p == L)
3912 * red o p = (prec o < prec p)
3913 * || (prec o == prec p && assoc o == R && assoc p == R)
3915 * ambig o p = (prec o == prec p)
3916 * && (assoc o == N || assoc p == N || assoc o /= assoc p)
3918 * The transitions when dealing with juxtaposed unary minus and infix
3919 * operators are as follows. The precedence of unary minus (infixl 6) is
3920 * hardwired in to these definitions, as it is to the definitions of the
3921 * Haskell grammar in the official report.
3923 * nshift o = (prec o > 6)
3924 * nred o = (prec o < 6) || (prec o == 6 && assoc o == L)
3925 * nambig o = prec o == 6 && (assoc o == R || assoc o == N)
3927 * An InfixExp of the form (Neg e) means negate the last thing in
3928 * the InfixExp e; we can force this negation using:
3930 * tidyNeg :: OpExp -> OpExp
3931 * tidyNeg (Only e) = Only (Negate e)
3932 * tidyNeg (Infix a o b) = Infix a o (Negate b)
3933 * tidyNeg (Neg e) = tidyNeg (tidyNeg e)
3935 * On the other hand, if we want to sneak application of an infix operator
3936 * under a negation, then we use:
3938 * underNeg :: Op -> Exp -> OpExp -> OpExp
3939 * underNeg o b (Only e) = Only (Apply o e b)
3940 * underNeg o b (Neg e) = Neg (underNeg o b e)
3941 * underNeg o b (Infix e p f) = Infix e p (Apply o f b)
3943 * As a concession to efficiency, we lower the number of calls to syntaxOf
3944 * by keeping track of the values of sye, sys throughout the process. The
3945 * value APPLIC is used to indicate that the syntax value is unknown.
3946 * ------------------------------------------------------------------------*/
3948 static Cell local tidyInfix(line,e) /* Convert infixExp to Exp */
3950 Cell e; { /* :: OpExp */
3951 Cell s = NIL; /* :: [(Op,Exp)] */
3952 Syntax sye = APPLIC; /* Syntax of op in e (init unknown)*/
3953 Syntax sys = APPLIC; /* Syntax of op in s (init unknown)*/
3956 while (fst(d)!=ONLY) { /* Attach fixities to operators */
3960 fun(fun(d)) = attachFixity(line,fun(fun(d)));
3966 switch (whatIs(e)) {
3967 case ONLY : e = snd(e);
3968 while (nonNull(s)) {
3969 Cell next = arg(fun(s));
3971 fun(fun(s)) = snd(fun(fun(s)));
3977 case NEG : if (nonNull(s)) {
3978 if (sys==APPLIC) { /* calculate sys */
3979 sys = intOf(fst(fun(fun(s))));
3982 if (precOf(sys)==UMINUS_PREC && /* nambig */
3983 assocOf(sys)!=UMINUS_ASSOC) {
3985 "Ambiguous use of unary minus with \""
3986 ETHEN ERREXPR(snd(fun(fun(s))));
3991 if (precOf(sys)>UMINUS_PREC) { /* nshift */
3995 while (whatIs(e1)==NEG)
3997 arg(fun(t)) = arg(e1);
3998 fun(fun(t)) = snd(fun(fun(t)));
4005 /* Intentional fall-thru for nreduce and isNull(s) */
4007 { Cell prev = e; /* e := tidyNeg e */
4008 Cell temp = arg(prev);
4010 for (; whatIs(temp)==NEG; nneg++) {
4011 fun(prev) = nameNegate;
4015 if (isInt(arg(temp))) { /* special cases */
4016 if (nneg&1) /* for literals */
4017 arg(temp) = mkInt(-intOf(arg(temp)));
4019 else if (isFloat(arg(temp))) {
4021 arg(temp) = floatNegate(arg(temp));
4022 //mkFloat(-floatOf(arg(temp)));
4025 fun(prev) = nameNegate;
4026 arg(prev) = arg(temp);
4033 default : if (isNull(s)) {/* Move operation onto empty stack */
4034 Cell next = arg(fun(e));
4041 else { /* deal with pair of operators */
4043 if (sye==APPLIC) { /* calculate sys and sye */
4044 sye = intOf(fst(fun(fun(e))));
4047 sys = intOf(fst(fun(fun(s))));
4050 if (precOf(sye)==precOf(sys) && /* ambig */
4051 (assocOf(sye)!=assocOf(sys) ||
4052 assocOf(sye)==NON_ASS)) {
4053 ERRMSG(line) "Ambiguous use of operator \""
4054 ETHEN ERREXPR(snd(fun(fun(e))));
4055 ERRTEXT "\" with \""
4056 ETHEN ERREXPR(snd(fun(fun(s))));
4061 if (precOf(sye)>precOf(sys) || /* shift */
4062 (precOf(sye)==precOf(sys) &&
4063 assocOf(sye)==LEFT_ASS &&
4064 assocOf(sys)==LEFT_ASS)) {
4065 Cell next = arg(fun(e));
4073 Cell next = arg(fun(s));
4074 arg(fun(s)) = arg(e);
4075 fun(fun(s)) = snd(fun(fun(s)));
4086 static Pair local attachFixity(line,op) /* Attach fixity to operator in an */
4087 Int line; /* infix expression */
4089 Syntax sy = DEF_OPSYNTAX;
4091 switch (whatIs(op)) {
4093 case VARIDCELL : if ((sy=lookupSyntax(textOf(op)))==NO_SYNTAX) {
4094 Name n = findName(textOf(op));
4096 ERRMSG(line) "Undefined variable \"%s\"",
4097 textToStr(textOf(op))
4106 case CONIDCELL : sy = syntaxOf(op = conDefined(line,op));
4109 case QUALIDENT : { Name n = findQualName(op);
4115 "Undefined qualified variable \"%s\"",
4125 return pair(mkInt(sy),op); /* Pair fixity with (possibly) */
4126 /* translated operator */
4129 static Syntax local lookupSyntax(t) /* Try to find fixity for var in */
4130 Text t; { /* enclosing bindings */
4131 List bounds1 = bounds;
4132 List bindings1 = bindings;
4134 while (nonNull(bindings1)) {
4135 if (nonNull(varIsMember(t,hd(bounds1)))) {
4136 return DEF_OPSYNTAX;
4138 Cell b = findBinding(t,hd(bindings1));
4140 Cell a = fst(snd(b));
4141 if (isVar(fst(b))) { /* Function binding */
4142 if (nonNull(a) && nonNull(snd(a))) {
4143 return intOf(snd(a));
4145 } else { /* Pattern binding */
4147 while (nonNull(vs) && nonNull(a)) {
4148 if (t==textOf(hd(vs))) {
4149 if (nonNull(hd(a)) && isInt(snd(hd(a)))) {
4150 return intOf(snd(hd(a)));
4158 return DEF_OPSYNTAX;
4161 bounds1 = tl(bounds1);
4162 bindings1 = tl(bindings1);
4167 /* --------------------------------------------------------------------------
4168 * To facilitate dependency analysis, lists of bindings are temporarily
4169 * augmented with an additional field, which is used in two ways:
4170 * - to build the `adjacency lists' for the dependency graph. Represented by
4171 * a list of pointers to other bindings in the same list of bindings.
4172 * - to hold strictly positive integer values (depth first search numbers) of
4173 * elements `on the stack' during the strongly connected components search
4174 * algorithm, or a special value mkInt(0), once the binding has been added
4175 * to a particular strongly connected component.
4177 * Using this extra field, the type of each list of declarations during
4178 * dependency analysis is [Binding'] where:
4180 * Binding' ::= (Var, (Attr, (Dep, [Alt]))) -- function binding
4181 * | ([Var], ([Attr], (Dep, (Pat,Rhs)))) -- pattern binding
4183 * ------------------------------------------------------------------------*/
4185 #define depVal(d) (fst(snd(snd(d)))) /* Access to dependency information*/
4187 static List local dependencyAnal(bs) /* Separate lists of bindings into */
4188 List bs; { /* mutually recursive groups in */
4189 /* order of dependency */
4190 mapProc(addDepField,bs); /* add extra field for dependents */
4191 mapProc(depBinding,bs); /* find dependents of each binding */
4192 bs = bscc(bs); /* sort to strongly connected comps*/
4193 mapProc(remDepField,bs); /* remove dependency info field */
4197 static List local topDependAnal(bs) /* Like dependencyAnal(), but at */
4198 List bs; { /* top level, reporting on progress*/
4202 setGoal("Dependency analysis",(Target)(length(bs)));
4204 mapProc(addDepField,bs); /* add extra field for dependents */
4205 for (xs=bs; nonNull(xs); xs=tl(xs)) {
4206 emptySubstitution();
4208 soFar((Target)(i++));
4210 bs = bscc(bs); /* sort to strongly connected comps */
4211 mapProc(remDepField,bs); /* remove dependency info field */
4216 static Void local addDepField(b) /* add extra field to binding to */
4217 Cell b; { /* hold list of dependents */
4218 snd(snd(b)) = pair(NIL,snd(snd(b)));
4221 static Void local remDepField(bs) /* remove dependency field from */
4222 List bs; { /* list of bindings */
4223 mapProc(remDepField1,bs);
4226 static Void local remDepField1(b) /* remove dependency field from */
4227 Cell b; { /* single binding */
4228 snd(snd(b)) = snd(snd(snd(b)));
4231 static Void local clearScope() { /* initialise dependency scoping */
4237 static Void local withinScope(bs) /* Enter scope of bindings bs */
4239 bounds = cons(NIL,bounds);
4240 bindings = cons(bs,bindings);
4241 depends = cons(NIL,depends);
4244 static Void local leaveScope() { /* Leave scope of last withinScope */
4245 List bs = hd(bindings); /* Remove fixity info from binds */
4246 Bool toplevel = isNull(tl(bindings));
4247 for (; nonNull(bs); bs=tl(bs)) {
4249 if (isVar(fst(b))) { /* Variable binding */
4250 Cell a = fst(snd(b));
4253 saveSyntax(fst(b),snd(a));
4255 fst(snd(b)) = fst(a);
4257 } else { /* Pattern binding */
4259 List as = fst(snd(b));
4260 while (nonNull(vs) && nonNull(as)) {
4261 if (isPair(hd(as))) {
4263 saveSyntax(hd(vs),snd(hd(as)));
4265 hd(as) = fst(hd(as));
4272 bounds = tl(bounds);
4273 bindings = tl(bindings);
4274 depends = tl(depends);
4277 static Void local saveSyntax(v,sy) /* Save syntax of top-level var */
4278 Cell v; /* in corresponding Name */
4280 Name n = findName(textOf(v));
4281 if (isNull(n) || name(n).syntax!=NO_SYNTAX) {
4282 internal("saveSyntax");
4285 name(n).syntax = intOf(sy);
4289 /* --------------------------------------------------------------------------
4290 * As a side effect of the dependency analysis we also make the following
4292 * - Each lhs is a valid pattern/function lhs, all constructor functions
4293 * have been defined and are used with the correct number of arguments.
4294 * - No lhs contains repeated pattern variables.
4295 * - Expressions used on the rhs of an eqn should be well formed. This
4297 * - Checking for valid patterns (including repeated vars) in lambda,
4298 * case, and list comprehension expressions.
4299 * - Recursively checking local lists of equations.
4300 * - No free (i.e. unbound) variables are used in the declaration list.
4301 * ------------------------------------------------------------------------*/
4303 static Void local depBinding(b) /* find dependents of binding */
4305 Cell defpart = snd(snd(snd(b))); /* definition part of binding */
4309 if (isVar(fst(b))) { /* function-binding? */
4310 mapProc(depAlt,defpart);
4311 if (isNull(fst(snd(b)))) { /* Save dep info if no type sig */
4312 fst(snd(b)) = pair(ap(IMPDEPS,hd(depends)),NIL);
4313 } else if (isNull(fst(fst(snd(b))))) {
4314 fst(fst(snd(b))) = ap(IMPDEPS,hd(depends));
4316 } else { /* pattern-binding? */
4317 Int line = rhsLine(snd(defpart));
4320 fst(defpart) = checkPat(line,fst(defpart));
4321 depRhs(snd(defpart));
4323 if (nonNull(hd(btyvars))) {
4325 "Sorry, no type variables are allowed in pattern binding type annotations"
4329 fst(defpart) = applyBtyvs(fst(defpart));
4331 depVal(b) = hd(depends);
4334 static Void local depDefaults(c) /* dependency analysis on defaults */
4335 Class c; { /* from class definition */
4336 depClassBindings(cclass(c).defaults);
4339 static Void local depInsts(in) /* dependency analysis on instance */
4340 Inst in; { /* bindings */
4341 depClassBindings(inst(in).implements);
4344 static Void local depClassBindings(bs) /* dependency analysis on list of */
4345 List bs; { /* bindings, possibly containing */
4346 for (; nonNull(bs); bs=tl(bs)) { /* NIL bindings ... */
4347 if (nonNull(hd(bs))) { /* No need to add extra field for */
4348 mapProc(depAlt,snd(hd(bs)));/* dependency information... */
4353 static Void local depAlt(a) /* Find dependents of alternative */
4355 List obvs = saveBvars(); /* Save list of bound variables */
4357 bindPats(rhsLine(snd(a)),fst(a)); /* add new bound vars for patterns */
4358 depRhs(snd(a)); /* find dependents of rhs */
4359 fst(a) = applyBtyvs(fst(a));
4360 restoreBvars(obvs); /* restore original list of bvars */
4363 static Void local depRhs(r) /* Find dependents of rhs */
4365 switch (whatIs(r)) {
4366 case GUARDED : mapProc(depGuard,snd(r));
4369 case LETREC : fst(snd(r)) = eqnsToBindings(fst(snd(r)),NIL,NIL,NIL);
4370 withinScope(fst(snd(r)));
4371 fst(snd(r)) = dependencyAnal(fst(snd(r)));
4372 hd(depends) = fst(snd(r));
4373 depRhs(snd(snd(r)));
4377 case RSIGN : snd(snd(r)) = checkPatType(rhsLine(fst(snd(r))),
4379 rhsExpr(fst(snd(r))),
4381 depRhs(fst(snd(r)));
4384 default : snd(r) = depExpr(intOf(fst(r)),snd(r));
4389 static Void local depGuard(g) /* find dependents of single guarded*/
4390 Cell g; { /* expression */
4391 depPair(intOf(fst(g)),snd(g));
4394 static Cell local depExpr(line,e) /* find dependents of expression */
4397 // Printf( "\n\n"); print(e,100); Printf("\n");
4398 //printExp(stdout,e);
4399 switch (whatIs(e)) {
4402 case VAROPCELL : return depVar(line,e);
4405 case CONOPCELL : return conDefined(line,e);
4407 case QUALIDENT : if (isQVar(e)) {
4408 return depQVar(line,e);
4409 } else { /* QConOrConOp */
4410 return conDefined(line,e);
4413 case INFIX : return depExpr(line,tidyInfix(line,snd(e)));
4416 case RECSEL : break;
4418 case AP : if (isAp(e) && isAp(fun(e)) && isExt(fun(fun(e)))) {
4419 return depRecord(line,e);
4425 arg(a) = depExpr(line,arg(a));
4428 fun(a) = depExpr(line,fun(a));
4432 case AP : depPair(line,e);
4446 case INTCELL : break;
4448 case COND : depTriple(line,snd(e));
4451 case FINLIST : map1Over(depExpr,line,snd(e));
4454 case LETREC : fst(snd(e)) = eqnsToBindings(fst(snd(e)),NIL,NIL,NIL);
4455 withinScope(fst(snd(e)));
4456 fst(snd(e)) = dependencyAnal(fst(snd(e)));
4457 hd(depends) = fst(snd(e));
4458 snd(snd(e)) = depExpr(line,snd(snd(e)));
4462 case LAMBDA : depAlt(snd(e));
4465 case DOCOMP : /* fall-thru */
4466 case COMP : depComp(line,snd(e),snd(snd(e)));
4469 case ESIGN : fst(snd(e)) = depExpr(line,fst(snd(e)));
4470 snd(snd(e)) = checkSigType(line,
4476 case CASE : fst(snd(e)) = depExpr(line,fst(snd(e)));
4477 map1Proc(depCaseAlt,line,snd(snd(e)));
4480 case CONFLDS : depConFlds(line,e,FALSE);
4483 case UPDFLDS : depUpdFlds(line,e);
4487 case WITHEXP : depWith(line,e);
4491 case ASPAT : ERRMSG(line) "Illegal `@' in expression"
4494 case LAZYPAT : ERRMSG(line) "Illegal `~' in expression"
4497 case WILDCARD : ERRMSG(line) "Illegal `_' in expression"
4501 case EXT : ERRMSG(line) "Illegal application of record"
4505 default : internal("depExpr");
4510 static Void local depPair(line,e) /* find dependents of pair of exprs*/
4513 fst(e) = depExpr(line,fst(e));
4514 snd(e) = depExpr(line,snd(e));
4517 static Void local depTriple(line,e) /* find dependents of triple exprs */
4520 fst3(e) = depExpr(line,fst3(e));
4521 snd3(e) = depExpr(line,snd3(e));
4522 thd3(e) = depExpr(line,thd3(e));
4525 static Void local depComp(l,e,qs) /* find dependents of comprehension*/
4530 fst(e) = depExpr(l,fst(e));
4534 switch (whatIs(q)) {
4535 case FROMQUAL : { List obvs = saveBvars();
4536 snd(snd(q)) = depExpr(l,snd(snd(q)));
4538 fst(snd(q)) = bindPat(l,fst(snd(q)));
4540 fst(snd(q)) = applyBtyvs(fst(snd(q)));
4545 case QWHERE : snd(q) = eqnsToBindings(snd(q),NIL,NIL,NIL);
4546 withinScope(snd(q));
4547 snd(q) = dependencyAnal(snd(q));
4548 hd(depends) = snd(q);
4553 case DOQUAL : /* fall-thru */
4554 case BOOLQUAL : snd(q) = depExpr(l,snd(q));
4561 static Void local depCaseAlt(line,a) /* Find dependents of case altern. */
4564 List obvs = saveBvars(); /* Save list of bound variables */
4566 fst(a) = bindPat(line,fst(a)); /* Add new bound vars for pats */
4567 depRhs(snd(a)); /* Find dependents of rhs */
4568 fst(a) = applyBtyvs(fst(a));
4569 restoreBvars(obvs); /* Restore original list of bvars */
4572 static Cell local depVar(line,e) /* Register occurrence of variable */
4575 List bounds1 = bounds;
4576 List bindings1 = bindings;
4577 List depends1 = depends;
4581 while (nonNull(bindings1)) {
4582 n = varIsMember(t,hd(bounds1)); /* look for t in bound variables */
4586 n = findBinding(t,hd(bindings1)); /* look for t in var bindings */
4588 if (!cellIsMember(n,hd(depends1))) {
4589 hd(depends1) = cons(n,hd(depends1));
4591 return (isVar(fst(n)) ? fst(n) : e);
4594 bounds1 = tl(bounds1);
4595 bindings1 = tl(bindings1);
4596 depends1 = tl(depends1);
4599 if (isNull(n=findName(t))) { /* check global definitions */
4600 ERRMSG(line) "Undefined variable \"%s\"", textToStr(t)
4604 if (!moduleThisScript(name(n).mod)) {
4607 /* Later phases of the system cannot cope if we resolve references
4608 * to unprocessed objects too early. This is the main reason that
4609 * we cannot cope with recursive modules at the moment.
4614 static Cell local depQVar(line,e)/* register occurrence of qualified variable */
4617 Name n = findQualName(e);
4618 if (isNull(n)) { /* check global definitions */
4619 ERRMSG(line) "Undefined qualified variable \"%s\"", identToStr(e)
4622 if (name(n).mod != currentModule) {
4625 if (fst(e) == VARIDCELL) {
4626 e = mkVar(qtextOf(e));
4628 e = mkVarop(qtextOf(e));
4630 return depVar(line,e);
4633 static Void local depConFlds(line,e,isP)/* check construction using fields */
4637 Name c = conDefined(line,fst(snd(e)));
4638 if (isNull(snd(snd(e))) ||
4639 nonNull(cellIsMember(c,depFields(line,e,snd(snd(e)),isP)))) {
4642 ERRMSG(line) "Constructor \"%s\" does not have selected fields in ",
4643 textToStr(name(c).text)
4648 if (!isP && isPair(name(c).defn)) { /* Check that banged fields defined*/
4649 List scs = fst(name(c).defn); /* List of strict components */
4650 Type t = name(c).type;
4651 Int a = userArity(c);
4652 List fs = snd(snd(e));
4654 if (isPolyType(t)) { /* Find tycon that c belongs to */
4657 if (isQualType(t)) {
4660 if (whatIs(t)==CDICTS) {
4669 for (ss=tycon(t).defn; hasCfun(ss); ss=tl(ss)) {
4671 /* Now we know the tycon t that c belongs to, and the corresponding
4672 * list of selectors for that type, ss. Now we have to check that
4673 * each of the fields identified by scs appears in fs, using ss to
4674 * cross reference, and convert integers to selector names.
4676 for (; nonNull(scs); scs=tl(scs)) {
4677 Int i = intOf(hd(scs));
4679 for (; nonNull(ss1); ss1=tl(ss1)) {
4680 List cns = name(hd(ss1)).defn;
4681 for (; nonNull(cns); cns=tl(cns)) {
4682 if (fst(hd(cns))==c) {
4686 if (nonNull(cns) && intOf(snd(hd(cns)))==i) {
4691 internal("depConFlds");
4695 for (; nonNull(fs1) && s!=fst(hd(fs1)); fs1=tl(fs1)) {
4698 ERRMSG(line) "Construction does not define strict field"
4700 ERRTEXT "\nExpression : " ETHEN ERREXPR(e);
4701 ERRTEXT "\nField : " ETHEN ERREXPR(s);
4710 static Void local depUpdFlds(line,e) /* check update using fields */
4713 if (isNull(thd3(snd(e)))) {
4714 ERRMSG(line) "Empty field list in update"
4717 fst3(snd(e)) = depExpr(line,fst3(snd(e)));
4718 snd3(snd(e)) = depFields(line,e,thd3(snd(e)),FALSE);
4721 static List local depFields(l,e,fs,isP) /* check field binding list */
4729 for (; nonNull(fs); fs=tl(fs)) { /* for each field binding */
4733 if (isVar(fb)) { /* expand var to var = var */
4734 h98DoesntSupport(l,"missing field bindings");
4735 fb = hd(fs) = pair(fb,fb);
4738 s = findQualName(fst(fb)); /* check for selector */
4739 if (nonNull(s) && isSfun(s)) {
4742 ERRMSG(l) "\"%s\" is not a selector function/field name",
4743 textToStr(textOf(fst(fb)))
4747 if (isNull(ss)) { /* for first named selector */
4748 List scs = name(s).defn; /* calculate list of constructors */
4749 for (; nonNull(scs); scs=tl(scs)) {
4750 cs = cons(fst(hd(scs)),cs);
4752 ss = singleton(s); /* initialize selector list */
4753 } else { /* for subsequent selectors */
4754 List ds = cs; /* intersect constructor lists */
4755 for (cs=NIL; nonNull(ds); ) {
4756 List scs = name(s).defn;
4757 while (nonNull(scs) && fst(hd(scs))!=hd(ds)) {
4770 if (cellIsMember(s,ss)) { /* check for repeated uses */
4771 ERRMSG(l) "Repeated field name \"%s\" in field list",
4772 textToStr(name(s).text)
4778 if (isNull(cs)) { /* Are there any matching constrs? */
4779 ERRMSG(l) "No constructor has all of the fields specified in "
4785 snd(fb) = (isP ? checkPat(l,snd(fb)) : depExpr(l,snd(fb)));
4791 static Void local depWith(line,e) /* check with using fields */
4794 fst(snd(e)) = depExpr(line,fst(snd(e)));
4795 snd(snd(e)) = depDwFlds(line,e,snd(snd(e)));
4798 static List local depDwFlds(l,e,fs)/* check field binding list */
4804 for (; nonNull(c); c=tl(c)) { /* for each field binding */
4805 snd(hd(c)) = depExpr(l,snd(hd(c)));
4812 static Cell local depRecord(line,e) /* find dependents of record and */
4813 Int line; /* sort fields into approp. order */
4814 Cell e; { /* to make construction and update */
4815 List exts = NIL; /* more efficient. */
4818 h98DoesntSupport(line,"extensible records");
4819 do { /* build up list of extensions */
4820 Text t = extText(fun(fun(r)));
4821 String s = textToStr(t);
4824 while (nonNull(nx) && strcmp(textToStr(extText(fun(fun(nx)))),s)>0) {
4828 if (nonNull(nx) && t==extText(fun(fun(nx)))) {
4829 ERRMSG(line) "Repeated label \"%s\" in record ", s
4835 exts = cons(fun(r),exts);
4837 tl(prev) = cons(fun(r),nx);
4839 extField(r) = depExpr(line,extField(r));
4841 } while (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r))));
4842 r = depExpr(line,r);
4843 return revOnto(exts,r);
4848 /* --------------------------------------------------------------------------
4849 * Several parts of this program require an algorithm for sorting a list
4850 * of values (with some added dependency information) into a list of strongly
4851 * connected components in which each value appears before its dependents.
4853 * Each of these algorithms is obtained by parameterising a standard
4854 * algorithm in "scc.c" as shown below.
4855 * ------------------------------------------------------------------------*/
4857 #define SCC2 tcscc /* make scc algorithm for Tycons */
4858 #define LOWLINK tclowlink
4859 #define DEPENDS(c) (isTycon(c) ? tycon(c).kind : cclass(c).kinds)
4860 #define SETDEPENDS(c,v) if(isTycon(c)) tycon(c).kind=v; else cclass(c).kinds=v
4867 #define SCC bscc /* make scc algorithm for Bindings */
4868 #define LOWLINK blowlink
4869 #define DEPENDS(t) depVal(t)
4870 #define SETDEPENDS(c,v) depVal(c)=v
4877 /* --------------------------------------------------------------------------
4878 * Main static analysis:
4879 * ------------------------------------------------------------------------*/
4881 Void checkExp() { /* Top level static check on Expr */
4882 staticAnalysis(RESET);
4883 clearScope(); /* Analyse expression in the scope */
4884 withinScope(NIL); /* of no local bindings */
4885 inputExpr = depExpr(0,inputExpr);
4887 staticAnalysis(RESET);
4890 Void checkContext(void) { /* Top level static check on Expr */
4893 staticAnalysis(RESET);
4894 clearScope(); /* Analyse expression in the scope */
4895 withinScope(NIL); /* of no local bindings */
4897 for (vs = NIL; nonNull(qs); qs=tl(qs)) {
4898 vs = typeVarsIn(hd(qs),NIL,NIL,vs);
4900 map2Proc(depPredExp,0,vs,inputContext);
4902 staticAnalysis(RESET);
4905 Void checkDefns() { /* Top level static analysis */
4906 Module thisModule = lastModule();
4907 staticAnalysis(RESET);
4909 setCurrModule(thisModule);
4911 /* Resolve module references */
4912 mapProc(checkQualImport, module(thisModule).qualImports);
4913 mapProc(checkUnqualImport,unqualImports);
4914 /* Add "import Prelude" if there`s no explicit import */
4915 if (thisModule!=modulePrelude
4916 && isNull(cellAssoc(modulePrelude,unqualImports))
4917 && isNull(cellRevAssoc(modulePrelude,module(thisModule).qualImports))) {
4918 unqualImports = cons(pair(modulePrelude,DOTDOT),unqualImports);
4920 /* Every module (including the Prelude) implicitly contains
4921 * "import qualified Prelude"
4923 module(thisModule).qualImports=cons(pair(mkCon(textPrelude),modulePrelude),
4924 module(thisModule).qualImports);
4926 mapProc(checkImportList, unqualImports);
4928 linkPreludeTC(); /* Get prelude tycons and classes */
4929 mapProc(checkTyconDefn,tyconDefns); /* validate tycon definitions */
4930 checkSynonyms(tyconDefns); /* check synonym definitions */
4931 mapProc(checkClassDefn,classDefns); /* process class definitions */
4932 mapProc(kindTCGroup,tcscc(tyconDefns,classDefns)); /* attach kinds */
4933 mapProc(addMembers,classDefns); /* add definitions for member funs */
4934 mapProc(visitClass,classDefns); /* check class hierarchy */
4935 linkPreludeCM(); /* Get prelude cfuns and mfuns */
4937 instDefns = rev(instDefns); /* process instance definitions */
4938 mapProc(checkInstDefn,instDefns);
4940 setCurrModule(thisModule);
4941 mapProc(addRSsigdecls,typeInDefns); /* add sigdecls for RESTRICTSYN */
4942 valDefns = eqnsToBindings(valDefns,tyconDefns,classDefns,/*primDefns*/NIL);
4943 mapProc(allNoPrevDef,valDefns); /* check against previous defns */
4944 mapProc(addDerivImp,derivedInsts); /* Add impls for derived instances */
4945 deriveContexts(derivedInsts); /* Calculate derived inst contexts */
4946 instDefns = appendOnto(instDefns,derivedInsts);
4947 checkDefaultDefns(); /* validate default definitions */
4949 mapProc(allNoPrevDef,valDefns); /* check against previous defns */
4953 mapProc(checkForeignImport,foreignImports); /* check foreign imports */
4954 mapProc(checkForeignExport,foreignExports); /* check foreign exports */
4955 foreignImports = NIL;
4956 foreignExports = NIL;
4958 /* Every top-level name has now been created - so we can build the */
4959 /* export list. Note that this has to happen before dependency */
4960 /* analysis so that references to Prelude.foo will be resolved */
4961 /* when compiling the prelude. */
4962 module(thisModule).exports = checkExports(module(thisModule).exports);
4964 mapProc(checkTypeIn,typeInDefns); /* check restricted synonym defns */
4967 withinScope(valDefns);
4968 valDefns = topDependAnal(valDefns); /* top level dependency ordering */
4969 mapProc(depDefaults,classDefns); /* dep. analysis on class defaults */
4970 mapProc(depInsts,instDefns); /* dep. analysis on inst defns */
4973 /* ToDo: evalDefaults should match current evaluation module */
4974 evalDefaults = defaultDefns; /* Set defaults for evaluator */
4976 staticAnalysis(RESET);
4982 static Void local addRSsigdecls(pr) /* add sigdecls from TYPE ... IN ..*/
4984 List vs = snd(pr); /* get list of variables */
4985 for (; nonNull(vs); vs=tl(vs)) {
4986 if (fst(hd(vs))==SIGDECL) { /* find a sigdecl */
4987 valDefns = cons(hd(vs),valDefns); /* add to valDefns */
4988 hd(vs) = hd(snd3(snd(hd(vs)))); /* and replace with var */
4993 static Void local allNoPrevDef(b) /* ensure no previous bindings for*/
4994 Cell b; { /* variables in new binding */
4995 if (isVar(fst(b))) {
4996 noPrevDef(rhsLine(snd(hd(snd(snd(b))))),fst(b));
4998 Int line = rhsLine(snd(snd(snd(b))));
4999 map1Proc(noPrevDef,line,fst(b));
5003 static Void local noPrevDef(line,v) /* ensure no previous binding for */
5004 Int line; /* new variable */
5006 Name n = findName(textOf(v));
5009 n = newName(textOf(v),NIL);
5010 name(n).defn = PREDEFINED;
5011 } else if (name(n).defn!=PREDEFINED) {
5012 duplicateError(line,name(n).mod,name(n).text,"variable");
5014 name(n).line = line;
5017 static Void local duplicateErrorAux(line,mod,t,kind)/* report duplicate defn */
5022 if (mod == currentModule) {
5023 ERRMSG(line) "Repeated definition for %s \"%s\"", kind,
5027 ERRMSG(line) "Definition of %s \"%s\" clashes with import", kind,
5033 static Void local checkTypeIn(cvs) /* Check that vars in restricted */
5034 Pair cvs; { /* synonym are defined */
5038 for (; nonNull(vs); vs=tl(vs)) {
5039 if (isNull(findName(textOf(hd(vs))))) {
5040 ERRMSG(tycon(c).line)
5041 "No top level binding of \"%s\" for restricted synonym \"%s\"",
5042 textToStr(textOf(hd(vs))), textToStr(tycon(c).text)
5048 /* --------------------------------------------------------------------------
5049 * Haskell 98 compatibility tests:
5050 * ------------------------------------------------------------------------*/
5052 Bool h98Pred(allowArgs,pi) /* Check syntax of Hask98 predicate*/
5055 return isClass(getHead(pi)) && argCount==1 &&
5056 isOffset(getHead(arg(pi))) && (argCount==0 || allowArgs);
5059 Cell h98Context(allowArgs,ps) /* Check syntax of Hask98 context */
5062 for (; nonNull(ps); ps=tl(ps)) {
5063 if (!h98Pred(allowArgs,hd(ps))) {
5070 Void h98CheckCtxt(line,wh,allowArgs,ps,in)
5071 Int line; /* Report illegal context/predicate*/
5077 Cell pi = h98Context(allowArgs,ps);
5079 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh ETHEN
5081 ERRTEXT "\n*** Instance : " ETHEN ERRPRED(inst(in).head);
5083 ERRTEXT "\n*** Constraint : " ETHEN ERRPRED(pi);
5084 if (nonNull(ps) && nonNull(tl(ps))) {
5085 ERRTEXT "\n*** Context : " ETHEN ERRCONTEXT(ps);
5093 Void h98CheckType(line,wh,e,t) /* Check for Haskell 98 type */
5102 if (isQualType(t)) {
5103 Cell pi = h98Context(TRUE,fst(snd(t)));
5105 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh
5107 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
5108 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(ty);
5116 Void h98DoesntSupport(line,wh) /* Report feature missing in H98 */
5120 ERRMSG(line) "Haskell 98 does not support %s", wh
5125 /* --------------------------------------------------------------------------
5126 * Static Analysis control:
5127 * ------------------------------------------------------------------------*/
5129 Void staticAnalysis(what)
5132 case RESET : cfunSfuns = NIL;
5145 case MARK : mark(daSccs);
5160 case INSTALL : staticAnalysis(RESET);
5162 extKind = pair(STAR,pair(ROW,ROW));
5168 /*-------------------------------------------------------------------------*/