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/03/01 14:46:54 $
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));
31 static Module local findQualifier Args((Text));
33 static List local insertTycon Args((Tycon,List));
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));
43 Module local moduleOfScript Args((Script));
44 Script local scriptThisFile Args((Text));
47 static Void local freeHandle Args((Int));
50 static Void local resetStablePtrs Args((Void));
54 /* --------------------------------------------------------------------------
57 * provides storage for the characters making up identifier and symbol
58 * names, string literals, character constants etc...
60 * All character strings are stored in a large character array, with textHw
61 * pointing to the next free position. Lookup in the array is improved using
62 * a hash table. Internally, text strings are represented by integer offsets
63 * from the beginning of the array to the string in question.
65 * Where memory permits, the use of multiple hashtables gives a significant
66 * increase in performance, particularly when large source files are used.
68 * Each string in the array is terminated by a zero byte. No string is
69 * stored more than once, so that it is safe to test equality of strings by
70 * comparing the corresponding offsets.
72 * Special text values (beyond the range of the text array table) are used
73 * to generate unique `new variable names' as required.
75 * The same text storage is also used to hold text values stored in a saved
76 * expression. This grows downwards from the top of the text table (and is
77 * not included in the hash table).
78 * ------------------------------------------------------------------------*/
80 #define TEXTHSZ 512 /* Size of Text hash table */
81 #define NOTEXT ((Text)(~0)) /* Empty bucket in Text hash table */
82 static Text textHw; /* Next unused position */
83 static Text savedText = NUM_TEXT; /* Start of saved portion of text */
84 static Text nextNewText; /* Next new text value */
85 static Text nextNewDText; /* Next new dict text value */
86 static char DEFTABLE(text,NUM_TEXT);/* Storage of character strings */
87 static Text textHash[TEXTHSZ][NUM_TEXTH]; /* Hash table storage */
89 String textToStr(t) /* find string corresp to given Text*/
91 static char newVar[16];
93 if (0<=t && t<NUM_TEXT) /* standard char string */
96 sprintf(newVar,"d%d",-t); /* dictionary variable */
98 sprintf(newVar,"v%d",t-NUM_TEXT); /* normal variable */
102 String identToStr(v) /*find string corresp to given ident or qualified name*/
105 internal("identToStr");
111 case CONOPCELL : return text+textOf(v);
113 case QUALIDENT : { Text pos = textHw;
115 while (pos+1 < savedText && text[t]!=0) {
116 text[pos++] = text[t++];
118 if (pos+1 < savedText) {
122 while (pos+1 < savedText && text[t]!=0) {
123 text[pos++] = text[t++];
129 internal("identToStr2");
130 assert(0); return 0; /* NOTREACHED */
133 Text inventText() { /* return new unused variable name */
134 return nextNewText++;
137 Text inventDictText() { /* return new unused dictvar name */
138 return nextNewDText--;
141 Bool inventedText(t) /* Signal TRUE if text has been */
142 Text t; { /* generated internally */
143 return (t<0 || t>=NUM_TEXT);
146 static Int local hash(s) /* Simple hash function on strings */
150 for (v=((int)(*s))*8; *s; s++)
151 v += ((int)(*s))*(j++);
157 Text findText(s) /* Locate string in Text array */
161 Text textPos = textHash[h][hashno];
163 #define TryMatch { Text originalTextPos = textPos; \
165 for (t=s; *t==text[textPos]; textPos++,t++) \
167 return originalTextPos; \
169 #define Skip while (text[textPos++]) ;
171 while (textPos!=NOTEXT) {
173 if (++hashno<NUM_TEXTH) /* look in next hashtable entry */
174 textPos = textHash[h][hashno];
177 while (textPos < textHw) {
188 textPos = textHw; /* if not found, save in array */
189 if (textHw + (Int)strlen(s) + 1 > savedText) {
190 ERRMSG(0) "Character string storage space exhausted"
193 while ((text[textHw++] = *s++) != 0) {
195 if (hashno<NUM_TEXTH) { /* updating hash table as necessary */
196 textHash[h][hashno] = textPos;
197 if (hashno<NUM_TEXTH-1)
198 textHash[h][hashno+1] = NOTEXT;
204 static Int local saveText(t) /* Save text value in buffer */
205 Text t; { /* at top of text table */
206 String s = textToStr(t);
209 if (textHw + l + 1 > savedText) {
210 ERRMSG(0) "Character string storage space exhausted"
214 strcpy(text+savedText,s);
219 /* --------------------------------------------------------------------------
222 * Currently, the only attributes that we store for each Ext value is the
223 * corresponding Text label. At some later stage, we may decide to cache
224 * types, predicates, etc. here as a space saving gesture. Given that Text
225 * comparison is cheap, and that this is an experimental implementation, we
226 * will use a straightforward linear search to locate Ext values from their
227 * corresponding Text labels; a hashing scheme can be introduced later if
228 * this turns out to be a problem.
229 * ------------------------------------------------------------------------*/
232 Text DEFTABLE(tabExt,NUM_EXT); /* Storage for Ext names */
235 Ext mkExt(t) /* Allocate or find an Ext value */
241 if (extHw-EXTMIN >= NUM_EXT) {
242 ERRMSG(0) "Ext storage space exhausted"
250 /* --------------------------------------------------------------------------
253 * A Tycon represents a user defined type constructor. Tycons are indexed
254 * by Text values ... a very simple hash function is used to improve lookup
255 * times. Tycon entries with the same hash code are chained together, with
256 * the most recent entry at the front of the list.
257 * ------------------------------------------------------------------------*/
259 Tycon tyconHw; /* next unused Tycon */
260 struct strTycon DEFTABLE(tabTycon,NUM_TYCON); /* Tycon storage */
262 Tycon newTycon(t) /* add new tycon to tycon table */
264 if (tyconHw-TYCMIN >= NUM_TYCON) {
265 ERRMSG(0) "Type constructor storage space exhausted"
268 tycon(tyconHw).text = t; /* clear new tycon record */
269 tycon(tyconHw).kind = NIL;
270 tycon(tyconHw).defn = NIL;
271 tycon(tyconHw).what = NIL;
272 tycon(tyconHw).conToTag = NIL;
273 tycon(tyconHw).tagToCon = NIL;
275 tycon(tyconHw).mod = currentModule;
276 module(currentModule).tycons = cons(tyconHw,module(currentModule).tycons);
281 Tycon findTycon ( Text t )
284 for (n = TYCMIN; n < tyconHw; n++)
285 if (tycon(n).text == t) return n;
289 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
291 Tycon oldtc = findTycon(tycon(tc).text);
295 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
302 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
304 if (!isPair(id)) internal("findQualTycon");
308 return findTycon(textOf(id));
311 return findTycon(qtextOf(id));
312 #else /* !IGNORE_MODULES */
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)
323 #endif /* !IGNORE_MODULES */
325 default : internal("findQualTycon2");
327 assert(0); return 0; /* NOTREACHED */
330 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
336 Tycon tc = newTycon(t);
338 tycon(tc).kind = kind;
339 tycon(tc).what = what;
340 tycon(tc).defn = defn;
341 tycon(tc).arity = ar;
345 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
350 String s = textToStr(tycon(tc).text);
352 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
353 if (hd(curr)==tc) /* just in case we get duplicates! */
359 tl(prev) = cons(tc,curr);
363 return cons(tc,curr);
366 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
367 String pat; /* to list of Tycons ts */
368 List ts; { /* Null pattern matches every tycon*/
369 Tycon tc; /* (Tycons with NIL kind excluded) */
370 for (tc=TYCMIN; tc<tyconHw; ++tc)
371 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
372 if (nonNull(tycon(tc).kind))
373 ts = insertTycon(tc,ts);
377 /* --------------------------------------------------------------------------
380 * A Name represents a top level binding of a value to an identifier.
381 * Such values may be a constructor function, a member function in a
382 * class, a user-defined or primitive value/function.
384 * Names are indexed by Text values ... a very simple hash functions speeds
385 * access to the table of Names and Name entries with the same hash value
386 * are chained together, with the most recent entry at the front of the
388 * ------------------------------------------------------------------------*/
390 #define NAMEHSZ 256 /* Size of Name hash table */
391 #define nHash(x) ((x)%NAMEHSZ) /* hash fn :: Text->Int */
392 Name nameHw; /* next unused name */
393 static Name DEFTABLE(nameHash,NAMEHSZ); /* Hash table storage */
394 struct strName DEFTABLE(tabName,NUM_NAME); /* Name table storage */
396 Name newName(t,parent) /* Add new name to name table */
401 if (nameHw-NAMEMIN >= NUM_NAME) {
402 ERRMSG(0) "Name storage space exhausted"
405 name(nameHw).text = t; /* clear new name record */
406 name(nameHw).line = 0;
407 name(nameHw).syntax = NO_SYNTAX;
408 name(nameHw).parent = parent;
409 name(nameHw).arity = 0;
410 name(nameHw).number = EXECNAME;
411 name(nameHw).defn = NIL;
412 name(nameHw).stgVar = NIL;
413 name(nameHw).type = NIL;
414 name(nameHw).primop = 0;
415 name(nameHw).mod = currentModule;
416 module(currentModule).names=cons(nameHw,module(currentModule).names);
420 Name findName ( Text t )
423 for (n = NAMEMIN; n < nameHw; n++)
424 if (name(n).text == t) return n;
430 Name addName(nm) /* Insert Name in name table - if */
431 Name nm; { /* no clash is caused */
432 Name oldnm = findName(name(nm).text);
436 module(currentModule).names=cons(nm,module(currentModule).names);
443 Name findQualName(id) /* Locate (possibly qualified) name*/
444 Cell id; { /* in name table */
446 internal("findQualName");
452 return findName(textOf(id));
455 return findName(qtextOf(id));
456 #else /* !IGNORE_MODULES */
457 Text t = qtextOf(id);
458 Module m = findQualifier(qmodOf(id));
460 if (isNull(m)) return NIL;
461 if (m==currentModule) {
462 /* The Haskell report (rightly) forbids this.
463 * We added it to let the Prelude refer to itself
464 * without having to import itself.
468 for(es=module(m).exports; nonNull(es); es=tl(es)) {
470 if (isName(e) && name(e).text==t)
472 else if (isPair(e) && DOTDOT==snd(e)) {
473 List subentities = NIL;
476 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
477 subentities = tycon(c).defn;
479 subentities = cclass(c).members;
480 for(; nonNull(subentities); subentities=tl(subentities)) {
481 assert(isName(hd(subentities)));
482 if (name(hd(subentities)).text == t)
483 return hd(subentities);
488 #endif /* !IGNORE_MODULES */
490 default : internal("findQualName2");
492 assert(0); return 0; /* NOTREACHED */
495 /* --------------------------------------------------------------------------
496 * Primitive functions:
497 * ------------------------------------------------------------------------*/
499 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
500 Text t; /* sets rep, not type */
503 Int rep; { /* Really AsmRep */
504 Name n = newName(t,NIL);
505 name(n).arity = arity;
506 name(n).number = cfunNo(no);
508 name(n).primop = (void*)rep;
513 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
518 Name n = newName(t,NIL);
519 name(n).arity = arity;
520 name(n).number = cfunNo(no);
526 Int sfunPos(s,c) /* Find position of field with */
527 Name s; /* selector s in constructor c. */
531 for (; nonNull(cns); cns=tl(cns))
533 return intOf(snd(hd(cns)));
535 return 0;/* NOTREACHED */
538 static List local insertName(nm,ns) /* insert name nm into sorted list */
543 String s = textToStr(name(nm).text);
545 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
546 if (hd(curr)==nm) /* just in case we get duplicates! */
552 tl(prev) = cons(nm,curr);
556 return cons(nm,curr);
559 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
560 String pat; /* to list of names ns */
561 List ns; { /* Null pattern matches every name */
562 Name nm; /* (Names with NIL type, or hidden */
564 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
565 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
566 String str = textToStr(name(nm).text);
567 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
568 ns = insertName(nm,ns);
572 List mns = module(currentModule).names;
573 for(; nonNull(mns); mns=tl(mns)) {
575 if (!inventedText(name(nm).text)) {
576 String str = textToStr(name(nm).text);
577 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
578 ns = insertName(nm,ns);
585 /* --------------------------------------------------------------------------
586 * A simple string matching routine
587 * `*' matches any sequence of zero or more characters
588 * `?' matches any single character exactly
589 * `@str' matches the string str exactly (ignoring any special chars)
590 * `\c' matches the character c only (ignoring special chars)
591 * c matches the character c only
592 * ------------------------------------------------------------------------*/
594 static Void local patternError(s) /* report error in pattern */
596 ERRMSG(0) "%s in pattern", s
600 static Bool local stringMatch(pat,str) /* match string against pattern */
606 case '\0' : return (*str=='\0');
609 if (stringMatch(pat+1,str))
614 case '?' : if (*str++=='\0')
619 case '[' : { Bool found = FALSE;
620 while (*++pat!='\0' && *pat!=']')
621 if (!found && ( pat[0] == *str ||
630 patternError("missing `]'");
638 case '\\' : if (*++pat == '\0')
639 patternError("extra trailing `\\'");
641 default : if (*pat++ != *str++)
647 /* --------------------------------------------------------------------------
648 * Storage of type classes, instances etc...:
649 * ------------------------------------------------------------------------*/
651 static Class classHw; /* next unused class */
652 static List classes; /* list of classes in current scope */
653 static Inst instHw; /* next unused instance record */
655 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
656 struct strInst far *tabInst; /* (pointer to) table of instances */
658 Class newClass(t) /* add new class to class table */
660 if (classHw-CLASSMIN >= NUM_CLASSES) {
661 ERRMSG(0) "Class storage space exhausted"
664 cclass(classHw).text = t;
665 cclass(classHw).arity = 0;
666 cclass(classHw).kinds = NIL;
667 cclass(classHw).head = NIL;
668 cclass(classHw).dcon = NIL;
669 cclass(classHw).supers = NIL;
670 cclass(classHw).dsels = NIL;
671 cclass(classHw).members = NIL;
672 cclass(classHw).dbuild = NIL;
673 cclass(classHw).defaults = NIL;
674 cclass(classHw).instances = NIL;
675 classes=cons(classHw,classes);
677 cclass(classHw).mod = currentModule;
678 module(currentModule).classes=cons(classHw,module(currentModule).classes);
683 Class classMax() { /* Return max Class in use ... */
684 return classHw; /* This is a bit ugly, but it's not*/
685 } /* worth a lot of effort right now */
687 Class findClass(t) /* look for named class in table */
691 for (cs=classes; nonNull(cs); cs=tl(cs)) {
693 if (cclass(cl).text==t)
699 Class addClass(c) /* Insert Class in class list */
700 Class c; { /* - if no clash caused */
701 Class oldc = findClass(cclass(c).text);
703 classes=cons(c,classes);
705 module(currentModule).classes=cons(c,module(currentModule).classes);
713 Class findQualClass(c) /* Look for (possibly qualified) */
714 Cell c; { /* class in class list */
715 if (!isQualIdent(c)) {
716 return findClass(textOf(c));
719 return findClass(qtextOf(c));
720 #else /* !IGNORE_MODULES */
722 Module m = findQualifier(qmodOf(c));
726 for (es=module(m).exports; nonNull(es); es=tl(es)) {
728 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
736 Inst newInst() { /* Add new instance to table */
737 if (instHw-INSTMIN >= NUM_INSTS) {
738 ERRMSG(0) "Instance storage space exhausted"
741 inst(instHw).kinds = NIL;
742 inst(instHw).head = NIL;
743 inst(instHw).specifics = NIL;
744 inst(instHw).implements = NIL;
745 inst(instHw).builder = NIL;
746 /* from STG */ inst(instHw).mod = currentModule;
752 extern Void printInst Args((Inst));
756 Class cl = inst(in).c;
757 Printf("%s-", textToStr(cclass(cl).text));
758 printType(stdout,inst(in).t);
760 #endif /* DEBUG_DICTS */
762 Inst findFirstInst(tc) /* look for 1st instance involving */
763 Tycon tc; { /* the type constructor tc */
764 return findNextInst(tc,INSTMIN-1);
767 Inst findNextInst(tc,in) /* look for next instance involving*/
768 Tycon tc; /* the type constructor tc */
769 Inst in; { /* starting after instance in */
770 while (++in < instHw) {
771 Cell pi = inst(in).head;
772 for (; isAp(pi); pi=fun(pi))
773 if (typeInvolves(arg(pi),tc))
779 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
780 Type ty; /* type constructor/tuple tc. */
783 || (isAp(ty) && (typeInvolves(fun(ty),tc)
784 || typeInvolves(arg(ty),tc)));
787 /* --------------------------------------------------------------------------
790 * Various parts of the system use a stack of cells. Most of the stack
791 * operations are defined as macros, expanded inline.
792 * ------------------------------------------------------------------------*/
794 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
795 StackPtr sp; /* stack pointer */
797 #if GIMME_STACK_DUMPS
799 #define UPPER_DISP 5 /* # display entries on top of stack */
800 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
802 Void hugsStackOverflow() { /* Report stack overflow */
804 extern Cell evalRoots[];
806 ERRMSG(0) "Control stack overflow" ETHEN
809 if (rootsp>=UPPER_DISP+LOWER_DISP) {
810 for (i=0; i<UPPER_DISP; i++) {
811 ERRTEXT "\nwhile evaluating: " ETHEN
812 ERREXPR(evalRoots[rootsp-i]);
814 ERRTEXT "\n..." ETHEN
815 for (i=LOWER_DISP-1; i>=0; i--) {
816 ERRTEXT "\nwhile evaluating: " ETHEN
817 ERREXPR(evalRoots[i]);
821 for (i=rootsp; i>=0; i--) {
822 ERRTEXT "\nwhile evaluating: " ETHEN
823 ERREXPR(evalRoots[i]);
831 #else /* !GIMME_STACK_DUMPS */
833 Void hugsStackOverflow() { /* Report stack overflow */
834 ERRMSG(0) "Control stack overflow"
838 #endif /* !GIMME_STACK_DUMPS */
840 /* --------------------------------------------------------------------------
843 * A Module represents a user defined module.
845 * Note: there are now two lookup mechanisms in the system:
847 * 1) The exports from a module are stored in a big list.
848 * We resolve qualified names, and import lists by linearly scanning
851 * 2) Unqualified imports and local definitions for the current module
852 * are stored in hash tables (tyconHash and nameHash) or linear lists
855 * ------------------------------------------------------------------------*/
858 static Module moduleHw; /* next unused Module */
859 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
860 Module currentModule; /* Module currently being processed*/
862 Bool isValidModule(m) /* is m a legitimate module id? */
864 return (MODMIN <= m && m < moduleHw);
867 Module newModule(t) /* add new module to module table */
869 if (moduleHw-MODMIN >= NUM_MODULE) {
870 ERRMSG(0) "Module storage space exhausted"
873 module(moduleHw).text = t; /* clear new module record */
874 module(moduleHw).qualImports = NIL;
875 module(moduleHw).exports = NIL;
876 module(moduleHw).tycons = NIL;
877 module(moduleHw).names = NIL;
878 module(moduleHw).classes = NIL;
879 module(moduleHw).objectFile = 0;
883 Module findModule(t) /* locate Module in module table */
886 for(m=MODMIN; m<moduleHw; ++m) {
887 if (module(m).text==t)
893 Module findModid(c) /* Find module by name or filename */
896 case STRCELL : { Script s = scriptThisFile(snd(c));
897 return (s==-1) ? NIL : moduleOfScript(s);
899 case CONIDCELL : return findModule(textOf(c));
900 default : internal("findModid");
902 assert(0); return 0; /* NOTREACHED */
905 static local Module findQualifier(t) /* locate Module in import list */
908 ////if (t==module(modulePreludeHugs).text) {
909 if (t==module(modulePrelude).text) {
910 /* The Haskell report (rightly) forbids this.
911 * We added it to let the Prelude refer to itself
912 * without having to import itself.
914 ////return modulePreludeHugs;
915 return modulePrelude;
917 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
918 if (textOf(fst(hd(ms)))==t)
922 if (module(currentModule).text==t)
923 return currentModule;
928 Void setCurrModule(m) /* set lookup tables for current module */
931 if (m!=currentModule) {
932 currentModule = m; /* This is the only assignment to currentModule */
934 for (i=0; i<TYCONHSZ; ++i)
936 mapProc(hashTycon,module(m).tycons);
937 for (i=0; i<NAMEHSZ; ++i)
939 mapProc(hashName,module(m).names);
941 classes = module(m).classes;
944 #endif /* !IGNORE_MODULES */
946 /* --------------------------------------------------------------------------
947 * Script file storage:
949 * script files are read into the system one after another. The state of
950 * the stored data structures (except the garbage-collected heap) is recorded
951 * before reading a new script. In the event of being unable to read the
952 * script, or if otherwise requested, the system can be restored to its
953 * original state immediately before the file was read.
954 * ------------------------------------------------------------------------*/
956 typedef struct { /* record of storage state prior to */
957 Text file; /* reading script/module */
974 static Void local showUse(msg,val,mx)
977 Printf("%6s : %d of %d (%d%%)\n",msg,val,mx,(100*val)/mx);
981 static Script scriptHw; /* next unused script number */
982 static script scripts[NUM_SCRIPTS]; /* storage for script records */
984 Script startNewScript(f) /* start new script, keeping record */
985 String f; { /* of status for later restoration */
986 if (scriptHw >= NUM_SCRIPTS) {
987 ERRMSG(0) "Too many script files in use"
991 showUse("Text", textHw, NUM_TEXT);
993 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
995 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
996 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
997 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
998 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
1000 showUse("Ext", extHw-EXTMIN, NUM_EXT);
1004 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
1005 scripts[scriptHw].textHw = textHw;
1006 scripts[scriptHw].nextNewText = nextNewText;
1007 scripts[scriptHw].nextNewDText = nextNewDText;
1009 scripts[scriptHw].moduleHw = moduleHw;
1011 scripts[scriptHw].tyconHw = tyconHw;
1012 scripts[scriptHw].nameHw = nameHw;
1013 scripts[scriptHw].classHw = classHw;
1014 scripts[scriptHw].instHw = instHw;
1016 scripts[scriptHw].extHw = extHw;
1021 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1023 /*ToDo: jrs hack*/ || scriptHw==1
1028 Bool moduleThisScript(m) /* Test if given module is defined */
1029 Module m; { /* in current script file */
1030 return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
1033 Module lastModule() { /* Return module in current script file */
1034 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1036 #endif /* !IGNORE_MODULES */
1038 #define scriptThis(nm,t,tag) Script nm(x) \
1042 && x>=scripts[s].tag) \
1046 scriptThis(scriptThisName,Name,nameHw)
1047 scriptThis(scriptThisTycon,Tycon,tyconHw)
1048 scriptThis(scriptThisInst,Inst,instHw)
1049 scriptThis(scriptThisClass,Class,classHw)
1052 Module moduleOfScript(s)
1054 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1058 String fileOfModule(m)
1061 if (m == modulePrelude) {
1064 for(s=0; s<scriptHw; ++s) {
1065 if (scripts[s].moduleHw == m) {
1066 return textToStr(scripts[s].file);
1073 Script scriptThisFile(f)
1076 for (s=0; s < scriptHw; ++s) {
1077 if (scripts[s].file == f) {
1081 if (f == findText(STD_PRELUDE)) {
1087 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1088 Script sno; { /* to reading script sno */
1089 if (sno<scriptHw) { /* is there anything to restore? */
1091 textHw = scripts[sno].textHw;
1092 nextNewText = scripts[sno].nextNewText;
1093 nextNewDText = scripts[sno].nextNewDText;
1095 moduleHw = scripts[sno].moduleHw;
1097 tyconHw = scripts[sno].tyconHw;
1098 nameHw = scripts[sno].nameHw;
1099 classHw = scripts[sno].classHw;
1100 instHw = scripts[sno].instHw;
1102 dictHw = scripts[sno].dictHw;
1105 extHw = scripts[sno].extHw;
1108 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1109 if (module(i).objectFile) {
1110 printf("[bogus] closing objectFile for module %d\n",i);
1111 /*dlclose(module(i).objectFile);*/
1114 moduleHw = scripts[sno].moduleHw;
1116 for (i=0; i<TEXTHSZ; ++i) {
1118 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1119 && textHash[i][j]<textHw)
1122 textHash[i][j] = NOTEXT;
1126 for (i=0; i<TYCONHSZ; ++i) {
1127 Tycon tc = tyconHash[i];
1128 while (nonNull(tc) && tc>=tyconHw)
1129 tc = tycon(tc).nextTyconHash;
1133 for (i=0; i<NAMEHSZ; ++i) {
1134 Name n = nameHash[i];
1135 while (nonNull(n) && n>=nameHw)
1136 n = name(n).nextNameHash;
1139 #else /* !IGNORE_MODULES */
1142 for (i=0; i<TYCONHSZ; ++i) {
1145 for (i=0; i<NAMEHSZ; ++i) {
1149 #endif /* !IGNORE_MODULES */
1151 for (i=CLASSMIN; i<classHw; i++) {
1152 List ins = cclass(i).instances;
1155 while (nonNull(ins)) {
1156 List temp = tl(ins);
1157 if (hd(ins)<instHw) {
1163 cclass(i).instances = rev(is);
1170 /* --------------------------------------------------------------------------
1173 * Provides a garbage collectable heap for storage of expressions etc.
1175 * Now incorporates a flat resource: A two-space collected extension of
1176 * the heap that provides storage for contiguous arrays of Cell storage,
1177 * cooperating with the garbage collection mechanisms for the main heap.
1178 * ------------------------------------------------------------------------*/
1180 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1181 Heap heapFst; /* array of fst component of pairs */
1182 Heap heapSnd; /* array of snd component of pairs */
1189 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1190 /* C stack; use with extreme care! */
1192 Heap heapThd, heapTopThd; /* to keep record of producers */
1193 Int sysCount; /* record unattached cells */
1194 Name producer; /* current producer, if any */
1195 Bool profiling = FALSE; /* should profiling be performed */
1196 Int profInterval = MAXPOSINT; /* interval between samples */
1197 FILE *profile = 0; /* pointer to profiler log, if any */
1200 Int numGcs; /* number of garbage collections */
1201 Int cellsRecovered; /* number of cells recovered */
1203 static Cell freeList; /* free list of unused cells */
1204 static Cell lsave, rsave; /* save components of pair */
1207 static List weakPtrs; /* list of weak ptrs */
1208 /* reconstructed during every GC */
1209 List finalizers = NIL;
1210 List liveWeakPtrs = NIL;
1215 static Int markCount, stackRoots;
1217 #define initStackRoots() stackRoots = 0
1218 #define recordStackRoot() stackRoots++
1231 #define start() markCount = 0
1232 #define end(thing,rs) \
1234 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1237 #define recordMark() markCount++
1239 #else /* !GC_STATISTICS */
1244 #define initStackRoots()
1245 #define recordStackRoot()
1248 #define end(thing,root)
1249 #define recordMark()
1251 #endif /* !GC_STATISTICS */
1253 Cell pair(l,r) /* Allocate pair (l, r) from */
1254 Cell l, r; { /* heap, garbage collecting first */
1255 Cell c = freeList; /* if necessary ... */
1267 freeList = snd(freeList);
1277 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1278 Cell dst, src; { /* both *MUST* be pairs */
1279 if (isPair(dst) && isPair(src)) {
1280 fst(dst) = fst(src);
1281 snd(dst) = snd(src);
1284 internal("overwrite");
1288 static Int marksSize;
1290 Cell markExpr(c) /* External interface to markCell */
1292 return isGenPair(c) ? markCell(c) : c;
1295 static Cell local markCell(c) /* Traverse part of graph marking */
1296 Cell c; { /* cells reachable from given root */
1297 /* markCell(c) is only called if c */
1299 { register int place = placeInSet(c);
1300 register int mask = maskInSet(c);
1301 if (marks[place]&mask)
1304 marks[place] |= mask;
1309 if (isGenPair(fst(c))) {
1310 fst(c) = markCell(fst(c));
1313 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1320 static Void local markSnd(c) /* Variant of markCell used to */
1321 Cell c; { /* update snd component of cell */
1322 Cell t; /* using tail recursion */
1324 ma: t = c; /* Keep pointer to original pair */
1329 { register int place = placeInSet(c);
1330 register int mask = maskInSet(c);
1331 if (marks[place]&mask)
1334 marks[place] |= mask;
1339 if (isGenPair(fst(c))) {
1340 fst(c) = markCell(fst(c));
1343 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1348 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1349 Cell n; { /* it was a cell ref, but don't */
1350 /* move cell so we don't have */
1351 /* to modify the stored value of n */
1358 Void garbageCollect() { /* Run garbage collector ... */
1359 Bool breakStat = breakOn(FALSE); /* disable break checking */
1365 jmp_buf regs; /* save registers on stack */
1366 printf("\n\n$$$$$$$$$$$ GARBAGE COLLECTION; aborting\n\n");
1371 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1374 weakPtrs = NIL; /* clear list of weak pointers */
1376 everybody(MARK); /* Mark all components of system */
1379 for (i=0; i<NUM_HANDLES; ++i) /* release any unused handles */
1380 if (nonNull(handles[i].hcell)) {
1381 register place = placeInSet(handles[i].hcell);
1382 register mask = maskInSet(handles[i].hcell);
1383 if ((marks[place]&mask)==0)
1388 for (i=0; i<NUM_MALLOCPTRS; ++i) /* release any unused mallocptrs */
1389 if (isPair(mallocPtrs[i].mpcell)) {
1390 register place = placeInSet(mallocPtrs[i].mpcell);
1391 register mask = maskInSet(mallocPtrs[i].mpcell);
1392 if ((marks[place]&mask)==0)
1393 incMallocPtrRefCnt(i,-1);
1395 #endif /* GC_MALLOCPTRS */
1397 /* After GC completes, we scan the list of weak pointers that are
1398 * still live and zap their contents unless the contents are still
1399 * live (by some other means).
1400 * Note that this means the contents must itself be heap allocated.
1401 * This means it can't be a nullary constructor or an Int or a Name
1402 * or lots of other things - hope this doesn't bite too hard.
1404 for (; nonNull(weakPtrs); weakPtrs=nextWeakPtr(weakPtrs)) {
1405 Cell ptr = derefWeakPtr(weakPtrs);
1406 if (isGenPair(ptr)) {
1407 Int place = placeInSet(ptr);
1408 Int mask = maskInSet(ptr);
1409 if ((marks[place]&mask)==0) {
1410 /* printf("Zapping weak pointer %d\n", ptr); */
1411 derefWeakPtr(weakPtrs) = NIL;
1413 /* printf("Keeping weak pointer %d\n", ptr); */
1415 } else if (nonNull(ptr)) {
1416 printf("Weak ptr contains object which isn't heap allocated %d\n", ptr);
1420 if (nonNull(liveWeakPtrs) || nonNull(finalizers)) {
1421 Bool anyMarked; /* Weak pointers with finalizers */
1425 /* Step 1: iterate until we've found out what is reachable */
1428 for (wps=liveWeakPtrs; nonNull(wps); wps=tl(wps)) {
1430 Cell k = fst(snd(wp));
1432 internal("bad weak ptr");
1435 Cell vf = snd(snd(wp));
1436 if (!isMarked(fst(vf)) || !isMarked(snd(vf))) {
1443 } while (anyMarked);
1445 /* Step 2: Now we know which weak pointers will die, so we can */
1446 /* remove them from the live set and gather their finalizers. But */
1447 /* note that we mustn't mark *anything* at this stage or we will */
1448 /* corrupt our view of what's alive, and what's dead. */
1450 while (nonNull(liveWeakPtrs)) {
1451 Cell wp = hd(liveWeakPtrs);
1452 List nx = tl(liveWeakPtrs);
1453 Cell k = fst(snd(wp));
1454 if (!isMarked(k)) { /* If the key is dead, then*/
1455 Cell vf = snd(snd(wp)); /* stomp on weak pointer */
1458 newFins = vf; /* reuse because we can't */
1459 fst(snd(wp)) = NIL; /* reallocate here ... */
1464 tl(liveWeakPtrs) = wps; /* Otherwise, weak pointer */
1465 wps = liveWeakPtrs;/* survives to face another*/
1466 liveWeakPtrs = nx; /* garbage collection */
1470 /* Step 3: Now we've identified the live cells and the newly */
1471 /* scheduled finalizers, but we had better make sure that they are */
1472 /* all marked now, including any internal structure, to ensure that*/
1473 /* they make it to the other side of gc. */
1474 for (liveWeakPtrs=wps; nonNull(wps); wps=tl(wps)) {
1479 finalizers = revOnto(newFins,finalizers);
1482 #endif /* GC_WEAKPTRS */
1483 gcScanning(); /* scan mark set */
1491 for (i=NAMEMIN; i<nameHw; i++)
1496 for (i=1; i<=heapSize; i++) {
1497 if ((marks[place] & mask) == 0) {
1504 else if (nonNull(thd(-i)))
1505 name(thd(-i)).count++;
1510 if (++j == bitsPerWord) {
1517 gcRecovered(recovered);
1518 breakOn(breakStat); /* restore break trapping if nec. */
1522 fprintf(profile,"BEGIN_SAMPLE %ld.00\n",numReductions);
1523 /* For the time being, we won't include the system count in the output:
1525 fprintf(profile," SYSTEM %d\n",sysCount);
1527 /* Accumulate costs in top level objects */
1528 for (i=NAMEMIN; i<nameHw; i++) {
1530 /* Use of "while" instead of "if" is pure paranoia - ADR */
1531 while (isName(name(cc).parent))
1532 cc = name(cc).parent;
1534 name(cc).count += name(i).count;
1538 for (i=NAMEMIN; i<nameHw; i++)
1539 if (name(i).count>0)
1540 if (isPair(name(i).parent)) {
1541 Pair p = name(i).parent;
1543 fprintf(profile," ");
1545 fprintf(profile,"%s",textToStr(cclass(f).text));
1547 fprintf(profile,"%s_",textToStr(cclass(inst(f).c).text));
1548 /* Will hp2ps accept the spaces produced by this? */
1549 printPred(profile,inst(f).head);
1551 fprintf(profile,"_%s %d\n",
1552 textToStr(name(snd(p)).text),
1555 fprintf(profile," %s %d\n",
1556 textToStr(name(i).text),
1559 fprintf(profile,"END_SAMPLE %ld.00\n",numReductions);
1563 /* can only return if freeList is nonempty on return. */
1564 if (recovered<minRecovery || isNull(freeList)) {
1565 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1568 cellsRecovered = recovered;
1572 Void profilerLog(s) /* turn heap profiling on, saving log*/
1573 String s; { /* in specified file */
1574 if ((profile=fopen(s,"w")) != NULL) {
1575 fprintf(profile,"JOB \"Hugs Heap Profile\"\n");
1576 fprintf(profile,"DATE \"%s\"\n",timeString());
1577 fprintf(profile,"SAMPLE_UNIT \"reductions\"\n");
1578 fprintf(profile,"VALUE_UNIT \"cells\"\n");
1581 ERRMSG(0) "Cannot open profile log file \"%s\"", s
1587 /* --------------------------------------------------------------------------
1588 * Code for saving last expression entered:
1590 * This is a little tricky because some text values (e.g. strings or variable
1591 * names) may not be defined or have the same value when the expression is
1592 * recalled. These text values are therefore saved in the top portion of
1594 * ------------------------------------------------------------------------*/
1596 static Cell lastExprSaved; /* last expression to be saved */
1598 Void setLastExpr(e) /* save expression for later recall*/
1600 lastExprSaved = NIL; /* in case attempt to save fails */
1601 savedText = NUM_TEXT;
1602 lastExprSaved = lowLevelLastIn(e);
1605 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
1606 Cell c; { /* acyclic graph) for later recall */
1607 if (isPair(c)) { /* Duplicating any text strings */
1608 if (isBoxTag(fst(c))) /* in case these are lost at some */
1609 switch (fst(c)) { /* point before the expr is reused */
1615 case STRCELL : return pair(fst(c),saveText(textOf(c)));
1616 default : return pair(fst(c),snd(c));
1619 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
1623 return pair(EXTCOPY,saveText(extText(c)));
1629 Cell getLastExpr() { /* recover previously saved expr */
1630 return lowLevelLastOut(lastExprSaved);
1633 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
1634 Cell c; { /* except that Cells refering to */
1635 if (isPair(c)) { /* Text values are restored to */
1636 if (isBoxTag(fst(c))) /* appropriate values */
1643 case STRCELL : return pair(fst(c),
1644 findText(text+intValOf(c)));
1646 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
1648 default : return pair(fst(c),snd(c));
1651 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
1657 /* --------------------------------------------------------------------------
1658 * Miscellaneous operations on heap cells:
1659 * ------------------------------------------------------------------------*/
1661 /* Profiling suggests that the number of calls to whatIs() is typically */
1662 /* rather high. The recoded version below attempts to improve the average */
1663 /* performance for whatIs() using a binary search for part of the analysis */
1665 Cell whatIs(c) /* identify type of cell */
1668 register Cell fstc = fst(c);
1669 return isTag(fstc) ? fstc : AP;
1671 if (c<TUPMIN) return c;
1672 if (c>=INTMIN) return INTCELL;
1674 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
1676 else if (c>=INSTMIN) return INSTANCE;
1678 else if (c>=MODMIN) {if (c>=TYCMIN) return TYCON;
1679 else return MODULE;}
1680 else if (c>=OFFMIN) return OFFSET;
1682 else return (c>=EXTMIN) ?
1689 register Cell fstc = fst(c);
1690 return isTag(fstc) ? fstc : AP;
1692 if (c>=INTMIN) return INTCELL;
1693 if (c>=CHARMIN) return CHARCELL;
1694 if (c>=CLASSMIN) return CLASS;
1695 if (c>=INSTMIN) return INSTANCE;
1696 if (c>=NAMEMIN) return NAME;
1697 if (c>=TYCMIN) return TYCON;
1698 if (c>=MODMIN) return MODULE;
1699 if (c>=OFFMIN) return OFFSET;
1701 if (c>=EXTMIN) return EXT;
1703 if (c>=TUPMIN) return TUPLE;
1708 /* A very, very simple printer.
1709 * Output is uglier than from printExp - but the printer is more
1710 * robust and can be used on any data structure irrespective of
1713 Void print Args((Cell, Int));
1714 Void print(c, depth)
1719 #if 0 /* Not in this version of Hugs */
1720 } else if (isPair(c) && !isGenPair(c)) {
1721 extern Void printEvalCell Args((Cell, Int));
1722 printEvalCell(c,depth);
1725 Int tag = whatIs(c);
1729 print(fst(c), depth-1);
1731 print(snd(c), depth-1);
1735 Printf("free(%d)", c);
1738 Printf("int(%d)", intOf(c));
1741 Printf("bignum(%s)", bignumToString(c));
1744 Printf("char('%c')", charOf(c));
1747 Printf("ptr(%p)",ptrOf(c));
1750 Printf("class(%d)", c-CLASSMIN);
1751 if (CLASSMIN <= c && c < classHw) {
1752 Printf("=\"%s\"", textToStr(cclass(c).text));
1756 Printf("instance(%d)", c - INSTMIN);
1759 Printf("name(%d)", c-NAMEMIN);
1760 if (NAMEMIN <= c && c < nameHw) {
1761 Printf("=\"%s\"", textToStr(name(c).text));
1765 Printf("tycon(%d)", c-TYCMIN);
1766 if (TYCMIN <= c && c < tyconHw)
1767 Printf("=\"%s\"", textToStr(tycon(c).text));
1770 Printf("module(%d)", c - MODMIN);
1773 Printf("Offset %d", offsetOf(c));
1776 Printf("Tuple %d", tupleOf(c));
1780 print(snd(c),depth-1);
1784 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
1785 Printf("%d ", intOf(fst(snd(c))));
1786 print(snd(snd(c)),depth-1);
1788 print(snd(c),depth-1);
1805 Printf("{dict %d}",textOf(c));
1811 Printf("{id %s}",textToStr(textOf(c)));
1814 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
1818 print(fst(snd(c)),depth-1);
1820 print(snd(snd(c)),depth-1);
1825 print(snd(c),depth-1);
1830 print(snd(c),depth-1);
1835 print(fst(snd(c)),depth-1);
1837 print(snd(snd(c)),depth-1);
1842 print(fst(snd(c)),depth-1);
1844 print(snd(snd(c)),depth-1);
1848 Printf("FromQual(");
1849 print(fst(snd(c)),depth-1);
1851 print(snd(snd(c)),depth-1);
1855 Printf("StgVar%d=",-c);
1856 print(snd(c), depth-1);
1860 print(fst(snd(c)),depth-1);
1862 print(snd(snd(c)),depth-1);
1867 print(fst(snd(c)),depth-1);
1869 print(snd(snd(c)),depth-1);
1874 print(fst(snd(c)),depth-1);
1876 print(snd(snd(c)),depth-1);
1880 Printf("PrimCase(");
1881 print(fst(snd(c)),depth-1);
1883 print(snd(snd(c)),depth-1);
1887 if (isBoxTag(tag)) {
1888 Printf("Tag(%d)=%d", c, tag);
1889 } else if (isConTag(tag)) {
1890 Printf("%d@(%d,",c,tag);
1891 print(snd(c), depth-1);
1894 } else if (c == tag) {
1895 Printf("Tag(%d)", c);
1897 Printf("Tag(%d)=%d", c, tag);
1906 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
1907 Cell c; { /* also recognises DICTVAR cells */
1909 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
1912 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
1914 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
1917 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
1919 if (!isPair(c)) return FALSE;
1922 case VAROPCELL : return TRUE;
1924 case QUALIDENT : return isVar(snd(snd(c)));
1926 default : return FALSE;
1930 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
1932 if (!isPair(c)) return FALSE;
1935 case CONOPCELL : return TRUE;
1937 case QUALIDENT : return isCon(snd(snd(c)));
1939 default : return FALSE;
1943 Bool isQualIdent(c) /* is cell a qualified identifier? */
1945 return isPair(c) && (fst(c)==QUALIDENT);
1948 Bool isIdent(c) /* is cell an identifier? */
1950 if (!isPair(c)) return FALSE;
1955 case CONOPCELL : return TRUE;
1957 case QUALIDENT : return TRUE;
1959 default : return FALSE;
1963 Bool isInt(c) /* cell holds integer value? */
1965 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
1968 Int intOf(c) /* find integer value of cell? */
1971 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
1974 Cell mkInt(n) /* make cell representing integer */
1976 return (MINSMALLINT <= n && n <= MAXSMALLINT)
1982 Bool isBignum(c) /* cell holds bignum value? */
1984 return c==ZERONUM || (isPair(c) && (fst(c)==POSNUM || fst(c)==NEGNUM));
1988 #if SIZEOF_INTP == SIZEOF_INT
1989 typedef union {Int i; Ptr p;} IntOrPtr;
1995 return pair(PTRCELL,x.i);
2002 assert(fst(c) == PTRCELL);
2006 #elif SIZEOF_INTP == 2*SIZEOF_INT
2007 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2013 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2020 assert(fst(c) == PTRCELL);
2021 x.i.i1 = intOf(fst(snd(c)));
2022 x.i.i2 = intOf(snd(snd(c)));
2026 #warning "type Addr not supported on this architecture - don't use it"
2030 ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
2037 ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
2042 /* --------------------------------------------------------------------------
2044 * ------------------------------------------------------------------------*/
2046 Int length(xs) /* calculate length of list xs */
2049 for (; nonNull(xs); ++n)
2054 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2055 List xs, ys; { /* ys by modifying xs ... */
2060 while (nonNull(tl(zs)))
2067 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2070 for (; nonNull(xs); xs=tl(xs))
2071 ys = cons(hd(xs),ys);
2075 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2078 return revOnto(dupOnto(xs,NIL),ys);
2081 List dupList(xs) /* Duplicate spine of list xs */
2084 for (; nonNull(xs); xs=tl(xs))
2085 ys = cons(hd(xs),ys);
2089 List revOnto(xs,ys) /* Destructively reverse elements of*/
2090 List xs, ys; { /* list xs onto list ys... */
2093 while (nonNull(xs)) {
2103 List delete(xs,y) /* Delete first use of y from xs */
2108 } else if (hs(xs) == y) {
2111 tl(xs) = delete(tl(xs),y);
2116 List minus(xs,ys) /* Delete members of ys from xs */
2118 mapAccum(delete,xs,ys);
2123 Cell varIsMember(t,xs) /* Test if variable is a member of */
2124 Text t; /* given list of variables */
2126 for (; nonNull(xs); xs=tl(xs))
2127 if (t==textOf(hd(xs)))
2132 Name nameIsMember(t,ns) /* Test if name with text t is a */
2133 Text t; /* member of list of names xs */
2135 for (; nonNull(ns); ns=tl(ns))
2136 if (t==name(hd(ns)).text)
2141 Cell intIsMember(n,xs) /* Test if integer n is member of */
2142 Int n; /* given list of integers */
2144 for (; nonNull(xs); xs=tl(xs))
2145 if (n==intOf(hd(xs)))
2150 Cell cellIsMember(x,xs) /* Test for membership of specific */
2151 Cell x; /* cell x in list xs */
2153 for (; nonNull(xs); xs=tl(xs))
2159 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2162 for (; nonNull(xs); xs=tl(xs))
2168 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2169 Cell c; /* association lists */
2171 for (; nonNull(xs); xs=tl(xs))
2177 List replicate(n,x) /* create list of n copies of x */
2186 List diffList(from,take) /* list difference: from\take */
2187 List from, take; { /* result contains all elements of */
2188 List result = NIL; /* `from' not appearing in `take' */
2190 while (nonNull(from)) {
2191 List next = tl(from);
2192 if (!cellIsMember(hd(from),take)) {
2201 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2205 for(;nonNull(xs);xs=tl(xs)) {
2208 result=cons(x,result);
2214 List take(n,xs) /* destructively truncate list to */
2215 Int n; /* specified length */
2221 while (1<n-- && nonNull(xs))
2228 List splitAt(n,xs) /* drop n things from front of list*/
2237 Cell nth(n,xs) /* extract n'th element of list */
2240 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2247 List removeCell(x,xs) /* destructively remove cell from */
2252 return tl(xs); /* element at front of list */
2256 for (; nonNull(curr); prev=curr, curr=tl(prev))
2258 tl(prev) = tl(curr);
2259 return xs; /* element in middle of list */
2263 return xs; /* here if element not found */
2266 /* --------------------------------------------------------------------------
2267 * Operations on applications:
2268 * ------------------------------------------------------------------------*/
2270 Int argCount; /* number of args in application */
2272 Cell getHead(e) /* get head cell of application */
2273 Cell e; { /* set number of args in argCount */
2274 for (argCount=0; isAp(e); e=fun(e))
2279 List getArgs(e) /* get list of arguments in function*/
2280 Cell e; { /* application: */
2281 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2283 for (as=NIL; isAp(e); e=fun(e))
2284 as = cons(arg(e),as);
2288 Cell nthArg(n,e) /* return nth arg in application */
2289 Int n; /* of function to m args (m>=n) */
2290 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2291 for (n=numArgs(e)-n-1; n>0; n--)
2296 Int numArgs(e) /* find number of arguments to expr */
2299 for (n=0; isAp(e); e=fun(e))
2304 Cell applyToArgs(f,args) /* destructively apply list of args */
2305 Cell f; /* to function f */
2307 while (nonNull(args)) {
2308 Cell temp = tl(args);
2309 tl(args) = hd(args);
2317 /* --------------------------------------------------------------------------
2318 * Handle operations:
2319 * ------------------------------------------------------------------------*/
2322 struct strHandle DEFTABLE(handles,NUM_HANDLES);
2324 Cell openHandle(s,hmode,binary) /* open handle to file named s in */
2325 String s; /* the specified hmode */
2330 for (i=0; i<NUM_HANDLES && nonNull(handles[i].hcell); ++i)
2331 ; /* Search for unused handle*/
2332 if (i>=NUM_HANDLES) { /* If at first we don't */
2333 garbageCollect(); /* succeed, garbage collect*/
2334 for (i=0; i<NUM_HANDLES && nonNull(handles[i].hcell); ++i)
2335 ; /* and try again ... */
2337 if (i>=NUM_HANDLES) { /* ... before we give up */
2338 ERRMSG(0) "Too many handles open; cannot open \"%s\"", s
2341 else { /* prepare to open file */
2344 stmode = (hmode&HAPPEND) ? "ab+" :
2345 (hmode&HWRITE) ? "wb+" :
2346 (hmode&HREAD) ? "rb" : (String)0;
2348 stmode = (hmode&HAPPEND) ? "a+" :
2349 (hmode&HWRITE) ? "w+" :
2350 (hmode&HREAD) ? "r" : (String)0;
2352 if (stmode && (handles[i].hfp=fopen(s,stmode))) {
2353 handles[i].hmode = hmode;
2354 return (handles[i].hcell = ap(HANDCELL,i));
2360 static Void local freeHandle(n) /* release handle storage when no */
2361 Int n; { /* heap references to it remain */
2362 if (0<=n && n<NUM_HANDLES && nonNull(handles[n].hcell)) {
2363 if (n>HSTDERR && handles[n].hmode!=HCLOSED && handles[n].hfp) {
2364 fclose(handles[n].hfp);
2367 fst(handles[n].hcell) = snd(handles[n].hcell) = NIL;
2368 handles[n].hcell = NIL;
2374 /* --------------------------------------------------------------------------
2376 * ------------------------------------------------------------------------*/
2378 struct strMallocPtr mallocPtrs[NUM_MALLOCPTRS];
2380 /* It might GC (because it uses a table not a list) which will trash any
2381 * unstable pointers.
2382 * (It happens that we never use it with unstable pointers.)
2384 Cell mkMallocPtr(ptr,cleanup) /* create a new malloc pointer */
2386 Void (*cleanup) Args((Ptr)); {
2388 for (i=0; i<NUM_MALLOCPTRS && mallocPtrs[i].refCount!=0; ++i)
2389 ; /* Search for unused entry */
2390 if (i>=NUM_MALLOCPTRS) { /* If at first we don't */
2391 garbageCollect(); /* succeed, garbage collect*/
2392 for (i=0; i<NUM_MALLOCPTRS && mallocPtrs[i].refCount!=0; ++i)
2393 ; /* and try again ... */
2395 if (i>=NUM_MALLOCPTRS) { /* ... before we give up */
2396 ERRMSG(0) "Too many ForeignObjs open"
2399 mallocPtrs[i].ptr = ptr;
2400 mallocPtrs[i].cleanup = cleanup;
2401 mallocPtrs[i].refCount = 1;
2402 return (mallocPtrs[i].mpcell = ap(MPCELL,i));
2405 Void incMallocPtrRefCnt(n,i) /* change ref count of MallocPtr */
2408 if (!(0<=n && n<NUM_MALLOCPTRS && mallocPtrs[n].refCount > 0))
2409 internal("freeMallocPtr");
2410 mallocPtrs[n].refCount += i;
2411 if (mallocPtrs[n].refCount <= 0) {
2412 mallocPtrs[n].cleanup(mallocPtrs[n].ptr);
2414 mallocPtrs[n].ptr = 0;
2415 mallocPtrs[n].cleanup = 0;
2416 mallocPtrs[n].refCount = 0;
2417 mallocPtrs[n].mpcell = NIL;
2420 #endif /* GC_MALLOCPTRS */
2422 /* --------------------------------------------------------------------------
2424 * This is a mechanism that allows the C world to manipulate pointers into the
2425 * Haskell heap without having to worry that the garbage collector is going
2426 * to delete it or move it around.
2427 * The implementation and interface is based on my implementation in
2428 * GHC - but, at least for now, is simplified by using a fixed size
2429 * table of stable pointers.
2430 * ------------------------------------------------------------------------*/
2434 /* Each entry in the stable pointer table is either a heap pointer
2435 * or is not currently allocated.
2436 * Unallocated entries are threaded together into a freelist.
2437 * The last entry in the list contains the Cell 0; all other values
2438 * contain a Cell whose value is the next free stable ptr in the list.
2439 * It follows that stable pointers are strictly positive (>0).
2441 static Cell stablePtrTable[NUM_STABLEPTRS];
2442 static Int sptFreeList;
2443 #define SPT(sp) stablePtrTable[(sp)-1]
2445 static Void local resetStablePtrs() {
2447 /* It would be easier to build the free list in the other direction
2448 * but, when debugging, it's way easier to understand if the first
2449 * pointer allocated is "1".
2451 for(i=1; i < NUM_STABLEPTRS; ++i)
2453 SPT(NUM_STABLEPTRS) = 0;
2457 Int mkStablePtr(c) /* Create a stable pointer */
2459 Int i = sptFreeList;
2462 sptFreeList = SPT(i);
2467 Cell derefStablePtr(p) /* Dereference a stable pointer */
2469 if (!(1 <= p && p <= NUM_STABLEPTRS)) {
2470 internal("derefStablePtr");
2475 Void freeStablePtr(i) /* Free a stable pointer */
2477 SPT(i) = sptFreeList;
2482 #endif /* GC_STABLEPTRS */
2484 /* --------------------------------------------------------------------------
2486 * ------------------------------------------------------------------------*/
2488 /*---------------------------------------------------------------------------
2489 * GreenCard entry points
2491 * GreenCard generated code accesses Hugs data structures and functions
2492 * (only) via these functions (which are stored in the virtual function
2494 *-------------------------------------------------------------------------*/
2498 static Cell makeTuple Args((Int));
2499 static Cell makeInt Args((Int));
2500 static Cell makeChar Args((Char));
2501 static Char CharOf Args((Cell));
2502 static Cell makeFloat Args((FloatPro));
2503 static Void* derefMallocPtr Args((Cell));
2504 static Cell* Fst Args((Cell));
2505 static Cell* Snd Args((Cell));
2507 static Cell makeTuple(n) Int n; { return mkTuple(n); }
2508 static Cell makeInt(n) Int n; { return mkInt(n); }
2509 static Cell makeChar(n) Char n; { return mkChar(n); }
2510 static Char CharOf(n) Cell n; { return charOf(n); }
2511 static Cell makeFloat(n) FloatPro n; { return mkFloat(n); }
2512 static Void* derefMallocPtr(n) Cell n; { return derefMP(n); }
2513 static Cell* Fst(n) Cell n; { return (Cell*)&fst(n); }
2514 static Cell* Snd(n) Cell n; { return (Cell*)&snd(n); }
2516 HugsAPI1* hugsAPI1() {
2517 static HugsAPI1 api;
2518 static Bool initialised = FALSE;
2520 api.nameTrue = nameTrue;
2521 api.nameFalse = nameFalse;
2522 api.nameNil = nameNil;
2523 api.nameCons = nameCons;
2524 api.nameJust = nameJust;
2525 api.nameNothing = nameNothing;
2526 api.nameLeft = nameLeft;
2527 api.nameRight = nameRight;
2528 api.nameUnit = nameUnit;
2529 api.nameIORun = nameIORun;
2530 api.makeInt = makeInt;
2531 api.makeChar = makeChar;
2532 api.CharOf = CharOf;
2533 api.makeFloat = makeFloat;
2534 api.makeTuple = makeTuple;
2536 api.mkMallocPtr = mkMallocPtr;
2537 api.derefMallocPtr = derefMallocPtr;
2538 api.mkStablePtr = mkStablePtr;
2539 api.derefStablePtr = derefStablePtr;
2540 api.freeStablePtr = freeStablePtr;
2542 api.evalWithNoError = evalWithNoError;
2543 api.evalFails = evalFails;
2544 api.whnfArgs = &whnfArgs;
2545 api.whnfHead = &whnfHead;
2546 api.whnfInt = &whnfInt;
2547 api.whnfFloat = &whnfFloat;
2548 api.garbageCollect = garbageCollect;
2549 api.stackOverflow = hugsStackOverflow;
2550 api.internal = internal;
2551 api.registerPrims = registerPrims;
2552 api.addPrimCfun = addPrimCfun;
2553 api.inventText = inventText;
2556 api.cellStack = cellStack;
2562 #endif /* GREENCARD */
2565 /* --------------------------------------------------------------------------
2567 * ------------------------------------------------------------------------*/
2570 static void far* safeFarCalloc Args((Int,Int));
2571 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
2572 Int n, s; { /* for non-null return */
2573 void far* tab = farCalloc(n,s);
2575 ERRMSG(0) "Cannot allocate run-time tables"
2580 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
2582 #define TABALLOC(v,t,n)
2590 case RESET : clearStack();
2592 /* the next 2 statements are particularly important
2593 * if you are using GLOBALfst or GLOBALsnd since the
2594 * corresponding registers may be reset to their
2595 * uninitialised initial values by a longjump.
2597 heapTopFst = heapFst + heapSize;
2598 heapTopSnd = heapSnd + heapSize;
2600 heapTopThd = heapThd + heapSize;
2605 system("hp2ps profile.hp");
2611 handles[HSTDIN].hmode = HREAD;
2612 handles[HSTDOUT].hmode = HAPPEND;
2613 handles[HSTDERR].hmode = HAPPEND;
2616 for (i=0; i<NUM_MALLOCPTRS; i++)
2617 mallocPtrs[i].mpcell = NIL;
2627 if (isNull(lastExprSaved))
2628 savedText = NUM_TEXT;
2633 for (i=NAMEMIN; i<nameHw; ++i) {
2634 mark(name(i).parent);
2636 mark(name(i).stgVar);
2639 end("Names", nameHw-NAMEMIN);
2643 for (i=MODMIN; i<moduleHw; ++i) {
2644 mark(module(i).tycons);
2645 mark(module(i).names);
2646 mark(module(i).classes);
2647 mark(module(i).exports);
2648 mark(module(i).qualImports);
2650 end("Modules", moduleHw-MODMIN);
2654 for (i=TYCMIN; i<tyconHw; ++i) {
2655 mark(tycon(i).defn);
2656 mark(tycon(i).kind);
2657 mark(tycon(i).what);
2659 end("Type constructors", tyconHw-TYCMIN);
2662 for (i=CLASSMIN; i<classHw; ++i) {
2663 mark(cclass(i).head);
2664 mark(cclass(i).kinds);
2665 mark(cclass(i).dsels);
2666 mark(cclass(i).supers);
2667 mark(cclass(i).members);
2668 mark(cclass(i).defaults);
2669 mark(cclass(i).instances);
2672 end("Classes", classHw-CLASSMIN);
2675 for (i=INSTMIN; i<instHw; ++i) {
2677 mark(inst(i).kinds);
2678 mark(inst(i).specifics);
2679 mark(inst(i).implements);
2681 end("Instances", instHw-INSTMIN);
2684 for (i=0; i<=sp; ++i)
2689 mark(lastExprSaved);
2692 end("Last expression", 3);
2695 mark(handles[HSTDIN].hcell);
2696 mark(handles[HSTDOUT].hcell);
2697 mark(handles[HSTDERR].hcell);
2698 end("Standard handles", 3);
2703 for (i=0; i<NUM_STABLEPTRS; ++i)
2704 mark(stablePtrTable[i]);
2705 end("Stable pointers", NUM_STABLEPTRS);
2715 end("C stack", stackRoots);
2720 case INSTALL : heapFst = heapAlloc(heapSize);
2721 heapSnd = heapAlloc(heapSize);
2723 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
2724 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
2729 heapTopFst = heapFst + heapSize;
2730 heapTopSnd = heapSnd + heapSize;
2732 heapThd = heapAlloc(heapSize);
2733 if (heapThd==(Heap)0) {
2734 ERRMSG(0) "Cannot allocate profiler storage space"
2737 heapTopThd = heapThd + heapSize;
2739 if (0 == profInterval)
2740 profInterval = heapSize / DEF_PROFINTDIV;
2742 for (i=1; i<heapSize; ++i) {
2746 snd(-heapSize) = NIL;
2753 marksSize = bitArraySize(heapSize);
2754 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
2755 ERRMSG(0) "Unable to allocate gc markspace"
2759 TABALLOC(text, char, NUM_TEXT)
2760 TABALLOC(tyconHash, Tycon, TYCONHSZ)
2761 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
2762 TABALLOC(nameHash, Name, NAMEHSZ)
2763 TABALLOC(tabName, struct strName, NUM_NAME)
2764 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
2765 TABALLOC(cellStack, Cell, NUM_STACK)
2766 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
2768 TABALLOC(tabExt, Text, NUM_EXT)
2773 TABALLOC(handles, struct strHandle, NUM_HANDLES)
2774 for (i=0; i<NUM_HANDLES; i++)
2775 handles[i].hcell = NIL;
2776 handles[HSTDIN].hcell = ap(HANDCELL,HSTDIN);
2777 handles[HSTDIN].hfp = stdin;
2778 handles[HSTDOUT].hcell = ap(HANDCELL,HSTDOUT);
2779 handles[HSTDOUT].hfp = stdout;
2780 handles[HSTDERR].hcell = ap(HANDCELL,HSTDERR);
2781 handles[HSTDERR].hfp = stderr;
2785 nextNewText = NUM_TEXT;
2786 nextNewDText = (-1);
2787 lastExprSaved = NIL;
2788 savedText = NUM_TEXT;
2789 for (i=0; i<TEXTHSZ; ++i)
2790 textHash[i][0] = NOTEXT;
2799 for (i=0; i<TYCONHSZ; ++i)
2816 for (i=0; i<NAMEHSZ; ++i)
2827 tabInst = (struct strInst far *)
2828 farCalloc(NUM_INSTS,sizeof(struct strInst));
2831 ERRMSG(0) "Cannot allocate instance tables"
2841 /*-------------------------------------------------------------------------*/