2 /* --------------------------------------------------------------------------
3 * Static Analysis for Hugs
5 * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
6 * Yale Haskell Group, and the Oregon Graduate Institute of Science and
7 * Technology, 1994-1999, All rights reserved. It is distributed as
8 * free software under the license in the file "License", which is
9 * included in the distribution.
11 * $RCSfile: static.c,v $
13 * $Date: 2000/03/22 18:14:23 $
14 * ------------------------------------------------------------------------*/
21 /* --------------------------------------------------------------------------
22 * local function prototypes:
23 * ------------------------------------------------------------------------*/
25 static Void local kindError ( Int,Constr,Constr,String,Kind,Int );
26 static Void local checkQualImport ( Pair );
27 static Void local checkUnqualImport ( Triple );
29 static Name local lookupName ( Text,List );
30 static List local checkSubentities ( List,List,List,String,Text );
31 static List local checkExportTycon ( List,Text,Cell,Tycon );
32 static List local checkExportClass ( List,Text,Cell,Class );
33 static List local checkExport ( List,Text,Cell );
34 static List local checkImportEntity ( List,Module,Bool,Cell );
35 static List local resolveImportList ( Module,Cell,Bool );
36 static Void local checkImportList ( Pair );
38 static Void local importEntity ( Module,Cell );
39 static Void local importName ( Module,Name );
40 static Void local importTycon ( Module,Tycon );
41 static Void local importClass ( Module,Class );
42 static List local checkExports ( List, Module );
44 static Void local checkTyconDefn ( Tycon );
45 static Void local depConstrs ( Tycon,List,Cell );
46 static List local addSels ( Int,Name,List,List );
47 static List local selectCtxt ( List,List );
48 static Void local checkSynonyms ( List );
49 static List local visitSyn ( List,Tycon,List );
50 static Type local instantiateSyn ( Type,Type );
52 static Void local checkClassDefn ( Class );
53 static Cell local depPredExp ( Int,List,Cell );
54 static Void local checkMems ( Class,List,Cell );
55 static Void local checkMems2 ( Class,Cell );
56 static Void local addMembers ( Class );
57 static Name local newMember ( Int,Int,Cell,Type,Class );
58 static Text local generateText ( String,Class );
60 static List local classBindings ( String,Class,List );
61 static Name local memberName ( Class,Text );
62 static List local numInsert ( Int,Cell,List );
64 static List local maybeAppendVar ( Cell,List );
66 static Type local checkSigType ( Int,String,Cell,Type );
67 static Void local checkOptQuantVars ( Int,List,List );
68 static Type local depTopType ( Int,List,Type );
69 static Type local depCompType ( Int,List,Type );
70 static Type local depTypeExp ( Int,List,Type );
71 static Type local depTypeVar ( Int,List,Text );
72 static List local checkQuantVars ( Int,List,List,Cell );
73 static List local otvars ( Cell,List );
74 static Bool local osubset ( List,List );
75 static Void local kindConstr ( Int,Int,Int,Constr );
76 static Kind local kindAtom ( Int,Constr );
77 static Void local kindPred ( Int,Int,Int,Cell );
78 static Void local kindType ( Int,String,Type );
79 static Void local fixKinds ( Void );
81 static Void local kindTCGroup ( List );
82 static Void local initTCKind ( Cell );
83 static Void local kindTC ( Cell );
84 static Void local genTC ( Cell );
86 static Void local checkInstDefn ( Inst );
87 static Void local insertInst ( Inst );
88 static Bool local instCompare ( Inst,Inst );
89 static Name local newInstImp ( Inst );
90 static Void local kindInst ( Inst,Int );
91 static Void local checkDerive ( Tycon,List,List,Cell );
92 static Void local addDerInst ( Int,Class,List,List,Type,Int );
93 static Void local deriveContexts ( List );
94 static Void local initDerInst ( Inst );
95 static Void local calcInstPreds ( Inst );
96 static Void local maybeAddPred ( Cell,Int,Int,List );
97 static List local calcFunDeps ( List );
98 static Cell local copyAdj ( Cell,Int,Int );
99 static Void local tidyDerInst ( Inst );
100 static List local otvarsZonk ( Cell,List,Int );
102 static Void local addDerivImp ( Inst );
104 static Void local checkDefaultDefns ( Void );
106 static Void local checkForeignImport ( Name );
107 static Void local checkForeignExport ( Name );
109 static Cell local tidyInfix ( Int,Cell );
110 static Pair local attachFixity ( Int,Cell );
111 static Syntax local lookupSyntax ( Text );
113 static Cell local checkPat ( Int,Cell );
114 static Cell local checkMaybeCnkPat ( Int,Cell );
115 static Cell local checkApPat ( Int,Int,Cell );
116 static Void local addToPatVars ( Int,Cell );
117 static Name local conDefined ( Int,Cell );
118 static Void local checkIsCfun ( Int,Name );
119 static Void local checkCfunArgs ( Int,Cell,Int );
120 static Cell local checkPatType ( Int,String,Cell,Type );
121 static Cell local applyBtyvs ( Cell );
122 static Cell local bindPat ( Int,Cell );
123 static Void local bindPats ( Int,List );
125 static List local extractSigdecls ( List );
126 static List local extractFixdecls ( List );
127 static List local extractBindings ( List );
128 static List local getPatVars ( Int,Cell,List );
129 static List local addPatVar ( Int,Cell,List );
130 static List local eqnsToBindings ( List,List,List,List );
131 static Void local notDefined ( Int,List,Cell );
132 static Cell local findBinding ( Text,List );
133 static Cell local getAttr ( List,Cell );
134 static Void local addSigdecl ( List,Cell );
135 static Void local addFixdecl ( List,List,List,List,Triple );
136 static Void local dupFixity ( Int,Text );
137 static Void local missFixity ( Int,Text );
139 static List local dependencyAnal ( List );
140 static List local topDependAnal ( List );
141 static Void local addDepField ( Cell );
142 static Void local remDepField ( List );
143 static Void local remDepField1 ( Cell );
144 static Void local clearScope ( Void );
145 static Void local withinScope ( List );
146 static Void local leaveScope ( Void );
147 static Void local saveSyntax ( Cell,Cell );
149 static Void local depBinding ( Cell );
150 static Void local depDefaults ( Class );
151 static Void local depInsts ( Inst );
152 static Void local depClassBindings ( List );
153 static Void local depAlt ( Cell );
154 static Void local depRhs ( Cell );
155 static Void local depGuard ( Cell );
156 static Cell local depExpr ( Int,Cell );
157 static Void local depPair ( Int,Cell );
158 static Void local depTriple ( Int,Cell );
159 static Void local depComp ( Int,Cell,List );
160 static Void local depCaseAlt ( Int,Cell );
161 static Cell local depVar ( Int,Cell );
162 static Cell local depQVar ( Int,Cell );
163 static Void local depConFlds ( Int,Cell,Bool );
164 static Void local depUpdFlds ( Int,Cell );
165 static List local depFields ( Int,Cell,List,Bool );
167 static Void local depWith ( Int,Cell );
168 static List local depDwFlds ( Int,Cell,List );
171 static Cell local depRecord ( Int,Cell );
174 static List local tcscc ( List,List );
175 static List local bscc ( List );
177 static Void local addRSsigdecls ( Pair );
178 static Void local allNoPrevDef ( Cell );
179 static Void local noPrevDef ( Int,Cell );
180 static Bool local odiff ( List,List );
182 static Void local duplicateErrorAux ( Int,Module,Text,String );
183 #define duplicateError(l,m,t,k) duplicateErrorAux(l,m,t,k)
184 static Void local checkTypeIn ( Pair );
186 /* --------------------------------------------------------------------------
187 * The code in this file is arranged in roughly the following order:
188 * - Kind inference preliminaries
189 * - Module declarations
190 * - Type declarations (data, type, newtype, type in)
191 * - Class declarations
193 * - Instance declarations
194 * - Default declarations
195 * - Primitive definitions
197 * - Infix expressions
198 * - Value definitions
199 * - Top-level static analysis and control
200 * - Haskell 98 compatibility tests
201 * ------------------------------------------------------------------------*/
203 /* --------------------------------------------------------------------------
204 * Kind checking preliminaries:
205 * ------------------------------------------------------------------------*/
207 Bool kindExpert = FALSE; /* TRUE => display kind errors in */
210 static Void local kindError(l,c,in,wh,k,o)
211 Int l; /* line number near constuctor exp */
212 Constr c; /* constructor */
213 Constr in; /* context (if any) */
214 String wh; /* place in which error occurs */
215 Kind k; /* expected kind (k,o) */
216 Int o; { /* inferred kind (typeIs,typeOff) */
219 if (!kindExpert) { /* for those with a fear of kinds */
220 ERRMSG(l) "Illegal type" ETHEN
222 ERRTEXT " \"" ETHEN ERRTYPE(in);
225 ERRTEXT " in %s\n", wh
229 ERRMSG(l) "Kind error in %s", wh ETHEN
231 ERRTEXT "\n*** expression : " ETHEN ERRTYPE(in);
233 ERRTEXT "\n*** constructor : " ETHEN ERRTYPE(c);
234 ERRTEXT "\n*** kind : " ETHEN ERRKIND(copyType(typeIs,typeOff));
235 ERRTEXT "\n*** does not match : " ETHEN ERRKIND(copyType(k,o));
237 ERRTEXT "\n*** because : %s", unifyFails ETHEN
243 #define shouldKind(l,c,in,wh,k,o) if (!kunify(typeIs,typeOff,k,o)) \
244 kindError(l,c,in,wh,k,o)
245 #define checkKind(l,a,m,c,in,wh,k,o) kindConstr(l,a,m,c); \
246 shouldKind(l,c,in,wh,k,o)
247 #define inferKind(k,o) typeIs=k; typeOff=o
249 static List unkindTypes; /* types in need of kind annotation*/
251 Kind extKind; /* Kind of extension, *->row->row */
254 /* --------------------------------------------------------------------------
255 * Static analysis of modules:
256 * ------------------------------------------------------------------------*/
258 Void startModule ( Module m ) /* switch to a new module */
260 if (isNull(m)) internal("startModule");
264 Void setExportList(exps) /* Add export list to current module */
266 module(currentModule).exports = exps;
269 Void addQualImport(orig,new) /* Add to qualified import list */
270 Cell orig; /* Original name of module */
271 Cell new; { /* Name module is called within this module (or NIL) */
272 module(currentModule).qualImports =
273 cons(pair(isNull(new)?orig:new,orig),module(currentModule).qualImports);
276 Void addUnqualImport(mod,entities) /* Add to unqualified import list */
277 Cell mod; /* Name of module */
278 List entities; { /* List of entity names */
279 unqualImports = cons(pair(mod,entities),unqualImports);
282 static Void local checkQualImport(i) /* Process qualified import */
284 Module m = findModid(snd(i));
286 ERRMSG(0) "Module \"%s\" not previously loaded",
287 textToStr(textOf(snd(i)))
293 static Void local checkUnqualImport(i) /* Process unqualified import */
295 Module m = findModid(fst(i));
297 ERRMSG(0) "Module \"%s\" not previously loaded",
298 textToStr(textOf(fst(i)))
304 static Name local lookupName(t,nms) /* find text t in list of Names */
306 List nms; { /* :: [Name] */
307 for(; nonNull(nms); nms=tl(nms)) {
308 if (t == name(hd(nms)).text)
314 static List local checkSubentities(imports,named,wanted,description,textParent)
316 List named; /* :: [ Q?(Var|Con)(Id|Op) ] */
317 List wanted; /* :: [Name] */
318 String description; /* "<constructor>|<member> of <type>|<class>" */
320 for(; nonNull(named); named=tl(named)) {
322 /* ToDo: ignores qualifier; doesn't check that entity is in scope */
323 Text t = isPair(snd(x)) ? qtextOf(x) : textOf(x);
324 Name n = lookupName(t,wanted);
326 ERRMSG(0) "Entity \"%s\" is not a %s \"%s\"",
329 textToStr(textParent)
332 imports = cons(n,imports);
337 static List local checkImportEntity(imports,exporter,priv,entity)
338 List imports; /* Accumulated list of things to import */
341 Cell entity; { /* Entry from import list */
342 List oldImports = imports;
343 Text t = isIdent(entity) ? textOf(entity) : textOf(fst(entity));
346 es = module(exporter).names;
347 es = dupOnto(module(exporter).tycons,es);
348 es = dupOnto(module(exporter).classes,es);
350 es = module(exporter).exports;
353 for(; nonNull(es); es=tl(es)) {
354 Cell e = hd(es); /* :: Entity
355 | (Entity, NIL|DOTDOT)
362 if (tycon(f).text == t) {
363 imports = cons(f,imports);
364 if (!isIdent(entity)) {
365 switch (tycon(f).what) {
368 if (DOTDOT == snd(entity)) {
369 imports = dupOnto(tycon(f).defn,imports);
371 imports = checkSubentities(
372 imports,snd(entity),tycon(f).defn,
373 "constructor of type",t);
377 /* deliberate fall thru */
381 } else if (isClass(f)) {
382 if (cclass(f).text == t) {
383 imports = cons(f,imports);
384 if (!isIdent(entity)) {
385 if (DOTDOT == snd(entity)) {
386 return dupOnto(cclass(f).members,imports);
388 return checkSubentities(
389 imports,snd(entity),cclass(f).members,
390 "member of class",t);
395 internal("checkImportEntity2");
397 } else if (isName(e)) {
398 if (isIdent(entity) && name(e).text == t) {
399 imports = cons(e,imports);
401 } else if (isTycon(e) && priv) {
402 if (tycon(e).text == t) {
403 imports = cons(e,imports);
404 return dupOnto(tycon(e).defn,imports);
406 } else if (isClass(e) && priv) {
407 if (cclass(e).text == t) {
408 imports = cons(e,imports);
409 return dupOnto(cclass(e).members,imports);
411 } else if (whatIs(e) == TUPLE && priv) {
414 internal("checkImportEntity3");
417 if (imports == oldImports) {
418 ERRMSG(0) "Unknown entity \"%s\" imported from module \"%s\"",
420 textToStr(module(exporter ).text)
426 static List local resolveImportList(m,impList,priv)
427 Module m; /* exporting module */
431 if (DOTDOT == impList) {
432 List es = module(m).exports;
433 for(; nonNull(es); es=tl(es)) {
436 imports = cons(e,imports);
439 List subentities = NIL;
440 imports = cons(c,imports);
442 && (tycon(c).what == DATATYPE
443 || tycon(c).what == NEWTYPE))
444 subentities = tycon(c).defn;
446 subentities = cclass(c).members;
447 if (DOTDOT == snd(e)) {
448 imports = dupOnto(subentities,imports);
453 map2Accum(checkImportEntity,imports,m,priv,impList);
458 static Void local checkImportList(importSpec) /*Import a module unqualified*/
460 Module m = fst(importSpec);
461 Cell impList = snd(importSpec);
463 List imports = NIL; /* entities we want to import */
464 List hidden = NIL; /* entities we want to hide */
466 if (isPair(impList) && HIDDEN == fst(impList)) {
467 /* Somewhat inefficient - but obviously correct:
468 * imports = importsOf("module Foo") `setDifference` hidden;
470 hidden = resolveImportList(m, snd(impList),FALSE);
471 imports = resolveImportList(m, DOTDOT,FALSE);
472 } else if (isPair(impList) && STAR == fst(impList)) {
474 imports = resolveImportList(m, DOTDOT, FALSE);
475 privileged = resolveImportList(m, snd(impList),TRUE);
476 imports = dupOnto(privileged,imports);
478 imports = resolveImportList(m, impList,FALSE);
481 for(; nonNull(imports); imports=tl(imports)) {
482 Cell e = hd(imports);
483 if (!cellIsMember(e,hidden))
486 /* ToDo: hang onto the imports list for processing export list entries
487 * of the form "module Foo"
491 static Void local importEntity(source,e)
495 case NAME : importName(source,e);
498 case TYCON : importTycon(source,e);
500 case CLASS : importClass(source,e);
502 default: internal("importEntity");
506 static Void local importName(source,n)
509 Name clash = addName(n);
510 if (nonNull(clash) && clash!=n) {
511 ERRMSG(0) "Entity \"%s\" imported from module \"%s\""
512 " already defined in module \"%s\"",
513 textToStr(name(n).text),
514 textToStr(module(source).text),
515 textToStr(module(name(clash).mod).text)
520 static Void local importTycon(source,tc)
523 Tycon clash=addTycon(tc);
524 if (nonNull(clash) && clash!=tc) {
525 ERRMSG(0) "Tycon \"%s\" imported from \"%s\" already defined in module \"%s\"",
526 textToStr(tycon(tc).text),
527 textToStr(module(source).text),
528 textToStr(module(tycon(clash).mod).text)
531 if (nonNull(findClass(tycon(tc).text))) {
532 ERRMSG(0) "Import of type constructor \"%s\" clashes with class in module \"%s\"",
533 textToStr(tycon(tc).text),
534 textToStr(module(tycon(tc).mod).text)
539 static Void local importClass(source,c)
542 Class clash=addClass(c);
543 if (nonNull(clash) && clash!=c) {
544 ERRMSG(0) "Class \"%s\" imported from \"%s\" already defined in module \"%s\"",
545 textToStr(cclass(c).text),
546 textToStr(module(source).text),
547 textToStr(module(cclass(clash).mod).text)
550 if (nonNull(findTycon(cclass(c).text))) {
551 ERRMSG(0) "Import of class \"%s\" clashes with type constructor in module \"%s\"",
552 textToStr(cclass(c).text),
553 textToStr(module(source).text)
558 static List local checkExportTycon(exports,mt,spec,tc)
563 if (DOTDOT == spec || SYNONYM == tycon(tc).what) {
564 return cons(pair(tc,DOTDOT), exports);
566 return cons(pair(tc,NIL), exports);
570 static List local checkExportClass(exports,mt,spec,cl)
575 if (DOTDOT == spec) {
576 return cons(pair(cl,DOTDOT), exports);
578 return cons(pair(cl,NIL), exports);
582 static List local checkExport(exports,mt,e) /* Process entry in export list*/
588 List origExports = exports;
589 if (nonNull(export=findQualName(e))) {
590 exports=cons(export,exports);
592 if (isQCon(e) && nonNull(export=findQualTycon(e))) {
593 exports = checkExportTycon(exports,mt,NIL,export);
595 if (isQCon(e) && nonNull(export=findQualClass(e))) {
596 /* opaque class export */
597 exports = checkExportClass(exports,mt,NIL,export);
599 if (exports == origExports) {
600 ERRMSG(0) "Unknown entity \"%s\" exported from module \"%s\"",
606 } else if (MODULEENT == fst(e)) {
607 Module m = findModid(snd(e));
608 /* ToDo: shouldn't allow export of module we didn't import */
610 ERRMSG(0) "Unknown module \"%s\" exported from module \"%s\"",
611 textToStr(textOf(snd(e))),
615 if (m == currentModule) {
616 /* Exporting the current module exports local definitions */
618 for(xs=module(m).classes; nonNull(xs); xs=tl(xs)) {
619 if (cclass(hd(xs)).mod==m)
620 exports = checkExportClass(exports,mt,DOTDOT,hd(xs));
622 for(xs=module(m).tycons; nonNull(xs); xs=tl(xs)) {
623 if (tycon(hd(xs)).mod==m)
624 exports = checkExportTycon(exports,mt,DOTDOT,hd(xs));
626 for(xs=module(m).names; nonNull(xs); xs=tl(xs)) {
627 if (name(hd(xs)).mod==m)
628 exports = cons(hd(xs),exports);
631 /* Exporting other modules imports all things imported
632 * unqualified from it.
633 * ToDo: we reexport everything exported by a module -
634 * whether we imported it or not. This gives the wrong
635 * result for "module M(module N) where import N(x)"
637 exports = dupOnto(module(m).exports,exports);
641 Cell ident = fst(e); /* class name or type name */
642 Cell parts = snd(e); /* members or constructors */
644 if (isQCon(ident) && nonNull(nm=findQualTycon(ident))) {
645 switch (tycon(nm).what) {
648 ERRMSG(0) "Explicit constructor list given for type synonym"
649 " \"%s\" in export list of module \"%s\"",
654 return cons(pair(nm,DOTDOT),exports);
656 ERRMSG(0) "Transparent export of restricted type synonym"
657 " \"%s\" in export list of module \"%s\"",
661 return exports; /* Not reached */
665 return cons(pair(nm,DOTDOT),exports);
667 exports = checkSubentities(exports,parts,tycon(nm).defn,
668 "constructor of type",
670 return cons(pair(nm,DOTDOT), exports);
673 internal("checkExport1");
675 } else if (isQCon(ident) && nonNull(nm=findQualClass(ident))) {
676 if (DOTDOT == parts) {
677 return cons(pair(nm,DOTDOT),exports);
679 exports = checkSubentities(exports,parts,cclass(nm).members,
680 "member of class",cclass(nm).text);
681 return cons(pair(nm,DOTDOT), exports);
684 ERRMSG(0) "Explicit export list given for non-class/datatype \"%s\" in export list of module \"%s\"",
690 return exports; /* NOTUSED */
693 static List local checkExports ( List exports, Module thisModule )
695 Module m = thisModule;
696 Text mt = module(m).text;
699 map1Accum(checkExport,es,mt,exports);
702 for(xs=es; nonNull(xs); xs=tl(xs)) {
703 Printf(" %s", textToStr(textOfEntity(hd(xs))));
710 /* --------------------------------------------------------------------------
711 * Static analysis of type declarations:
713 * Type declarations come in two forms:
714 * - data declarations - define new constructed data types
715 * - type declarations - define new type synonyms
717 * A certain amount of work is carried out as the declarations are
718 * read during parsing. In particular, for each type constructor
719 * definition encountered:
720 * - check that there is no previous definition of constructor
721 * - ensure type constructor not previously used as a class name
722 * - make a new entry in the type constructor table
723 * - record line number of declaration
724 * - Build separate lists of newly defined constructors for later use.
725 * ------------------------------------------------------------------------*/
727 Void tyconDefn(line,lhs,rhs,what) /* process new type definition */
728 Int line; /* definition line number */
729 Cell lhs; /* left hand side of definition */
730 Cell rhs; /* right hand side of definition */
731 Cell what; { /* SYNONYM/DATATYPE/etc... */
732 Text t = textOf(getHead(lhs));
734 if (nonNull(findTycon(t))) {
735 ERRMSG(line) "Repeated definition of type constructor \"%s\"",
739 else if (nonNull(findClass(t))) {
740 ERRMSG(line) "\"%s\" used as both class and type constructor",
745 Tycon nw = newTycon(t);
746 tyconDefns = cons(nw,tyconDefns);
747 tycon(nw).line = line;
748 tycon(nw).arity = argCount;
749 tycon(nw).what = what;
750 if (what==RESTRICTSYN) {
751 h98DoesntSupport(line,"restricted type synonyms");
752 typeInDefns = cons(pair(nw,snd(rhs)),typeInDefns);
755 tycon(nw).defn = pair(lhs,rhs);
759 Void setTypeIns(bs) /* set local synonyms for given */
760 List bs; { /* binding group */
761 List cvs = typeInDefns;
762 for (; nonNull(cvs); cvs=tl(cvs)) {
763 Tycon c = fst(hd(cvs));
764 List vs = snd(hd(cvs));
765 for (tycon(c).what = RESTRICTSYN; nonNull(vs); vs=tl(vs)) {
766 if (nonNull(findBinding(textOf(hd(vs)),bs))) {
767 tycon(c).what = SYNONYM;
774 Void clearTypeIns() { /* clear list of local synonyms */
775 for (; nonNull(typeInDefns); typeInDefns=tl(typeInDefns))
776 tycon(fst(hd(typeInDefns))).what = RESTRICTSYN;
779 /* --------------------------------------------------------------------------
780 * Further analysis of Type declarations:
782 * In order to allow the definition of mutually recursive families of
783 * data types, the static analysis of the right hand sides of type
784 * declarations cannot be performed until all of the type declarations
787 * Once parsing is complete, we carry out the following:
789 * - check format of lhs, extracting list of bound vars and ensuring that
790 * there are no repeated variables and no Skolem variables.
791 * - run dependency analysis on rhs to check that only bound type vars
792 * appear in type and that all constructors are defined.
793 * Replace type variables by offsets, constructors by Tycons.
794 * - use list of dependents to sort into strongly connected components.
795 * - ensure that there is not more than one synonym in each group.
796 * - kind-check each group of type definitions.
798 * - check that there are no previous definitions for constructor
799 * functions in data type definitions.
800 * - install synonym expansions and constructor definitions.
801 * ------------------------------------------------------------------------*/
803 static List tcDeps = NIL; /* list of dependent tycons/classes*/
805 static Void local checkTyconDefn(d) /* validate type constructor defn */
807 Cell lhs = fst(tycon(d).defn);
808 Cell rhs = snd(tycon(d).defn);
809 Int line = tycon(d).line;
810 List tyvars = getArgs(lhs);
812 /* check for repeated tyvars on lhs*/
813 for (temp=tyvars; nonNull(temp); temp=tl(temp))
814 if (nonNull(varIsMember(textOf(hd(temp)),tl(temp)))) {
815 ERRMSG(line) "Repeated type variable \"%s\" on left hand side",
816 textToStr(textOf(hd(temp)))
820 tcDeps = NIL; /* find dependents */
821 switch (whatIs(tycon(d).what)) {
823 case SYNONYM : rhs = depTypeExp(line,tyvars,rhs);
824 if (cellIsMember(d,tcDeps)) {
825 ERRMSG(line) "Recursive type synonym \"%s\"",
826 textToStr(tycon(d).text)
832 case NEWTYPE : depConstrs(d,tyvars,rhs);
836 default : internal("checkTyconDefn");
841 tycon(d).kind = tcDeps;
845 static Void local depConstrs(t,tyvars,cd)
846 Tycon t; /* Define constructor functions and*/
847 List tyvars; /* do dependency analysis for data */
848 Cell cd; { /* definitions (w or w/o deriving) */
849 Int line = tycon(t).line;
854 List derivs = snd(cd);
855 List compTypes = NIL;
859 for (i=0; i<tycon(t).arity; ++i) /* build representation for tycon */
860 lhs = ap(lhs,mkOffset(i)); /* applied to full comp. of args */
862 if (isQualType(cs)) { /* allow for possible context */
865 map2Over(depPredExp,line,tyvars,ctxt);
866 h98CheckCtxt(line,"context",TRUE,ctxt,NIL);
869 if (nonNull(cs) && isNull(tl(cs))) /* Single constructor datatype? */
872 for (; nonNull(cs); cs=tl(cs)) { /* For each constructor function: */
874 List sig = dupList(tyvars);
875 List evs = NIL; /* locally quantified vars */
876 List lps = NIL; /* locally bound predicates */
877 List ctxt1 = ctxt; /* constructor function context */
878 List scs = NIL; /* strict components */
879 List fs = NONE; /* selector names */
880 Type type = lhs; /* constructor function type */
881 Int arity = 0; /* arity of constructor function */
882 Int nr2 = 0; /* Number of rank 2 args */
883 Name n; /* name for constructor function */
885 if (whatIs(con)==POLYTYPE) { /* Locally quantified vars */
888 sig = checkQuantVars(line,evs,sig,con);
891 if (isQualType(con)) { /* Local predicates */
894 for (us = typeVarsIn(lps,NIL,NIL,NIL); nonNull(us); us=tl(us))
895 if (!varIsMember(textOf(hd(us)),evs)) {
897 "Variable \"%s\" in constraint is not locally bound",
898 textToStr(textOf(hd(us)))
901 map2Over(depPredExp,line,sig,lps);
906 if (whatIs(con)==LABC) { /* Skeletize constr components */
907 Cell fls = snd(snd(con)); /* get field specifications */
910 for (; nonNull(fls); fls=tl(fls)) { /* for each field spec: */
911 List vs = fst(hd(fls));
912 Type t = snd(hd(fls)); /* - scrutinize type */
913 Bool banged = whatIs(t)==BANG;
914 t = depCompType(line,sig,(banged ? arg(t) : t));
915 while (nonNull(vs)) { /* - add named components */
923 scs = cons(mkInt(arity),scs);
927 scs = rev(scs); /* put strict comps in ascend ord */
929 else { /* Non-labelled constructor */
932 for (; isAp(c); c=fun(c))
934 for (compNo=arity, c=con; isAp(c); c=fun(c)) {
936 if (whatIs(t)==BANG) {
937 scs = cons(mkInt(compNo),scs);
941 arg(c) = depCompType(line,sig,t);
945 if (nonNull(ctxt1)) /* Extract relevant part of context*/
946 ctxt1 = selectCtxt(ctxt1,offsetTyvarsIn(con,NIL));
948 for (i=arity; isAp(con); i--) { /* Calculate type of constructor */
951 fun(con) = typeArrow;
952 if (isPolyOrQualType(cmp)) {
953 if (nonNull(derivs)) {
954 ERRMSG(line) "Cannot derive instances for types" ETHEN
955 ERRTEXT " with polymorphic or qualified components"
961 if (nonNull(derivs)) /* and build list of components */
962 compTypes = cons(cmp,compTypes);
967 if (nr2>0) { /* Add rank 2 annotation */
968 type = ap(RANK2,pair(mkInt(nr2-length(lps)),type));
971 if (nonNull(evs)) { /* Add existential annotation */
972 if (nonNull(derivs)) {
973 ERRMSG(line) "Cannot derive instances for types" ETHEN
974 ERRTEXT " with existentially typed components"
979 "Cannot use selectors with existentially typed components"
982 type = ap(EXIST,pair(mkInt(length(evs)),type));
985 if (nonNull(lps)) { /* Add local preds part to type */
986 type = ap(CDICTS,pair(lps,type));
989 if (nonNull(ctxt1)) { /* Add context part to type */
990 type = ap(QUAL,pair(ctxt1,type));
993 if (nonNull(sig)) { /* Add quantifiers to type */
995 for (; nonNull(ts1); ts1=tl(ts1)) {
998 type = mkPolyType(sig,type);
1001 n = findName(textOf(con)); /* Allocate constructor fun name */
1003 n = newName(textOf(con),NIL);
1004 } else if (name(n).defn!=PREDEFINED) {
1005 duplicateError(line,name(n).mod,name(n).text,
1006 "constructor function");
1008 name(n).arity = arity; /* Save constructor fun details */
1009 name(n).line = line;
1011 name(n).number = cfunNo(conNo++);
1012 name(n).type = type;
1013 if (tycon(t).what==NEWTYPE) {
1016 "A newtype constructor cannot have class constraints"
1021 "A newtype constructor must have exactly one argument"
1026 "Illegal strictess annotation for newtype constructor"
1029 name(n).defn = nameId;
1031 implementCfun(n,scs);
1036 sels = addSels(line,n,fs,sels);
1040 if (nonNull(sels)) {
1042 fst(cd) = appendOnto(fst(cd),sels);
1043 selDefns = cons(sels,selDefns);
1046 if (nonNull(derivs)) { /* Generate derived instances */
1047 map3Proc(checkDerive,t,ctxt,compTypes,derivs);
1051 Int userArity(c) /* Find arity for cfun, ignoring */
1052 Name c; { /* CDICTS parameters */
1053 Int a = name(c).arity;
1054 Type t = name(c).type;
1056 if (isPolyType(t)) {
1059 if ((w=whatIs(t))==QUAL) {
1060 w = whatIs(t=snd(snd(t)));
1063 a -= length(fst(snd(t)));
1069 static List local addSels(line,c,fs,ss) /* Add fields to selector list */
1070 Int line; /* line number of constructor */
1071 Name c; /* corresponding constr function */
1072 List fs; /* list of fields (varids) */
1073 List ss; { /* list of existing selectors */
1075 cfunSfuns = cons(pair(c,fs),cfunSfuns);
1076 for (; nonNull(fs); fs=tl(fs), ++sn) {
1078 Text t = textOf(hd(fs));
1080 if (nonNull(varIsMember(t,tl(fs)))) {
1081 ERRMSG(line) "Repeated field name \"%s\" for constructor \"%s\"",
1082 textToStr(t), textToStr(name(c).text)
1086 while (nonNull(ns) && t!=name(hd(ns)).text) {
1091 name(hd(ns)).defn = cons(pair(c,mkInt(sn)),name(hd(ns)).defn);
1093 Name n = findName(t);
1095 ERRMSG(line) "Repeated definition for selector \"%s\"",
1100 name(n).line = line;
1101 name(n).number = SELNAME;
1102 name(n).defn = singleton(pair(c,mkInt(sn)));
1109 static List local selectCtxt(ctxt,vs) /* calculate subset of context */
1116 for (; nonNull(ctxt); ctxt=tl(ctxt)) {
1117 List us = offsetTyvarsIn(hd(ctxt),NIL);
1118 for (; nonNull(us) && cellIsMember(hd(us),vs); us=tl(us)) {
1121 ps = cons(hd(ctxt),ps);
1128 static Void local checkSynonyms(ts) /* Check for mutually recursive */
1129 List ts; { /* synonyms */
1131 for (; nonNull(ts); ts=tl(ts)) { /* build list of all synonyms */
1133 switch (whatIs(tycon(t).what)) {
1135 case RESTRICTSYN : syns = cons(t,syns);
1139 while (nonNull(syns)) { /* then visit each synonym */
1140 syns = visitSyn(NIL,hd(syns),syns);
1144 static List local visitSyn(path,t,syns) /* visit synonym definition to look*/
1145 List path; /* for cycles */
1148 if (cellIsMember(t,path)) { /* every elt in path depends on t */
1149 ERRMSG(tycon(t).line)
1150 "Type synonyms \"%s\" and \"%s\" are mutually recursive",
1151 textToStr(tycon(t).text), textToStr(tycon(hd(path)).text)
1154 List ds = tycon(t).kind;
1156 for (; nonNull(ds); ds=tl(ds)) {
1157 if (cellIsMember(hd(ds),syns)) {
1158 if (isNull(path1)) {
1159 path1 = cons(t,path);
1161 syns = visitSyn(path1,hd(ds),syns);
1165 tycon(t).defn = fullExpand(tycon(t).defn);
1166 return removeCell(t,syns);
1169 /* --------------------------------------------------------------------------
1170 * Expanding out all type synonyms in a type expression:
1171 * ------------------------------------------------------------------------*/
1173 Type fullExpand(t) /* find full expansion of type exp */
1174 Type t; { /* assuming that all relevant */
1175 Cell h = t; /* synonym defns of lower rank have*/
1176 Int n = 0; /* already been fully expanded */
1178 for (args=NIL; isAp(h); h=fun(h), n++) {
1179 args = cons(fullExpand(arg(h)),args);
1181 t = applyToArgs(h,args);
1182 if (isSynonym(h) && n>=tycon(h).arity) {
1183 if (n==tycon(h).arity) {
1184 t = instantiateSyn(tycon(h).defn,t);
1187 while (--n > tycon(h).arity) {
1190 fun(p) = instantiateSyn(tycon(h).defn,fun(p));
1196 static Type local instantiateSyn(t,env) /* instantiate type according using*/
1197 Type t; /* env to determine appropriate */
1198 Type env; { /* values for OFFSET type vars */
1199 switch (whatIs(t)) {
1200 case AP : return ap(instantiateSyn(fun(t),env),
1201 instantiateSyn(arg(t),env));
1203 case OFFSET : return nthArg(offsetOf(t),env);
1209 /* --------------------------------------------------------------------------
1210 * Static analysis of class declarations:
1212 * Performed in a similar manner to that used for type declarations.
1214 * The first part of the static analysis is performed as the declarations
1215 * are read during parsing. The parser ensures that:
1216 * - the class header and all superclass predicates are of the form
1219 * The classDefn() function:
1220 * - ensures that there is no previous definition for class
1221 * - checks that class name has not previously been used as a type constr.
1222 * - make new entry in class table
1223 * - record line number of declaration
1224 * - build list of classes defined in current script for use in later
1225 * stages of static analysis.
1226 * ------------------------------------------------------------------------*/
1228 Void classDefn(line,head,ms,fds) /* process new class definition */
1229 Int line; /* definition line number */
1230 Cell head; /* class header :: ([Supers],Class) */
1231 List ms; /* class definition body */
1232 List fds; { /* functional dependencies */
1233 Text ct = textOf(getHead(snd(head)));
1234 Int arity = argCount;
1236 if (nonNull(findClass(ct))) {
1237 ERRMSG(line) "Repeated definition of class \"%s\"",
1240 } else if (nonNull(findTycon(ct))) {
1241 ERRMSG(line) "\"%s\" used as both class and type constructor",
1245 Class nw = newClass(ct);
1246 cclass(nw).line = line;
1247 cclass(nw).arity = arity;
1248 cclass(nw).head = snd(head);
1249 cclass(nw).supers = fst(head);
1250 cclass(nw).members = ms;
1251 cclass(nw).level = 0;
1252 cclass(nw).fds = fds;
1253 cclass(nw).xfds = NIL;
1254 classDefns = cons(nw,classDefns);
1256 h98DoesntSupport(line,"multiple parameter classes");
1260 /* --------------------------------------------------------------------------
1261 * Further analysis of class declarations:
1263 * Full static analysis of class definitions must be postponed until the
1264 * complete script has been read and all static analysis on type definitions
1265 * has been completed.
1267 * Once this has been achieved, we carry out the following checks on each
1269 * - check that variables in header are distinct
1270 * - replace head by skeleton
1271 * - check superclass declarations, replace by skeletons
1272 * - split body of class into members and declarations
1273 * - make new name entry for each member function
1274 * - record member function number (eventually an offset into dictionary!)
1275 * - no member function has a previous definition ...
1276 * - no member function is mentioned more than once in the list of members
1277 * - each member function type is valid, replace vars by offsets
1278 * - qualify each member function type by class header
1279 * - only bindings for members appear in defaults
1280 * - only function bindings appear in defaults
1281 * - check that extended class hierarchy does not contain any cycles
1282 * ------------------------------------------------------------------------*/
1284 static Void local checkClassDefn(c) /* validate class definition */
1287 Int args = cclass(c).arity - 1;
1288 Cell temp = cclass(c).head;
1292 for (; isAp(temp); temp=fun(temp)) {
1293 if (!isVar(arg(temp))) {
1294 ERRMSG(cclass(c).line) "Type variable required in class head"
1297 if (nonNull(varIsMember(textOf(arg(temp)),tyvars))) {
1298 ERRMSG(cclass(c).line)
1299 "Repeated type variable \"%s\" in class head",
1300 textToStr(textOf(arg(temp)))
1303 tyvars = cons(arg(temp),tyvars);
1306 for (fs=cclass(c).fds; nonNull(fs); fs=tl(fs)) {
1310 /* Check for trivial dependency
1313 ERRMSG(cclass(c).line) "Functional dependency is trivial"
1317 /* Check for duplicated vars on right hand side, and for vars on
1318 * right that also appear on the left:
1320 for (vs=snd(fd); nonNull(vs); vs=tl(vs)) {
1321 if (varIsMember(textOf(hd(vs)),fst(fd))) {
1322 ERRMSG(cclass(c).line)
1323 "Trivial dependency for variable \"%s\"",
1324 textToStr(textOf(hd(vs)))
1327 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1328 ERRMSG(cclass(c).line)
1329 "Repeated variable \"%s\" in functional dependency",
1330 textToStr(textOf(hd(vs)))
1333 hd(vs) = depTypeVar(cclass(c).line,tyvars,textOf(hd(vs)));
1336 /* Check for duplicated vars on left hand side:
1338 for (vs=fst(fd); nonNull(vs); vs=tl(vs)) {
1339 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1340 ERRMSG(cclass(c).line)
1341 "Repeated variable \"%s\" in functional dependency",
1342 textToStr(textOf(hd(vs)))
1345 hd(vs) = depTypeVar(cclass(c).line,tyvars,textOf(hd(vs)));
1349 if (cclass(c).arity==0) {
1352 Int args = cclass(c).arity - 1;
1353 for (temp=cclass(c).head; args>0; temp=fun(temp), args--) {
1354 arg(temp) = mkOffset(args);
1356 arg(temp) = mkOffset(0);
1360 tcDeps = NIL; /* find dependents */
1361 map2Over(depPredExp,cclass(c).line,tyvars,cclass(c).supers);
1362 h98CheckCtxt(cclass(c).line,"class definition",FALSE,cclass(c).supers,NIL);
1363 cclass(c).numSupers = length(cclass(c).supers);
1364 cclass(c).defaults = extractBindings(cclass(c).members); /* defaults*/
1365 ss = extractSigdecls(cclass(c).members);
1366 fs = extractFixdecls(cclass(c).members);
1367 cclass(c).members = pair(ss,fs);
1368 map2Proc(checkMems,c,tyvars,ss);
1370 cclass(c).kinds = tcDeps;
1375 /* --------------------------------------------------------------------------
1376 * Functional dependencies are inherited from superclasses.
1377 * For example, if I've got the following classes:
1379 * class C a b | a -> b
1380 * class C [b] a => D a b
1382 * then C will have the dependency ([a], [b]) as expected, and D will inherit
1383 * the dependency ([b], [a]) from C.
1384 * When doing pairwise improvement, we have to consider not just improving
1385 * when we see a pair of Cs or a pair of Ds in the context, but when we've
1386 * got a C and a D as well. In this case, we only improve when the
1387 * predicate in question matches the type skeleton in the relevant superclass
1388 * constraint. E.g., we improve the pair (C [Int] a, D b Int) (unifying
1389 * a and b), but we don't improve the pair (C Int a, D b Int).
1390 * To implement functional dependency inheritance, we calculate
1391 * the closure of all functional dependencies, and store the result
1392 * in an additional field `xfds' (extended functional dependencies).
1393 * The `xfds' field is a list of functional dependency lists, annotated
1394 * with a list of predicate skeletons constraining when improvement can
1395 * happen against this dependency list. For example, the xfds field
1396 * for C above would be:
1397 * [([C a b], [([a], [b])])]
1398 * and the xfds field for D would be:
1399 * [([C [b] a, D a b], [([b], [a])])]
1400 * Self-improvement (of a C with a C, or a D with a D) is treated as a
1401 * special case of an inherited dependency.
1402 * ------------------------------------------------------------------------*/
1403 static List local inheritFundeps ( Class c, Cell pi, Int o )
1405 Int alpha = newKindedVars(cclass(c).kinds);
1406 List scs = cclass(c).supers;
1409 /* better not fail ;-) */
1410 if (!matchPred(pi,o,cclass(c).head,alpha))
1411 internal("inheritFundeps - predicate failed to match it's own head!");
1412 this = copyPred(pi,o);
1413 for (; nonNull(scs); scs=tl(scs)) {
1414 Class s = getHead(hd(scs));
1416 List sfds = inheritFundeps(s,hd(scs),alpha);
1417 for (; nonNull(sfds); sfds=tl(sfds)) {
1419 xfds = cons(pair(cons(this,fst(h)),snd(h)),xfds);
1423 if (nonNull(cclass(c).fds)) {
1424 List fds = NIL, fs = cclass(c).fds;
1425 for (; nonNull(fs); fs=tl(fs)) {
1426 fds = cons(pair(otvars(this,fst(hd(fs))),
1427 otvars(this,snd(hd(fs)))),fds);
1429 xfds = cons(pair(cons(this,NIL),fds),xfds);
1434 static Void local extendFundeps ( Class c )
1437 emptySubstitution();
1438 alpha = newKindedVars(cclass(c).kinds);
1439 cclass(c).xfds = inheritFundeps(c,cclass(c).head,alpha);
1441 /* we can now check for ambiguity */
1442 map1Proc(checkMems2,c,fst(cclass(c).members));
1446 static Cell local depPredExp(line,tyvars,pred)
1453 for (; isAp(h); args++) {
1454 arg(h) = depTypeExp(line,tyvars,arg(h));
1460 h98DoesntSupport(line,"tag classes");
1461 } else if (args!=1) {
1462 h98DoesntSupport(line,"multiple parameter classes");
1465 if (isQCon(h)) { /* standard class constraint */
1466 Class c = findQualClass(h);
1468 ERRMSG(line) "Undefined class \"%s\"", identToStr(h)
1476 if (args!=cclass(c).arity) {
1477 ERRMSG(line) "Wrong number of arguments for class \"%s\"",
1478 textToStr(cclass(c).text)
1481 if (cellIsMember(c,classDefns) && !cellIsMember(c,tcDeps)) {
1482 tcDeps = cons(c,tcDeps);
1486 else if (isExt(h)) { /* Lacks predicate */
1487 if (args!=1) { /* parser shouldn't let this happen*/
1488 ERRMSG(line) "Wrong number of arguments for lacks predicate"
1495 if (whatIs(h) != IPCELL)
1498 internal("depPredExp");
1503 static Void local checkMems(c,tyvars,m) /* check member function details */
1507 Int line = intOf(fst3(m));
1514 if (isPolyType(t)) {
1520 tyvars = typeVarsIn(t,NIL,xtvs,tyvars);
1521 /* Look for extra type vars. */
1522 checkOptQuantVars(line,xtvs,tyvars);
1524 if (isQualType(t)) { /* Overloaded member signatures? */
1525 map2Over(depPredExp,line,tyvars,fst(snd(t)));
1527 t = ap(QUAL,pair(NIL,t));
1530 fst(snd(t)) = cons(cclass(c).head,fst(snd(t)));/* Add main predicate */
1531 snd(snd(t)) = depTopType(line,tyvars,snd(snd(t)));
1533 for (tvs=tyvars; nonNull(tvs); tvs=tl(tvs)){/* Quantify */
1537 t = mkPolyType(sig,t);
1539 thd3(m) = t; /* Save type */
1540 take(cclass(c).arity,tyvars); /* Delete extra type vars */
1542 if (isAmbiguous(t)) {
1543 ambigError(line,"class declaration",hd(vs),t);
1545 h98CheckType(line,"member type",hd(vs),t);
1548 static Void local checkMems2(c,m) /* check member function details */
1551 Int line = intOf(fst3(m));
1556 static Void local addMembers(c) /* Add definitions of member funs */
1557 Class c; { /* and other parts of class struct.*/
1558 List ms = fst(cclass(c).members);
1559 List fs = snd(cclass(c).members);
1560 List ns = NIL; /* List of names */
1561 Int mno; /* Member function number */
1563 for (mno=0; mno<cclass(c).numSupers; mno++) {
1564 ns = cons(newDSel(c,mno),ns);
1566 cclass(c).dsels = rev(ns); /* Save dictionary selectors */
1568 for (mno=1, ns=NIL; nonNull(ms); ms=tl(ms)) {
1569 Int line = intOf(fst3(hd(ms)));
1570 List vs = rev(snd3(hd(ms)));
1571 Type t = thd3(hd(ms));
1572 for (; nonNull(vs); vs=tl(vs)) {
1573 ns = cons(newMember(line,mno++,hd(vs),t,c),ns);
1576 cclass(c).members = rev(ns); /* Save list of members */
1577 cclass(c).numMembers = length(cclass(c).members);
1579 for (; nonNull(fs); fs=tl(fs)) { /* fixity declarations */
1580 Int line = intOf(fst3(hd(fs)));
1581 List ops = snd3(hd(fs));
1582 Syntax s = intOf(thd3(hd(fs)));
1583 for (; nonNull(ops); ops=tl(ops)) {
1584 Name n = nameIsMember(textOf(hd(ops)),cclass(c).members);
1586 missFixity(line,textOf(hd(ops)));
1587 } else if (name(n).syntax!=NO_SYNTAX) {
1588 dupFixity(line,textOf(hd(ops)));
1594 /* Not actually needed just yet; for the time being, dictionary code will
1595 not be passed through the type checker.
1597 cclass(c).dtycon = addPrimTycon(generateText("Dict.%s",c),
1604 mno = cclass(c).numSupers + cclass(c).numMembers;
1605 /* cclass(c).dcon = addPrimCfun(generateText("Make.%s",c),mno,0,NIL); */
1606 cclass(c).dcon = addPrimCfun(generateText(":D%s",c),mno,0,NIL);
1607 /* implementCfun(cclass(c).dcon,NIL);
1608 Don't manufacture a wrapper fn for dictionary constructors.
1609 Applications of dictionary constructors are always saturated,
1610 and translate.c:stgExpr() special-cases saturated constructor apps.
1613 if (mno==1) { /* Single entry dicts use newtype */
1614 name(cclass(c).dcon).defn = nameId;
1615 if (nonNull(cclass(c).members)) {
1616 name(hd(cclass(c).members)).number = mfunNo(0);
1619 cclass(c).defaults = classBindings("class",c,cclass(c).defaults);
1622 static Name local newMember(l,no,v,t,parent)
1623 Int l; /* Make definition for member fn */
1628 Name m = findName(textOf(v));
1631 m = newName(textOf(v),parent);
1632 } else if (name(m).defn!=PREDEFINED) {
1633 ERRMSG(l) "Repeated definition for member function \"%s\"",
1634 textToStr(name(m).text)
1640 name(m).number = mfunNo(no);
1645 Name newDSel(c,no) /* Make definition for dict selectr*/
1651 /* sprintf(buf,"sc%d.%s",no,"%s"); */
1652 sprintf(buf,"$p%d%s",no+1,"%s");
1653 s = newName(generateText(buf,c),c);
1654 name(s).line = cclass(c).line;
1656 name(s).number = DFUNNAME;
1662 static Text local generateText(sk,c) /* We need to generate names for */
1663 String sk; /* certain objects corresponding */
1664 Class c; { /* to each class. */
1665 String cname = textToStr(cclass(c).text);
1666 char buffer[MAX_GEN+1];
1668 if ((strlen(sk)+strlen(cname))>=MAX_GEN) {
1669 ERRMSG(0) "Please use a shorter name for class \"%s\"", cname
1672 sprintf(buffer,sk,cname);
1673 return findText(buffer);
1676 Int visitClass(c) /* visit class defn to check that */
1677 Class c; { /* class hierarchy is acyclic */
1679 if (isExt(c)) { /* special case for lacks preds */
1683 if (cclass(c).level < 0) { /* already visiting this class? */
1684 ERRMSG(cclass(c).line) "Class hierarchy for \"%s\" is not acyclic",
1685 textToStr(cclass(c).text)
1687 } else if (cclass(c).level == 0) { /* visiting class for first time */
1688 List scs = cclass(c).supers;
1690 cclass(c).level = (-1);
1691 for (; nonNull(scs); scs=tl(scs)) {
1692 Int l = visitClass(getHead(hd(scs)));
1695 cclass(c).level = 1+lev; /* level = 1 + max level of supers */
1697 return cclass(c).level;
1700 /* --------------------------------------------------------------------------
1701 * Process class and instance declaration binding groups:
1702 * ------------------------------------------------------------------------*/
1704 static List local classBindings(where,c,bs)
1705 String where; /* Check validity of bindings bs */
1706 Class c; /* for class c (or an inst of c) */
1707 List bs; { /* sort into approp. member order */
1710 for (; nonNull(bs); bs=tl(bs)) {
1712 Cell body = snd(snd(b));
1715 if (!isVar(fst(b))) { /* Only allow function bindings */
1716 ERRMSG(rhsLine(snd(body)))
1717 "Pattern binding illegal in %s declaration", where
1721 if (isNull(mnm=memberName(c,textOf(fst(b))))) {
1722 ERRMSG(rhsLine(snd(hd(body))))
1723 "No member \"%s\" in class \"%s\"",
1724 textToStr(textOf(fst(b))), textToStr(cclass(c).text)
1728 nbs = numInsert(mfunOf(mnm)-1,b,nbs);
1733 static Name local memberName(c,t) /* return name of member function */
1734 Class c; /* with name t in class c */
1735 Text t; { /* return NIL if not a member */
1736 List ms = cclass(c).members;
1737 for (; nonNull(ms); ms=tl(ms)) {
1738 if (t==name(hd(ms)).text) {
1745 static List local numInsert(n,x,xs) /* insert x at nth position in xs, */
1746 Int n; /* filling gaps with NIL */
1749 List start = isNull(xs) ? cons(NIL,NIL) : xs;
1751 for (xs=start; 0<n--; xs=tl(xs)) {
1752 if (isNull(tl(xs))) {
1753 tl(xs) = cons(NIL,NIL);
1760 /* --------------------------------------------------------------------------
1761 * Calculate set of variables appearing in a given type expression (possibly
1762 * qualified) as a list of distinct values. The order in which variables
1763 * appear in the list is the same as the order in which those variables
1764 * occur in the type expression when read from left to right.
1765 * ------------------------------------------------------------------------*/
1767 List local typeVarsIn(ty,us,ws,vs) /*Calculate list of type variables*/
1768 Cell ty; /* used in type expression, reading*/
1769 List us; /* from left to right ignoring any */
1770 List ws; /* listed in us. */
1771 List vs; { /* ws = explicitly quantified vars */
1772 if (isNull(ty)) return vs;
1773 switch (whatIs(ty)) {
1774 case DICTAP : return typeVarsIn(snd(snd(ty)),us,ws,vs);
1775 case UNBOXEDTUP: return typeVarsIn(snd(ty),us,ws,vs);
1777 case AP : return typeVarsIn(snd(ty),us,ws,
1778 typeVarsIn(fst(ty),us,ws,vs));
1781 case VAROPCELL : if ((nonNull(findBtyvs(textOf(ty)))
1782 && !varIsMember(textOf(ty),ws))
1783 || varIsMember(textOf(ty),us)) {
1786 return maybeAppendVar(ty,vs);
1789 case POLYTYPE : return typeVarsIn(monotypeOf(ty),polySigOf(ty),ws,vs);
1791 case QUAL : { vs = typeVarsIn(fst(snd(ty)),us,ws,vs);
1792 return typeVarsIn(snd(snd(ty)),us,ws,vs);
1795 case BANG : return typeVarsIn(snd(ty),us,ws,vs);
1797 case LABC : { List fs = snd(snd(ty));
1798 for (; nonNull(fs); fs=tl(fs)) {
1799 vs = typeVarsIn(snd(hd(fs)),us,ws,vs);
1806 case QUALIDENT: return vs;
1808 default: fprintf(stderr, " bad tag = %d\n", whatIs(ty));internal("typeVarsIn");
1813 static List local maybeAppendVar(v,vs) /* append variable to list if not */
1814 Cell v; /* already included */
1820 while (nonNull(c)) {
1821 if (textOf(hd(c))==t) {
1829 tl(p) = cons(v,NIL);
1837 /* --------------------------------------------------------------------------
1838 * Static analysis for type expressions is required to:
1839 * - ensure that each type constructor or class used has been defined.
1840 * - replace type variables by offsets, constructor names by Tycons.
1841 * - ensure that the type is well-kinded.
1842 * ------------------------------------------------------------------------*/
1844 static Type local checkSigType(line,where,e,type)
1845 Int line; /* Check validity of type expr in */
1846 String where; /* explicit type signature */
1853 if (isPolyType(type)) {
1854 xtvs = fst(snd(type));
1855 type = monotypeOf(type);
1857 tvs = typeVarsIn(type,NIL,xtvs,NIL);
1859 checkOptQuantVars(line,xtvs,tvs);
1861 if (isQualType(type)) {
1862 map2Over(depPredExp,line,tvs,fst(snd(type)));
1863 snd(snd(type)) = depTopType(line,tvs,snd(snd(type)));
1865 if (isAmbiguous(type)) {
1866 ambigError(line,where,e,type);
1869 type = depTopType(line,tvs,type);
1873 if (length(tvs) >= (OFF_MAX-OFF_MIN+1)) {
1874 ERRMSG(line) "Too many type variables in %s\n", where
1878 for (; nonNull(ts); ts=tl(ts)) {
1881 type = mkPolyType(tvs,type);
1886 kindType(line,"type expression",type);
1890 h98CheckType(line,where,e,type);
1894 static Void local checkOptQuantVars(line,xtvs,tvs)
1896 List xtvs; /* Explicitly quantified vars */
1897 List tvs; { /* Implicitly quantified vars */
1898 if (nonNull(xtvs)) {
1900 for (; nonNull(vs); vs=tl(vs)) {
1901 if (!varIsMember(textOf(hd(vs)),xtvs)) {
1902 ERRMSG(line) "Quantifier does not mention type variable \"%s\"",
1903 textToStr(textOf(hd(vs)))
1907 for (vs=xtvs; nonNull(vs); vs=tl(vs)) {
1908 if (!varIsMember(textOf(hd(vs)),tvs)) {
1909 ERRMSG(line) "Quantified type variable \"%s\" is not used",
1910 textToStr(textOf(hd(vs)))
1913 if (varIsMember(textOf(hd(vs)),tl(vs))) {
1914 ERRMSG(line) "Quantified type variable \"%s\" is repeated",
1915 textToStr(textOf(hd(vs)))
1922 static Type local depTopType(l,tvs,t) /* Check top-level of type sig */
1930 for (; getHead(t1)==typeArrow && argCount==2; ++i) {
1931 arg(fun(t1)) = depCompType(l,tvs,arg(fun(t1)));
1932 if (isPolyOrQualType(arg(fun(t1)))) {
1938 if (nonNull(prev)) {
1939 arg(prev) = depTypeExp(l,tvs,t1);
1941 t = depTypeExp(l,tvs,t1);
1944 t = ap(RANK2,pair(mkInt(nr2),t));
1949 static Type local depCompType(l,tvs,t) /* Check component type for constr */
1953 Int ntvs = length(tvs);
1955 if (isPolyType(t)) {
1956 List vs = fst(snd(t));
1958 tvs = checkQuantVars(l,vs,tvs,t);
1959 nfr = replicate(length(vs),NIL);
1961 if (isQualType(t)) {
1962 map2Over(depPredExp,l,tvs,fst(snd(t)));
1963 snd(snd(t)) = depTypeExp(l,tvs,snd(snd(t)));
1964 if (isAmbiguous(t)) {
1965 ambigError(l,"type component",NIL,t);
1968 t = depTypeExp(l,tvs,t);
1974 return mkPolyType(nfr,t);
1977 static Type local depTypeExp(line,tyvars,type)
1981 switch (whatIs(type)) {
1982 case AP : fst(type) = depTypeExp(line,tyvars,fst(type));
1983 snd(type) = depTypeExp(line,tyvars,snd(type));
1986 case VARIDCELL : return depTypeVar(line,tyvars,textOf(type));
1988 case QUALIDENT : if (isQVar(type)) {
1989 ERRMSG(line) "Qualified type variables not allowed"
1992 /* deliberate fall through */
1993 case CONIDCELL : { Tycon tc = findQualTycon(type);
1996 "Undefined type constructor \"%s\"",
2000 if (cellIsMember(tc,tyconDefns) &&
2001 !cellIsMember(tc,tcDeps)) {
2002 tcDeps = cons(tc,tcDeps);
2008 case EXT : h98DoesntSupport(line,"extensible records");
2013 default : internal("depTypeExp");
2018 static Type local depTypeVar(line,tyvars,tv)
2025 for (; nonNull(tyvars); offset++) {
2026 if (tv==textOf(hd(tyvars))) {
2029 tyvars = tl(tyvars);
2032 Cell vt = findBtyvs(tv);
2036 ERRMSG(line) "Undefined type variable \"%s\"", textToStr(tv)
2039 return mkOffset(found);
2042 static List local checkQuantVars(line,vs,tvs,body)
2044 List vs; /* variables to quantify over */
2045 List tvs; /* variables already in scope */
2046 Cell body; { /* type/constr for scope of vars */
2048 List bvs = typeVarsIn(body,NIL,NIL,NIL);
2050 for (; nonNull(us); us=tl(us)) {
2051 Text u = textOf(hd(us));
2052 if (varIsMember(u,tl(us))) {
2053 ERRMSG(line) "Duplicated quantified variable %s",
2058 if (varIsMember(u,tvs)) {
2059 ERRMSG(line) "Local quantifier for %s hides an outer use",
2064 if (!varIsMember(u,bvs)) {
2065 ERRMSG(line) "Locally quantified variable %s is not used",
2070 tvs = appendOnto(tvs,vs);
2075 /* --------------------------------------------------------------------------
2076 * Check for ambiguous types:
2077 * A type Preds => type is ambiguous if not (TV(P) `subset` TV(type))
2078 * ------------------------------------------------------------------------*/
2080 List offsetTyvarsIn(t,vs) /* add list of offset tyvars in t */
2081 Type t; /* to list vs */
2083 switch (whatIs(t)) {
2084 case AP : return offsetTyvarsIn(fun(t),
2085 offsetTyvarsIn(arg(t),vs));
2087 case OFFSET : if (cellIsMember(t,vs))
2092 case QUAL : return offsetTyvarsIn(snd(t),vs);
2094 case POLYTYPE : return offsetTyvarsIn(monotypeOf(t),vs);
2095 /* slightly inaccurate, but won't matter here */
2098 case RANK2 : return offsetTyvarsIn(snd(snd(t)),vs);
2100 default : return vs;
2104 List zonkTyvarsIn(t,vs)
2107 switch (whatIs(t)) {
2108 case AP : return zonkTyvarsIn(fun(t),
2109 zonkTyvarsIn(arg(t),vs));
2111 case INTCELL : if (cellIsMember(t,vs))
2116 /* this case will lead to a type error --
2117 much better than reporting an internal error ;-) */
2118 /* case OFFSET : internal("zonkTyvarsIn"); */
2120 default : return vs;
2124 static List local otvars(pi,os) /* os is a list of offsets that */
2125 Cell pi; /* refer to the arguments of pi; */
2126 List os; { /* find list of offsets in those */
2127 List us = NIL; /* positions */
2128 for (; nonNull(os); os=tl(os)) {
2129 us = offsetTyvarsIn(nthArg(offsetOf(hd(os)),pi),us);
2134 static List local otvarsZonk(pi,os,o) /* same as above, but zonks */
2138 for (; nonNull(os); os=tl(os)) {
2139 Type t = zonkType(nthArg(offsetOf(hd(os)),pi),o);
2140 us = zonkTyvarsIn(t,us);
2145 static Bool local odiff(us,vs)
2147 while (nonNull(us) && cellIsMember(hd(us),vs)) {
2153 static Bool local osubset(us,vs) /* Determine whether us is subset */
2154 List us, vs; { /* of vs */
2155 while (nonNull(us) && cellIsMember(hd(us),vs)) {
2161 List oclose(fds,vs) /* Compute closure of vs wrt to fds*/
2164 Bool changed = TRUE;
2168 while (nonNull(fds)) {
2170 List next = tl(fds);
2171 if (osubset(fst(fd),vs)) { /* Test if fd applies */
2173 for (; nonNull(os); os=tl(os)) {
2174 if (!cellIsMember(hd(os),vs)) {
2175 vs = cons(hd(os),vs);
2179 } else { /* Didn't apply this time, so keep */
2190 Bool isAmbiguous(type) /* Determine whether type is */
2191 Type type; { /* ambiguous */
2192 if (isPolyType(type)) {
2193 type = monotypeOf(type);
2195 if (isQualType(type)) { /* only qualified types can be */
2196 List ps = fst(snd(type)); /* ambiguous */
2197 List tvps = offsetTyvarsIn(ps,NIL);
2198 List tvts = offsetTyvarsIn(snd(snd(type)),NIL);
2199 List fds = calcFunDeps(ps);
2201 tvts = oclose(fds,tvts); /* Close tvts under fds */
2202 return !osubset(tvps,tvts);
2207 List calcFunDeps(ps)
2210 for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies */
2212 Cell c = getHead(pi);
2214 List xfs = cclass(c).xfds;
2215 for (; nonNull(xfs); xfs=tl(xfs)) {
2216 List fs = snd(hd(xfs));
2217 for (; nonNull(fs); fs=tl(fs)) {
2218 fds = cons(pair(otvars(pi,fst(hd(fs))),
2219 otvars(pi,snd(hd(fs)))),fds);
2225 fds = cons(pair(NIL,offsetTyvarsIn(arg(pi),NIL)),fds);
2232 List calcFunDepsPreds(ps)
2235 for (; nonNull(ps); ps=tl(ps)) {/* Calc functional dependencies */
2237 Cell pi = fst3(pi3);
2238 Cell c = getHead(pi);
2239 Int o = intOf(snd3(pi3));
2241 List xfs = cclass(c).xfds;
2242 for (; nonNull(xfs); xfs=tl(xfs)) {
2243 List fs = snd(hd(xfs));
2244 for (; nonNull(fs); fs=tl(fs)) {
2245 fds = cons(pair(otvarsZonk(pi,fst(hd(fs)),o),
2246 otvarsZonk(pi,snd(hd(fs)),o)),fds);
2252 fds = cons(pair(NIL,zonkTyvarsIn(arg(pi),NIL)),fds);
2259 Void ambigError(line,where,e,type) /* produce error message for */
2260 Int line; /* ambiguity */
2264 ERRMSG(line) "Ambiguous type signature in %s", where ETHEN
2265 ERRTEXT "\n*** ambiguous type : " ETHEN ERRTYPE(type);
2267 ERRTEXT "\n*** assigned to : " ETHEN ERREXPR(e);
2273 /* --------------------------------------------------------------------------
2274 * Kind inference for simple types:
2275 * ------------------------------------------------------------------------*/
2277 static Void local kindConstr(line,alpha,m,c)
2278 Int line; /* Determine kind of constructor */
2282 Cell h = getHead(c);
2286 Printf("kindConstr: alpha=%d, m=%d, c=",alpha,m);
2287 printType(stdout,c);
2291 switch (whatIs(h)) {
2292 case POLYTYPE : if (n!=0) {
2293 internal("kindConstr1");
2295 static String pt = "polymorphic type";
2296 Type t = dropRank1(c,alpha,m);
2297 Kinds ks = polySigOf(t);
2300 for (; isAp(ks); ks=tl(ks)) {
2303 beta = newKindvars(m1);
2304 unkindTypes = cons(pair(mkInt(beta),t),unkindTypes);
2305 checkKind(line,beta,m1,monotypeOf(t),NIL,pt,STAR,0);
2310 case QUAL : if (n!=0) {
2311 internal("kindConstr2");
2313 map3Proc(kindPred,line,alpha,m,fst(snd(c)));
2314 kindConstr(line,alpha,m,snd(snd(c)));
2318 case RANK2 : kindConstr(line,alpha,m,snd(snd(c)));
2322 case EXT : if (n!=2) {
2324 "Illegal use of row in " ETHEN ERRTYPE(c);
2331 case TYCON : if (isSynonym(h) && n<tycon(h).arity) {
2333 "Not enough arguments for type synonym \"%s\"",
2334 textToStr(tycon(h).text)
2340 if (n==0) { /* trivial case, no arguments */
2341 typeIs = kindAtom(alpha,c);
2342 } else { /* non-trivial application */
2343 static String app = "constructor application";
2353 typeIs = kindAtom(alpha,h); /* h :: v1 -> ... -> vn -> w */
2354 shouldKind(line,h,c,app,k,beta);
2356 for (i=n; i>0; --i) { /* ci :: vi for each 1 <- 1..n */
2357 checkKind(line,alpha,m,arg(a),c,app,aVar,beta+i-1);
2360 tyvarType(beta+n); /* inferred kind is w */
2364 static Kind local kindAtom(alpha,c) /* Find kind of atomic constructor */
2367 switch (whatIs(c)) {
2368 case TUPLE : return simpleKind(tupleOf(c)); /*(,)::* -> * -> * */
2369 case OFFSET : return mkInt(alpha+offsetOf(c));
2370 case TYCON : return tycon(c).kind;
2371 case INTCELL : return c;
2373 case VAROPCELL : { Cell vt = findBtyvs(textOf(c));
2379 case EXT : return extKind;
2383 Printf("kindAtom(%d,whatIs(%d)) on ",alpha,whatIs(c));
2384 printType(stdout,c);
2387 internal("kindAtom");
2388 return STAR;/* not reached */
2391 static Void local kindPred(l,alpha,m,pi)/* Check kinds of arguments in pred*/
2397 if (isAp(pi) && isExt(fun(pi))) {
2398 static String lackspred = "lacks predicate";
2399 checkKind(l,alpha,m,arg(pi),NIL,lackspred,ROW,0);
2404 if (isAp(pi) && whatIs(fun(pi)) == IPCELL) {
2405 static String ippred = "iparam predicate";
2406 checkKind(l,alpha,m,arg(pi),NIL,ippred,STAR,0);
2410 { static String predicate = "class constraint";
2411 Class c = getHead(pi);
2412 List as = getArgs(pi);
2413 Kinds ks = cclass(c).kinds;
2415 while (nonNull(ks)) {
2416 checkKind(l,alpha,m,hd(as),NIL,predicate,hd(ks),0);
2423 static Void local kindType(line,wh,type)/* check that (poss qualified) type*/
2424 Int line; /* is well-kinded */
2427 checkKind(line,0,0,type,NIL,wh,STAR,0);
2430 static Void local fixKinds() { /* add kind annotations to types */
2431 for (; nonNull(unkindTypes); unkindTypes=tl(unkindTypes)) {
2432 Pair pr = hd(unkindTypes);
2433 Int beta = intOf(fst(pr));
2434 Cell qts = polySigOf(snd(pr));
2436 if (isNull(hd(qts))) {
2437 hd(qts) = copyKindvar(beta++);
2439 internal("fixKinds");
2441 if (nonNull(tl(qts))) {
2449 Printf("Type expression: ");
2450 printType(stdout,snd(pr));
2452 printKind(stdout,polySigOf(snd(pr)));
2458 /* --------------------------------------------------------------------------
2459 * Kind checking of groups of type constructors and classes:
2460 * ------------------------------------------------------------------------*/
2462 static Void local kindTCGroup(tcs) /* find kinds for mutually rec. gp */
2463 List tcs; { /* of tycons and classes */
2464 emptySubstitution();
2466 mapProc(initTCKind,tcs);
2467 mapProc(kindTC,tcs);
2470 emptySubstitution();
2473 static Void local initTCKind(c) /* build initial kind/arity for c */
2475 if (isTycon(c)) { /* Initial kind of tycon is: */
2476 Int beta = newKindvars(1); /* v1 -> ... -> vn -> vn+1 */
2477 varKind(tycon(c).arity); /* where n is the arity of c. */
2478 bindTv(beta,typeIs,typeOff); /* For data definitions, vn+1 == * */
2479 switch (whatIs(tycon(c).what)) {
2481 case DATATYPE : bindTv(typeOff+tycon(c).arity,STAR,0);
2483 tycon(c).kind = mkInt(beta);
2485 Int n = cclass(c).arity;
2486 Int beta = newKindvars(n);
2487 cclass(c).kinds = NIL;
2490 cclass(c).kinds = pair(mkInt(beta+n),cclass(c).kinds);
2495 static Void local kindTC(c) /* check each part of a tycon/class*/
2496 Cell c; { /* is well-kinded */
2498 static String cfun = "constructor function";
2499 static String tsyn = "synonym definition";
2500 Int line = tycon(c).line;
2501 Int beta = tyvar(intOf(tycon(c).kind))->offs;
2502 Int m = tycon(c).arity;
2503 switch (whatIs(tycon(c).what)) {
2505 case DATATYPE : { List cs = tycon(c).defn;
2506 if (isQualType(cs)) {
2507 map3Proc(kindPred,line,beta,m,
2509 tycon(c).defn = cs = snd(snd(cs));
2511 for (; hasCfun(cs); cs=tl(cs)) {
2512 kindType(line,cfun,name(hd(cs)).type);
2517 default : checkKind(line,beta,m,tycon(c).defn,NIL,
2521 else { /* scan type exprs in class defn to*/
2522 List ms = fst(cclass(c).members);
2523 Int m = cclass(c).arity; /* determine the class signature */
2524 Int beta = newKindvars(m);
2525 kindPred(cclass(c).line,beta,m,cclass(c).head);
2526 map3Proc(kindPred,cclass(c).line,beta,m,cclass(c).supers);
2527 for (; nonNull(ms); ms=tl(ms)) {
2528 Int line = intOf(fst3(hd(ms)));
2529 Type type = thd3(hd(ms));
2530 kindType(line,"member function type signature",type);
2535 static Void local genTC(c) /* generalise kind inferred for */
2536 Cell c; { /* given tycon/class */
2538 tycon(c).kind = copyKindvar(intOf(tycon(c).kind));
2540 Printf("%s :: ",textToStr(tycon(c).text));
2541 printKind(stdout,tycon(c).kind);
2545 Kinds ks = cclass(c).kinds;
2546 for (; nonNull(ks); ks=tl(ks)) {
2547 hd(ks) = copyKindvar(intOf(hd(ks)));
2550 Printf("%s :: ",textToStr(cclass(c).text));
2551 printKinds(stdout,cclass(c).kinds);
2557 /* --------------------------------------------------------------------------
2558 * Static analysis of instance declarations:
2560 * The first part of the static analysis is performed as the declarations
2561 * are read during parsing:
2562 * - make new entry in instance table
2563 * - record line number of declaration
2564 * - build list of instances defined in current script for use in later
2565 * stages of static analysis.
2566 * ------------------------------------------------------------------------*/
2568 Void instDefn(line,head,ms) /* process new instance definition */
2569 Int line; /* definition line number */
2570 Cell head; /* inst header :: (context,Class) */
2571 List ms; { /* instance members */
2572 Inst nw = newInst();
2573 inst(nw).line = line;
2574 inst(nw).specifics = fst(head);
2575 inst(nw).head = snd(head);
2576 inst(nw).implements = ms;
2577 instDefns = cons(nw,instDefns);
2580 /* --------------------------------------------------------------------------
2581 * Further static analysis of instance declarations:
2583 * Makes the following checks:
2584 * - Class part of header has form C (T a1 ... an) where C is a known
2585 * class, and T is a known datatype constructor (or restricted synonym),
2586 * and there is no previous C-T instance, and (T a1 ... an) has a kind
2587 * appropriate for the class C.
2588 * - Each element of context is a valid class expression, with type vars
2589 * drawn from a1, ..., an.
2590 * - All bindings are function bindings
2591 * - All bindings define member functions for class C
2592 * - Arrange bindings into appropriate order for member list
2593 * - No top level type signature declarations
2594 * ------------------------------------------------------------------------*/
2596 Bool allowOverlap = FALSE; /* TRUE => allow overlapping insts */
2597 Name nameListMonad = NIL; /* builder function for List Monad */
2599 static Void local checkInstDefn(in) /* Validate instance declaration */
2601 Int line = inst(in).line;
2602 List tyvars = typeVarsIn(inst(in).head,NIL,NIL,NIL);
2603 List tvps = NIL, tvts = NIL;
2606 if (haskell98) { /* Check for `simple' type */
2608 Cell t = arg(inst(in).head);
2609 for (; isAp(t); t=fun(t)) {
2610 if (!isVar(arg(t))) {
2612 "syntax error in instance head (variable expected)"
2615 if (varIsMember(textOf(arg(t)),tvs)) {
2616 ERRMSG(line) "repeated type variable \"%s\" in instance head",
2617 textToStr(textOf(arg(t)))
2620 tvs = cons(arg(t),tvs);
2624 "syntax error in instance head (constructor expected)"
2629 /* add in the tyvars from the `specifics' so that we don't
2630 prematurely complain about undefined tyvars */
2631 tyvars = typeVarsIn(inst(in).specifics,NIL,NIL,tyvars);
2632 inst(in).head = depPredExp(line,tyvars,inst(in).head);
2635 Type h = getHead(arg(inst(in).head));
2637 ERRMSG(line) "Cannot use type synonym in instance head"
2642 map2Over(depPredExp,line,tyvars,inst(in).specifics);
2644 /* OK, now we start over, and test for ambiguity */
2645 tvts = offsetTyvarsIn(inst(in).head,NIL);
2646 tvps = offsetTyvarsIn(inst(in).specifics,NIL);
2647 fds = calcFunDeps(inst(in).specifics);
2648 tvts = oclose(fds,tvts);
2649 tvts = odiff(tvps,tvts);
2650 if (!isNull(tvts)) {
2651 ERRMSG(line) "Undefined type variable \"%s\"",
2652 textToStr(textOf(nth(offsetOf(hd(tvts)),tyvars)))
2656 h98CheckCtxt(line,"instance definition",FALSE,inst(in).specifics,NIL);
2657 inst(in).numSpecifics = length(inst(in).specifics);
2658 inst(in).c = getHead(inst(in).head);
2659 if (!isClass(inst(in).c)) {
2660 ERRMSG(line) "Illegal predicate in instance declaration"
2664 if (nonNull(cclass(inst(in).c).fds)) {
2665 List fds = cclass(inst(in).c).fds;
2666 for (; nonNull(fds); fds=tl(fds)) {
2667 List as = otvars(inst(in).head, fst(hd(fds)));
2668 List bs = otvars(inst(in).head, snd(hd(fds)));
2669 List fs = calcFunDeps(inst(in).specifics);
2671 if (!osubset(bs,as)) {
2672 ERRMSG(inst(in).line)
2673 "Instance is more general than a dependency allows"
2675 ERRTEXT "\n*** Instance : "
2676 ETHEN ERRPRED(inst(in).head);
2677 ERRTEXT "\n*** For class : "
2678 ETHEN ERRPRED(cclass(inst(in).c).head);
2679 ERRTEXT "\n*** Under dependency : "
2680 ETHEN ERRFD(hd(fds));
2687 kindInst(in,length(tyvars));
2690 if (nonNull(extractSigdecls(inst(in).implements))) {
2692 "Type signature declarations not permitted in instance declaration"
2695 if (nonNull(extractFixdecls(inst(in).implements))) {
2697 "Fixity declarations not permitted in instance declaration"
2700 inst(in).implements = classBindings("instance",
2702 extractBindings(inst(in).implements));
2703 inst(in).builder = newInstImp(in);
2704 if (!preludeLoaded && isNull(nameListMonad) && isAp(inst(in).head)
2705 && fun(inst(in).head)==classMonad && arg(inst(in).head)==typeList) {
2706 nameListMonad = inst(in).builder;
2710 static Void local insertInst(in) /* Insert instance into class */
2712 Class c = inst(in).c;
2713 List ins = cclass(c).instances;
2716 if (nonNull(cclass(c).fds)) { /* Check for conflicts with fds */
2717 List ins1 = cclass(c).instances;
2718 for (; nonNull(ins1); ins1=tl(ins1)) {
2719 List fds = cclass(c).fds;
2720 substitution(RESET);
2721 for (; nonNull(fds); fds=tl(fds)) {
2722 Int alpha = newKindedVars(inst(in).kinds);
2723 Int beta = newKindedVars(inst(hd(ins1)).kinds);
2724 List as = fst(hd(fds));
2726 for (; same && nonNull(as); as=tl(as)) {
2727 Int n = offsetOf(hd(as));
2728 same &= unify(nthArg(n,inst(in).head),alpha,
2729 nthArg(n,inst(hd(ins1)).head),beta);
2731 if (isNull(as) && same) {
2732 for (as=snd(hd(fds)); same && nonNull(as); as=tl(as)) {
2733 Int n = offsetOf(hd(as));
2734 same &= sameType(nthArg(n,inst(in).head),alpha,
2735 nthArg(n,inst(hd(ins1)).head),beta);
2738 ERRMSG(inst(in).line)
2739 "Instances are not consistent with dependencies"
2741 ERRTEXT "\n*** This instance : "
2742 ETHEN ERRPRED(inst(in).head);
2743 ERRTEXT "\n*** Conflicts with : "
2744 ETHEN ERRPRED(inst(hd(ins)).head);
2745 ERRTEXT "\n*** For class : "
2746 ETHEN ERRPRED(cclass(c).head);
2747 ERRTEXT "\n*** Under dependency : "
2748 ETHEN ERRFD(hd(fds));
2758 substitution(RESET);
2759 while (nonNull(ins)) { /* Look for overlap w/ other insts */
2760 Int alpha = newKindedVars(inst(in).kinds);
2761 Int beta = newKindedVars(inst(hd(ins)).kinds);
2762 if (unifyPred(inst(in).head,alpha,inst(hd(ins)).head,beta)) {
2763 Cell pi = copyPred(inst(in).head,alpha);
2764 if (allowOverlap && !haskell98) {
2765 Bool bef = instCompare(in,hd(ins));
2766 Bool aft = instCompare(hd(ins),in);
2767 if (bef && !aft) { /* in comes strictly before hd(ins)*/
2770 if (aft && !bef) { /* in comes strictly after hd(ins) */
2777 if (multiInstRes && nonNull(inst(in).specifics)) {
2781 ERRMSG(inst(in).line) "Overlapping instances for class \"%s\"",
2782 textToStr(cclass(c).text)
2784 ERRTEXT "\n*** This instance : " ETHEN ERRPRED(inst(in).head);
2785 ERRTEXT "\n*** Overlaps with : " ETHEN
2786 ERRPRED(inst(hd(ins)).head);
2787 ERRTEXT "\n*** Common instance : " ETHEN
2795 prev = ins; /* No overlap detected, so move on */
2796 ins = tl(ins); /* to next instance */
2798 substitution(RESET);
2800 if (nonNull(prev)) { /* Insert instance at this point */
2801 tl(prev) = cons(in,ins);
2803 cclass(c).instances = cons(in,ins);
2807 static Bool local instCompare(ia,ib) /* See if ia is an instance of ib */
2809 Int alpha = newKindedVars(inst(ia).kinds);
2810 Int beta = newKindedVars(inst(ib).kinds);
2811 return matchPred(inst(ia).head,alpha,inst(ib).head,beta);
2814 static Name local newInstImp(in) /* Make definition for inst builder*/
2816 Name b = newName(inventText(),in);
2817 name(b).line = inst(in).line;
2818 name(b).arity = inst(in).numSpecifics;
2819 name(b).number = DFUNNAME;
2823 /* --------------------------------------------------------------------------
2824 * Kind checking of instance declaration headers:
2825 * ------------------------------------------------------------------------*/
2827 static Void local kindInst(in,freedom) /* check predicates in instance */
2832 emptySubstitution();
2833 beta = newKindvars(freedom);
2834 kindPred(inst(in).line,beta,freedom,inst(in).head);
2835 if (whatIs(inst(in).specifics)!=DERIVE) {
2836 map3Proc(kindPred,inst(in).line,beta,freedom,inst(in).specifics);
2838 for (inst(in).kinds = NIL; 0<freedom--; ) {
2839 inst(in).kinds = cons(copyKindvar(beta+freedom),inst(in).kinds);
2842 Printf("instance ");
2843 printPred(stdout,inst(in).head);
2845 printKinds(stdout,inst(in).kinds);
2848 emptySubstitution();
2851 /* --------------------------------------------------------------------------
2852 * Process derived instance requests:
2853 * ------------------------------------------------------------------------*/
2855 static List derivedInsts; /* list of derived instances */
2857 static Void local checkDerive(t,p,ts,ct)/* verify derived instance request */
2858 Tycon t; /* for tycon t, with explicit */
2859 List p; /* context p, component types ts */
2860 List ts; /* and named class ct */
2862 Int line = tycon(t).line;
2863 Class c = findQualClass(ct);
2865 ERRMSG(line) "Unknown class \"%s\" in derived instance",
2869 addDerInst(line,c,p,dupList(ts),t,tycon(t).arity);
2872 static Void local addDerInst(line,c,p,cts,t,a) /* Add a derived instance */
2879 Cell head = t; /* Build instance head */
2883 head = ap(head,mkOffset(i));
2889 inst(in).line = line;
2890 inst(in).head = head;
2891 inst(in).specifics = ap(DERIVE,pair(dupList(p),cts));
2892 inst(in).implements = NIL;
2893 inst(in).kinds = mkInt(a);
2894 derivedInsts = cons(in,derivedInsts);
2897 Void addTupInst(c,n) /* Request derived instance of c */
2898 Class c; /* for mkTuple(n) constructor */
2903 cts = cons(mkOffset(m),cts);
2906 addDerInst(0,c,NIL,cts,mkTuple(n),n);
2910 Inst addRecShowInst(c,e) /* Generate instance for ShowRecRow*/
2911 Class c; /* c *must* be ShowRecRow */
2913 Inst in = newInst();
2915 inst(in).head = ap(c,ap2(e,aVar,bVar));
2916 inst(in).kinds = extKind;
2917 inst(in).specifics = cons(ap(classShow,aVar),
2919 cons(ap(c,bVar),NIL)));
2920 inst(in).numSpecifics = 3;
2921 inst(in).builder = implementRecShw(extText(e),in);
2922 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2926 Inst addRecEqInst(c,e) /* Generate instance for EqRecRow */
2927 Class c; /* c *must* be EqRecRow */
2929 Inst in = newInst();
2931 inst(in).head = ap(c,ap2(e,aVar,bVar));
2932 inst(in).kinds = extKind;
2933 inst(in).specifics = cons(ap(classEq,aVar),
2935 cons(ap(c,bVar),NIL)));
2936 inst(in).numSpecifics = 3;
2937 inst(in).builder = implementRecEq(extText(e),in);
2938 cclass(c).instances = appendOnto(cclass(c).instances,singleton(in));
2943 /* --------------------------------------------------------------------------
2944 * Calculation of contexts for derived instances:
2946 * Allowing arbitrary types to appear in contexts makes it rather harder
2947 * to decide what the context for a derived instance should be. For
2950 * data T a = MkT [a] deriving Show,
2952 * we could have either of the following:
2954 * instance (Show [a]) => Show (T a) where ...
2955 * instance (Show a) => Show (T a) where ...
2957 * (assuming, of course, that instance (Show a) => Show [a]). For now, we
2958 * choose to reduce contexts in the hope of detecting errors at an earlier
2959 * stage---in contrast with value definitions, there is no way for a user
2960 * to provide something analogous to a `type signature' by which they might
2961 * be able to control this behaviour themselves. We eliminate tautological
2962 * predicates, but only allow predicates to appear in the final result if
2963 * they have at least one argument with a variable at its head.
2965 * In general, we have to deal with mutually recursive instance declarations.
2966 * We find a solution in the obvious way by iterating to find a fixed point.
2967 * Of course, without restrictions on the form of instance declarations, we
2968 * cannot be sure that this will always terminate!
2970 * For each instance we maintain a pair of the form DERIVE (ctxt,ps).
2971 * Ctxt is a list giving the parts of the context that have been produced
2972 * so far in the form of predicate skeletons. During the calculation of
2973 * derived instances, we attach a dummy NIL value to the end of the list
2974 * which acts as a kind of `variable': other parts of the system maintain
2975 * pointers to this variable, and use it to detect when the context has
2976 * been extended with new elements. Meanwhile, ps is a list containing
2977 * predicates (pi,o) together with (delayed) substitutions of the form
2978 * (o,xs) where o is an offset and xs is one of the context variables
2979 * described above, which may have been partially instantiated.
2980 * ------------------------------------------------------------------------*/
2982 static Bool instsChanged;
2984 static Void local deriveContexts(is) /* Calc contexts for derived insts */
2986 emptySubstitution();
2987 mapProc(initDerInst,is); /* Prepare derived instances */
2989 do { /* Main calculation of contexts */
2990 instsChanged = FALSE;
2991 mapProc(calcInstPreds,is);
2992 } while (instsChanged);
2994 mapProc(tidyDerInst,is); /* Tidy up results */
2997 static Void local initDerInst(in) /* Prepare instance for calculation*/
2998 Inst in; { /* of derived instance context */
2999 Cell spcs = inst(in).specifics;
3000 Int beta = newKindedVars(inst(in).kinds);
3001 if (whatIs(spcs)!=DERIVE) {
3002 internal("initDerInst");
3004 fst(snd(spcs)) = appendOnto(fst(snd(spcs)),singleton(NIL));
3005 for (spcs=snd(snd(spcs)); nonNull(spcs); spcs=tl(spcs)) {
3006 hd(spcs) = ap2(inst(in).c,hd(spcs),mkInt(beta));
3008 inst(in).numSpecifics = beta;
3010 #ifdef DEBUG_DERIVING
3011 Printf("initDerInst: ");
3012 printPred(stdout,inst(in).head);
3014 printContext(stdout,snd(snd(inst(in).specifics)));
3019 static Void local calcInstPreds(in) /* Calculate next approximation */
3020 Inst in; { /* of the context for a derived */
3021 List retain = NIL; /* instance */
3022 List ps = snd(snd(inst(in).specifics));
3023 List spcs = fst(snd(inst(in).specifics));
3024 Int beta = inst(in).numSpecifics;
3026 Int factor = 1+length(ps);
3028 #ifdef DEBUG_DERIVING
3029 Printf("calcInstPreds: ");
3030 printPred(stdout,inst(in).head);
3034 while (nonNull(ps)) {
3037 if (its++ >= factor*cutoff) {
3038 Cell bpi = inst(in).head;
3039 ERRMSG(inst(in).line) "\n*** Cannot derive " ETHEN ERRPRED(bpi);
3040 ERRTEXT " after %d iterations.", its-1 ETHEN
3042 "\n*** This may indicate that the problem is undecidable. However,\n"
3044 "*** you may still try to increase the cutoff limit using the -c\n"
3046 "*** option and then try again. (The current setting is -c%d)\n",
3050 if (isInt(fst(p))) { /* Delayed substitution? */
3052 for (; nonNull(hd(qs)); qs=tl(qs)) {
3053 ps = cons(pair(hd(qs),fst(p)),ps);
3055 retain = cons(pair(fst(p),qs),retain);
3058 else if (isExt(fun(fst(p)))) { /* Lacks predicate */
3059 Text l = extText(fun(fst(p)));
3060 Type t = arg(fst(p));
3061 Int o = intOf(snd(p));
3066 h = getDerefHead(t,o);
3067 while (isExt(h) && argCount==2 && l!=extText(h)) {
3070 h = getDerefHead(t,o);
3072 if (argCount==0 && isOffset(h)) {
3073 maybeAddPred(ap(fun(fun(p)),h),o,beta,spcs);
3074 } else if (argCount!=0 || h!=typeNoRow) {
3075 Cell bpi = inst(in).head;
3076 Cell pi = copyPred(fun(p),intOf(snd(p)));
3077 ERRMSG(inst(in).line) "Cannot derive " ETHEN ERRPRED(bpi);
3078 ERRTEXT " because predicate " ETHEN ERRPRED(pi);
3079 ERRTEXT " does not hold\n"
3084 else { /* Class predicate */
3086 Int o = intOf(snd(p));
3087 Inst in1 = findInstFor(pi,o);
3089 List qs = inst(in1).specifics;
3090 Int off = mkInt(typeOff);
3091 if (whatIs(qs)==DERIVE) { /* Still being derived */
3092 for (qs=fst(snd(qs)); nonNull(hd(qs)); qs=tl(qs)) {
3093 ps = cons(pair(hd(qs),off),ps);
3095 retain = cons(pair(off,qs),retain);
3096 } else { /* Previously def'd inst */
3097 for (; nonNull(qs); qs=tl(qs)) {
3098 ps = cons(pair(hd(qs),off),ps);
3101 } else { /* No matching instance */
3103 while (isAp(qi) && isOffset(getDerefHead(arg(qi),o))) {
3107 Cell bpi = inst(in).head;
3108 pi = copyPred(pi,o);
3109 ERRMSG(inst(in).line) "An instance of " ETHEN ERRPRED(pi);
3110 ERRTEXT " is required to derive " ETHEN ERRPRED(bpi);
3114 maybeAddPred(pi,o,beta,spcs);
3119 snd(snd(inst(in).specifics)) = retain;
3122 static Void local maybeAddPred(pi,o,beta,ps)
3123 Cell pi; /* Add predicate pi to the list ps,*/
3124 Int o; /* setting the instsChanged flag if*/
3125 Int beta; /* pi is not already a member and */
3126 List ps; { /* using beta to adjust vars */
3127 Cell c = getHead(pi);
3128 for (; nonNull(ps); ps=tl(ps)) {
3129 if (isNull(hd(ps))) { /* reached the `dummy' end of list?*/
3130 hd(ps) = copyAdj(pi,o,beta);
3131 tl(ps) = pair(NIL,NIL);
3132 instsChanged = TRUE;
3134 } else if (c==getHead(hd(ps)) && samePred(pi,o,hd(ps),beta)) {
3140 static Cell local copyAdj(c,o,beta) /* Copy (c,o), replacing vars with */
3141 Cell c; /* offsets relative to beta. */
3144 switch (whatIs(c)) {
3145 case AP : { Cell l = copyAdj(fst(c),o,beta);
3146 Cell r = copyAdj(snd(c),o,beta);
3150 case OFFSET : { Int vn = o+offsetOf(c);
3151 Tyvar *tyv = tyvar(vn);
3153 return copyAdj(tyv->bound,tyv->offs,beta);
3156 if (vn<0 || vn>=(OFF_MAX-OFF_MIN+1)) {
3157 internal("copyAdj");
3159 return mkOffset(vn);
3165 static Void local tidyDerInst(in) /* Tidy up results of derived inst */
3166 Inst in; { /* calculations */
3167 Int o = inst(in).numSpecifics;
3168 List ps = tl(rev(fst(snd(inst(in).specifics))));
3170 copyPred(inst(in).head,o);
3171 inst(in).specifics = simpleContext(ps,o);
3172 h98CheckCtxt(inst(in).line,"derived instance",FALSE,inst(in).specifics,in);
3173 inst(in).numSpecifics = length(inst(in).specifics);
3175 #ifdef DEBUG_DERIVING
3176 Printf("Derived instance: ");
3177 printContext(stdout,inst(in).specifics);
3179 printPred(stdout,inst(in).head);
3184 /* --------------------------------------------------------------------------
3185 * Generate code for derived instances:
3186 * ------------------------------------------------------------------------*/
3188 static Void local addDerivImp(in)
3191 Type t = getHead(arg(inst(in).head));
3192 Class c = inst(in).c;
3195 } else if (c==classOrd) {
3197 } else if (c==classEnum) {
3198 imp = deriveEnum(t);
3199 } else if (c==classIx) {
3201 } else if (c==classShow) {
3202 imp = deriveShow(t);
3203 } else if (c==classRead) {
3204 imp = deriveRead(t);
3205 } else if (c==classBounded) {
3206 imp = deriveBounded(t);
3208 ERRMSG(inst(in).line) "Cannot derive instances of class \"%s\"",
3209 textToStr(cclass(inst(in).c).text)
3213 kindInst(in,intOf(inst(in).kinds));
3215 inst(in).builder = newInstImp(in);
3216 inst(in).implements = classBindings("derived instance",
3222 /* --------------------------------------------------------------------------
3223 * Default definitions; only one default definition is permitted in a
3224 * given script file. If no default is supplied, then a standard system
3225 * default will be used where necessary.
3226 * ------------------------------------------------------------------------*/
3228 Void defaultDefn(line,defs) /* Handle default types definition */
3231 if (defaultLine!=0) {
3232 ERRMSG(line) "Multiple default declarations are not permitted in" ETHEN
3233 ERRTEXT "a single script file.\n"
3236 defaultDefns = defs;
3240 static Void local checkDefaultDefns() { /* check that default types are */
3241 List ds = NIL; /* well-kinded instances of Num */
3243 if (defaultLine!=0) {
3244 map2Over(depTypeExp,defaultLine,NIL,defaultDefns);
3245 emptySubstitution();
3247 map2Proc(kindType,defaultLine,"default type",defaultDefns);
3249 emptySubstitution();
3250 mapOver(fullExpand,defaultDefns);
3252 defaultDefns = stdDefaults;
3255 if (isNull(classNum)) {
3256 classNum = findClass(findText("Num"));
3259 for (ds=defaultDefns; nonNull(ds); ds=tl(ds)) {
3260 if (isNull(provePred(NIL,NIL,ap(classNum,hd(ds))))) {
3262 "Default types must be instances of the Num class"
3269 /* --------------------------------------------------------------------------
3270 * Foreign import declarations are Hugs' equivalent of GHC's ccall mechanism.
3271 * They are used to "import" C functions into a module.
3272 * They are usually not written by hand but, rather, generated automatically
3273 * by GreenCard, IDL compilers or whatever. We support foreign import
3274 * (static) and foreign import dynamic. In the latter case, extName==NIL.
3276 * Foreign export declarations generate C wrappers for Hugs functions.
3277 * Hugs only provides "foreign export dynamic" because it's not obvious
3278 * what "foreign export static" would mean in an interactive setting.
3279 * ------------------------------------------------------------------------*/
3281 Void foreignImport(line,callconv,extName,intName,type)
3282 /* Handle foreign imports */
3288 Text t = textOf(intName);
3289 Name n = findName(t);
3290 Int l = intOf(line);
3294 } else if (name(n).defn!=PREDEFINED) {
3295 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
3299 name(n).defn = extName;
3300 name(n).type = type;
3301 name(n).callconv = callconv;
3302 foreignImports = cons(n,foreignImports);
3305 static Void local checkForeignImport(p) /* Check foreign import */
3307 emptySubstitution();
3308 name(p).type = checkSigType(name(p).line,
3309 "foreign import declaration",
3312 /* We don't expand synonyms here because we don't want the IO
3313 * part to be expanded.
3314 * name(p).type = fullExpand(name(p).type);
3316 implementForeignImport(p);
3319 Void foreignExport(line,callconv,extName,intName,type)
3320 /* Handle foreign exports */
3326 Text t = textOf(intName);
3327 Name n = findName(t);
3328 Int l = intOf(line);
3332 } else if (name(n).defn!=PREDEFINED) {
3333 ERRMSG(l) "Redeclaration of foreign \"%s\"", textToStr(t)
3337 name(n).defn = NIL; /* nothing to say */
3338 name(n).type = type;
3339 name(n).callconv = callconv;
3340 foreignExports = cons(n,foreignExports);
3343 static Void local checkForeignExport(p) /* Check foreign export */
3345 emptySubstitution();
3346 name(p).type = checkSigType(name(p).line,
3347 "foreign export declaration",
3350 implementForeignExport(p);
3355 /* --------------------------------------------------------------------------
3356 * Static analysis of patterns:
3358 * Patterns are parsed as ordinary (atomic) expressions. Static analysis
3359 * makes the following checks:
3360 * - Patterns are well formed (according to pattern syntax), including the
3361 * special case of (n+k) patterns.
3362 * - All constructor functions have been defined and are used with the
3363 * correct number of arguments.
3364 * - No variable name is used more than once in a pattern.
3366 * The list of pattern variables occuring in each pattern is accumulated in
3367 * a global list `patVars', which must be initialised to NIL at appropriate
3368 * points before using these routines to check for valid patterns. This
3369 * mechanism enables the pattern checking routine to be mapped over a list
3370 * of patterns, ensuring that no variable occurs more than once in the
3371 * complete pattern list (as is required on the lhs of a function defn).
3372 * ------------------------------------------------------------------------*/
3374 static List patVars; /* List of vars bound in pattern */
3376 static Cell local checkPat(line,p) /* Check valid pattern syntax */
3379 switch (whatIs(p)) {
3381 case VAROPCELL : addToPatVars(line,p);
3384 case INFIX : return checkPat(line,tidyInfix(line,snd(p)));
3386 case AP : return checkMaybeCnkPat(line,p);
3391 case CONOPCELL : return checkApPat(line,0,p);
3396 case FLOATCELL : break;
3397 case INTCELL : break;
3399 case ASPAT : addToPatVars(line,fst(snd(p)));
3400 snd(snd(p)) = checkPat(line,snd(snd(p)));
3403 case LAZYPAT : snd(p) = checkPat(line,snd(p));
3406 case FINLIST : map1Over(checkPat,line,snd(p));
3409 case CONFLDS : depConFlds(line,p,TRUE);
3412 case ESIGN : snd(snd(p)) = checkPatType(line,
3416 fst(snd(p)) = checkPat(line,fst(snd(p)));
3419 default : ERRMSG(line) "Illegal pattern syntax"
3425 static Cell local checkMaybeCnkPat(l,p)/* Check applicative pattern with */
3426 Int l; /* the possibility of n+k pattern */
3428 Cell h = getHead(p);
3430 if (argCount==2 && isVar(h) && textOf(h)==textPlus) { /* n+k */
3431 Cell v = arg(fun(p));
3432 if (!isInt(arg(p))) {
3433 ERRMSG(l) "Second argument in (n+k) pattern must be an integer"
3436 if (intOf(arg(p))<=0) {
3437 ERRMSG(l) "Integer k in (n+k) pattern must be > 0"
3440 fst(fun(p)) = ADDPAT;
3441 intValOf(fun(p)) = intOf(arg(p));
3442 arg(p) = checkPat(l,v);
3445 return checkApPat(l,0,p);
3448 static Cell local checkApPat(line,args,p)
3449 Int line; /* check validity of application */
3450 Int args; /* of constructor to arguments */
3452 switch (whatIs(p)) {
3453 case AP : fun(p) = checkApPat(line,args+1,fun(p));
3454 arg(p) = checkPat(line,arg(p));
3457 case TUPLE : if (tupleOf(p)!=args) {
3458 ERRMSG(line) "Illegal tuple pattern"
3464 case EXT : h98DoesntSupport(line,"extensible records");
3466 ERRMSG(line) "Illegal record pattern"
3472 case QUALIDENT : if (!isQCon(p)) {
3474 "Illegal use of qualified variable in pattern"
3477 /* deliberate fall through */
3479 case CONOPCELL : p = conDefined(line,p);
3480 checkCfunArgs(line,p,args);
3483 case NAME : checkIsCfun(line,p);
3484 checkCfunArgs(line,p,args);
3487 default : ERRMSG(line) "Illegal pattern syntax"
3493 static Void local addToPatVars(line,v) /* Add variable v to list of vars */
3494 Int line; /* in current pattern, checking */
3495 Cell v; { /* for repeated variables. */
3500 for (; nonNull(n); p=n, n=tl(n)) {
3501 if (textOf(hd(n))==t) {
3502 ERRMSG(line) "Repeated variable \"%s\" in pattern",
3509 patVars = cons(v,NIL);
3511 tl(p) = cons(v,NIL);
3515 static Name local conDefined(line,nm) /* check that nm is the name of a */
3516 Int line; /* previously defined constructor */
3517 Cell nm; { /* function. */
3518 Name n = findQualName(nm);
3520 ERRMSG(line) "Undefined constructor function \"%s\"", identToStr(nm)
3523 checkIsCfun(line,n);
3527 static Void local checkIsCfun(line,c) /* Check that c is a constructor fn */
3531 ERRMSG(line) "\"%s\" is not a constructor function",
3532 textToStr(name(c).text)
3537 static Void local checkCfunArgs(line,c,args)
3538 Int line; /* Check constructor applied with */
3539 Cell c; /* correct number of arguments */
3541 Int a = userArity(c);
3544 "Constructor \"%s\" must have exactly %d argument%s in pattern",
3545 textToStr(name(c).text), a, ((a==1)?"":"s")
3550 static Cell local checkPatType(l,wh,e,t)/* Check type appearing in pattern */
3555 List tvs = typeVarsIn(t,NIL,NIL,NIL);
3556 h98DoesntSupport(l,"pattern type annotations");
3557 for (; nonNull(tvs); tvs=tl(tvs)) {
3558 Int beta = newKindvars(1);
3559 hd(btyvars) = cons(pair(hd(tvs),mkInt(beta)), hd(btyvars));
3561 t = checkSigType(l,"pattern type",e,t);
3562 if (isPolyOrQualType(t) || whatIs(t)==RANK2) {
3563 ERRMSG(l) "Illegal syntax in %s type annotation", wh
3569 static Cell local applyBtyvs(pat) /* Record bound type vars in pat */
3571 List bts = hd(btyvars);
3574 pat = ap(BIGLAM,pair(bts,pat));
3575 for (; nonNull(bts); bts=tl(bts)) {
3576 snd(hd(bts)) = copyKindvar(intOf(snd(hd(bts))));
3582 /* --------------------------------------------------------------------------
3583 * Maintaining lists of bound variables and local definitions, for
3584 * dependency and scope analysis.
3585 * ------------------------------------------------------------------------*/
3587 static List bounds; /* list of lists of bound vars */
3588 static List bindings; /* list of lists of binds in scope */
3589 static List depends; /* list of lists of dependents */
3591 /* bounds :: [[Var]] -- var equality used on Vars */
3592 /* bindings :: [[([Var],?)]] -- var equality used on Vars */
3593 /* depends :: [[Var]] -- pointer equality used on Vars */
3595 #define saveBvars() hd(bounds) /* list of bvars in current scope */
3596 #define restoreBvars(bs) hd(bounds)=bs /* restore list of bound variables */
3598 static Cell local bindPat(line,p) /* add new bound vars for pattern */
3602 p = checkPat(line,p);
3603 hd(bounds) = revOnto(patVars,hd(bounds));
3607 static Void local bindPats(line,ps) /* add new bound vars for patterns */
3611 map1Over(checkPat,line,ps);
3612 hd(bounds) = revOnto(patVars,hd(bounds));
3615 /* --------------------------------------------------------------------------
3616 * Before processing value and type signature declarations, all data and
3617 * type definitions have been processed so that:
3618 * - all valid type constructors (with their arities) are known.
3619 * - all valid constructor functions (with their arities and types) are
3622 * The result of parsing a list of value declarations is a list of Eqns:
3623 * Eqn ::= (SIGDECL,(Line,[Var],type))
3624 * | (FIXDECL,(Line,[Op],SyntaxInt))
3626 * The ordering of the equations in this list is the reverse of the original
3627 * ordering in the script parsed. This is a consequence of the structure of
3628 * the parser ... but also turns out to be most convenient for the static
3631 * As the first stage of the static analysis of value declarations, each
3632 * list of Eqns is converted to a list of Bindings. As part of this
3634 * - The ordering of the list of Bindings produced is the same as in the
3636 * - When a variable (function) is defined over a number of lines, all
3637 * of the definitions should appear together and each should give the
3638 * same arity to the variable being defined.
3639 * - No variable can have more than one definition.
3640 * - For pattern bindings:
3641 * - Each lhs is a valid pattern/function lhs, all constructor functions
3642 * have been defined and are used with the correct number of arguments.
3643 * - Each lhs contains no repeated pattern variables.
3644 * - Each equation defines at least one variable (e.g. True = False is
3646 * - Types appearing in type signatures are well formed:
3647 * - Type constructors used are defined and used with correct number
3649 * - type variables are replaced by offsets, type constructor names
3651 * - Every variable named in a type signature declaration is defined by
3652 * one or more equations elsewhere in the script.
3653 * - No variable has more than one type declaration.
3654 * - Similar properties for fixity declarations.
3656 * ------------------------------------------------------------------------*/
3658 #define bindingAttr(b) fst(snd(b)) /* type(s)/fixity(ies) for binding */
3659 #define fbindAlts(b) snd(snd(b)) /* alternatives for function binding*/
3661 static List local extractSigdecls(es) /* Extract the SIGDECLS from list */
3662 List es; { /* of equations */
3663 List sigdecls = NIL; /* :: [(Line,[Var],Type)] */
3665 for(; nonNull(es); es=tl(es)) {
3666 if (fst(hd(es))==SIGDECL) { /* type-declaration? */
3667 Pair sig = snd(hd(es));
3668 Int line = intOf(fst3(sig));
3669 List vs = snd3(sig);
3670 for(; nonNull(vs); vs=tl(vs)) {
3671 if (isQualIdent(hd(vs))) {
3672 ERRMSG(line) "Type signature for qualified variable \"%s\" is not allowed",
3677 sigdecls = cons(sig,sigdecls); /* discard SIGDECL tag*/
3683 static List local extractFixdecls(es) /* Extract the FIXDECLS from list */
3684 List es; { /* of equations */
3685 List fixdecls = NIL; /* :: [(Line,SyntaxInt,[Op])] */
3687 for(; nonNull(es); es=tl(es)) {
3688 if (fst(hd(es))==FIXDECL) { /* fixity declaration?*/
3689 fixdecls = cons(snd(hd(es)),fixdecls); /* discard FIXDECL tag*/
3695 static List local extractBindings(ds) /* extract untyped bindings from */
3696 List ds; { /* given list of equations */
3697 Cell lastVar = NIL; /* = var def'd in last eqn (if any)*/
3698 Int lastArity = 0; /* = number of args in last defn */
3699 List bs = NIL; /* :: [Binding] */
3701 for(; nonNull(ds); ds=tl(ds)) {
3703 if (fst(d)==FUNBIND) { /* Function bindings */
3704 Cell rhs = snd(snd(d));
3705 Int line = rhsLine(rhs);
3706 Cell lhs = fst(snd(d));
3707 Cell v = getHead(lhs);
3708 Cell newAlt = pair(getArgs(lhs),rhs);
3710 internal("FUNBIND");
3712 if (nonNull(lastVar) && textOf(v)==textOf(lastVar)) {
3713 if (argCount!=lastArity) {
3714 ERRMSG(line) "Equations give different arities for \"%s\"",
3715 textToStr(textOf(v))
3718 fbindAlts(hd(bs)) = cons(newAlt,fbindAlts(hd(bs)));
3722 lastArity = argCount;
3723 notDefined(line,bs,v);
3724 bs = cons(pair(v,pair(NIL,singleton(newAlt))),bs);
3727 } else if (fst(d)==PATBIND) { /* Pattern bindings */
3728 Cell rhs = snd(snd(d));
3729 Int line = rhsLine(rhs);
3730 Cell pat = fst(snd(d));
3731 while (whatIs(pat)==ESIGN) {/* Move type annotations to rhs */
3732 Cell p = fst(snd(pat));
3733 fst(snd(pat)) = rhs;
3734 snd(snd(d)) = rhs = pat;
3735 fst(snd(d)) = pat = p;
3738 if (isVar(pat)) { /* Convert simple pattern bind to */
3739 notDefined(line,bs,pat);/* a function binding */
3740 bs = cons(pair(pat,pair(NIL,singleton(pair(NIL,rhs)))),bs);
3742 List vs = getPatVars(line,pat,NIL);
3744 ERRMSG(line) "No variables defined in lhs pattern"
3747 map2Proc(notDefined,line,bs,vs);
3748 bs = cons(pair(vs,pair(NIL,snd(d))),bs);
3756 static List local getPatVars(line,p,vs) /* Find list of variables bound in */
3757 Int line; /* pattern p */
3760 switch (whatIs(p)) {
3762 vs = getPatVars(line,arg(p),vs);
3765 return vs; /* Ignore head of application */
3767 case CONFLDS : { List pfs = snd(snd(p));
3768 for (; nonNull(pfs); pfs=tl(pfs)) {
3769 if (isVar(hd(pfs))) {
3770 vs = addPatVar(line,hd(pfs),vs);
3772 vs = getPatVars(line,snd(hd(pfs)),vs);
3778 case FINLIST : { List ps = snd(p);
3779 for (; nonNull(ps); ps=tl(ps)) {
3780 vs = getPatVars(line,hd(ps),vs);
3785 case ESIGN : return getPatVars(line,fst(snd(p)),vs);
3790 case INFIX : return getPatVars(line,snd(p),vs);
3792 case ASPAT : return addPatVar(line,fst(snd(p)),
3793 getPatVars(line,snd(snd(p)),vs));
3796 case VAROPCELL : return addPatVar(line,p,vs);
3806 case WILDCARD : return vs;
3808 default : internal("getPatVars");
3813 static List local addPatVar(line,v,vs) /* Add var to list of previously */
3814 Int line; /* encountered variables */
3817 if (varIsMember(textOf(v),vs)) {
3818 ERRMSG(line) "Repeated use of variable \"%s\" in pattern binding",
3819 textToStr(textOf(v))
3825 static List local eqnsToBindings(es,ts,cs,ps)
3826 List es; /* Convert list of equations to */
3827 List ts; /* list of typed bindings */
3830 List bs = extractBindings(es);
3831 map1Proc(addSigdecl,bs,extractSigdecls(es));
3832 map4Proc(addFixdecl,bs,ts,cs,ps,extractFixdecls(es));
3836 static Void local notDefined(line,bs,v)/* check if name already defined in */
3837 Int line; /* list of bindings */
3840 if (nonNull(findBinding(textOf(v),bs))) {
3841 ERRMSG(line) "\"%s\" multiply defined", textToStr(textOf(v))
3846 static Cell local findBinding(t,bs) /* look for binding for variable t */
3847 Text t; /* in list of bindings bs */
3849 for (; nonNull(bs); bs=tl(bs)) {
3850 if (isVar(fst(hd(bs)))) { /* function-binding? */
3851 if (textOf(fst(hd(bs)))==t) {
3854 } else if (nonNull(varIsMember(t,fst(hd(bs))))){/* pattern-binding?*/
3861 static Cell local getAttr(bs,v) /* Locate type/fixity attribute */
3862 List bs; /* for variable v in bindings bs */
3865 Cell b = findBinding(t,bs);
3867 if (isNull(b)) { /* No binding */
3869 } else if (isVar(fst(b))) { /* func binding? */
3870 if (isNull(bindingAttr(b))) {
3871 bindingAttr(b) = pair(NIL,NIL);
3873 return bindingAttr(b);
3874 } else { /* pat binding? */
3876 List as = bindingAttr(b);
3879 bindingAttr(b) = as = replicate(length(vs),NIL);
3882 while (nonNull(vs) && t!=textOf(hd(vs))) {
3888 internal("getAttr");
3889 } else if (isNull(hd(as))) {
3890 hd(as) = pair(NIL,NIL);
3896 static Void local addSigdecl(bs,sigdecl)/* add type information to bindings*/
3897 List bs; /* :: [Binding] */
3898 Cell sigdecl; { /* :: (Line,[Var],Type) */
3899 Int l = intOf(fst3(sigdecl));
3900 List vs = snd3(sigdecl);
3901 Type type = checkSigType(l,"type declaration",hd(vs),thd3(sigdecl));
3903 for (; nonNull(vs); vs=tl(vs)) {
3905 Pair attr = getAttr(bs,v);
3907 ERRMSG(l) "Missing binding for variable \"%s\" in type signature",
3908 textToStr(textOf(v))
3910 } else if (nonNull(fst(attr))) {
3911 ERRMSG(l) "Repeated type signature for \"%s\"",
3912 textToStr(textOf(v))
3919 static Void local addFixdecl(bs,ts,cs,ps,fixdecl)
3925 Int line = intOf(fst3(fixdecl));
3926 List ops = snd3(fixdecl);
3927 Cell sy = thd3(fixdecl);
3929 for (; nonNull(ops); ops=tl(ops)) {
3931 Text t = textOf(op);
3932 Cell attr = getAttr(bs,op);
3933 if (nonNull(attr)) { /* Found name in binding? */
3934 if (nonNull(snd(attr))) {
3938 } else { /* Look in tycons, classes, prims */
3943 for (; isNull(n) && nonNull(ts1); ts1=tl(ts1)) { /* tycons */
3945 if (tycon(tc).what==DATATYPE || tycon(tc).what==NEWTYPE) {
3946 n = nameIsMember(t,tycon(tc).defn);
3949 for (; isNull(n) && nonNull(cs1); cs1=tl(cs1)) { /* classes */
3950 n = nameIsMember(t,cclass(hd(cs1)).members);
3952 for (; isNull(n) && nonNull(ps1); ps1=tl(ps1)) { /* prims */
3953 n = nameIsMember(t,hd(ps1));
3958 } else if (name(n).syntax!=NO_SYNTAX) {
3961 name(n).syntax = intOf(sy);
3966 static Void local dupFixity(line,t) /* Report repeated fixity decl */
3970 "Repeated fixity declaration for operator \"%s\"", textToStr(t)
3974 static Void local missFixity(line,t) /* Report missing op for fixity */
3978 "Cannot find binding for operator \"%s\" in fixity declaration",
3983 /* --------------------------------------------------------------------------
3984 * Dealing with infix operators:
3986 * Expressions involving infix operators or unary minus are parsed as
3987 * elements of the following type:
3989 * data InfixExp = Only Exp | Neg InfixExp | Infix InfixExp Op Exp
3991 * (The algorithms here do not assume that negation can be applied only once,
3992 * i.e., that - - x is a syntax error, as required by the Haskell report.
3993 * Instead, that restriction is captured by the grammar itself, given above.)
3995 * There are rules of precedence and grouping, expressed by two functions:
3997 * prec :: Op -> Int; assoc :: Op -> Assoc (Assoc = {L, N, R})
3999 * InfixExp values are rearranged accordingly when a complete expression
4000 * has been read using a simple shift-reduce parser whose result may be taken
4001 * to be a value of the following type:
4003 * data Exp = Atom Int | Negate Exp | Apply Op Exp Exp | Error String
4005 * The machine on which this parser is based can be defined as follows:
4007 * tidy :: InfixExp -> [(Op,Exp)] -> Exp
4008 * tidy (Only a) [] = a
4009 * tidy (Only a) ((o,b):ss) = tidy (Only (Apply o a b)) ss
4010 * tidy (Infix a o b) [] = tidy a [(o,b)]
4011 * tidy (Infix a o b) ((p,c):ss)
4012 * | shift o p = tidy a ((o,b):(p,c):ss)
4013 * | red o p = tidy (Infix a o (Apply p b c)) ss
4014 * | ambig o p = Error "ambiguous use of operators"
4015 * tidy (Neg e) [] = tidy (tidyNeg e) []
4016 * tidy (Neg e) ((o,b):ss)
4017 * | nshift o = tidy (Neg (underNeg o b e)) ss
4018 * | nred o = tidy (tidyNeg e) ((o,b):ss)
4019 * | nambig o = Error "illegal use of negation"
4021 * At each stage, the parser can either shift, reduce, accept, or error.
4022 * The transitions when dealing with juxtaposed operators o and p are
4023 * determined by the following rules:
4025 * shift o p = (prec o > prec p)
4026 * || (prec o == prec p && assoc o == L && assoc p == L)
4028 * red o p = (prec o < prec p)
4029 * || (prec o == prec p && assoc o == R && assoc p == R)
4031 * ambig o p = (prec o == prec p)
4032 * && (assoc o == N || assoc p == N || assoc o /= assoc p)
4034 * The transitions when dealing with juxtaposed unary minus and infix
4035 * operators are as follows. The precedence of unary minus (infixl 6) is
4036 * hardwired in to these definitions, as it is to the definitions of the
4037 * Haskell grammar in the official report.
4039 * nshift o = (prec o > 6)
4040 * nred o = (prec o < 6) || (prec o == 6 && assoc o == L)
4041 * nambig o = prec o == 6 && (assoc o == R || assoc o == N)
4043 * An InfixExp of the form (Neg e) means negate the last thing in
4044 * the InfixExp e; we can force this negation using:
4046 * tidyNeg :: OpExp -> OpExp
4047 * tidyNeg (Only e) = Only (Negate e)
4048 * tidyNeg (Infix a o b) = Infix a o (Negate b)
4049 * tidyNeg (Neg e) = tidyNeg (tidyNeg e)
4051 * On the other hand, if we want to sneak application of an infix operator
4052 * under a negation, then we use:
4054 * underNeg :: Op -> Exp -> OpExp -> OpExp
4055 * underNeg o b (Only e) = Only (Apply o e b)
4056 * underNeg o b (Neg e) = Neg (underNeg o b e)
4057 * underNeg o b (Infix e p f) = Infix e p (Apply o f b)
4059 * As a concession to efficiency, we lower the number of calls to syntaxOf
4060 * by keeping track of the values of sye, sys throughout the process. The
4061 * value APPLIC is used to indicate that the syntax value is unknown.
4062 * ------------------------------------------------------------------------*/
4064 static Cell local tidyInfix(line,e) /* Convert infixExp to Exp */
4066 Cell e; { /* :: OpExp */
4067 Cell s = NIL; /* :: [(Op,Exp)] */
4068 Syntax sye = APPLIC; /* Syntax of op in e (init unknown)*/
4069 Syntax sys = APPLIC; /* Syntax of op in s (init unknown)*/
4072 while (fst(d)!=ONLY) { /* Attach fixities to operators */
4076 fun(fun(d)) = attachFixity(line,fun(fun(d)));
4082 switch (whatIs(e)) {
4083 case ONLY : e = snd(e);
4084 while (nonNull(s)) {
4085 Cell next = arg(fun(s));
4087 fun(fun(s)) = snd(fun(fun(s)));
4093 case NEG : if (nonNull(s)) {
4094 if (sys==APPLIC) { /* calculate sys */
4095 sys = intOf(fst(fun(fun(s))));
4098 if (precOf(sys)==UMINUS_PREC && /* nambig */
4099 assocOf(sys)!=UMINUS_ASSOC) {
4101 "Ambiguous use of unary minus with \""
4102 ETHEN ERREXPR(snd(fun(fun(s))));
4107 if (precOf(sys)>UMINUS_PREC) { /* nshift */
4111 while (whatIs(e1)==NEG)
4113 arg(fun(t)) = arg(e1);
4114 fun(fun(t)) = snd(fun(fun(t)));
4121 /* Intentional fall-thru for nreduce and isNull(s) */
4123 { Cell prev = e; /* e := tidyNeg e */
4124 Cell temp = arg(prev);
4126 for (; whatIs(temp)==NEG; nneg++) {
4127 fun(prev) = nameNegate;
4131 if (isInt(arg(temp))) { /* special cases */
4132 if (nneg&1) /* for literals */
4133 arg(temp) = mkInt(-intOf(arg(temp)));
4135 else if (isFloat(arg(temp))) {
4137 arg(temp) = floatNegate(arg(temp));
4138 //mkFloat(-floatOf(arg(temp)));
4141 fun(prev) = nameNegate;
4142 arg(prev) = arg(temp);
4149 default : if (isNull(s)) {/* Move operation onto empty stack */
4150 Cell next = arg(fun(e));
4157 else { /* deal with pair of operators */
4159 if (sye==APPLIC) { /* calculate sys and sye */
4160 sye = intOf(fst(fun(fun(e))));
4163 sys = intOf(fst(fun(fun(s))));
4166 if (precOf(sye)==precOf(sys) && /* ambig */
4167 (assocOf(sye)!=assocOf(sys) ||
4168 assocOf(sye)==NON_ASS)) {
4169 ERRMSG(line) "Ambiguous use of operator \""
4170 ETHEN ERREXPR(snd(fun(fun(e))));
4171 ERRTEXT "\" with \""
4172 ETHEN ERREXPR(snd(fun(fun(s))));
4177 if (precOf(sye)>precOf(sys) || /* shift */
4178 (precOf(sye)==precOf(sys) &&
4179 assocOf(sye)==LEFT_ASS &&
4180 assocOf(sys)==LEFT_ASS)) {
4181 Cell next = arg(fun(e));
4189 Cell next = arg(fun(s));
4190 arg(fun(s)) = arg(e);
4191 fun(fun(s)) = snd(fun(fun(s)));
4202 static Pair local attachFixity(line,op) /* Attach fixity to operator in an */
4203 Int line; /* infix expression */
4205 Syntax sy = DEF_OPSYNTAX;
4207 switch (whatIs(op)) {
4209 case VARIDCELL : if ((sy=lookupSyntax(textOf(op)))==NO_SYNTAX) {
4210 Name n = findName(textOf(op));
4212 ERRMSG(line) "Undefined variable \"%s\"",
4213 textToStr(textOf(op))
4222 case CONIDCELL : sy = syntaxOf(op = conDefined(line,op));
4225 case QUALIDENT : { Name n = findQualName(op);
4231 "Undefined qualified variable \"%s\"",
4241 return pair(mkInt(sy),op); /* Pair fixity with (possibly) */
4242 /* translated operator */
4245 static Syntax local lookupSyntax(t) /* Try to find fixity for var in */
4246 Text t; { /* enclosing bindings */
4247 List bounds1 = bounds;
4248 List bindings1 = bindings;
4250 while (nonNull(bindings1)) {
4251 if (nonNull(varIsMember(t,hd(bounds1)))) {
4252 return DEF_OPSYNTAX;
4254 Cell b = findBinding(t,hd(bindings1));
4256 Cell a = fst(snd(b));
4257 if (isVar(fst(b))) { /* Function binding */
4258 if (nonNull(a) && nonNull(snd(a))) {
4259 return intOf(snd(a));
4261 } else { /* Pattern binding */
4263 while (nonNull(vs) && nonNull(a)) {
4264 if (t==textOf(hd(vs))) {
4265 if (nonNull(hd(a)) && isInt(snd(hd(a)))) {
4266 return intOf(snd(hd(a)));
4274 return DEF_OPSYNTAX;
4277 bounds1 = tl(bounds1);
4278 bindings1 = tl(bindings1);
4283 /* --------------------------------------------------------------------------
4284 * To facilitate dependency analysis, lists of bindings are temporarily
4285 * augmented with an additional field, which is used in two ways:
4286 * - to build the `adjacency lists' for the dependency graph. Represented by
4287 * a list of pointers to other bindings in the same list of bindings.
4288 * - to hold strictly positive integer values (depth first search numbers) of
4289 * elements `on the stack' during the strongly connected components search
4290 * algorithm, or a special value mkInt(0), once the binding has been added
4291 * to a particular strongly connected component.
4293 * Using this extra field, the type of each list of declarations during
4294 * dependency analysis is [Binding'] where:
4296 * Binding' ::= (Var, (Attr, (Dep, [Alt]))) -- function binding
4297 * | ([Var], ([Attr], (Dep, (Pat,Rhs)))) -- pattern binding
4299 * ------------------------------------------------------------------------*/
4301 #define depVal(d) (fst(snd(snd(d)))) /* Access to dependency information*/
4303 static List local dependencyAnal(bs) /* Separate lists of bindings into */
4304 List bs; { /* mutually recursive groups in */
4305 /* order of dependency */
4306 mapProc(addDepField,bs); /* add extra field for dependents */
4307 mapProc(depBinding,bs); /* find dependents of each binding */
4308 bs = bscc(bs); /* sort to strongly connected comps*/
4309 mapProc(remDepField,bs); /* remove dependency info field */
4313 static List local topDependAnal(bs) /* Like dependencyAnal(), but at */
4314 List bs; { /* top level, reporting on progress*/
4318 setGoal("Dependency analysis",(Target)(length(bs)));
4320 mapProc(addDepField,bs); /* add extra field for dependents */
4321 for (xs=bs; nonNull(xs); xs=tl(xs)) {
4322 emptySubstitution();
4324 soFar((Target)(i++));
4326 bs = bscc(bs); /* sort to strongly connected comps */
4327 mapProc(remDepField,bs); /* remove dependency info field */
4332 static Void local addDepField(b) /* add extra field to binding to */
4333 Cell b; { /* hold list of dependents */
4334 snd(snd(b)) = pair(NIL,snd(snd(b)));
4337 static Void local remDepField(bs) /* remove dependency field from */
4338 List bs; { /* list of bindings */
4339 mapProc(remDepField1,bs);
4342 static Void local remDepField1(b) /* remove dependency field from */
4343 Cell b; { /* single binding */
4344 snd(snd(b)) = snd(snd(snd(b)));
4347 static Void local clearScope() { /* initialise dependency scoping */
4353 static Void local withinScope(bs) /* Enter scope of bindings bs */
4355 bounds = cons(NIL,bounds);
4356 bindings = cons(bs,bindings);
4357 depends = cons(NIL,depends);
4360 static Void local leaveScope() { /* Leave scope of last withinScope */
4361 List bs = hd(bindings); /* Remove fixity info from binds */
4362 Bool toplevel = isNull(tl(bindings));
4363 for (; nonNull(bs); bs=tl(bs)) {
4365 if (isVar(fst(b))) { /* Variable binding */
4366 Cell a = fst(snd(b));
4369 saveSyntax(fst(b),snd(a));
4371 fst(snd(b)) = fst(a);
4373 } else { /* Pattern binding */
4375 List as = fst(snd(b));
4376 while (nonNull(vs) && nonNull(as)) {
4377 if (isPair(hd(as))) {
4379 saveSyntax(hd(vs),snd(hd(as)));
4381 hd(as) = fst(hd(as));
4388 bounds = tl(bounds);
4389 bindings = tl(bindings);
4390 depends = tl(depends);
4393 static Void local saveSyntax(v,sy) /* Save syntax of top-level var */
4394 Cell v; /* in corresponding Name */
4396 Name n = findName(textOf(v));
4397 if (isNull(n) || name(n).syntax!=NO_SYNTAX) {
4398 internal("saveSyntax");
4401 name(n).syntax = intOf(sy);
4405 /* --------------------------------------------------------------------------
4406 * As a side effect of the dependency analysis we also make the following
4408 * - Each lhs is a valid pattern/function lhs, all constructor functions
4409 * have been defined and are used with the correct number of arguments.
4410 * - No lhs contains repeated pattern variables.
4411 * - Expressions used on the rhs of an eqn should be well formed. This
4413 * - Checking for valid patterns (including repeated vars) in lambda,
4414 * case, and list comprehension expressions.
4415 * - Recursively checking local lists of equations.
4416 * - No free (i.e. unbound) variables are used in the declaration list.
4417 * ------------------------------------------------------------------------*/
4419 static Void local depBinding(b) /* find dependents of binding */
4421 Cell defpart = snd(snd(snd(b))); /* definition part of binding */
4425 if (isVar(fst(b))) { /* function-binding? */
4426 mapProc(depAlt,defpart);
4427 if (isNull(fst(snd(b)))) { /* Save dep info if no type sig */
4428 fst(snd(b)) = pair(ap(IMPDEPS,hd(depends)),NIL);
4429 } else if (isNull(fst(fst(snd(b))))) {
4430 fst(fst(snd(b))) = ap(IMPDEPS,hd(depends));
4432 } else { /* pattern-binding? */
4433 Int line = rhsLine(snd(defpart));
4436 fst(defpart) = checkPat(line,fst(defpart));
4437 depRhs(snd(defpart));
4439 if (nonNull(hd(btyvars))) {
4441 "Sorry, no type variables are allowed in pattern binding type annotations"
4445 fst(defpart) = applyBtyvs(fst(defpart));
4447 depVal(b) = hd(depends);
4450 static Void local depDefaults(c) /* dependency analysis on defaults */
4451 Class c; { /* from class definition */
4452 depClassBindings(cclass(c).defaults);
4455 static Void local depInsts(in) /* dependency analysis on instance */
4456 Inst in; { /* bindings */
4457 depClassBindings(inst(in).implements);
4460 static Void local depClassBindings(bs) /* dependency analysis on list of */
4461 List bs; { /* bindings, possibly containing */
4462 for (; nonNull(bs); bs=tl(bs)) { /* NIL bindings ... */
4463 if (nonNull(hd(bs))) { /* No need to add extra field for */
4464 mapProc(depAlt,snd(hd(bs)));/* dependency information... */
4469 static Void local depAlt(a) /* Find dependents of alternative */
4471 List obvs = saveBvars(); /* Save list of bound variables */
4473 bindPats(rhsLine(snd(a)),fst(a)); /* add new bound vars for patterns */
4474 depRhs(snd(a)); /* find dependents of rhs */
4475 fst(a) = applyBtyvs(fst(a));
4476 restoreBvars(obvs); /* restore original list of bvars */
4479 static Void local depRhs(r) /* Find dependents of rhs */
4481 switch (whatIs(r)) {
4482 case GUARDED : mapProc(depGuard,snd(r));
4485 case LETREC : fst(snd(r)) = eqnsToBindings(fst(snd(r)),NIL,NIL,NIL);
4486 withinScope(fst(snd(r)));
4487 fst(snd(r)) = dependencyAnal(fst(snd(r)));
4488 hd(depends) = fst(snd(r));
4489 depRhs(snd(snd(r)));
4493 case RSIGN : snd(snd(r)) = checkPatType(rhsLine(fst(snd(r))),
4495 rhsExpr(fst(snd(r))),
4497 depRhs(fst(snd(r)));
4500 default : snd(r) = depExpr(intOf(fst(r)),snd(r));
4505 static Void local depGuard(g) /* find dependents of single guarded*/
4506 Cell g; { /* expression */
4507 depPair(intOf(fst(g)),snd(g));
4510 static Cell local depExpr(line,e) /* find dependents of expression */
4513 // Printf( "\n\n"); print(e,100); Printf("\n");
4514 //printExp(stdout,e);
4515 switch (whatIs(e)) {
4518 case VAROPCELL : return depVar(line,e);
4521 case CONOPCELL : return conDefined(line,e);
4523 case QUALIDENT : if (isQVar(e)) {
4524 return depQVar(line,e);
4525 } else { /* QConOrConOp */
4526 return conDefined(line,e);
4529 case INFIX : return depExpr(line,tidyInfix(line,snd(e)));
4532 case RECSEL : break;
4534 case AP : if (isAp(e) && isAp(fun(e)) && isExt(fun(fun(e)))) {
4535 return depRecord(line,e);
4541 arg(a) = depExpr(line,arg(a));
4544 fun(a) = depExpr(line,fun(a));
4548 case AP : depPair(line,e);
4562 case INTCELL : break;
4564 case COND : depTriple(line,snd(e));
4567 case FINLIST : map1Over(depExpr,line,snd(e));
4570 case LETREC : fst(snd(e)) = eqnsToBindings(fst(snd(e)),NIL,NIL,NIL);
4571 withinScope(fst(snd(e)));
4572 fst(snd(e)) = dependencyAnal(fst(snd(e)));
4573 hd(depends) = fst(snd(e));
4574 snd(snd(e)) = depExpr(line,snd(snd(e)));
4578 case LAMBDA : depAlt(snd(e));
4581 case DOCOMP : /* fall-thru */
4582 case COMP : depComp(line,snd(e),snd(snd(e)));
4585 case ESIGN : fst(snd(e)) = depExpr(line,fst(snd(e)));
4586 snd(snd(e)) = checkSigType(line,
4592 case CASE : fst(snd(e)) = depExpr(line,fst(snd(e)));
4593 map1Proc(depCaseAlt,line,snd(snd(e)));
4596 case CONFLDS : depConFlds(line,e,FALSE);
4599 case UPDFLDS : depUpdFlds(line,e);
4603 case WITHEXP : depWith(line,e);
4607 case ASPAT : ERRMSG(line) "Illegal `@' in expression"
4610 case LAZYPAT : ERRMSG(line) "Illegal `~' in expression"
4613 case WILDCARD : ERRMSG(line) "Illegal `_' in expression"
4617 case EXT : ERRMSG(line) "Illegal application of record"
4621 default : internal("depExpr");
4626 static Void local depPair(line,e) /* find dependents of pair of exprs*/
4629 fst(e) = depExpr(line,fst(e));
4630 snd(e) = depExpr(line,snd(e));
4633 static Void local depTriple(line,e) /* find dependents of triple exprs */
4636 fst3(e) = depExpr(line,fst3(e));
4637 snd3(e) = depExpr(line,snd3(e));
4638 thd3(e) = depExpr(line,thd3(e));
4641 static Void local depComp(l,e,qs) /* find dependents of comprehension*/
4646 fst(e) = depExpr(l,fst(e));
4650 switch (whatIs(q)) {
4651 case FROMQUAL : { List obvs = saveBvars();
4652 snd(snd(q)) = depExpr(l,snd(snd(q)));
4654 fst(snd(q)) = bindPat(l,fst(snd(q)));
4656 fst(snd(q)) = applyBtyvs(fst(snd(q)));
4661 case QWHERE : snd(q) = eqnsToBindings(snd(q),NIL,NIL,NIL);
4662 withinScope(snd(q));
4663 snd(q) = dependencyAnal(snd(q));
4664 hd(depends) = snd(q);
4669 case DOQUAL : /* fall-thru */
4670 case BOOLQUAL : snd(q) = depExpr(l,snd(q));
4677 static Void local depCaseAlt(line,a) /* Find dependents of case altern. */
4680 List obvs = saveBvars(); /* Save list of bound variables */
4682 fst(a) = bindPat(line,fst(a)); /* Add new bound vars for pats */
4683 depRhs(snd(a)); /* Find dependents of rhs */
4684 fst(a) = applyBtyvs(fst(a));
4685 restoreBvars(obvs); /* Restore original list of bvars */
4688 static Cell local depVar(line,e) /* Register occurrence of variable */
4691 List bounds1 = bounds;
4692 List bindings1 = bindings;
4693 List depends1 = depends;
4697 while (nonNull(bindings1)) {
4698 n = varIsMember(t,hd(bounds1)); /* look for t in bound variables */
4702 n = findBinding(t,hd(bindings1)); /* look for t in var bindings */
4704 if (!cellIsMember(n,hd(depends1))) {
4705 hd(depends1) = cons(n,hd(depends1));
4707 return (isVar(fst(n)) ? fst(n) : e);
4710 bounds1 = tl(bounds1);
4711 bindings1 = tl(bindings1);
4712 depends1 = tl(depends1);
4715 if (isNull(n=findName(t))) { /* check global definitions */
4716 ERRMSG(line) "Undefined variable \"%s\"", textToStr(t)
4722 if (!moduleThisScript(name(n).mod)) {
4726 /* Later phases of the system cannot cope if we resolve references
4727 * to unprocessed objects too early. This is the main reason that
4728 * we cannot cope with recursive modules at the moment.
4733 static Cell local depQVar(line,e)/* register occurrence of qualified variable */
4736 Name n = findQualName(e);
4737 if (isNull(n)) { /* check global definitions */
4738 ERRMSG(line) "Undefined qualified variable \"%s\"", identToStr(e)
4741 if (name(n).mod != currentModule) {
4744 if (fst(e) == VARIDCELL) {
4745 e = mkVar(qtextOf(e));
4747 e = mkVarop(qtextOf(e));
4749 return depVar(line,e);
4752 static Void local depConFlds(line,e,isP)/* check construction using fields */
4756 Name c = conDefined(line,fst(snd(e)));
4757 if (isNull(snd(snd(e))) ||
4758 nonNull(cellIsMember(c,depFields(line,e,snd(snd(e)),isP)))) {
4761 ERRMSG(line) "Constructor \"%s\" does not have selected fields in ",
4762 textToStr(name(c).text)
4767 if (!isP && isPair(name(c).defn)) { /* Check that banged fields defined*/
4768 List scs = fst(name(c).defn); /* List of strict components */
4769 Type t = name(c).type;
4770 Int a = userArity(c);
4771 List fs = snd(snd(e));
4773 if (isPolyType(t)) { /* Find tycon that c belongs to */
4776 if (isQualType(t)) {
4779 if (whatIs(t)==CDICTS) {
4788 for (ss=tycon(t).defn; hasCfun(ss); ss=tl(ss)) {
4790 /* Now we know the tycon t that c belongs to, and the corresponding
4791 * list of selectors for that type, ss. Now we have to check that
4792 * each of the fields identified by scs appears in fs, using ss to
4793 * cross reference, and convert integers to selector names.
4795 for (; nonNull(scs); scs=tl(scs)) {
4796 Int i = intOf(hd(scs));
4798 for (; nonNull(ss1); ss1=tl(ss1)) {
4799 List cns = name(hd(ss1)).defn;
4800 for (; nonNull(cns); cns=tl(cns)) {
4801 if (fst(hd(cns))==c) {
4805 if (nonNull(cns) && intOf(snd(hd(cns)))==i) {
4810 internal("depConFlds");
4814 for (; nonNull(fs1) && s!=fst(hd(fs1)); fs1=tl(fs1)) {
4817 ERRMSG(line) "Construction does not define strict field"
4819 ERRTEXT "\nExpression : " ETHEN ERREXPR(e);
4820 ERRTEXT "\nField : " ETHEN ERREXPR(s);
4829 static Void local depUpdFlds(line,e) /* check update using fields */
4832 if (isNull(thd3(snd(e)))) {
4833 ERRMSG(line) "Empty field list in update"
4836 fst3(snd(e)) = depExpr(line,fst3(snd(e)));
4837 snd3(snd(e)) = depFields(line,e,thd3(snd(e)),FALSE);
4840 static List local depFields(l,e,fs,isP) /* check field binding list */
4848 for (; nonNull(fs); fs=tl(fs)) { /* for each field binding */
4852 if (isVar(fb)) { /* expand var to var = var */
4853 h98DoesntSupport(l,"missing field bindings");
4854 fb = hd(fs) = pair(fb,fb);
4857 s = findQualName(fst(fb)); /* check for selector */
4858 if (nonNull(s) && isSfun(s)) {
4861 ERRMSG(l) "\"%s\" is not a selector function/field name",
4862 textToStr(textOf(fst(fb)))
4866 if (isNull(ss)) { /* for first named selector */
4867 List scs = name(s).defn; /* calculate list of constructors */
4868 for (; nonNull(scs); scs=tl(scs)) {
4869 cs = cons(fst(hd(scs)),cs);
4871 ss = singleton(s); /* initialize selector list */
4872 } else { /* for subsequent selectors */
4873 List ds = cs; /* intersect constructor lists */
4874 for (cs=NIL; nonNull(ds); ) {
4875 List scs = name(s).defn;
4876 while (nonNull(scs) && fst(hd(scs))!=hd(ds)) {
4889 if (cellIsMember(s,ss)) { /* check for repeated uses */
4890 ERRMSG(l) "Repeated field name \"%s\" in field list",
4891 textToStr(name(s).text)
4897 if (isNull(cs)) { /* Are there any matching constrs? */
4898 ERRMSG(l) "No constructor has all of the fields specified in "
4904 snd(fb) = (isP ? checkPat(l,snd(fb)) : depExpr(l,snd(fb)));
4910 static Void local depWith(line,e) /* check with using fields */
4913 fst(snd(e)) = depExpr(line,fst(snd(e)));
4914 snd(snd(e)) = depDwFlds(line,e,snd(snd(e)));
4917 static List local depDwFlds(l,e,fs)/* check field binding list */
4923 for (; nonNull(c); c=tl(c)) { /* for each field binding */
4924 snd(hd(c)) = depExpr(l,snd(hd(c)));
4931 static Cell local depRecord(line,e) /* find dependents of record and */
4932 Int line; /* sort fields into approp. order */
4933 Cell e; { /* to make construction and update */
4934 List exts = NIL; /* more efficient. */
4937 h98DoesntSupport(line,"extensible records");
4938 do { /* build up list of extensions */
4939 Text t = extText(fun(fun(r)));
4940 String s = textToStr(t);
4943 while (nonNull(nx) && strcmp(textToStr(extText(fun(fun(nx)))),s)>0) {
4947 if (nonNull(nx) && t==extText(fun(fun(nx)))) {
4948 ERRMSG(line) "Repeated label \"%s\" in record ", s
4954 exts = cons(fun(r),exts);
4956 tl(prev) = cons(fun(r),nx);
4958 extField(r) = depExpr(line,extField(r));
4960 } while (isAp(r) && isAp(fun(r)) && isExt(fun(fun(r))));
4961 r = depExpr(line,r);
4962 return revOnto(exts,r);
4967 /* --------------------------------------------------------------------------
4968 * Several parts of this program require an algorithm for sorting a list
4969 * of values (with some added dependency information) into a list of strongly
4970 * connected components in which each value appears before its dependents.
4972 * Each of these algorithms is obtained by parameterising a standard
4973 * algorithm in "scc.c" as shown below.
4974 * ------------------------------------------------------------------------*/
4976 #define SCC2 tcscc /* make scc algorithm for Tycons */
4977 #define LOWLINK tclowlink
4978 #define DEPENDS(c) (isTycon(c) ? tycon(c).kind : cclass(c).kinds)
4979 #define SETDEPENDS(c,v) if(isTycon(c)) tycon(c).kind=v; else cclass(c).kinds=v
4986 #define SCC bscc /* make scc algorithm for Bindings */
4987 #define LOWLINK blowlink
4988 #define DEPENDS(t) depVal(t)
4989 #define SETDEPENDS(c,v) depVal(c)=v
4996 /* --------------------------------------------------------------------------
4997 * Main static analysis:
4998 * ------------------------------------------------------------------------*/
5000 Void checkExp() { /* Top level static check on Expr */
5001 staticAnalysis(RESET);
5002 clearScope(); /* Analyse expression in the scope */
5003 withinScope(NIL); /* of no local bindings */
5004 inputExpr = depExpr(0,inputExpr);
5006 staticAnalysis(RESET);
5009 #if EXPLAIN_INSTANCE_RESOLUTION
5010 Void checkContext(void) { /* Top level static check on Expr */
5013 staticAnalysis(RESET);
5014 clearScope(); /* Analyse expression in the scope */
5015 withinScope(NIL); /* of no local bindings */
5017 for (vs = NIL; nonNull(qs); qs=tl(qs)) {
5018 vs = typeVarsIn(hd(qs),NIL,NIL,vs);
5020 map2Proc(depPredExp,0,vs,inputContext);
5022 staticAnalysis(RESET);
5026 Void checkDefns ( Module thisModule ) { /* Top level static analysis */
5028 staticAnalysis(RESET);
5030 setCurrModule(thisModule);
5032 /* Resolve module references */
5033 mapProc(checkQualImport, module(thisModule).qualImports);
5034 mapProc(checkUnqualImport,unqualImports);
5035 /* Add "import Prelude" if there`s no explicit import */
5036 if (thisModule!=modulePrelude
5037 && isNull(cellAssoc(modulePrelude,unqualImports))
5038 && isNull(cellRevAssoc(modulePrelude,module(thisModule).qualImports))) {
5039 unqualImports = cons(pair(modulePrelude,DOTDOT),unqualImports);
5041 /* Every module (including the Prelude) implicitly contains
5042 * "import qualified Prelude"
5044 module(thisModule).qualImports
5045 =cons(pair(mkCon(textPrelude),modulePrelude),
5046 module(thisModule).qualImports);
5048 mapProc(checkImportList, unqualImports);
5050 /* Note: there's a lot of side-effecting going on here, so
5051 don't monkey about with the order of operations here unless
5052 you know what you are doing */
5053 if (!combined) linkPreludeTC(); /* Get prelude tycons and classes */
5055 mapProc(checkTyconDefn,tyconDefns); /* validate tycon definitions */
5056 checkSynonyms(tyconDefns); /* check synonym definitions */
5057 mapProc(checkClassDefn,classDefns); /* process class definitions */
5058 mapProc(kindTCGroup,tcscc(tyconDefns,classDefns)); /* attach kinds */
5059 mapProc(visitClass,classDefns); /* check class hierarchy */
5060 mapProc(extendFundeps,classDefns); /* finish class definitions */
5061 /* (convenient if we do this after */
5062 /* calling `visitClass' so that we */
5063 /* know the class hierarchy is */
5066 mapProc(addMembers,classDefns); /* add definitions for member funs */
5068 if (!combined) linkPreludeCM(); /* Get prelude cfuns and mfuns */
5070 instDefns = rev(instDefns); /* process instance definitions */
5071 mapProc(checkInstDefn,instDefns);
5073 setCurrModule(thisModule);
5074 mapProc(addRSsigdecls,typeInDefns); /* add sigdecls for RESTRICTSYN */
5075 valDefns = eqnsToBindings(valDefns,tyconDefns,classDefns,/*primDefns*/NIL);
5076 mapProc(allNoPrevDef,valDefns); /* check against previous defns */
5077 mapProc(addDerivImp,derivedInsts); /* Add impls for derived instances */
5078 deriveContexts(derivedInsts); /* Calculate derived inst contexts */
5079 instDefns = appendOnto(instDefns,derivedInsts);
5080 checkDefaultDefns(); /* validate default definitions */
5082 mapProc(allNoPrevDef,valDefns); /* check against previous defns */
5084 if (!combined) linkPrimNames(); /* link primitive names */
5086 mapProc(checkForeignImport,foreignImports); /* check foreign imports */
5087 mapProc(checkForeignExport,foreignExports); /* check foreign exports */
5088 foreignImports = NIL;
5089 foreignExports = NIL;
5091 /* Every top-level name has now been created - so we can build the */
5092 /* export list. Note that this has to happen before dependency */
5093 /* analysis so that references to Prelude.foo will be resolved */
5094 /* when compiling the prelude. */
5095 module(thisModule).exports
5096 = checkExports ( module(thisModule).exports, thisModule );
5098 mapProc(checkTypeIn,typeInDefns); /* check restricted synonym defns */
5101 withinScope(valDefns);
5102 valDefns = topDependAnal(valDefns); /* top level dependency ordering */
5103 mapProc(depDefaults,classDefns); /* dep. analysis on class defaults */
5104 mapProc(depInsts,instDefns); /* dep. analysis on inst defns */
5107 /* ToDo: evalDefaults should match current evaluation module */
5108 evalDefaults = defaultDefns; /* Set defaults for evaluator */
5110 staticAnalysis(RESET);
5116 static Void local addRSsigdecls(pr) /* add sigdecls from TYPE ... IN ..*/
5118 List vs = snd(pr); /* get list of variables */
5119 for (; nonNull(vs); vs=tl(vs)) {
5120 if (fst(hd(vs))==SIGDECL) { /* find a sigdecl */
5121 valDefns = cons(hd(vs),valDefns); /* add to valDefns */
5122 hd(vs) = hd(snd3(snd(hd(vs)))); /* and replace with var */
5127 static Void local allNoPrevDef(b) /* ensure no previous bindings for*/
5128 Cell b; { /* variables in new binding */
5129 if (isVar(fst(b))) {
5130 noPrevDef(rhsLine(snd(hd(snd(snd(b))))),fst(b));
5132 Int line = rhsLine(snd(snd(snd(b))));
5133 map1Proc(noPrevDef,line,fst(b));
5137 static Void local noPrevDef(line,v) /* ensure no previous binding for */
5138 Int line; /* new variable */
5140 Name n = findName(textOf(v));
5143 n = newName(textOf(v),NIL);
5144 name(n).defn = PREDEFINED;
5145 } else if (name(n).defn!=PREDEFINED) {
5146 duplicateError(line,name(n).mod,name(n).text,"variable");
5148 name(n).line = line;
5151 static Void local duplicateErrorAux(line,mod,t,kind)/* report duplicate defn */
5156 if (mod == currentModule) {
5157 ERRMSG(line) "Repeated definition for %s \"%s\"", kind,
5161 ERRMSG(line) "Definition of %s \"%s\" clashes with import", kind,
5167 static Void local checkTypeIn(cvs) /* Check that vars in restricted */
5168 Pair cvs; { /* synonym are defined */
5172 for (; nonNull(vs); vs=tl(vs)) {
5173 if (isNull(findName(textOf(hd(vs))))) {
5174 ERRMSG(tycon(c).line)
5175 "No top level binding of \"%s\" for restricted synonym \"%s\"",
5176 textToStr(textOf(hd(vs))), textToStr(tycon(c).text)
5182 /* --------------------------------------------------------------------------
5183 * Haskell 98 compatibility tests:
5184 * ------------------------------------------------------------------------*/
5186 Bool h98Pred(allowArgs,pi) /* Check syntax of Hask98 predicate*/
5189 return isClass(getHead(pi)) && argCount==1 &&
5190 isOffset(getHead(arg(pi))) && (argCount==0 || allowArgs);
5193 Cell h98Context(allowArgs,ps) /* Check syntax of Hask98 context */
5196 for (; nonNull(ps); ps=tl(ps)) {
5197 if (!h98Pred(allowArgs,hd(ps))) {
5204 Void h98CheckCtxt(line,wh,allowArgs,ps,in)
5205 Int line; /* Report illegal context/predicate*/
5211 Cell pi = h98Context(allowArgs,ps);
5213 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh ETHEN
5215 ERRTEXT "\n*** Instance : " ETHEN ERRPRED(inst(in).head);
5217 ERRTEXT "\n*** Constraint : " ETHEN ERRPRED(pi);
5218 if (nonNull(ps) && nonNull(tl(ps))) {
5219 ERRTEXT "\n*** Context : " ETHEN ERRCONTEXT(ps);
5227 Void h98CheckType(line,wh,e,t) /* Check for Haskell 98 type */
5236 if (isQualType(t)) {
5237 Cell pi = h98Context(TRUE,fst(snd(t)));
5239 ERRMSG(line) "Illegal Haskell 98 class constraint in %s",wh
5241 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(e);
5242 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(ty);
5250 Void h98DoesntSupport(line,wh) /* Report feature missing in H98 */
5254 ERRMSG(line) "Haskell 98 does not support %s", wh
5259 /* --------------------------------------------------------------------------
5260 * Static Analysis control:
5261 * ------------------------------------------------------------------------*/
5263 Void staticAnalysis(what)
5266 case RESET : cfunSfuns = NIL;
5279 case MARK : mark(daSccs);
5294 case POSTPREL: break;
5296 case PREPREL : staticAnalysis(RESET);
5298 extKind = pair(STAR,pair(ROW,ROW));
5303 /*-------------------------------------------------------------------------*/