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/07/06 15:24:43 $
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;
507 /* --------------------------------------------------------------------------
508 * Primitive functions:
509 * ------------------------------------------------------------------------*/
511 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
512 Text t; /* sets rep, not type */
515 Int rep; { /* Really AsmRep */
516 Name n = newName(t,NIL);
517 name(n).arity = arity;
518 name(n).number = cfunNo(no);
520 name(n).primop = (void*)rep;
525 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
530 Name n = newName(t,NIL);
531 name(n).arity = arity;
532 name(n).number = cfunNo(no);
538 Int sfunPos(s,c) /* Find position of field with */
539 Name s; /* selector s in constructor c. */
543 for (; nonNull(cns); cns=tl(cns))
545 return intOf(snd(hd(cns)));
547 return 0;/* NOTREACHED */
550 static List local insertName(nm,ns) /* insert name nm into sorted list */
555 String s = textToStr(name(nm).text);
557 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
558 if (hd(curr)==nm) /* just in case we get duplicates! */
564 tl(prev) = cons(nm,curr);
568 return cons(nm,curr);
571 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
572 String pat; /* to list of names ns */
573 List ns; { /* Null pattern matches every name */
574 Name nm; /* (Names with NIL type, or hidden */
576 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
577 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
578 String str = textToStr(name(nm).text);
579 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
580 ns = insertName(nm,ns);
584 List mns = module(currentModule).names;
585 for(; nonNull(mns); mns=tl(mns)) {
587 if (!inventedText(name(nm).text)) {
588 String str = textToStr(name(nm).text);
589 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
590 ns = insertName(nm,ns);
597 /* --------------------------------------------------------------------------
598 * A simple string matching routine
599 * `*' matches any sequence of zero or more characters
600 * `?' matches any single character exactly
601 * `@str' matches the string str exactly (ignoring any special chars)
602 * `\c' matches the character c only (ignoring special chars)
603 * c matches the character c only
604 * ------------------------------------------------------------------------*/
606 static Void local patternError(s) /* report error in pattern */
608 ERRMSG(0) "%s in pattern", s
612 static Bool local stringMatch(pat,str) /* match string against pattern */
618 case '\0' : return (*str=='\0');
621 if (stringMatch(pat+1,str))
626 case '?' : if (*str++=='\0')
631 case '[' : { Bool found = FALSE;
632 while (*++pat!='\0' && *pat!=']')
633 if (!found && ( pat[0] == *str ||
642 patternError("missing `]'");
650 case '\\' : if (*++pat == '\0')
651 patternError("extra trailing `\\'");
653 default : if (*pat++ != *str++)
659 /* --------------------------------------------------------------------------
660 * Storage of type classes, instances etc...:
661 * ------------------------------------------------------------------------*/
663 static Class classHw; /* next unused class */
664 static List classes; /* list of classes in current scope */
665 static Inst instHw; /* next unused instance record */
667 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
668 struct strInst far *tabInst; /* (pointer to) table of instances */
670 Class newClass(t) /* add new class to class table */
672 if (classHw-CLASSMIN >= NUM_CLASSES) {
673 ERRMSG(0) "Class storage space exhausted"
676 cclass(classHw).text = t;
677 cclass(classHw).arity = 0;
678 cclass(classHw).kinds = NIL;
679 cclass(classHw).head = NIL;
680 cclass(classHw).dcon = NIL;
681 cclass(classHw).supers = NIL;
682 cclass(classHw).dsels = NIL;
683 cclass(classHw).members = NIL;
684 cclass(classHw).dbuild = NIL;
685 cclass(classHw).defaults = NIL;
686 cclass(classHw).instances = NIL;
687 classes=cons(classHw,classes);
688 cclass(classHw).mod = currentModule;
689 module(currentModule).classes=cons(classHw,module(currentModule).classes);
693 Class classMax() { /* Return max Class in use ... */
694 return classHw; /* This is a bit ugly, but it's not*/
695 } /* worth a lot of effort right now */
697 Class findClass(t) /* look for named class in table */
701 for (cs=classes; nonNull(cs); cs=tl(cs)) {
703 if (cclass(cl).text==t)
709 Class addClass(c) /* Insert Class in class list */
710 Class c; { /* - if no clash caused */
711 Class oldc = findClass(cclass(c).text);
713 classes=cons(c,classes);
714 module(currentModule).classes=cons(c,module(currentModule).classes);
721 Class findQualClass(c) /* Look for (possibly qualified) */
722 Cell c; { /* class in class list */
723 if (!isQualIdent(c)) {
724 return findClass(textOf(c));
727 Module m = findQualifier(qmodOf(c));
731 for (es=module(m).exports; nonNull(es); es=tl(es)) {
733 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
740 Inst newInst() { /* Add new instance to table */
741 if (instHw-INSTMIN >= NUM_INSTS) {
742 ERRMSG(0) "Instance storage space exhausted"
745 inst(instHw).kinds = NIL;
746 inst(instHw).head = NIL;
747 inst(instHw).specifics = NIL;
748 inst(instHw).implements = NIL;
749 inst(instHw).builder = NIL;
750 inst(instHw).mod = currentModule;
756 extern Void printInst Args((Inst));
760 Class cl = inst(in).c;
761 Printf("%s-", textToStr(cclass(cl).text));
762 printType(stdout,inst(in).t);
764 #endif /* DEBUG_DICTS */
766 Inst findFirstInst(tc) /* look for 1st instance involving */
767 Tycon tc; { /* the type constructor tc */
768 return findNextInst(tc,INSTMIN-1);
771 Inst findNextInst(tc,in) /* look for next instance involving*/
772 Tycon tc; /* the type constructor tc */
773 Inst in; { /* starting after instance in */
774 while (++in < instHw) {
775 Cell pi = inst(in).head;
776 for (; isAp(pi); pi=fun(pi))
777 if (typeInvolves(arg(pi),tc))
783 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
784 Type ty; /* type constructor/tuple tc. */
787 || (isAp(ty) && (typeInvolves(fun(ty),tc)
788 || typeInvolves(arg(ty),tc)));
791 /* --------------------------------------------------------------------------
794 * Various parts of the system use a stack of cells. Most of the stack
795 * operations are defined as macros, expanded inline.
796 * ------------------------------------------------------------------------*/
798 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
799 StackPtr sp; /* stack pointer */
801 #if GIMME_STACK_DUMPS
803 #define UPPER_DISP 5 /* # display entries on top of stack */
804 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
806 Void hugsStackOverflow() { /* Report stack overflow */
808 extern Cell evalRoots[];
810 ERRMSG(0) "Control stack overflow" ETHEN
813 if (rootsp>=UPPER_DISP+LOWER_DISP) {
814 for (i=0; i<UPPER_DISP; i++) {
815 ERRTEXT "\nwhile evaluating: " ETHEN
816 ERREXPR(evalRoots[rootsp-i]);
818 ERRTEXT "\n..." ETHEN
819 for (i=LOWER_DISP-1; i>=0; i--) {
820 ERRTEXT "\nwhile evaluating: " ETHEN
821 ERREXPR(evalRoots[i]);
825 for (i=rootsp; i>=0; i--) {
826 ERRTEXT "\nwhile evaluating: " ETHEN
827 ERREXPR(evalRoots[i]);
835 #else /* !GIMME_STACK_DUMPS */
837 Void hugsStackOverflow() { /* Report stack overflow */
838 ERRMSG(0) "Control stack overflow"
842 #endif /* !GIMME_STACK_DUMPS */
844 /* --------------------------------------------------------------------------
847 * A Module represents a user defined module.
849 * Note: there are now two lookup mechanisms in the system:
851 * 1) The exports from a module are stored in a big list.
852 * We resolve qualified names, and import lists by linearly scanning
855 * 2) Unqualified imports and local definitions for the current module
856 * are stored in hash tables (tyconHash and nameHash) or linear lists
859 * ------------------------------------------------------------------------*/
861 static Module moduleHw; /* next unused Module */
862 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
863 Module currentModule; /* Module currently being processed*/
865 Bool isValidModule(m) /* is m a legitimate module id? */
867 return (MODMIN <= m && m < moduleHw);
870 Module newModule(t) /* add new module to module table */
872 if (moduleHw-MODMIN >= NUM_MODULE) {
873 ERRMSG(0) "Module storage space exhausted"
876 module(moduleHw).text = t; /* clear new module record */
877 module(moduleHw).qualImports = NIL;
878 module(moduleHw).exports = NIL;
879 module(moduleHw).tycons = NIL;
880 module(moduleHw).names = NIL;
881 module(moduleHw).classes = NIL;
882 module(moduleHw).oImage = NULL;
883 module(moduleHw).oTab = NULL;
884 module(moduleHw).sizeoTab = 0;
885 module(moduleHw).usedoTab = 0;
886 module(moduleHw).dlTab = NULL;
887 module(moduleHw).sizedlTab = 0;
888 module(moduleHw).useddlTab = 0;
892 void ppModules ( void )
895 fflush(stderr); fflush(stdout);
896 printf ( "begin MODULES\n" );
897 for (i = moduleHw-1; i >= MODMIN; i--)
898 printf ( " %2d: %16s\n",
899 i-MODMIN, textToStr(module(i).text)
901 printf ( "end MODULES\n" );
902 fflush(stderr); fflush(stdout);
906 Module findModule(t) /* locate Module in module table */
909 for(m=MODMIN; m<moduleHw; ++m) {
910 if (module(m).text==t)
916 Module findModid(c) /* Find module by name or filename */
919 case STRCELL : { Script s = scriptThisFile(snd(c));
920 return (s==-1) ? NIL : moduleOfScript(s);
922 case CONIDCELL : return findModule(textOf(c));
923 default : internal("findModid");
925 assert(0); return 0; /* NOTREACHED */
928 static local Module findQualifier(t) /* locate Module in import list */
931 printf ( "findQualifier %s\n", textToStr(t));
932 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
933 if (textOf(fst(hd(ms)))==t)
937 if (module(currentModule).text==t)
938 return currentModule;
943 Void setCurrModule(m) /* set lookup tables for current module */
946 if (m!=currentModule) {
947 currentModule = m; /* This is the only assignment to currentModule */
948 for (i=0; i<TYCONHSZ; ++i)
950 mapProc(hashTycon,module(m).tycons);
951 for (i=0; i<NAMEHSZ; ++i)
953 mapProc(hashName,module(m).names);
954 classes = module(m).classes;
958 Name jrsFindQualName ( Text mn, Text sn )
963 for (m=MODMIN; m<moduleHw; m++)
964 if (module(m).text == mn) break;
965 if (m == moduleHw) return NIL;
967 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
968 if (name(hd(ns)).text == sn) return hd(ns);
974 /* A bit tricky. Assumes that if tab==NULL, then
975 currUsed and *currSize must be zero.
978 void* genericExpand ( void* tab,
979 int* currSize, int currUsed,
980 int initSize, int elemSize )
984 if (currUsed < *currSize)
986 size2 = (*currSize == 0) ? initSize : (2 * *currSize);
987 tab2 = malloc ( size2 * elemSize );
989 ERRMSG(0) "Can't allocate enough memory to resize a table"
993 memcpy ( tab2, tab, elemSize * *currSize );
995 if (tab) free ( tab );
999 void addOTabName ( Module m, char* nm, void* ad )
1002 = genericExpand ( module(m).oTab,
1003 &module(m).sizeoTab,
1007 module(m).oTab[ module(m).usedoTab ].nm = nm;
1008 module(m).oTab[ module(m).usedoTab ].ad = ad;
1009 module(m).usedoTab++;
1013 void addDLSect ( Module m, void* start, void* end, DLSect sect )
1016 = genericExpand ( module(m).dlTab,
1017 &module(m).sizedlTab,
1018 module(m).useddlTab,
1019 4, sizeof(DLTabEnt) );
1020 module(m).dlTab[ module(m).useddlTab ].start = start;
1021 module(m).dlTab[ module(m).useddlTab ].end = end;
1022 module(m).dlTab[ module(m).useddlTab ].sect = sect;
1023 module(m).useddlTab++;
1027 void* lookupOTabName ( Module m, char* nm )
1030 for (i = 0; i < module(m).usedoTab; i++)
1031 if (0==strcmp(nm,module(m).oTab[i].nm))
1032 return module(m).oTab[i].ad;
1037 char* nameFromOPtr ( void* p )
1041 for (m=MODMIN; m<moduleHw; m++)
1042 for (i = 0; i < module(m).usedoTab; i++)
1043 if (p == module(m).oTab[i].ad)
1044 return module(m).oTab[i].nm;
1049 DLSect lookupDLSect ( void* ad )
1053 for (m=MODMIN; m<moduleHw; m++)
1054 for (i = 0; i < module(m).useddlTab; i++)
1055 if (module(m).dlTab[i].start <= ad &&
1056 ad <= module(m).dlTab[i].end)
1057 return module(m).dlTab[i].sect;
1058 return HUGS_DL_SECTION_OTHER;
1062 /* --------------------------------------------------------------------------
1063 * Script file storage:
1065 * script files are read into the system one after another. The state of
1066 * the stored data structures (except the garbage-collected heap) is recorded
1067 * before reading a new script. In the event of being unable to read the
1068 * script, or if otherwise requested, the system can be restored to its
1069 * original state immediately before the file was read.
1070 * ------------------------------------------------------------------------*/
1072 typedef struct { /* record of storage state prior to */
1073 Text file; /* reading script/module */
1087 #ifdef DEBUG_SHOWUSE
1088 static Void local showUse(msg,val,mx)
1091 Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1095 static Script scriptHw; /* next unused script number */
1096 static script scripts[NUM_SCRIPTS]; /* storage for script records */
1099 void ppScripts ( void )
1102 fflush(stderr); fflush(stdout);
1103 printf ( "begin SCRIPTS\n" );
1104 for (i = scriptHw-1; i >= 0; i--)
1105 printf ( " %2d: %16s tH=%d mH=%d yH=%d "
1106 "nH=%d cH=%d iH=%d nnS=%d,%d\n",
1107 i, textToStr(scripts[i].file),
1108 scripts[i].textHw, scripts[i].moduleHw,
1109 scripts[i].tyconHw, scripts[i].nameHw,
1110 scripts[i].classHw, scripts[i].instHw,
1111 scripts[i].nextNewText, scripts[i].nextNewDText
1113 printf ( "end SCRIPTS\n" );
1114 fflush(stderr); fflush(stdout);
1117 Script startNewScript(f) /* start new script, keeping record */
1118 String f; { /* of status for later restoration */
1119 if (scriptHw >= NUM_SCRIPTS) {
1120 ERRMSG(0) "Too many script files in use"
1123 #ifdef DEBUG_SHOWUSE
1124 showUse("Text", textHw, NUM_TEXT);
1125 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
1126 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
1127 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
1128 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
1129 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
1131 showUse("Ext", extHw-EXTMIN, NUM_EXT);
1134 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
1135 scripts[scriptHw].textHw = textHw;
1136 scripts[scriptHw].nextNewText = nextNewText;
1137 scripts[scriptHw].nextNewDText = nextNewDText;
1138 scripts[scriptHw].moduleHw = moduleHw;
1139 scripts[scriptHw].tyconHw = tyconHw;
1140 scripts[scriptHw].nameHw = nameHw;
1141 scripts[scriptHw].classHw = classHw;
1142 scripts[scriptHw].instHw = instHw;
1144 scripts[scriptHw].extHw = extHw;
1149 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1150 return (scriptHw==0);
1153 Bool moduleThisScript(m) /* Test if given module is defined */
1154 Module m; { /* in current script file */
1155 return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
1158 Module lastModule() { /* Return module in current script file */
1159 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1162 #define scriptThis(nm,t,tag) Script nm(x) \
1166 && x>=scripts[s].tag) \
1170 scriptThis(scriptThisName,Name,nameHw)
1171 scriptThis(scriptThisTycon,Tycon,tyconHw)
1172 scriptThis(scriptThisInst,Inst,instHw)
1173 scriptThis(scriptThisClass,Class,classHw)
1176 Module moduleOfScript(s)
1178 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1181 String fileOfModule(m)
1184 if (m == modulePrelude) {
1187 for(s=0; s<scriptHw; ++s) {
1188 if (scripts[s].moduleHw == m) {
1189 return textToStr(scripts[s].file);
1195 Script scriptThisFile(f)
1198 for (s=0; s < scriptHw; ++s) {
1199 if (scripts[s].file == f) {
1203 if (f == findText(STD_PRELUDE)) {
1209 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1210 Script sno; { /* to reading script sno */
1211 if (sno<scriptHw) { /* is there anything to restore? */
1213 textHw = scripts[sno].textHw;
1214 nextNewText = scripts[sno].nextNewText;
1215 nextNewDText = scripts[sno].nextNewDText;
1216 moduleHw = scripts[sno].moduleHw;
1217 tyconHw = scripts[sno].tyconHw;
1218 nameHw = scripts[sno].nameHw;
1219 classHw = scripts[sno].classHw;
1220 instHw = scripts[sno].instHw;
1222 dictHw = scripts[sno].dictHw;
1225 extHw = scripts[sno].extHw;
1229 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1230 if (module(i).objectFile) {
1231 printf("[bogus] closing objectFile for module %d\n",i);
1232 /*dlclose(module(i).objectFile);*/
1235 moduleHw = scripts[sno].moduleHw;
1237 for (i=0; i<TEXTHSZ; ++i) {
1239 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1240 && textHash[i][j]<textHw)
1243 textHash[i][j] = NOTEXT;
1247 for (i=0; i<TYCONHSZ; ++i) {
1250 for (i=0; i<NAMEHSZ; ++i) {
1254 for (i=CLASSMIN; i<classHw; i++) {
1255 List ins = cclass(i).instances;
1258 while (nonNull(ins)) {
1259 List temp = tl(ins);
1260 if (hd(ins)<instHw) {
1266 cclass(i).instances = rev(is);
1273 /* --------------------------------------------------------------------------
1276 * Provides a garbage collectable heap for storage of expressions etc.
1278 * Now incorporates a flat resource: A two-space collected extension of
1279 * the heap that provides storage for contiguous arrays of Cell storage,
1280 * cooperating with the garbage collection mechanisms for the main heap.
1281 * ------------------------------------------------------------------------*/
1283 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1284 Heap heapFst; /* array of fst component of pairs */
1285 Heap heapSnd; /* array of snd component of pairs */
1292 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1293 /* C stack; use with extreme care! */
1295 Int numGcs; /* number of garbage collections */
1296 Int cellsRecovered; /* number of cells recovered */
1298 static Cell freeList; /* free list of unused cells */
1299 static Cell lsave, rsave; /* save components of pair */
1303 static Int markCount, stackRoots;
1305 #define initStackRoots() stackRoots = 0
1306 #define recordStackRoot() stackRoots++
1319 #define start() markCount = 0
1320 #define end(thing,rs) \
1322 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1325 #define recordMark() markCount++
1327 #else /* !GC_STATISTICS */
1332 #define initStackRoots()
1333 #define recordStackRoot()
1336 #define end(thing,root)
1337 #define recordMark()
1339 #endif /* !GC_STATISTICS */
1341 Cell pair(l,r) /* Allocate pair (l, r) from */
1342 Cell l, r; { /* heap, garbage collecting first */
1343 Cell c = freeList; /* if necessary ... */
1355 freeList = snd(freeList);
1362 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1363 Cell dst, src; { /* both *MUST* be pairs */
1364 if (isPair(dst) && isPair(src)) {
1365 fst(dst) = fst(src);
1366 snd(dst) = snd(src);
1369 internal("overwrite");
1373 static Int marksSize;
1375 Cell markExpr(c) /* External interface to markCell */
1377 return isGenPair(c) ? markCell(c) : c;
1380 static Cell local markCell(c) /* Traverse part of graph marking */
1381 Cell c; { /* cells reachable from given root */
1382 /* markCell(c) is only called if c */
1384 { register int place = placeInSet(c);
1385 register int mask = maskInSet(c);
1386 if (marks[place]&mask)
1389 marks[place] |= mask;
1394 if (isGenPair(fst(c))) {
1395 fst(c) = markCell(fst(c));
1398 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1405 static Void local markSnd(c) /* Variant of markCell used to */
1406 Cell c; { /* update snd component of cell */
1407 Cell t; /* using tail recursion */
1409 ma: t = c; /* Keep pointer to original pair */
1414 { register int place = placeInSet(c);
1415 register int mask = maskInSet(c);
1416 if (marks[place]&mask)
1419 marks[place] |= mask;
1424 if (isGenPair(fst(c))) {
1425 fst(c) = markCell(fst(c));
1428 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1433 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1434 Cell n; { /* it was a cell ref, but don't */
1435 /* move cell so we don't have */
1436 /* to modify the stored value of n */
1443 Void garbageCollect() { /* Run garbage collector ... */
1444 Bool breakStat = breakOn(FALSE); /* disable break checking */
1450 jmp_buf regs; /* save registers on stack */
1454 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1457 everybody(MARK); /* Mark all components of system */
1459 gcScanning(); /* scan mark set */
1466 for (i=1; i<=heapSize; i++) {
1467 if ((marks[place] & mask) == 0) {
1474 if (++j == bitsPerWord) {
1481 gcRecovered(recovered);
1482 breakOn(breakStat); /* restore break trapping if nec. */
1486 /* can only return if freeList is nonempty on return. */
1487 if (recovered<minRecovery || isNull(freeList)) {
1488 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1491 cellsRecovered = recovered;
1494 /* --------------------------------------------------------------------------
1495 * Code for saving last expression entered:
1497 * This is a little tricky because some text values (e.g. strings or variable
1498 * names) may not be defined or have the same value when the expression is
1499 * recalled. These text values are therefore saved in the top portion of
1501 * ------------------------------------------------------------------------*/
1503 static Cell lastExprSaved; /* last expression to be saved */
1505 Void setLastExpr(e) /* save expression for later recall*/
1507 lastExprSaved = NIL; /* in case attempt to save fails */
1508 savedText = NUM_TEXT;
1509 lastExprSaved = lowLevelLastIn(e);
1512 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
1513 Cell c; { /* acyclic graph) for later recall */
1514 if (isPair(c)) { /* Duplicating any text strings */
1515 if (isBoxTag(fst(c))) /* in case these are lost at some */
1516 switch (fst(c)) { /* point before the expr is reused */
1522 case STRCELL : return pair(fst(c),saveText(textOf(c)));
1523 default : return pair(fst(c),snd(c));
1526 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
1530 return pair(EXTCOPY,saveText(extText(c)));
1536 Cell getLastExpr() { /* recover previously saved expr */
1537 return lowLevelLastOut(lastExprSaved);
1540 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
1541 Cell c; { /* except that Cells refering to */
1542 if (isPair(c)) { /* Text values are restored to */
1543 if (isBoxTag(fst(c))) /* appropriate values */
1550 case STRCELL : return pair(fst(c),
1551 findText(text+intValOf(c)));
1553 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
1555 default : return pair(fst(c),snd(c));
1558 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
1564 /* --------------------------------------------------------------------------
1565 * Miscellaneous operations on heap cells:
1566 * ------------------------------------------------------------------------*/
1568 /* Profiling suggests that the number of calls to whatIs() is typically */
1569 /* rather high. The recoded version below attempts to improve the average */
1570 /* performance for whatIs() using a binary search for part of the analysis */
1572 Cell whatIs(c) /* identify type of cell */
1575 register Cell fstc = fst(c);
1576 return isTag(fstc) ? fstc : AP;
1578 if (c<TUPMIN) return c;
1579 if (c>=INTMIN) return INTCELL;
1581 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
1583 else if (c>=INSTMIN) return INSTANCE;
1585 else if (c>=MODMIN) {if (c>=TYCMIN) return TYCON;
1586 else return MODULE;}
1587 else if (c>=OFFMIN) return OFFSET;
1589 else return (c>=EXTMIN) ?
1596 register Cell fstc = fst(c);
1597 return isTag(fstc) ? fstc : AP;
1599 if (c>=INTMIN) return INTCELL;
1600 if (c>=CHARMIN) return CHARCELL;
1601 if (c>=CLASSMIN) return CLASS;
1602 if (c>=INSTMIN) return INSTANCE;
1603 if (c>=NAMEMIN) return NAME;
1604 if (c>=TYCMIN) return TYCON;
1605 if (c>=MODMIN) return MODULE;
1606 if (c>=OFFMIN) return OFFSET;
1608 if (c>=EXTMIN) return EXT;
1610 if (c>=TUPMIN) return TUPLE;
1615 /* A very, very simple printer.
1616 * Output is uglier than from printExp - but the printer is more
1617 * robust and can be used on any data structure irrespective of
1620 Void print Args((Cell, Int));
1621 Void print(c, depth)
1626 #if 0 /* Not in this version of Hugs */
1627 } else if (isPair(c) && !isGenPair(c)) {
1628 extern Void printEvalCell Args((Cell, Int));
1629 printEvalCell(c,depth);
1632 Int tag = whatIs(c);
1636 print(fst(c), depth-1);
1638 print(snd(c), depth-1);
1642 Printf("free(%d)", c);
1645 Printf("int(%d)", intOf(c));
1648 Printf("bignum(%s)", bignumToString(c));
1651 Printf("char('%c')", charOf(c));
1654 Printf("ptr(%p)",ptrOf(c));
1657 Printf("class(%d)", c-CLASSMIN);
1658 if (CLASSMIN <= c && c < classHw) {
1659 Printf("=\"%s\"", textToStr(cclass(c).text));
1663 Printf("instance(%d)", c - INSTMIN);
1666 Printf("name(%d)", c-NAMEMIN);
1667 if (NAMEMIN <= c && c < nameHw) {
1668 Printf("=\"%s\"", textToStr(name(c).text));
1672 Printf("tycon(%d)", c-TYCMIN);
1673 if (TYCMIN <= c && c < tyconHw)
1674 Printf("=\"%s\"", textToStr(tycon(c).text));
1677 Printf("module(%d)", c - MODMIN);
1680 Printf("Offset %d", offsetOf(c));
1683 Printf("Tuple %d", tupleOf(c));
1687 print(snd(c),depth-1);
1691 print(snd(c),depth-1);
1695 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
1696 Printf("%d ", intOf(fst(snd(c))));
1697 print(snd(snd(c)),depth-1);
1699 print(snd(c),depth-1);
1716 Printf("{dict %d}",textOf(c));
1722 Printf("{id %s}",textToStr(textOf(c)));
1725 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
1729 print(fst(snd(c)),depth-1);
1731 print(snd(snd(c)),depth-1);
1736 print(snd(c),depth-1);
1741 print(snd(c),depth-1);
1746 print(fst(snd(c)),depth-1);
1748 print(snd(snd(c)),depth-1);
1753 print(fst(snd(c)),depth-1);
1755 print(snd(snd(c)),depth-1);
1759 Printf("FromQual(");
1760 print(fst(snd(c)),depth-1);
1762 print(snd(snd(c)),depth-1);
1766 Printf("StgVar%d=",-c);
1767 print(snd(c), depth-1);
1771 print(fst(snd(c)),depth-1);
1773 print(snd(snd(c)),depth-1);
1778 print(fst(snd(c)),depth-1);
1780 print(snd(snd(c)),depth-1);
1785 print(fst(snd(c)),depth-1);
1787 print(snd(snd(c)),depth-1);
1791 Printf("PrimCase(");
1792 print(fst(snd(c)),depth-1);
1794 print(snd(snd(c)),depth-1);
1798 if (isBoxTag(tag)) {
1799 Printf("Tag(%d)=%d", c, tag);
1800 } else if (isConTag(tag)) {
1801 Printf("%d@(%d,",c,tag);
1802 print(snd(c), depth-1);
1805 } else if (c == tag) {
1806 Printf("Tag(%d)", c);
1808 Printf("Tag(%d)=%d", c, tag);
1817 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
1818 Cell c; { /* also recognises DICTVAR cells */
1820 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
1823 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
1825 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
1828 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
1830 if (!isPair(c)) return FALSE;
1833 case VAROPCELL : return TRUE;
1835 case QUALIDENT : return isVar(snd(snd(c)));
1837 default : return FALSE;
1841 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
1843 if (!isPair(c)) return FALSE;
1846 case CONOPCELL : return TRUE;
1848 case QUALIDENT : return isCon(snd(snd(c)));
1850 default : return FALSE;
1854 Bool isQualIdent(c) /* is cell a qualified identifier? */
1856 return isPair(c) && (fst(c)==QUALIDENT);
1859 Bool isIdent(c) /* is cell an identifier? */
1861 if (!isPair(c)) return FALSE;
1866 case CONOPCELL : return TRUE;
1868 case QUALIDENT : return TRUE;
1870 default : return FALSE;
1874 Bool isInt(c) /* cell holds integer value? */
1876 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
1879 Int intOf(c) /* find integer value of cell? */
1883 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
1886 Cell mkInt(n) /* make cell representing integer */
1888 return (MINSMALLINT <= n && n <= MAXSMALLINT)
1893 #if SIZEOF_INTP == SIZEOF_INT
1894 typedef union {Int i; Ptr p;} IntOrPtr;
1900 return pair(PTRCELL,x.i);
1907 assert(fst(c) == PTRCELL);
1916 return pair(CPTRCELL,x.i);
1923 assert(fst(c) == CPTRCELL);
1927 #elif SIZEOF_INTP == 2*SIZEOF_INT
1928 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
1934 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
1941 assert(fst(c) == PTRCELL);
1942 x.i.i1 = intOf(fst(snd(c)));
1943 x.i.i2 = intOf(snd(snd(c)));
1947 #warning "type Addr not supported on this architecture - don't use it"
1951 ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
1958 ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
1963 String stringNegate( s )
1971 strcpy(&t[1],s); /* ToDo: use strncpy instead */
1976 /* --------------------------------------------------------------------------
1978 * ------------------------------------------------------------------------*/
1980 Int length(xs) /* calculate length of list xs */
1983 for (; nonNull(xs); ++n)
1988 List appendOnto(xs,ys) /* Destructively prepend xs onto */
1989 List xs, ys; { /* ys by modifying xs ... */
1994 while (nonNull(tl(zs)))
2001 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2004 for (; nonNull(xs); xs=tl(xs))
2005 ys = cons(hd(xs),ys);
2009 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2012 return revOnto(dupOnto(xs,NIL),ys);
2015 List dupList(xs) /* Duplicate spine of list xs */
2018 for (; nonNull(xs); xs=tl(xs))
2019 ys = cons(hd(xs),ys);
2023 List revOnto(xs,ys) /* Destructively reverse elements of*/
2024 List xs, ys; { /* list xs onto list ys... */
2027 while (nonNull(xs)) {
2036 Cell varIsMember(t,xs) /* Test if variable is a member of */
2037 Text t; /* given list of variables */
2039 for (; nonNull(xs); xs=tl(xs))
2040 if (t==textOf(hd(xs)))
2045 Name nameIsMember(t,ns) /* Test if name with text t is a */
2046 Text t; /* member of list of names xs */
2048 for (; nonNull(ns); ns=tl(ns))
2049 if (t==name(hd(ns)).text)
2054 Cell intIsMember(n,xs) /* Test if integer n is member of */
2055 Int n; /* given list of integers */
2057 for (; nonNull(xs); xs=tl(xs))
2058 if (n==intOf(hd(xs)))
2063 Cell cellIsMember(x,xs) /* Test for membership of specific */
2064 Cell x; /* cell x in list xs */
2066 for (; nonNull(xs); xs=tl(xs))
2072 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2075 for (; nonNull(xs); xs=tl(xs))
2081 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2082 Cell c; /* association lists */
2084 for (; nonNull(xs); xs=tl(xs))
2090 List replicate(n,x) /* create list of n copies of x */
2099 List diffList(from,take) /* list difference: from\take */
2100 List from, take; { /* result contains all elements of */
2101 List result = NIL; /* `from' not appearing in `take' */
2103 while (nonNull(from)) {
2104 List next = tl(from);
2105 if (!cellIsMember(hd(from),take)) {
2114 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2118 for(;nonNull(xs);xs=tl(xs)) {
2121 result=cons(x,result);
2127 List take(n,xs) /* destructively truncate list to */
2128 Int n; /* specified length */
2134 while (1<n-- && nonNull(xs))
2141 List splitAt(n,xs) /* drop n things from front of list*/
2150 Cell nth(n,xs) /* extract n'th element of list */
2153 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2160 List removeCell(x,xs) /* destructively remove cell from */
2165 return tl(xs); /* element at front of list */
2169 for (; nonNull(curr); prev=curr, curr=tl(prev))
2171 tl(prev) = tl(curr);
2172 return xs; /* element in middle of list */
2176 return xs; /* here if element not found */
2179 List nubList(xs) /* nuke dups in list */
2180 List xs; { /* non destructive */
2182 for (; nonNull(xs); xs=tl(xs))
2183 if (isNull(cellIsMember(hd(xs),outs)))
2184 outs = cons(hd(xs),outs);
2189 /* --------------------------------------------------------------------------
2190 * Operations on applications:
2191 * ------------------------------------------------------------------------*/
2193 Int argCount; /* number of args in application */
2195 Cell getHead(e) /* get head cell of application */
2196 Cell e; { /* set number of args in argCount */
2197 for (argCount=0; isAp(e); e=fun(e))
2202 List getArgs(e) /* get list of arguments in function*/
2203 Cell e; { /* application: */
2204 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2206 for (as=NIL; isAp(e); e=fun(e))
2207 as = cons(arg(e),as);
2211 Cell nthArg(n,e) /* return nth arg in application */
2212 Int n; /* of function to m args (m>=n) */
2213 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2214 for (n=numArgs(e)-n-1; n>0; n--)
2219 Int numArgs(e) /* find number of arguments to expr */
2222 for (n=0; isAp(e); e=fun(e))
2227 Cell applyToArgs(f,args) /* destructively apply list of args */
2228 Cell f; /* to function f */
2230 while (nonNull(args)) {
2231 Cell temp = tl(args);
2232 tl(args) = hd(args);
2241 /* --------------------------------------------------------------------------
2243 * ------------------------------------------------------------------------*/
2245 /*---------------------------------------------------------------------------
2246 * GreenCard entry points
2248 * GreenCard generated code accesses Hugs data structures and functions
2249 * (only) via these functions (which are stored in the virtual function
2251 *-------------------------------------------------------------------------*/
2255 static Cell makeTuple Args((Int));
2256 static Cell makeInt Args((Int));
2257 static Cell makeChar Args((Char));
2258 static Char CharOf Args((Cell));
2259 static Cell makeFloat Args((FloatPro));
2260 static Void* derefMallocPtr Args((Cell));
2261 static Cell* Fst Args((Cell));
2262 static Cell* Snd Args((Cell));
2264 static Cell makeTuple(n) Int n; { return mkTuple(n); }
2265 static Cell makeInt(n) Int n; { return mkInt(n); }
2266 static Cell makeChar(n) Char n; { return mkChar(n); }
2267 static Char CharOf(n) Cell n; { return charOf(n); }
2268 static Cell makeFloat(n) FloatPro n; { return mkFloat(n); }
2269 static Void* derefMallocPtr(n) Cell n; { return derefMP(n); }
2270 static Cell* Fst(n) Cell n; { return (Cell*)&fst(n); }
2271 static Cell* Snd(n) Cell n; { return (Cell*)&snd(n); }
2273 HugsAPI1* hugsAPI1() {
2274 static HugsAPI1 api;
2275 static Bool initialised = FALSE;
2277 api.nameTrue = nameTrue;
2278 api.nameFalse = nameFalse;
2279 api.nameNil = nameNil;
2280 api.nameCons = nameCons;
2281 api.nameJust = nameJust;
2282 api.nameNothing = nameNothing;
2283 api.nameLeft = nameLeft;
2284 api.nameRight = nameRight;
2285 api.nameUnit = nameUnit;
2286 api.nameIORun = nameIORun;
2287 api.makeInt = makeInt;
2288 api.makeChar = makeChar;
2289 api.CharOf = CharOf;
2290 api.makeFloat = makeFloat;
2291 api.makeTuple = makeTuple;
2293 api.mkMallocPtr = mkMallocPtr;
2294 api.derefMallocPtr = derefMallocPtr;
2295 api.mkStablePtr = mkStablePtr;
2296 api.derefStablePtr = derefStablePtr;
2297 api.freeStablePtr = freeStablePtr;
2299 api.evalWithNoError = evalWithNoError;
2300 api.evalFails = evalFails;
2301 api.whnfArgs = &whnfArgs;
2302 api.whnfHead = &whnfHead;
2303 api.whnfInt = &whnfInt;
2304 api.whnfFloat = &whnfFloat;
2305 api.garbageCollect = garbageCollect;
2306 api.stackOverflow = hugsStackOverflow;
2307 api.internal = internal;
2308 api.registerPrims = registerPrims;
2309 api.addPrimCfun = addPrimCfun;
2310 api.inventText = inventText;
2313 api.cellStack = cellStack;
2319 #endif /* GREENCARD */
2322 /* --------------------------------------------------------------------------
2324 * ------------------------------------------------------------------------*/
2327 static void far* safeFarCalloc Args((Int,Int));
2328 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
2329 Int n, s; { /* for non-null return */
2330 void far* tab = farCalloc(n,s);
2332 ERRMSG(0) "Cannot allocate run-time tables"
2337 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
2339 #define TABALLOC(v,t,n)
2347 case RESET : clearStack();
2349 /* the next 2 statements are particularly important
2350 * if you are using GLOBALfst or GLOBALsnd since the
2351 * corresponding registers may be reset to their
2352 * uninitialised initial values by a longjump.
2354 heapTopFst = heapFst + heapSize;
2355 heapTopSnd = heapSnd + heapSize;
2359 if (isNull(lastExprSaved))
2360 savedText = NUM_TEXT;
2365 for (i=NAMEMIN; i<nameHw; ++i) {
2366 mark(name(i).parent);
2368 mark(name(i).stgVar);
2371 end("Names", nameHw-NAMEMIN);
2374 for (i=MODMIN; i<moduleHw; ++i) {
2375 mark(module(i).tycons);
2376 mark(module(i).names);
2377 mark(module(i).classes);
2378 mark(module(i).exports);
2379 mark(module(i).qualImports);
2381 end("Modules", moduleHw-MODMIN);
2384 for (i=TYCMIN; i<tyconHw; ++i) {
2385 mark(tycon(i).defn);
2386 mark(tycon(i).kind);
2387 mark(tycon(i).what);
2389 end("Type constructors", tyconHw-TYCMIN);
2392 for (i=CLASSMIN; i<classHw; ++i) {
2393 mark(cclass(i).head);
2394 mark(cclass(i).kinds);
2395 mark(cclass(i).dsels);
2396 mark(cclass(i).supers);
2397 mark(cclass(i).members);
2398 mark(cclass(i).defaults);
2399 mark(cclass(i).instances);
2402 end("Classes", classHw-CLASSMIN);
2405 for (i=INSTMIN; i<instHw; ++i) {
2407 mark(inst(i).kinds);
2408 mark(inst(i).specifics);
2409 mark(inst(i).implements);
2411 end("Instances", instHw-INSTMIN);
2414 for (i=0; i<=sp; ++i)
2419 mark(lastExprSaved);
2422 end("Last expression", 3);
2427 end("C stack", stackRoots);
2432 case INSTALL : heapFst = heapAlloc(heapSize);
2433 heapSnd = heapAlloc(heapSize);
2435 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
2436 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
2441 heapTopFst = heapFst + heapSize;
2442 heapTopSnd = heapSnd + heapSize;
2443 for (i=1; i<heapSize; ++i) {
2447 snd(-heapSize) = NIL;
2454 marksSize = bitArraySize(heapSize);
2455 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
2456 ERRMSG(0) "Unable to allocate gc markspace"
2460 TABALLOC(text, char, NUM_TEXT)
2461 TABALLOC(tyconHash, Tycon, TYCONHSZ)
2462 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
2463 TABALLOC(nameHash, Name, NAMEHSZ)
2464 TABALLOC(tabName, struct strName, NUM_NAME)
2465 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
2466 TABALLOC(cellStack, Cell, NUM_STACK)
2467 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
2469 TABALLOC(tabExt, Text, NUM_EXT)
2474 nextNewText = NUM_TEXT;
2475 nextNewDText = (-1);
2476 lastExprSaved = NIL;
2477 savedText = NUM_TEXT;
2478 for (i=0; i<TEXTHSZ; ++i)
2479 textHash[i][0] = NOTEXT;
2485 for (i=0; i<TYCONHSZ; ++i)
2492 for (i=0; i<NAMEHSZ; ++i)
2503 tabInst = (struct strInst far *)
2504 farCalloc(NUM_INSTS,sizeof(struct strInst));
2507 ERRMSG(0) "Cannot allocate instance tables"
2517 /*-------------------------------------------------------------------------*/