2 /* --------------------------------------------------------------------------
3 * Primitives for manipulating global data structures
5 * Hugs 98 is Copyright (c) Mark P Jones, Alastair Reid and the Yale
6 * Haskell Group 1994-99, and is distributed as Open Source software
7 * under the Artistic License; see the file "Artistic" that is included
8 * in the distribution for details.
10 * $RCSfile: storage.c,v $
12 * $Date: 1999/10/15 11:02:26 $
13 * ------------------------------------------------------------------------*/
22 /*#define DEBUG_SHOWUSE*/
24 /* --------------------------------------------------------------------------
25 * local function prototypes:
26 * ------------------------------------------------------------------------*/
28 static Int local hash Args((String));
29 static Int local saveText Args((Text));
30 static Module local findQualifier Args((Text));
31 static Void local hashTycon Args((Tycon));
32 static List local insertTycon Args((Tycon,List));
33 static Void local hashName Args((Name));
34 static List local insertName Args((Name,List));
35 static Void local patternError Args((String));
36 static Bool local stringMatch Args((String,String));
37 static Bool local typeInvolves Args((Type,Type));
38 static Cell local markCell Args((Cell));
39 static Void local markSnd Args((Cell));
40 static Cell local lowLevelLastIn Args((Cell));
41 static Cell local lowLevelLastOut Args((Cell));
42 Module local moduleOfScript Args((Script));
43 Script local scriptThisFile Args((Text));
45 /* --------------------------------------------------------------------------
48 * provides storage for the characters making up identifier and symbol
49 * names, string literals, character constants etc...
51 * All character strings are stored in a large character array, with textHw
52 * pointing to the next free position. Lookup in the array is improved using
53 * a hash table. Internally, text strings are represented by integer offsets
54 * from the beginning of the array to the string in question.
56 * Where memory permits, the use of multiple hashtables gives a significant
57 * increase in performance, particularly when large source files are used.
59 * Each string in the array is terminated by a zero byte. No string is
60 * stored more than once, so that it is safe to test equality of strings by
61 * comparing the corresponding offsets.
63 * Special text values (beyond the range of the text array table) are used
64 * to generate unique `new variable names' as required.
66 * The same text storage is also used to hold text values stored in a saved
67 * expression. This grows downwards from the top of the text table (and is
68 * not included in the hash table).
69 * ------------------------------------------------------------------------*/
71 #define TEXTHSZ 512 /* Size of Text hash table */
72 #define NOTEXT ((Text)(~0)) /* Empty bucket in Text hash table */
73 static Text textHw; /* Next unused position */
74 static Text savedText = NUM_TEXT; /* Start of saved portion of text */
75 static Text nextNewText; /* Next new text value */
76 static Text nextNewDText; /* Next new dict text value */
77 static char DEFTABLE(text,NUM_TEXT);/* Storage of character strings */
78 static Text textHash[TEXTHSZ][NUM_TEXTH]; /* Hash table storage */
80 String textToStr(t) /* find string corresp to given Text*/
82 static char newVar[16];
84 if (0<=t && t<NUM_TEXT) /* standard char string */
87 sprintf(newVar,"d%d",-t); /* dictionary variable */
89 sprintf(newVar,"v%d",t-NUM_TEXT); /* normal variable */
93 String identToStr(v) /*find string corresp to given ident or qualified name*/
96 internal("identToStr");
102 case CONOPCELL : return text+textOf(v);
104 case QUALIDENT : { Text pos = textHw;
106 while (pos+1 < savedText && text[t]!=0) {
107 text[pos++] = text[t++];
109 if (pos+1 < savedText) {
113 while (pos+1 < savedText && text[t]!=0) {
114 text[pos++] = text[t++];
120 internal("identToStr2");
121 return 0; /* NOTREACHED */
124 Text inventText() { /* return new unused variable name */
125 return nextNewText++;
128 Text inventDictText() { /* return new unused dictvar name */
129 return nextNewDText--;
132 Bool inventedText(t) /* Signal TRUE if text has been */
133 Text t; { /* generated internally */
134 return (t<0 || t>=NUM_TEXT);
137 static Int local hash(s) /* Simple hash function on strings */
141 for (v=((int)(*s))*8; *s; s++)
142 v += ((int)(*s))*(j++);
148 Text findText(s) /* Locate string in Text array */
152 Text textPos = textHash[h][hashno];
154 #define TryMatch { Text originalTextPos = textPos; \
156 for (t=s; *t==text[textPos]; textPos++,t++) \
158 return originalTextPos; \
160 #define Skip while (text[textPos++]) ;
162 while (textPos!=NOTEXT) {
164 if (++hashno<NUM_TEXTH) /* look in next hashtable entry */
165 textPos = textHash[h][hashno];
168 while (textPos < textHw) {
179 textPos = textHw; /* if not found, save in array */
180 if (textHw + (Int)strlen(s) + 1 > savedText) {
181 ERRMSG(0) "Character string storage space exhausted"
184 while ((text[textHw++] = *s++) != 0) {
186 if (hashno<NUM_TEXTH) { /* updating hash table as necessary */
187 textHash[h][hashno] = textPos;
188 if (hashno<NUM_TEXTH-1)
189 textHash[h][hashno+1] = NOTEXT;
195 static Int local saveText(t) /* Save text value in buffer */
196 Text t; { /* at top of text table */
197 String s = textToStr(t);
200 if (textHw + l + 1 > savedText) {
201 ERRMSG(0) "Character string storage space exhausted"
205 strcpy(text+savedText,s);
210 /* --------------------------------------------------------------------------
213 * Currently, the only attributes that we store for each Ext value is the
214 * corresponding Text label. At some later stage, we may decide to cache
215 * types, predicates, etc. here as a space saving gesture. Given that Text
216 * comparison is cheap, and that this is an experimental implementation, we
217 * will use a straightforward linear search to locate Ext values from their
218 * corresponding Text labels; a hashing scheme can be introduced later if
219 * this turns out to be a problem.
220 * ------------------------------------------------------------------------*/
223 Text DEFTABLE(tabExt,NUM_EXT); /* Storage for Ext names */
226 Ext mkExt(t) /* Allocate or find an Ext value */
232 if (extHw-EXTMIN >= NUM_EXT) {
233 ERRMSG(0) "Ext storage space exhausted"
241 /* --------------------------------------------------------------------------
244 * A Tycon represents a user defined type constructor. Tycons are indexed
245 * by Text values ... a very simple hash function is used to improve lookup
246 * times. Tycon entries with the same hash code are chained together, with
247 * the most recent entry at the front of the list.
248 * ------------------------------------------------------------------------*/
250 #define TYCONHSZ 256 /* Size of Tycon hash table*/
251 #define tHash(x) ((x)%TYCONHSZ) /* Tycon hash function */
252 static Tycon tyconHw; /* next unused Tycon */
253 static Tycon DEFTABLE(tyconHash,TYCONHSZ); /* Hash table storage */
254 struct strTycon DEFTABLE(tabTycon,NUM_TYCON); /* Tycon storage */
256 Tycon newTycon(t) /* add new tycon to tycon table */
259 if (tyconHw-TYCMIN >= NUM_TYCON) {
260 ERRMSG(0) "Type constructor storage space exhausted"
263 tycon(tyconHw).text = t; /* clear new tycon record */
264 tycon(tyconHw).kind = NIL;
265 tycon(tyconHw).defn = NIL;
266 tycon(tyconHw).what = NIL;
267 tycon(tyconHw).conToTag = NIL;
268 tycon(tyconHw).tagToCon = NIL;
269 tycon(tyconHw).mod = currentModule;
270 module(currentModule).tycons = cons(tyconHw,module(currentModule).tycons);
271 tycon(tyconHw).nextTyconHash = tyconHash[h];
272 tyconHash[h] = tyconHw;
277 Tycon findTycon(t) /* locate Tycon in tycon table */
279 Tycon tc = tyconHash[tHash(t)];
281 while (nonNull(tc) && tycon(tc).text!=t)
282 tc = tycon(tc).nextTyconHash;
286 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
288 Tycon oldtc = findTycon(tycon(tc).text);
291 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
297 static Void local hashTycon(tc) /* Insert Tycon into hash table */
299 Text t = tycon(tc).text;
301 tycon(tc).nextTyconHash = tyconHash[h];
305 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
307 if (!isPair(id)) internal("findQualTycon");
311 return findTycon(textOf(id));
313 Text t = qtextOf(id);
314 Module m = findQualifier(qmodOf(id));
316 if (isNull(m)) return NIL;
317 for(es=module(m).exports; nonNull(es); es=tl(es)) {
319 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
324 default : internal("findQualTycon2");
326 return 0; /* NOTREACHED */
329 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
335 Tycon tc = newTycon(t);
337 tycon(tc).kind = kind;
338 tycon(tc).what = what;
339 tycon(tc).defn = defn;
340 tycon(tc).arity = ar;
344 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
349 String s = textToStr(tycon(tc).text);
351 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
352 if (hd(curr)==tc) /* just in case we get duplicates! */
358 tl(prev) = cons(tc,curr);
362 return cons(tc,curr);
365 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
366 String pat; /* to list of Tycons ts */
367 List ts; { /* Null pattern matches every tycon*/
368 Tycon tc; /* (Tycons with NIL kind excluded) */
369 for (tc=TYCMIN; tc<tyconHw; ++tc)
370 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
371 if (nonNull(tycon(tc).kind))
372 ts = insertTycon(tc,ts);
376 /* --------------------------------------------------------------------------
379 * A Name represents a top level binding of a value to an identifier.
380 * Such values may be a constructor function, a member function in a
381 * class, a user-defined or primitive value/function.
383 * Names are indexed by Text values ... a very simple hash functions speeds
384 * access to the table of Names and Name entries with the same hash value
385 * are chained together, with the most recent entry at the front of the
387 * ------------------------------------------------------------------------*/
389 #define NAMEHSZ 256 /* Size of Name hash table */
390 #define nHash(x) ((x)%NAMEHSZ) /* hash fn :: Text->Int */
391 Name nameHw; /* next unused name */
392 static Name DEFTABLE(nameHash,NAMEHSZ); /* Hash table storage */
393 struct strName DEFTABLE(tabName,NUM_NAME); /* Name table storage */
395 Name newName(t,parent) /* Add new name to name table */
399 if (nameHw-NAMEMIN >= NUM_NAME) {
400 ERRMSG(0) "Name storage space exhausted"
403 name(nameHw).text = t; /* clear new name record */
404 name(nameHw).line = 0;
405 name(nameHw).syntax = NO_SYNTAX;
406 name(nameHw).parent = parent;
407 name(nameHw).arity = 0;
408 name(nameHw).number = EXECNAME;
409 name(nameHw).defn = NIL;
410 name(nameHw).stgVar = NIL;
411 name(nameHw).stgSize = 0;
412 name(nameHw).inlineMe = FALSE;
413 name(nameHw).simplified = FALSE;
414 name(nameHw).isDBuilder = FALSE;
415 name(nameHw).type = NIL;
416 name(nameHw).primop = 0;
417 name(nameHw).mod = currentModule;
418 module(currentModule).names=cons(nameHw,module(currentModule).names);
419 name(nameHw).nextNameHash = nameHash[h];
420 nameHash[h] = nameHw;
424 Name findName(t) /* Locate name in name table */
426 Name n = nameHash[nHash(t)];
428 while (nonNull(n) && name(n).text!=t)
429 n = name(n).nextNameHash;
433 Name addName(nm) /* Insert Name in name table - if */
434 Name nm; { /* no clash is caused */
435 Name oldnm = findName(name(nm).text);
438 module(currentModule).names=cons(nm,module(currentModule).names);
444 static Void local hashName(nm) /* Insert Name into hash table */
451 name(nm).nextNameHash = nameHash[h];
455 Name findQualName(id) /* Locate (possibly qualified) name*/
456 Cell id; { /* in name table */
458 internal("findQualName");
464 return findName(textOf(id));
466 Text t = qtextOf(id);
467 Module m = findQualifier(qmodOf(id));
469 if (isNull(m)) return NIL;
470 for(es=module(m).exports; nonNull(es); es=tl(es)) {
472 if (isName(e) && name(e).text==t)
474 else if (isPair(e) && DOTDOT==snd(e)) {
475 List subentities = NIL;
478 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
479 subentities = tycon(c).defn;
481 subentities = cclass(c).members;
482 for(; nonNull(subentities); subentities=tl(subentities)) {
483 if (!isName(hd(subentities)))
484 internal("findQualName3");
485 if (name(hd(subentities)).text == t)
486 return hd(subentities);
492 default : internal("findQualName2");
494 return 0; /* NOTREACHED */
498 Name nameFromStgVar ( StgVar v )
501 for (n = NAMEMIN; n < nameHw; n++)
502 if (name(n).stgVar == v) return n;
506 void* getHugs_AsmObject_for ( char* s )
509 Name n = findName(findText(s));
510 if (isNull(n)) internal("getHugs_AsmObject_for(1)");
512 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
513 internal("getHugs_AsmObject_for(2)");
514 return ptrOf(stgVarInfo(v));
517 /* --------------------------------------------------------------------------
518 * Primitive functions:
519 * ------------------------------------------------------------------------*/
521 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
522 Text t; /* sets rep, not type */
525 Int rep; { /* Really AsmRep */
526 Name n = newName(t,NIL);
527 name(n).arity = arity;
528 name(n).number = cfunNo(no);
530 name(n).primop = (void*)rep;
535 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
540 Name n = newName(t,NIL);
541 name(n).arity = arity;
542 name(n).number = cfunNo(no);
548 Int sfunPos(s,c) /* Find position of field with */
549 Name s; /* selector s in constructor c. */
553 for (; nonNull(cns); cns=tl(cns))
555 return intOf(snd(hd(cns)));
557 return 0;/* NOTREACHED */
560 static List local insertName(nm,ns) /* insert name nm into sorted list */
565 String s = textToStr(name(nm).text);
567 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
568 if (hd(curr)==nm) /* just in case we get duplicates! */
574 tl(prev) = cons(nm,curr);
578 return cons(nm,curr);
581 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
582 String pat; /* to list of names ns */
583 List ns; { /* Null pattern matches every name */
584 Name nm; /* (Names with NIL type, or hidden */
586 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
587 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
588 String str = textToStr(name(nm).text);
589 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
590 ns = insertName(nm,ns);
594 List mns = module(currentModule).names;
595 for(; nonNull(mns); mns=tl(mns)) {
597 if (!inventedText(name(nm).text)) {
598 String str = textToStr(name(nm).text);
599 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
600 ns = insertName(nm,ns);
607 /* --------------------------------------------------------------------------
608 * A simple string matching routine
609 * `*' matches any sequence of zero or more characters
610 * `?' matches any single character exactly
611 * `@str' matches the string str exactly (ignoring any special chars)
612 * `\c' matches the character c only (ignoring special chars)
613 * c matches the character c only
614 * ------------------------------------------------------------------------*/
616 static Void local patternError(s) /* report error in pattern */
618 ERRMSG(0) "%s in pattern", s
622 static Bool local stringMatch(pat,str) /* match string against pattern */
628 case '\0' : return (*str=='\0');
631 if (stringMatch(pat+1,str))
636 case '?' : if (*str++=='\0')
641 case '[' : { Bool found = FALSE;
642 while (*++pat!='\0' && *pat!=']')
643 if (!found && ( pat[0] == *str ||
652 patternError("missing `]'");
660 case '\\' : if (*++pat == '\0')
661 patternError("extra trailing `\\'");
663 default : if (*pat++ != *str++)
669 /* --------------------------------------------------------------------------
670 * Storage of type classes, instances etc...:
671 * ------------------------------------------------------------------------*/
673 static Class classHw; /* next unused class */
674 static List classes; /* list of classes in current scope */
675 static Inst instHw; /* next unused instance record */
677 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
678 struct strInst far *tabInst; /* (pointer to) table of instances */
680 Class newClass(t) /* add new class to class table */
682 if (classHw-CLASSMIN >= NUM_CLASSES) {
683 ERRMSG(0) "Class storage space exhausted"
686 cclass(classHw).text = t;
687 cclass(classHw).arity = 0;
688 cclass(classHw).kinds = NIL;
689 cclass(classHw).head = NIL;
690 cclass(classHw).dcon = NIL;
691 cclass(classHw).supers = NIL;
692 cclass(classHw).dsels = NIL;
693 cclass(classHw).members = NIL;
694 cclass(classHw).dbuild = NIL;
695 cclass(classHw).defaults = NIL;
696 cclass(classHw).instances = NIL;
697 classes=cons(classHw,classes);
698 cclass(classHw).mod = currentModule;
699 module(currentModule).classes=cons(classHw,module(currentModule).classes);
703 Class classMax() { /* Return max Class in use ... */
704 return classHw; /* This is a bit ugly, but it's not*/
705 } /* worth a lot of effort right now */
707 Class findClass(t) /* look for named class in table */
711 for (cs=classes; nonNull(cs); cs=tl(cs)) {
713 if (cclass(cl).text==t)
719 Class addClass(c) /* Insert Class in class list */
720 Class c; { /* - if no clash caused */
721 Class oldc = findClass(cclass(c).text);
723 classes=cons(c,classes);
724 module(currentModule).classes=cons(c,module(currentModule).classes);
731 Class findQualClass(c) /* Look for (possibly qualified) */
732 Cell c; { /* class in class list */
733 if (!isQualIdent(c)) {
734 return findClass(textOf(c));
737 Module m = findQualifier(qmodOf(c));
741 for (es=module(m).exports; nonNull(es); es=tl(es)) {
743 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
750 Inst newInst() { /* Add new instance to table */
751 if (instHw-INSTMIN >= NUM_INSTS) {
752 ERRMSG(0) "Instance storage space exhausted"
755 inst(instHw).kinds = NIL;
756 inst(instHw).head = NIL;
757 inst(instHw).specifics = NIL;
758 inst(instHw).implements = NIL;
759 inst(instHw).builder = NIL;
760 inst(instHw).mod = currentModule;
766 extern Void printInst Args((Inst));
770 Class cl = inst(in).c;
771 Printf("%s-", textToStr(cclass(cl).text));
772 printType(stdout,inst(in).t);
774 #endif /* DEBUG_DICTS */
776 Inst findFirstInst(tc) /* look for 1st instance involving */
777 Tycon tc; { /* the type constructor tc */
778 return findNextInst(tc,INSTMIN-1);
781 Inst findNextInst(tc,in) /* look for next instance involving*/
782 Tycon tc; /* the type constructor tc */
783 Inst in; { /* starting after instance in */
784 while (++in < instHw) {
785 Cell pi = inst(in).head;
786 for (; isAp(pi); pi=fun(pi))
787 if (typeInvolves(arg(pi),tc))
793 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
794 Type ty; /* type constructor/tuple tc. */
797 || (isAp(ty) && (typeInvolves(fun(ty),tc)
798 || typeInvolves(arg(ty),tc)));
801 /* --------------------------------------------------------------------------
804 * Various parts of the system use a stack of cells. Most of the stack
805 * operations are defined as macros, expanded inline.
806 * ------------------------------------------------------------------------*/
808 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
809 StackPtr sp; /* stack pointer */
811 #if GIMME_STACK_DUMPS
813 #define UPPER_DISP 5 /* # display entries on top of stack */
814 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
816 Void hugsStackOverflow() { /* Report stack overflow */
818 extern Cell evalRoots[];
820 ERRMSG(0) "Control stack overflow" ETHEN
823 if (rootsp>=UPPER_DISP+LOWER_DISP) {
824 for (i=0; i<UPPER_DISP; i++) {
825 ERRTEXT "\nwhile evaluating: " ETHEN
826 ERREXPR(evalRoots[rootsp-i]);
828 ERRTEXT "\n..." ETHEN
829 for (i=LOWER_DISP-1; i>=0; i--) {
830 ERRTEXT "\nwhile evaluating: " ETHEN
831 ERREXPR(evalRoots[i]);
835 for (i=rootsp; i>=0; i--) {
836 ERRTEXT "\nwhile evaluating: " ETHEN
837 ERREXPR(evalRoots[i]);
845 #else /* !GIMME_STACK_DUMPS */
847 Void hugsStackOverflow() { /* Report stack overflow */
848 ERRMSG(0) "Control stack overflow"
852 #endif /* !GIMME_STACK_DUMPS */
854 /* --------------------------------------------------------------------------
857 * A Module represents a user defined module.
859 * Note: there are now two lookup mechanisms in the system:
861 * 1) The exports from a module are stored in a big list.
862 * We resolve qualified names, and import lists by linearly scanning
865 * 2) Unqualified imports and local definitions for the current module
866 * are stored in hash tables (tyconHash and nameHash) or linear lists
869 * ------------------------------------------------------------------------*/
871 static Module moduleHw; /* next unused Module */
872 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
873 Module currentModule; /* Module currently being processed*/
875 Bool isValidModule(m) /* is m a legitimate module id? */
877 return (MODMIN <= m && m < moduleHw);
880 Module newModule(t) /* add new module to module table */
882 if (moduleHw-MODMIN >= NUM_MODULE) {
883 ERRMSG(0) "Module storage space exhausted"
886 module(moduleHw).text = t; /* clear new module record */
887 module(moduleHw).qualImports = NIL;
888 module(moduleHw).exports = NIL;
889 module(moduleHw).tycons = NIL;
890 module(moduleHw).names = NIL;
891 module(moduleHw).classes = NIL;
892 module(moduleHw).oImage = NULL;
893 module(moduleHw).oTab = NULL;
894 module(moduleHw).sizeoTab = 0;
895 module(moduleHw).usedoTab = 0;
896 module(moduleHw).dlTab = NULL;
897 module(moduleHw).sizedlTab = 0;
898 module(moduleHw).useddlTab = 0;
902 void ppModules ( void )
905 fflush(stderr); fflush(stdout);
906 printf ( "begin MODULES\n" );
907 for (i = moduleHw-1; i >= MODMIN; i--)
908 printf ( " %2d: %16s\n",
909 i-MODMIN, textToStr(module(i).text)
911 printf ( "end MODULES\n" );
912 fflush(stderr); fflush(stdout);
916 Module findModule(t) /* locate Module in module table */
919 for(m=MODMIN; m<moduleHw; ++m) {
920 if (module(m).text==t)
926 Module findModid(c) /* Find module by name or filename */
929 case STRCELL : { Script s = scriptThisFile(snd(c));
930 return (s==-1) ? NIL : moduleOfScript(s);
932 case CONIDCELL : return findModule(textOf(c));
933 default : internal("findModid");
935 assert(0); return 0; /* NOTREACHED */
938 static local Module findQualifier(t) /* locate Module in import list */
941 printf ( "findQualifier %s\n", textToStr(t));
942 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
943 if (textOf(fst(hd(ms)))==t)
947 if (module(currentModule).text==t)
948 return currentModule;
953 Void setCurrModule(m) /* set lookup tables for current module */
956 if (m!=currentModule) {
957 currentModule = m; /* This is the only assignment to currentModule */
958 for (i=0; i<TYCONHSZ; ++i)
960 mapProc(hashTycon,module(m).tycons);
961 for (i=0; i<NAMEHSZ; ++i)
963 mapProc(hashName,module(m).names);
964 classes = module(m).classes;
968 Name jrsFindQualName ( Text mn, Text sn )
973 for (m=MODMIN; m<moduleHw; m++)
974 if (module(m).text == mn) break;
975 if (m == moduleHw) return NIL;
977 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
978 if (name(hd(ns)).text == sn) return hd(ns);
984 /* A bit tricky. Assumes that if tab==NULL, then
985 currUsed and *currSize must be zero.
988 void* genericExpand ( void* tab,
989 int* currSize, int currUsed,
990 int initSize, int elemSize )
994 if (currUsed < *currSize)
996 size2 = (*currSize == 0) ? initSize : (2 * *currSize);
997 tab2 = malloc ( size2 * elemSize );
999 ERRMSG(0) "Can't allocate enough memory to resize a table"
1003 memcpy ( tab2, tab, elemSize * *currSize );
1005 if (tab) free ( tab );
1009 void addOTabName ( Module m, char* nm, void* ad )
1012 = genericExpand ( module(m).oTab,
1013 &module(m).sizeoTab,
1017 module(m).oTab[ module(m).usedoTab ].nm = nm;
1018 module(m).oTab[ module(m).usedoTab ].ad = ad;
1019 module(m).usedoTab++;
1023 void addDLSect ( Module m, void* start, void* end, DLSect sect )
1026 = genericExpand ( module(m).dlTab,
1027 &module(m).sizedlTab,
1028 module(m).useddlTab,
1029 4, sizeof(DLTabEnt) );
1030 module(m).dlTab[ module(m).useddlTab ].start = start;
1031 module(m).dlTab[ module(m).useddlTab ].end = end;
1032 module(m).dlTab[ module(m).useddlTab ].sect = sect;
1033 module(m).useddlTab++;
1037 void* lookupOTabName ( Module m, char* nm )
1040 for (i = 0; i < module(m).usedoTab; i++)
1041 if (0==strcmp(nm,module(m).oTab[i].nm))
1042 return module(m).oTab[i].ad;
1047 char* nameFromOPtr ( void* p )
1051 for (m=MODMIN; m<moduleHw; m++)
1052 for (i = 0; i < module(m).usedoTab; i++)
1053 if (p == module(m).oTab[i].ad)
1054 return module(m).oTab[i].nm;
1059 DLSect lookupDLSect ( void* ad )
1063 for (m=MODMIN; m<moduleHw; m++)
1064 for (i = 0; i < module(m).useddlTab; i++)
1065 if (module(m).dlTab[i].start <= ad &&
1066 ad <= module(m).dlTab[i].end)
1067 return module(m).dlTab[i].sect;
1068 return HUGS_DL_SECTION_OTHER;
1072 /* --------------------------------------------------------------------------
1073 * Script file storage:
1075 * script files are read into the system one after another. The state of
1076 * the stored data structures (except the garbage-collected heap) is recorded
1077 * before reading a new script. In the event of being unable to read the
1078 * script, or if otherwise requested, the system can be restored to its
1079 * original state immediately before the file was read.
1080 * ------------------------------------------------------------------------*/
1082 typedef struct { /* record of storage state prior to */
1083 Text file; /* reading script/module */
1097 #ifdef DEBUG_SHOWUSE
1098 static Void local showUse(msg,val,mx)
1101 Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1105 static Script scriptHw; /* next unused script number */
1106 static script scripts[NUM_SCRIPTS]; /* storage for script records */
1109 void ppScripts ( void )
1112 fflush(stderr); fflush(stdout);
1113 printf ( "begin SCRIPTS\n" );
1114 for (i = scriptHw-1; i >= 0; i--)
1115 printf ( " %2d: %16s tH=%d mH=%d yH=%d "
1116 "nH=%d cH=%d iH=%d nnS=%d,%d\n",
1117 i, textToStr(scripts[i].file),
1118 scripts[i].textHw, scripts[i].moduleHw,
1119 scripts[i].tyconHw, scripts[i].nameHw,
1120 scripts[i].classHw, scripts[i].instHw,
1121 scripts[i].nextNewText, scripts[i].nextNewDText
1123 printf ( "end SCRIPTS\n" );
1124 fflush(stderr); fflush(stdout);
1127 Script startNewScript(f) /* start new script, keeping record */
1128 String f; { /* of status for later restoration */
1129 if (scriptHw >= NUM_SCRIPTS) {
1130 ERRMSG(0) "Too many script files in use"
1133 #ifdef DEBUG_SHOWUSE
1134 showUse("Text", textHw, NUM_TEXT);
1135 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
1136 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
1137 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
1138 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
1139 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
1141 showUse("Ext", extHw-EXTMIN, NUM_EXT);
1144 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
1145 scripts[scriptHw].textHw = textHw;
1146 scripts[scriptHw].nextNewText = nextNewText;
1147 scripts[scriptHw].nextNewDText = nextNewDText;
1148 scripts[scriptHw].moduleHw = moduleHw;
1149 scripts[scriptHw].tyconHw = tyconHw;
1150 scripts[scriptHw].nameHw = nameHw;
1151 scripts[scriptHw].classHw = classHw;
1152 scripts[scriptHw].instHw = instHw;
1154 scripts[scriptHw].extHw = extHw;
1159 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1160 return (scriptHw==0);
1163 Bool moduleThisScript(m) /* Test if given module is defined */
1164 Module m; { /* in current script file */
1165 return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
1168 Module lastModule() { /* Return module in current script file */
1169 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1172 #define scriptThis(nm,t,tag) Script nm(x) \
1176 && x>=scripts[s].tag) \
1180 scriptThis(scriptThisName,Name,nameHw)
1181 scriptThis(scriptThisTycon,Tycon,tyconHw)
1182 scriptThis(scriptThisInst,Inst,instHw)
1183 scriptThis(scriptThisClass,Class,classHw)
1186 Module moduleOfScript(s)
1188 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1191 String fileOfModule(m)
1194 if (m == modulePrelude) {
1197 for(s=0; s<scriptHw; ++s) {
1198 if (scripts[s].moduleHw == m) {
1199 return textToStr(scripts[s].file);
1205 Script scriptThisFile(f)
1208 for (s=0; s < scriptHw; ++s) {
1209 if (scripts[s].file == f) {
1213 if (f == findText(STD_PRELUDE)) {
1219 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1220 Script sno; { /* to reading script sno */
1221 if (sno<scriptHw) { /* is there anything to restore? */
1223 textHw = scripts[sno].textHw;
1224 nextNewText = scripts[sno].nextNewText;
1225 nextNewDText = scripts[sno].nextNewDText;
1226 moduleHw = scripts[sno].moduleHw;
1227 tyconHw = scripts[sno].tyconHw;
1228 nameHw = scripts[sno].nameHw;
1229 classHw = scripts[sno].classHw;
1230 instHw = scripts[sno].instHw;
1232 dictHw = scripts[sno].dictHw;
1235 extHw = scripts[sno].extHw;
1239 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1240 if (module(i).objectFile) {
1241 printf("[bogus] closing objectFile for module %d\n",i);
1242 /*dlclose(module(i).objectFile);*/
1245 moduleHw = scripts[sno].moduleHw;
1247 for (i=0; i<TEXTHSZ; ++i) {
1249 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1250 && textHash[i][j]<textHw)
1253 textHash[i][j] = NOTEXT;
1257 for (i=0; i<TYCONHSZ; ++i) {
1260 for (i=0; i<NAMEHSZ; ++i) {
1264 for (i=CLASSMIN; i<classHw; i++) {
1265 List ins = cclass(i).instances;
1268 while (nonNull(ins)) {
1269 List temp = tl(ins);
1270 if (hd(ins)<instHw) {
1276 cclass(i).instances = rev(is);
1283 /* --------------------------------------------------------------------------
1286 * Provides a garbage collectable heap for storage of expressions etc.
1288 * Now incorporates a flat resource: A two-space collected extension of
1289 * the heap that provides storage for contiguous arrays of Cell storage,
1290 * cooperating with the garbage collection mechanisms for the main heap.
1291 * ------------------------------------------------------------------------*/
1293 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1294 Heap heapFst; /* array of fst component of pairs */
1295 Heap heapSnd; /* array of snd component of pairs */
1302 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1303 /* C stack; use with extreme care! */
1305 Int numGcs; /* number of garbage collections */
1306 Int cellsRecovered; /* number of cells recovered */
1308 static Cell freeList; /* free list of unused cells */
1309 static Cell lsave, rsave; /* save components of pair */
1313 static Int markCount, stackRoots;
1315 #define initStackRoots() stackRoots = 0
1316 #define recordStackRoot() stackRoots++
1329 #define start() markCount = 0
1330 #define end(thing,rs) \
1332 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1335 #define recordMark() markCount++
1337 #else /* !GC_STATISTICS */
1342 #define initStackRoots()
1343 #define recordStackRoot()
1346 #define end(thing,root)
1347 #define recordMark()
1349 #endif /* !GC_STATISTICS */
1351 Cell pair(l,r) /* Allocate pair (l, r) from */
1352 Cell l, r; { /* heap, garbage collecting first */
1353 Cell c = freeList; /* if necessary ... */
1365 freeList = snd(freeList);
1372 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1373 Cell dst, src; { /* both *MUST* be pairs */
1374 if (isPair(dst) && isPair(src)) {
1375 fst(dst) = fst(src);
1376 snd(dst) = snd(src);
1379 internal("overwrite");
1383 static Int marksSize;
1385 Cell markExpr(c) /* External interface to markCell */
1387 return isGenPair(c) ? markCell(c) : c;
1390 static Cell local markCell(c) /* Traverse part of graph marking */
1391 Cell c; { /* cells reachable from given root */
1392 /* markCell(c) is only called if c */
1394 { register int place = placeInSet(c);
1395 register int mask = maskInSet(c);
1396 if (marks[place]&mask)
1399 marks[place] |= mask;
1404 if (isGenPair(fst(c))) {
1405 fst(c) = markCell(fst(c));
1408 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1415 static Void local markSnd(c) /* Variant of markCell used to */
1416 Cell c; { /* update snd component of cell */
1417 Cell t; /* using tail recursion */
1419 ma: t = c; /* Keep pointer to original pair */
1424 { register int place = placeInSet(c);
1425 register int mask = maskInSet(c);
1426 if (marks[place]&mask)
1429 marks[place] |= mask;
1434 if (isGenPair(fst(c))) {
1435 fst(c) = markCell(fst(c));
1438 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1443 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1444 Cell n; { /* it was a cell ref, but don't */
1445 /* move cell so we don't have */
1446 /* to modify the stored value of n */
1453 Void garbageCollect() { /* Run garbage collector ... */
1454 Bool breakStat = breakOn(FALSE); /* disable break checking */
1460 jmp_buf regs; /* save registers on stack */
1464 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1467 everybody(MARK); /* Mark all components of system */
1469 gcScanning(); /* scan mark set */
1476 for (i=1; i<=heapSize; i++) {
1477 if ((marks[place] & mask) == 0) {
1484 if (++j == bitsPerWord) {
1491 gcRecovered(recovered);
1492 breakOn(breakStat); /* restore break trapping if nec. */
1496 /* can only return if freeList is nonempty on return. */
1497 if (recovered<minRecovery || isNull(freeList)) {
1498 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1501 cellsRecovered = recovered;
1504 /* --------------------------------------------------------------------------
1505 * Code for saving last expression entered:
1507 * This is a little tricky because some text values (e.g. strings or variable
1508 * names) may not be defined or have the same value when the expression is
1509 * recalled. These text values are therefore saved in the top portion of
1511 * ------------------------------------------------------------------------*/
1513 static Cell lastExprSaved; /* last expression to be saved */
1515 Void setLastExpr(e) /* save expression for later recall*/
1517 lastExprSaved = NIL; /* in case attempt to save fails */
1518 savedText = NUM_TEXT;
1519 lastExprSaved = lowLevelLastIn(e);
1522 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
1523 Cell c; { /* acyclic graph) for later recall */
1524 if (isPair(c)) { /* Duplicating any text strings */
1525 if (isBoxTag(fst(c))) /* in case these are lost at some */
1526 switch (fst(c)) { /* point before the expr is reused */
1532 case STRCELL : return pair(fst(c),saveText(textOf(c)));
1533 default : return pair(fst(c),snd(c));
1536 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
1540 return pair(EXTCOPY,saveText(extText(c)));
1546 Cell getLastExpr() { /* recover previously saved expr */
1547 return lowLevelLastOut(lastExprSaved);
1550 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
1551 Cell c; { /* except that Cells refering to */
1552 if (isPair(c)) { /* Text values are restored to */
1553 if (isBoxTag(fst(c))) /* appropriate values */
1560 case STRCELL : return pair(fst(c),
1561 findText(text+intValOf(c)));
1563 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
1565 default : return pair(fst(c),snd(c));
1568 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
1574 /* --------------------------------------------------------------------------
1575 * Miscellaneous operations on heap cells:
1576 * ------------------------------------------------------------------------*/
1578 /* Profiling suggests that the number of calls to whatIs() is typically */
1579 /* rather high. The recoded version below attempts to improve the average */
1580 /* performance for whatIs() using a binary search for part of the analysis */
1582 Cell whatIs(c) /* identify type of cell */
1585 register Cell fstc = fst(c);
1586 return isTag(fstc) ? fstc : AP;
1588 if (c<TUPMIN) return c;
1589 if (c>=INTMIN) return INTCELL;
1591 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
1593 else if (c>=INSTMIN) return INSTANCE;
1595 else if (c>=MODMIN) {if (c>=TYCMIN) return TYCON;
1596 else return MODULE;}
1597 else if (c>=OFFMIN) return OFFSET;
1599 else return (c>=EXTMIN) ?
1606 register Cell fstc = fst(c);
1607 return isTag(fstc) ? fstc : AP;
1609 if (c>=INTMIN) return INTCELL;
1610 if (c>=CHARMIN) return CHARCELL;
1611 if (c>=CLASSMIN) return CLASS;
1612 if (c>=INSTMIN) return INSTANCE;
1613 if (c>=NAMEMIN) return NAME;
1614 if (c>=TYCMIN) return TYCON;
1615 if (c>=MODMIN) return MODULE;
1616 if (c>=OFFMIN) return OFFSET;
1618 if (c>=EXTMIN) return EXT;
1620 if (c>=TUPMIN) return TUPLE;
1625 /* A very, very simple printer.
1626 * Output is uglier than from printExp - but the printer is more
1627 * robust and can be used on any data structure irrespective of
1630 Void print Args((Cell, Int));
1631 Void print(c, depth)
1636 #if 0 /* Not in this version of Hugs */
1637 } else if (isPair(c) && !isGenPair(c)) {
1638 extern Void printEvalCell Args((Cell, Int));
1639 printEvalCell(c,depth);
1642 Int tag = whatIs(c);
1646 print(fst(c), depth-1);
1648 print(snd(c), depth-1);
1652 Printf("free(%d)", c);
1655 Printf("int(%d)", intOf(c));
1658 Printf("bignum(%s)", bignumToString(c));
1661 Printf("char('%c')", charOf(c));
1664 Printf("ptr(%p)",ptrOf(c));
1667 Printf("class(%d)", c-CLASSMIN);
1668 if (CLASSMIN <= c && c < classHw) {
1669 Printf("=\"%s\"", textToStr(cclass(c).text));
1673 Printf("instance(%d)", c - INSTMIN);
1676 Printf("name(%d)", c-NAMEMIN);
1677 if (NAMEMIN <= c && c < nameHw) {
1678 Printf("=\"%s\"", textToStr(name(c).text));
1682 Printf("tycon(%d)", c-TYCMIN);
1683 if (TYCMIN <= c && c < tyconHw)
1684 Printf("=\"%s\"", textToStr(tycon(c).text));
1687 Printf("module(%d)", c - MODMIN);
1690 Printf("Offset %d", offsetOf(c));
1693 Printf("Tuple %d", tupleOf(c));
1697 print(snd(c),depth-1);
1701 print(snd(c),depth-1);
1705 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
1706 Printf("%d ", intOf(fst(snd(c))));
1707 print(snd(snd(c)),depth-1);
1709 print(snd(c),depth-1);
1726 Printf("{dict %d}",textOf(c));
1732 Printf("{id %s}",textToStr(textOf(c)));
1735 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
1739 print(fst(snd(c)),depth-1);
1741 print(snd(snd(c)),depth-1);
1746 print(snd(c),depth-1);
1751 print(snd(c),depth-1);
1756 print(fst(snd(c)),depth-1);
1758 print(snd(snd(c)),depth-1);
1763 print(fst(snd(c)),depth-1);
1765 print(snd(snd(c)),depth-1);
1769 Printf("FromQual(");
1770 print(fst(snd(c)),depth-1);
1772 print(snd(snd(c)),depth-1);
1776 Printf("StgVar%d=",-c);
1777 print(snd(c), depth-1);
1781 print(fst(snd(c)),depth-1);
1783 print(snd(snd(c)),depth-1);
1788 print(fst(snd(c)),depth-1);
1790 print(snd(snd(c)),depth-1);
1795 print(fst(snd(c)),depth-1);
1797 print(snd(snd(c)),depth-1);
1801 Printf("PrimCase(");
1802 print(fst(snd(c)),depth-1);
1804 print(snd(snd(c)),depth-1);
1808 if (isBoxTag(tag)) {
1809 Printf("Tag(%d)=%d", c, tag);
1810 } else if (isConTag(tag)) {
1811 Printf("%d@(%d,",c,tag);
1812 print(snd(c), depth-1);
1815 } else if (c == tag) {
1816 Printf("Tag(%d)", c);
1818 Printf("Tag(%d)=%d", c, tag);
1827 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
1828 Cell c; { /* also recognises DICTVAR cells */
1830 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
1833 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
1835 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
1838 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
1840 if (!isPair(c)) return FALSE;
1843 case VAROPCELL : return TRUE;
1845 case QUALIDENT : return isVar(snd(snd(c)));
1847 default : return FALSE;
1851 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
1853 if (!isPair(c)) return FALSE;
1856 case CONOPCELL : return TRUE;
1858 case QUALIDENT : return isCon(snd(snd(c)));
1860 default : return FALSE;
1864 Bool isQualIdent(c) /* is cell a qualified identifier? */
1866 return isPair(c) && (fst(c)==QUALIDENT);
1869 Bool isIdent(c) /* is cell an identifier? */
1871 if (!isPair(c)) return FALSE;
1876 case CONOPCELL : return TRUE;
1878 case QUALIDENT : return TRUE;
1880 default : return FALSE;
1884 Bool isInt(c) /* cell holds integer value? */
1886 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
1889 Int intOf(c) /* find integer value of cell? */
1893 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
1896 Cell mkInt(n) /* make cell representing integer */
1898 return (MINSMALLINT <= n && n <= MAXSMALLINT)
1903 #if SIZEOF_INTP == SIZEOF_INT
1904 typedef union {Int i; Ptr p;} IntOrPtr;
1910 return pair(PTRCELL,x.i);
1917 assert(fst(c) == PTRCELL);
1926 return pair(CPTRCELL,x.i);
1933 assert(fst(c) == CPTRCELL);
1937 #elif SIZEOF_INTP == 2*SIZEOF_INT
1938 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
1944 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
1951 assert(fst(c) == PTRCELL);
1952 x.i.i1 = intOf(fst(snd(c)));
1953 x.i.i2 = intOf(snd(snd(c)));
1957 #warning "type Addr not supported on this architecture - don't use it"
1961 ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
1968 ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
1973 String stringNegate( s )
1981 strcpy(&t[1],s); /* ToDo: use strncpy instead */
1986 /* --------------------------------------------------------------------------
1988 * ------------------------------------------------------------------------*/
1990 Int length(xs) /* calculate length of list xs */
1993 for (; nonNull(xs); ++n)
1998 List appendOnto(xs,ys) /* Destructively prepend xs onto */
1999 List xs, ys; { /* ys by modifying xs ... */
2004 while (nonNull(tl(zs)))
2011 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2014 for (; nonNull(xs); xs=tl(xs))
2015 ys = cons(hd(xs),ys);
2019 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2022 return revOnto(dupOnto(xs,NIL),ys);
2025 List dupList(xs) /* Duplicate spine of list xs */
2028 for (; nonNull(xs); xs=tl(xs))
2029 ys = cons(hd(xs),ys);
2033 List revOnto(xs,ys) /* Destructively reverse elements of*/
2034 List xs, ys; { /* list xs onto list ys... */
2037 while (nonNull(xs)) {
2046 Cell varIsMember(t,xs) /* Test if variable is a member of */
2047 Text t; /* given list of variables */
2049 for (; nonNull(xs); xs=tl(xs))
2050 if (t==textOf(hd(xs)))
2055 Name nameIsMember(t,ns) /* Test if name with text t is a */
2056 Text t; /* member of list of names xs */
2058 for (; nonNull(ns); ns=tl(ns))
2059 if (t==name(hd(ns)).text)
2064 Cell intIsMember(n,xs) /* Test if integer n is member of */
2065 Int n; /* given list of integers */
2067 for (; nonNull(xs); xs=tl(xs))
2068 if (n==intOf(hd(xs)))
2073 Cell cellIsMember(x,xs) /* Test for membership of specific */
2074 Cell x; /* cell x in list xs */
2076 for (; nonNull(xs); xs=tl(xs))
2082 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2085 for (; nonNull(xs); xs=tl(xs))
2091 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2092 Cell c; /* association lists */
2094 for (; nonNull(xs); xs=tl(xs))
2100 List replicate(n,x) /* create list of n copies of x */
2109 List diffList(from,take) /* list difference: from\take */
2110 List from, take; { /* result contains all elements of */
2111 List result = NIL; /* `from' not appearing in `take' */
2113 while (nonNull(from)) {
2114 List next = tl(from);
2115 if (!cellIsMember(hd(from),take)) {
2124 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2128 for(;nonNull(xs);xs=tl(xs)) {
2131 result=cons(x,result);
2137 List take(n,xs) /* destructively truncate list to */
2138 Int n; /* specified length */
2144 while (1<n-- && nonNull(xs))
2151 List splitAt(n,xs) /* drop n things from front of list*/
2160 Cell nth(n,xs) /* extract n'th element of list */
2163 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2170 List removeCell(x,xs) /* destructively remove cell from */
2175 return tl(xs); /* element at front of list */
2179 for (; nonNull(curr); prev=curr, curr=tl(prev))
2181 tl(prev) = tl(curr);
2182 return xs; /* element in middle of list */
2186 return xs; /* here if element not found */
2189 List nubList(xs) /* nuke dups in list */
2190 List xs; { /* non destructive */
2192 for (; nonNull(xs); xs=tl(xs))
2193 if (isNull(cellIsMember(hd(xs),outs)))
2194 outs = cons(hd(xs),outs);
2199 /* --------------------------------------------------------------------------
2200 * Operations on applications:
2201 * ------------------------------------------------------------------------*/
2203 Int argCount; /* number of args in application */
2205 Cell getHead(e) /* get head cell of application */
2206 Cell e; { /* set number of args in argCount */
2207 for (argCount=0; isAp(e); e=fun(e))
2212 List getArgs(e) /* get list of arguments in function*/
2213 Cell e; { /* application: */
2214 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2216 for (as=NIL; isAp(e); e=fun(e))
2217 as = cons(arg(e),as);
2221 Cell nthArg(n,e) /* return nth arg in application */
2222 Int n; /* of function to m args (m>=n) */
2223 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2224 for (n=numArgs(e)-n-1; n>0; n--)
2229 Int numArgs(e) /* find number of arguments to expr */
2232 for (n=0; isAp(e); e=fun(e))
2237 Cell applyToArgs(f,args) /* destructively apply list of args */
2238 Cell f; /* to function f */
2240 while (nonNull(args)) {
2241 Cell temp = tl(args);
2242 tl(args) = hd(args);
2251 /* --------------------------------------------------------------------------
2253 * ------------------------------------------------------------------------*/
2255 /*---------------------------------------------------------------------------
2256 * GreenCard entry points
2258 * GreenCard generated code accesses Hugs data structures and functions
2259 * (only) via these functions (which are stored in the virtual function
2261 *-------------------------------------------------------------------------*/
2265 static Cell makeTuple Args((Int));
2266 static Cell makeInt Args((Int));
2267 static Cell makeChar Args((Char));
2268 static Char CharOf Args((Cell));
2269 static Cell makeFloat Args((FloatPro));
2270 static Void* derefMallocPtr Args((Cell));
2271 static Cell* Fst Args((Cell));
2272 static Cell* Snd Args((Cell));
2274 static Cell makeTuple(n) Int n; { return mkTuple(n); }
2275 static Cell makeInt(n) Int n; { return mkInt(n); }
2276 static Cell makeChar(n) Char n; { return mkChar(n); }
2277 static Char CharOf(n) Cell n; { return charOf(n); }
2278 static Cell makeFloat(n) FloatPro n; { return mkFloat(n); }
2279 static Void* derefMallocPtr(n) Cell n; { return derefMP(n); }
2280 static Cell* Fst(n) Cell n; { return (Cell*)&fst(n); }
2281 static Cell* Snd(n) Cell n; { return (Cell*)&snd(n); }
2283 HugsAPI1* hugsAPI1() {
2284 static HugsAPI1 api;
2285 static Bool initialised = FALSE;
2287 api.nameTrue = nameTrue;
2288 api.nameFalse = nameFalse;
2289 api.nameNil = nameNil;
2290 api.nameCons = nameCons;
2291 api.nameJust = nameJust;
2292 api.nameNothing = nameNothing;
2293 api.nameLeft = nameLeft;
2294 api.nameRight = nameRight;
2295 api.nameUnit = nameUnit;
2296 api.nameIORun = nameIORun;
2297 api.makeInt = makeInt;
2298 api.makeChar = makeChar;
2299 api.CharOf = CharOf;
2300 api.makeFloat = makeFloat;
2301 api.makeTuple = makeTuple;
2303 api.mkMallocPtr = mkMallocPtr;
2304 api.derefMallocPtr = derefMallocPtr;
2305 api.mkStablePtr = mkStablePtr;
2306 api.derefStablePtr = derefStablePtr;
2307 api.freeStablePtr = freeStablePtr;
2309 api.evalWithNoError = evalWithNoError;
2310 api.evalFails = evalFails;
2311 api.whnfArgs = &whnfArgs;
2312 api.whnfHead = &whnfHead;
2313 api.whnfInt = &whnfInt;
2314 api.whnfFloat = &whnfFloat;
2315 api.garbageCollect = garbageCollect;
2316 api.stackOverflow = hugsStackOverflow;
2317 api.internal = internal;
2318 api.registerPrims = registerPrims;
2319 api.addPrimCfun = addPrimCfun;
2320 api.inventText = inventText;
2323 api.cellStack = cellStack;
2329 #endif /* GREENCARD */
2332 /* --------------------------------------------------------------------------
2334 * ------------------------------------------------------------------------*/
2337 static void far* safeFarCalloc Args((Int,Int));
2338 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
2339 Int n, s; { /* for non-null return */
2340 void far* tab = farCalloc(n,s);
2342 ERRMSG(0) "Cannot allocate run-time tables"
2347 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
2349 #define TABALLOC(v,t,n)
2357 case RESET : clearStack();
2359 /* the next 2 statements are particularly important
2360 * if you are using GLOBALfst or GLOBALsnd since the
2361 * corresponding registers may be reset to their
2362 * uninitialised initial values by a longjump.
2364 heapTopFst = heapFst + heapSize;
2365 heapTopSnd = heapSnd + heapSize;
2369 if (isNull(lastExprSaved))
2370 savedText = NUM_TEXT;
2375 for (i=NAMEMIN; i<nameHw; ++i) {
2376 mark(name(i).parent);
2378 mark(name(i).stgVar);
2381 end("Names", nameHw-NAMEMIN);
2384 for (i=MODMIN; i<moduleHw; ++i) {
2385 mark(module(i).tycons);
2386 mark(module(i).names);
2387 mark(module(i).classes);
2388 mark(module(i).exports);
2389 mark(module(i).qualImports);
2391 end("Modules", moduleHw-MODMIN);
2394 for (i=TYCMIN; i<tyconHw; ++i) {
2395 mark(tycon(i).defn);
2396 mark(tycon(i).kind);
2397 mark(tycon(i).what);
2399 end("Type constructors", tyconHw-TYCMIN);
2402 for (i=CLASSMIN; i<classHw; ++i) {
2403 mark(cclass(i).head);
2404 mark(cclass(i).kinds);
2405 mark(cclass(i).dsels);
2406 mark(cclass(i).supers);
2407 mark(cclass(i).members);
2408 mark(cclass(i).defaults);
2409 mark(cclass(i).instances);
2412 end("Classes", classHw-CLASSMIN);
2415 for (i=INSTMIN; i<instHw; ++i) {
2417 mark(inst(i).kinds);
2418 mark(inst(i).specifics);
2419 mark(inst(i).implements);
2421 end("Instances", instHw-INSTMIN);
2424 for (i=0; i<=sp; ++i)
2429 mark(lastExprSaved);
2432 end("Last expression", 3);
2437 end("C stack", stackRoots);
2442 case INSTALL : heapFst = heapAlloc(heapSize);
2443 heapSnd = heapAlloc(heapSize);
2445 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
2446 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
2451 heapTopFst = heapFst + heapSize;
2452 heapTopSnd = heapSnd + heapSize;
2453 for (i=1; i<heapSize; ++i) {
2457 snd(-heapSize) = NIL;
2464 marksSize = bitArraySize(heapSize);
2465 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
2466 ERRMSG(0) "Unable to allocate gc markspace"
2470 TABALLOC(text, char, NUM_TEXT)
2471 TABALLOC(tyconHash, Tycon, TYCONHSZ)
2472 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
2473 TABALLOC(nameHash, Name, NAMEHSZ)
2474 TABALLOC(tabName, struct strName, NUM_NAME)
2475 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
2476 TABALLOC(cellStack, Cell, NUM_STACK)
2477 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
2479 TABALLOC(tabExt, Text, NUM_EXT)
2484 nextNewText = NUM_TEXT;
2485 nextNewDText = (-1);
2486 lastExprSaved = NIL;
2487 savedText = NUM_TEXT;
2488 for (i=0; i<TEXTHSZ; ++i)
2489 textHash[i][0] = NOTEXT;
2495 for (i=0; i<TYCONHSZ; ++i)
2502 for (i=0; i<NAMEHSZ; ++i)
2513 tabInst = (struct strInst far *)
2514 farCalloc(NUM_INSTS,sizeof(struct strInst));
2517 ERRMSG(0) "Cannot allocate instance tables"
2527 /*-------------------------------------------------------------------------*/