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/04/27 10:07:05 $
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 */
446 Text t = name(nm).text;
448 name(nm).nextNameHash = nameHash[h];
452 Name findQualName(id) /* Locate (possibly qualified) name*/
453 Cell id; { /* in name table */
455 internal("findQualName");
461 return findName(textOf(id));
463 Text t = qtextOf(id);
464 Module m = findQualifier(qmodOf(id));
466 if (isNull(m)) return NIL;
467 for(es=module(m).exports; nonNull(es); es=tl(es)) {
469 if (isName(e) && name(e).text==t)
471 else if (isPair(e) && DOTDOT==snd(e)) {
472 List subentities = NIL;
475 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
476 subentities = tycon(c).defn;
478 subentities = cclass(c).members;
479 for(; nonNull(subentities); subentities=tl(subentities)) {
480 if (!isName(hd(subentities)))
481 internal("findQualName3");
482 if (name(hd(subentities)).text == t)
483 return hd(subentities);
489 default : internal("findQualName2");
491 return 0; /* NOTREACHED */
495 Name nameFromStgVar ( StgVar v )
498 for (n = NAMEMIN; n < nameHw; n++)
499 if (name(n).stgVar == v) return n;
503 /* --------------------------------------------------------------------------
504 * Primitive functions:
505 * ------------------------------------------------------------------------*/
507 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
508 Text t; /* sets rep, not type */
511 Int rep; { /* Really AsmRep */
512 Name n = newName(t,NIL);
513 name(n).arity = arity;
514 name(n).number = cfunNo(no);
516 name(n).primop = (void*)rep;
521 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
526 Name n = newName(t,NIL);
527 name(n).arity = arity;
528 name(n).number = cfunNo(no);
534 Int sfunPos(s,c) /* Find position of field with */
535 Name s; /* selector s in constructor c. */
539 for (; nonNull(cns); cns=tl(cns))
541 return intOf(snd(hd(cns)));
543 return 0;/* NOTREACHED */
546 static List local insertName(nm,ns) /* insert name nm into sorted list */
551 String s = textToStr(name(nm).text);
553 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
554 if (hd(curr)==nm) /* just in case we get duplicates! */
560 tl(prev) = cons(nm,curr);
564 return cons(nm,curr);
567 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
568 String pat; /* to list of names ns */
569 List ns; { /* Null pattern matches every name */
570 Name nm; /* (Names with NIL type, or hidden */
572 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
573 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
574 String str = textToStr(name(nm).text);
575 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
576 ns = insertName(nm,ns);
580 List mns = module(currentModule).names;
581 for(; nonNull(mns); mns=tl(mns)) {
583 if (!inventedText(name(nm).text)) {
584 String str = textToStr(name(nm).text);
585 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
586 ns = insertName(nm,ns);
593 /* --------------------------------------------------------------------------
594 * A simple string matching routine
595 * `*' matches any sequence of zero or more characters
596 * `?' matches any single character exactly
597 * `@str' matches the string str exactly (ignoring any special chars)
598 * `\c' matches the character c only (ignoring special chars)
599 * c matches the character c only
600 * ------------------------------------------------------------------------*/
602 static Void local patternError(s) /* report error in pattern */
604 ERRMSG(0) "%s in pattern", s
608 static Bool local stringMatch(pat,str) /* match string against pattern */
614 case '\0' : return (*str=='\0');
617 if (stringMatch(pat+1,str))
622 case '?' : if (*str++=='\0')
627 case '[' : { Bool found = FALSE;
628 while (*++pat!='\0' && *pat!=']')
629 if (!found && ( pat[0] == *str ||
638 patternError("missing `]'");
646 case '\\' : if (*++pat == '\0')
647 patternError("extra trailing `\\'");
649 default : if (*pat++ != *str++)
655 /* --------------------------------------------------------------------------
656 * Storage of type classes, instances etc...:
657 * ------------------------------------------------------------------------*/
659 static Class classHw; /* next unused class */
660 static List classes; /* list of classes in current scope */
661 static Inst instHw; /* next unused instance record */
663 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
664 struct strInst far *tabInst; /* (pointer to) table of instances */
666 Class newClass(t) /* add new class to class table */
668 if (classHw-CLASSMIN >= NUM_CLASSES) {
669 ERRMSG(0) "Class storage space exhausted"
672 cclass(classHw).text = t;
673 cclass(classHw).arity = 0;
674 cclass(classHw).kinds = NIL;
675 cclass(classHw).head = NIL;
676 cclass(classHw).dcon = NIL;
677 cclass(classHw).supers = NIL;
678 cclass(classHw).dsels = NIL;
679 cclass(classHw).members = NIL;
680 cclass(classHw).dbuild = NIL;
681 cclass(classHw).defaults = NIL;
682 cclass(classHw).instances = NIL;
683 classes=cons(classHw,classes);
684 cclass(classHw).mod = currentModule;
685 module(currentModule).classes=cons(classHw,module(currentModule).classes);
689 Class classMax() { /* Return max Class in use ... */
690 return classHw; /* This is a bit ugly, but it's not*/
691 } /* worth a lot of effort right now */
693 Class findClass(t) /* look for named class in table */
697 for (cs=classes; nonNull(cs); cs=tl(cs)) {
699 if (cclass(cl).text==t)
705 Class addClass(c) /* Insert Class in class list */
706 Class c; { /* - if no clash caused */
707 Class oldc = findClass(cclass(c).text);
709 classes=cons(c,classes);
710 module(currentModule).classes=cons(c,module(currentModule).classes);
717 Class findQualClass(c) /* Look for (possibly qualified) */
718 Cell c; { /* class in class list */
719 if (!isQualIdent(c)) {
720 return findClass(textOf(c));
723 Module m = findQualifier(qmodOf(c));
727 for (es=module(m).exports; nonNull(es); es=tl(es)) {
729 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;
751 extern Void printInst Args((Inst));
755 Class cl = inst(in).c;
756 Printf("%s-", textToStr(cclass(cl).text));
757 printType(stdout,inst(in).t);
759 #endif /* DEBUG_DICTS */
761 Inst findFirstInst(tc) /* look for 1st instance involving */
762 Tycon tc; { /* the type constructor tc */
763 return findNextInst(tc,INSTMIN-1);
766 Inst findNextInst(tc,in) /* look for next instance involving*/
767 Tycon tc; /* the type constructor tc */
768 Inst in; { /* starting after instance in */
769 while (++in < instHw) {
770 Cell pi = inst(in).head;
771 for (; isAp(pi); pi=fun(pi))
772 if (typeInvolves(arg(pi),tc))
778 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
779 Type ty; /* type constructor/tuple tc. */
782 || (isAp(ty) && (typeInvolves(fun(ty),tc)
783 || typeInvolves(arg(ty),tc)));
786 /* --------------------------------------------------------------------------
789 * Various parts of the system use a stack of cells. Most of the stack
790 * operations are defined as macros, expanded inline.
791 * ------------------------------------------------------------------------*/
793 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
794 StackPtr sp; /* stack pointer */
796 #if GIMME_STACK_DUMPS
798 #define UPPER_DISP 5 /* # display entries on top of stack */
799 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
801 Void hugsStackOverflow() { /* Report stack overflow */
803 extern Cell evalRoots[];
805 ERRMSG(0) "Control stack overflow" ETHEN
808 if (rootsp>=UPPER_DISP+LOWER_DISP) {
809 for (i=0; i<UPPER_DISP; i++) {
810 ERRTEXT "\nwhile evaluating: " ETHEN
811 ERREXPR(evalRoots[rootsp-i]);
813 ERRTEXT "\n..." ETHEN
814 for (i=LOWER_DISP-1; i>=0; i--) {
815 ERRTEXT "\nwhile evaluating: " ETHEN
816 ERREXPR(evalRoots[i]);
820 for (i=rootsp; i>=0; i--) {
821 ERRTEXT "\nwhile evaluating: " ETHEN
822 ERREXPR(evalRoots[i]);
830 #else /* !GIMME_STACK_DUMPS */
832 Void hugsStackOverflow() { /* Report stack overflow */
833 ERRMSG(0) "Control stack overflow"
837 #endif /* !GIMME_STACK_DUMPS */
839 /* --------------------------------------------------------------------------
842 * A Module represents a user defined module.
844 * Note: there are now two lookup mechanisms in the system:
846 * 1) The exports from a module are stored in a big list.
847 * We resolve qualified names, and import lists by linearly scanning
850 * 2) Unqualified imports and local definitions for the current module
851 * are stored in hash tables (tyconHash and nameHash) or linear lists
854 * ------------------------------------------------------------------------*/
856 static Module moduleHw; /* next unused Module */
857 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
858 Module currentModule; /* Module currently being processed*/
860 Bool isValidModule(m) /* is m a legitimate module id? */
862 return (MODMIN <= m && m < moduleHw);
865 Module newModule(t) /* add new module to module table */
867 if (moduleHw-MODMIN >= NUM_MODULE) {
868 ERRMSG(0) "Module storage space exhausted"
871 module(moduleHw).text = t; /* clear new module record */
872 module(moduleHw).qualImports = NIL;
873 module(moduleHw).exports = NIL;
874 module(moduleHw).tycons = NIL;
875 module(moduleHw).names = NIL;
876 module(moduleHw).classes = NIL;
877 module(moduleHw).objectFile = 0;
881 Module findModule(t) /* locate Module in module table */
884 for(m=MODMIN; m<moduleHw; ++m) {
885 if (module(m).text==t)
891 Module findModid(c) /* Find module by name or filename */
894 case STRCELL : { Script s = scriptThisFile(snd(c));
895 return (s==-1) ? NIL : moduleOfScript(s);
897 case CONIDCELL : return findModule(textOf(c));
898 default : internal("findModid");
900 assert(0); return 0; /* NOTREACHED */
903 static local Module findQualifier(t) /* locate Module in import list */
906 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
907 if (textOf(fst(hd(ms)))==t)
911 if (module(currentModule).text==t)
912 return currentModule;
917 Void setCurrModule(m) /* set lookup tables for current module */
920 if (m!=currentModule) {
921 currentModule = m; /* This is the only assignment to currentModule */
922 for (i=0; i<TYCONHSZ; ++i)
924 mapProc(hashTycon,module(m).tycons);
925 for (i=0; i<NAMEHSZ; ++i)
927 mapProc(hashName,module(m).names);
928 classes = module(m).classes;
932 /* --------------------------------------------------------------------------
933 * Script file storage:
935 * script files are read into the system one after another. The state of
936 * the stored data structures (except the garbage-collected heap) is recorded
937 * before reading a new script. In the event of being unable to read the
938 * script, or if otherwise requested, the system can be restored to its
939 * original state immediately before the file was read.
940 * ------------------------------------------------------------------------*/
942 typedef struct { /* record of storage state prior to */
943 Text file; /* reading script/module */
958 static Void local showUse(msg,val,mx)
961 Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
965 static Script scriptHw; /* next unused script number */
966 static script scripts[NUM_SCRIPTS]; /* storage for script records */
968 Script startNewScript(f) /* start new script, keeping record */
969 String f; { /* of status for later restoration */
970 if (scriptHw >= NUM_SCRIPTS) {
971 ERRMSG(0) "Too many script files in use"
975 showUse("Text", textHw, NUM_TEXT);
976 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
977 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
978 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
979 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
980 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
982 showUse("Ext", extHw-EXTMIN, NUM_EXT);
985 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
986 scripts[scriptHw].textHw = textHw;
987 scripts[scriptHw].nextNewText = nextNewText;
988 scripts[scriptHw].nextNewDText = nextNewDText;
989 scripts[scriptHw].moduleHw = moduleHw;
990 scripts[scriptHw].tyconHw = tyconHw;
991 scripts[scriptHw].nameHw = nameHw;
992 scripts[scriptHw].classHw = classHw;
993 scripts[scriptHw].instHw = instHw;
995 scripts[scriptHw].extHw = extHw;
1000 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1001 return (scriptHw==0);
1004 Bool moduleThisScript(m) /* Test if given module is defined */
1005 Module m; { /* in current script file */
1006 return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
1009 Module lastModule() { /* Return module in current script file */
1010 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1013 #define scriptThis(nm,t,tag) Script nm(x) \
1017 && x>=scripts[s].tag) \
1021 scriptThis(scriptThisName,Name,nameHw)
1022 scriptThis(scriptThisTycon,Tycon,tyconHw)
1023 scriptThis(scriptThisInst,Inst,instHw)
1024 scriptThis(scriptThisClass,Class,classHw)
1027 Module moduleOfScript(s)
1029 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1032 String fileOfModule(m)
1035 if (m == modulePrelude) {
1038 for(s=0; s<scriptHw; ++s) {
1039 if (scripts[s].moduleHw == m) {
1040 return textToStr(scripts[s].file);
1046 Script scriptThisFile(f)
1049 for (s=0; s < scriptHw; ++s) {
1050 if (scripts[s].file == f) {
1054 if (f == findText(STD_PRELUDE)) {
1060 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1061 Script sno; { /* to reading script sno */
1062 if (sno<scriptHw) { /* is there anything to restore? */
1064 textHw = scripts[sno].textHw;
1065 nextNewText = scripts[sno].nextNewText;
1066 nextNewDText = scripts[sno].nextNewDText;
1067 moduleHw = scripts[sno].moduleHw;
1068 tyconHw = scripts[sno].tyconHw;
1069 nameHw = scripts[sno].nameHw;
1070 classHw = scripts[sno].classHw;
1071 instHw = scripts[sno].instHw;
1073 dictHw = scripts[sno].dictHw;
1076 extHw = scripts[sno].extHw;
1080 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1081 if (module(i).objectFile) {
1082 printf("[bogus] closing objectFile for module %d\n",i);
1083 /*dlclose(module(i).objectFile);*/
1086 moduleHw = scripts[sno].moduleHw;
1088 for (i=0; i<TEXTHSZ; ++i) {
1090 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1091 && textHash[i][j]<textHw)
1094 textHash[i][j] = NOTEXT;
1098 for (i=0; i<TYCONHSZ; ++i) {
1101 for (i=0; i<NAMEHSZ; ++i) {
1105 for (i=CLASSMIN; i<classHw; i++) {
1106 List ins = cclass(i).instances;
1109 while (nonNull(ins)) {
1110 List temp = tl(ins);
1111 if (hd(ins)<instHw) {
1117 cclass(i).instances = rev(is);
1124 /* --------------------------------------------------------------------------
1127 * Provides a garbage collectable heap for storage of expressions etc.
1129 * Now incorporates a flat resource: A two-space collected extension of
1130 * the heap that provides storage for contiguous arrays of Cell storage,
1131 * cooperating with the garbage collection mechanisms for the main heap.
1132 * ------------------------------------------------------------------------*/
1134 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1135 Heap heapFst; /* array of fst component of pairs */
1136 Heap heapSnd; /* array of snd component of pairs */
1143 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1144 /* C stack; use with extreme care! */
1146 Int numGcs; /* number of garbage collections */
1147 Int cellsRecovered; /* number of cells recovered */
1149 static Cell freeList; /* free list of unused cells */
1150 static Cell lsave, rsave; /* save components of pair */
1154 static Int markCount, stackRoots;
1156 #define initStackRoots() stackRoots = 0
1157 #define recordStackRoot() stackRoots++
1170 #define start() markCount = 0
1171 #define end(thing,rs) \
1173 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1176 #define recordMark() markCount++
1178 #else /* !GC_STATISTICS */
1183 #define initStackRoots()
1184 #define recordStackRoot()
1187 #define end(thing,root)
1188 #define recordMark()
1190 #endif /* !GC_STATISTICS */
1192 Cell pair(l,r) /* Allocate pair (l, r) from */
1193 Cell l, r; { /* heap, garbage collecting first */
1194 Cell c = freeList; /* if necessary ... */
1206 freeList = snd(freeList);
1213 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1214 Cell dst, src; { /* both *MUST* be pairs */
1215 if (isPair(dst) && isPair(src)) {
1216 fst(dst) = fst(src);
1217 snd(dst) = snd(src);
1220 internal("overwrite");
1224 static Int marksSize;
1226 Cell markExpr(c) /* External interface to markCell */
1228 return isGenPair(c) ? markCell(c) : c;
1231 static Cell local markCell(c) /* Traverse part of graph marking */
1232 Cell c; { /* cells reachable from given root */
1233 /* markCell(c) is only called if c */
1235 { register int place = placeInSet(c);
1236 register int mask = maskInSet(c);
1237 if (marks[place]&mask)
1240 marks[place] |= mask;
1245 if (isGenPair(fst(c))) {
1246 fst(c) = markCell(fst(c));
1249 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1256 static Void local markSnd(c) /* Variant of markCell used to */
1257 Cell c; { /* update snd component of cell */
1258 Cell t; /* using tail recursion */
1260 ma: t = c; /* Keep pointer to original pair */
1265 { register int place = placeInSet(c);
1266 register int mask = maskInSet(c);
1267 if (marks[place]&mask)
1270 marks[place] |= mask;
1275 if (isGenPair(fst(c))) {
1276 fst(c) = markCell(fst(c));
1279 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1284 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1285 Cell n; { /* it was a cell ref, but don't */
1286 /* move cell so we don't have */
1287 /* to modify the stored value of n */
1294 Void garbageCollect() { /* Run garbage collector ... */
1295 Bool breakStat = breakOn(FALSE); /* disable break checking */
1301 jmp_buf regs; /* save registers on stack */
1305 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1308 everybody(MARK); /* Mark all components of system */
1310 gcScanning(); /* scan mark set */
1317 for (i=1; i<=heapSize; i++) {
1318 if ((marks[place] & mask) == 0) {
1325 if (++j == bitsPerWord) {
1332 gcRecovered(recovered);
1333 breakOn(breakStat); /* restore break trapping if nec. */
1337 /* can only return if freeList is nonempty on return. */
1338 if (recovered<minRecovery || isNull(freeList)) {
1339 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1342 cellsRecovered = recovered;
1345 /* --------------------------------------------------------------------------
1346 * Code for saving last expression entered:
1348 * This is a little tricky because some text values (e.g. strings or variable
1349 * names) may not be defined or have the same value when the expression is
1350 * recalled. These text values are therefore saved in the top portion of
1352 * ------------------------------------------------------------------------*/
1354 static Cell lastExprSaved; /* last expression to be saved */
1356 Void setLastExpr(e) /* save expression for later recall*/
1358 lastExprSaved = NIL; /* in case attempt to save fails */
1359 savedText = NUM_TEXT;
1360 lastExprSaved = lowLevelLastIn(e);
1363 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
1364 Cell c; { /* acyclic graph) for later recall */
1365 if (isPair(c)) { /* Duplicating any text strings */
1366 if (isBoxTag(fst(c))) /* in case these are lost at some */
1367 switch (fst(c)) { /* point before the expr is reused */
1373 case STRCELL : return pair(fst(c),saveText(textOf(c)));
1374 default : return pair(fst(c),snd(c));
1377 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
1381 return pair(EXTCOPY,saveText(extText(c)));
1387 Cell getLastExpr() { /* recover previously saved expr */
1388 return lowLevelLastOut(lastExprSaved);
1391 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
1392 Cell c; { /* except that Cells refering to */
1393 if (isPair(c)) { /* Text values are restored to */
1394 if (isBoxTag(fst(c))) /* appropriate values */
1401 case STRCELL : return pair(fst(c),
1402 findText(text+intValOf(c)));
1404 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
1406 default : return pair(fst(c),snd(c));
1409 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
1415 /* --------------------------------------------------------------------------
1416 * Miscellaneous operations on heap cells:
1417 * ------------------------------------------------------------------------*/
1419 /* Profiling suggests that the number of calls to whatIs() is typically */
1420 /* rather high. The recoded version below attempts to improve the average */
1421 /* performance for whatIs() using a binary search for part of the analysis */
1423 Cell whatIs(c) /* identify type of cell */
1426 register Cell fstc = fst(c);
1427 return isTag(fstc) ? fstc : AP;
1429 if (c<TUPMIN) return c;
1430 if (c>=INTMIN) return INTCELL;
1432 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
1434 else if (c>=INSTMIN) return INSTANCE;
1436 else if (c>=MODMIN) {if (c>=TYCMIN) return TYCON;
1437 else return MODULE;}
1438 else if (c>=OFFMIN) return OFFSET;
1440 else return (c>=EXTMIN) ?
1447 register Cell fstc = fst(c);
1448 return isTag(fstc) ? fstc : AP;
1450 if (c>=INTMIN) return INTCELL;
1451 if (c>=CHARMIN) return CHARCELL;
1452 if (c>=CLASSMIN) return CLASS;
1453 if (c>=INSTMIN) return INSTANCE;
1454 if (c>=NAMEMIN) return NAME;
1455 if (c>=TYCMIN) return TYCON;
1456 if (c>=MODMIN) return MODULE;
1457 if (c>=OFFMIN) return OFFSET;
1459 if (c>=EXTMIN) return EXT;
1461 if (c>=TUPMIN) return TUPLE;
1466 /* A very, very simple printer.
1467 * Output is uglier than from printExp - but the printer is more
1468 * robust and can be used on any data structure irrespective of
1471 Void print Args((Cell, Int));
1472 Void print(c, depth)
1477 #if 0 /* Not in this version of Hugs */
1478 } else if (isPair(c) && !isGenPair(c)) {
1479 extern Void printEvalCell Args((Cell, Int));
1480 printEvalCell(c,depth);
1483 Int tag = whatIs(c);
1487 print(fst(c), depth-1);
1489 print(snd(c), depth-1);
1493 Printf("free(%d)", c);
1496 Printf("int(%d)", intOf(c));
1499 Printf("bignum(%s)", bignumToString(c));
1502 Printf("char('%c')", charOf(c));
1505 Printf("ptr(%p)",ptrOf(c));
1508 Printf("class(%d)", c-CLASSMIN);
1509 if (CLASSMIN <= c && c < classHw) {
1510 Printf("=\"%s\"", textToStr(cclass(c).text));
1514 Printf("instance(%d)", c - INSTMIN);
1517 Printf("name(%d)", c-NAMEMIN);
1518 if (NAMEMIN <= c && c < nameHw) {
1519 Printf("=\"%s\"", textToStr(name(c).text));
1523 Printf("tycon(%d)", c-TYCMIN);
1524 if (TYCMIN <= c && c < tyconHw)
1525 Printf("=\"%s\"", textToStr(tycon(c).text));
1528 Printf("module(%d)", c - MODMIN);
1531 Printf("Offset %d", offsetOf(c));
1534 Printf("Tuple %d", tupleOf(c));
1538 print(snd(c),depth-1);
1542 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
1543 Printf("%d ", intOf(fst(snd(c))));
1544 print(snd(snd(c)),depth-1);
1546 print(snd(c),depth-1);
1563 Printf("{dict %d}",textOf(c));
1569 Printf("{id %s}",textToStr(textOf(c)));
1572 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
1576 print(fst(snd(c)),depth-1);
1578 print(snd(snd(c)),depth-1);
1583 print(snd(c),depth-1);
1588 print(snd(c),depth-1);
1593 print(fst(snd(c)),depth-1);
1595 print(snd(snd(c)),depth-1);
1600 print(fst(snd(c)),depth-1);
1602 print(snd(snd(c)),depth-1);
1606 Printf("FromQual(");
1607 print(fst(snd(c)),depth-1);
1609 print(snd(snd(c)),depth-1);
1613 Printf("StgVar%d=",-c);
1614 print(snd(c), depth-1);
1618 print(fst(snd(c)),depth-1);
1620 print(snd(snd(c)),depth-1);
1625 print(fst(snd(c)),depth-1);
1627 print(snd(snd(c)),depth-1);
1632 print(fst(snd(c)),depth-1);
1634 print(snd(snd(c)),depth-1);
1638 Printf("PrimCase(");
1639 print(fst(snd(c)),depth-1);
1641 print(snd(snd(c)),depth-1);
1645 if (isBoxTag(tag)) {
1646 Printf("Tag(%d)=%d", c, tag);
1647 } else if (isConTag(tag)) {
1648 Printf("%d@(%d,",c,tag);
1649 print(snd(c), depth-1);
1652 } else if (c == tag) {
1653 Printf("Tag(%d)", c);
1655 Printf("Tag(%d)=%d", c, tag);
1664 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
1665 Cell c; { /* also recognises DICTVAR cells */
1667 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
1670 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
1672 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
1675 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
1677 if (!isPair(c)) return FALSE;
1680 case VAROPCELL : return TRUE;
1682 case QUALIDENT : return isVar(snd(snd(c)));
1684 default : return FALSE;
1688 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
1690 if (!isPair(c)) return FALSE;
1693 case CONOPCELL : return TRUE;
1695 case QUALIDENT : return isCon(snd(snd(c)));
1697 default : return FALSE;
1701 Bool isQualIdent(c) /* is cell a qualified identifier? */
1703 return isPair(c) && (fst(c)==QUALIDENT);
1706 Bool isIdent(c) /* is cell an identifier? */
1708 if (!isPair(c)) return FALSE;
1713 case CONOPCELL : return TRUE;
1715 case QUALIDENT : return TRUE;
1717 default : return FALSE;
1721 Bool isInt(c) /* cell holds integer value? */
1723 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
1726 Int intOf(c) /* find integer value of cell? */
1730 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
1733 Cell mkInt(n) /* make cell representing integer */
1735 return (MINSMALLINT <= n && n <= MAXSMALLINT)
1740 #if SIZEOF_INTP == SIZEOF_INT
1741 typedef union {Int i; Ptr p;} IntOrPtr;
1747 return pair(PTRCELL,x.i);
1754 assert(fst(c) == PTRCELL);
1758 #elif SIZEOF_INTP == 2*SIZEOF_INT
1759 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
1765 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
1772 assert(fst(c) == PTRCELL);
1773 x.i.i1 = intOf(fst(snd(c)));
1774 x.i.i2 = intOf(snd(snd(c)));
1778 #warning "type Addr not supported on this architecture - don't use it"
1782 ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
1789 ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
1794 String stringNegate( s )
1802 strcpy(&t[1],s); /* ToDo: use strncpy instead */
1807 /* --------------------------------------------------------------------------
1809 * ------------------------------------------------------------------------*/
1811 Int length(xs) /* calculate length of list xs */
1814 for (; nonNull(xs); ++n)
1819 List appendOnto(xs,ys) /* Destructively prepend xs onto */
1820 List xs, ys; { /* ys by modifying xs ... */
1825 while (nonNull(tl(zs)))
1832 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
1835 for (; nonNull(xs); xs=tl(xs))
1836 ys = cons(hd(xs),ys);
1840 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
1843 return revOnto(dupOnto(xs,NIL),ys);
1846 List dupList(xs) /* Duplicate spine of list xs */
1849 for (; nonNull(xs); xs=tl(xs))
1850 ys = cons(hd(xs),ys);
1854 List revOnto(xs,ys) /* Destructively reverse elements of*/
1855 List xs, ys; { /* list xs onto list ys... */
1858 while (nonNull(xs)) {
1867 Cell varIsMember(t,xs) /* Test if variable is a member of */
1868 Text t; /* given list of variables */
1870 for (; nonNull(xs); xs=tl(xs))
1871 if (t==textOf(hd(xs)))
1876 Name nameIsMember(t,ns) /* Test if name with text t is a */
1877 Text t; /* member of list of names xs */
1879 for (; nonNull(ns); ns=tl(ns))
1880 if (t==name(hd(ns)).text)
1885 Cell intIsMember(n,xs) /* Test if integer n is member of */
1886 Int n; /* given list of integers */
1888 for (; nonNull(xs); xs=tl(xs))
1889 if (n==intOf(hd(xs)))
1894 Cell cellIsMember(x,xs) /* Test for membership of specific */
1895 Cell x; /* cell x in list xs */
1897 for (; nonNull(xs); xs=tl(xs))
1903 Cell cellAssoc(c,xs) /* Lookup cell in association list */
1906 for (; nonNull(xs); xs=tl(xs))
1912 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
1913 Cell c; /* association lists */
1915 for (; nonNull(xs); xs=tl(xs))
1921 List replicate(n,x) /* create list of n copies of x */
1930 List diffList(from,take) /* list difference: from\take */
1931 List from, take; { /* result contains all elements of */
1932 List result = NIL; /* `from' not appearing in `take' */
1934 while (nonNull(from)) {
1935 List next = tl(from);
1936 if (!cellIsMember(hd(from),take)) {
1945 List deleteCell(xs, y) /* copy xs deleting pointers to y */
1949 for(;nonNull(xs);xs=tl(xs)) {
1952 result=cons(x,result);
1958 List take(n,xs) /* destructively truncate list to */
1959 Int n; /* specified length */
1965 while (1<n-- && nonNull(xs))
1972 List splitAt(n,xs) /* drop n things from front of list*/
1981 Cell nth(n,xs) /* extract n'th element of list */
1984 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
1991 List removeCell(x,xs) /* destructively remove cell from */
1996 return tl(xs); /* element at front of list */
2000 for (; nonNull(curr); prev=curr, curr=tl(prev))
2002 tl(prev) = tl(curr);
2003 return xs; /* element in middle of list */
2007 return xs; /* here if element not found */
2010 /* --------------------------------------------------------------------------
2011 * Operations on applications:
2012 * ------------------------------------------------------------------------*/
2014 Int argCount; /* number of args in application */
2016 Cell getHead(e) /* get head cell of application */
2017 Cell e; { /* set number of args in argCount */
2018 for (argCount=0; isAp(e); e=fun(e))
2023 List getArgs(e) /* get list of arguments in function*/
2024 Cell e; { /* application: */
2025 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2027 for (as=NIL; isAp(e); e=fun(e))
2028 as = cons(arg(e),as);
2032 Cell nthArg(n,e) /* return nth arg in application */
2033 Int n; /* of function to m args (m>=n) */
2034 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2035 for (n=numArgs(e)-n-1; n>0; n--)
2040 Int numArgs(e) /* find number of arguments to expr */
2043 for (n=0; isAp(e); e=fun(e))
2048 Cell applyToArgs(f,args) /* destructively apply list of args */
2049 Cell f; /* to function f */
2051 while (nonNull(args)) {
2052 Cell temp = tl(args);
2053 tl(args) = hd(args);
2062 /* --------------------------------------------------------------------------
2064 * ------------------------------------------------------------------------*/
2066 /*---------------------------------------------------------------------------
2067 * GreenCard entry points
2069 * GreenCard generated code accesses Hugs data structures and functions
2070 * (only) via these functions (which are stored in the virtual function
2072 *-------------------------------------------------------------------------*/
2076 static Cell makeTuple Args((Int));
2077 static Cell makeInt Args((Int));
2078 static Cell makeChar Args((Char));
2079 static Char CharOf Args((Cell));
2080 static Cell makeFloat Args((FloatPro));
2081 static Void* derefMallocPtr Args((Cell));
2082 static Cell* Fst Args((Cell));
2083 static Cell* Snd Args((Cell));
2085 static Cell makeTuple(n) Int n; { return mkTuple(n); }
2086 static Cell makeInt(n) Int n; { return mkInt(n); }
2087 static Cell makeChar(n) Char n; { return mkChar(n); }
2088 static Char CharOf(n) Cell n; { return charOf(n); }
2089 static Cell makeFloat(n) FloatPro n; { return mkFloat(n); }
2090 static Void* derefMallocPtr(n) Cell n; { return derefMP(n); }
2091 static Cell* Fst(n) Cell n; { return (Cell*)&fst(n); }
2092 static Cell* Snd(n) Cell n; { return (Cell*)&snd(n); }
2094 HugsAPI1* hugsAPI1() {
2095 static HugsAPI1 api;
2096 static Bool initialised = FALSE;
2098 api.nameTrue = nameTrue;
2099 api.nameFalse = nameFalse;
2100 api.nameNil = nameNil;
2101 api.nameCons = nameCons;
2102 api.nameJust = nameJust;
2103 api.nameNothing = nameNothing;
2104 api.nameLeft = nameLeft;
2105 api.nameRight = nameRight;
2106 api.nameUnit = nameUnit;
2107 api.nameIORun = nameIORun;
2108 api.makeInt = makeInt;
2109 api.makeChar = makeChar;
2110 api.CharOf = CharOf;
2111 api.makeFloat = makeFloat;
2112 api.makeTuple = makeTuple;
2114 api.mkMallocPtr = mkMallocPtr;
2115 api.derefMallocPtr = derefMallocPtr;
2116 api.mkStablePtr = mkStablePtr;
2117 api.derefStablePtr = derefStablePtr;
2118 api.freeStablePtr = freeStablePtr;
2120 api.evalWithNoError = evalWithNoError;
2121 api.evalFails = evalFails;
2122 api.whnfArgs = &whnfArgs;
2123 api.whnfHead = &whnfHead;
2124 api.whnfInt = &whnfInt;
2125 api.whnfFloat = &whnfFloat;
2126 api.garbageCollect = garbageCollect;
2127 api.stackOverflow = hugsStackOverflow;
2128 api.internal = internal;
2129 api.registerPrims = registerPrims;
2130 api.addPrimCfun = addPrimCfun;
2131 api.inventText = inventText;
2134 api.cellStack = cellStack;
2140 #endif /* GREENCARD */
2143 /* --------------------------------------------------------------------------
2145 * ------------------------------------------------------------------------*/
2148 static void far* safeFarCalloc Args((Int,Int));
2149 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
2150 Int n, s; { /* for non-null return */
2151 void far* tab = farCalloc(n,s);
2153 ERRMSG(0) "Cannot allocate run-time tables"
2158 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
2160 #define TABALLOC(v,t,n)
2168 case RESET : clearStack();
2170 /* the next 2 statements are particularly important
2171 * if you are using GLOBALfst or GLOBALsnd since the
2172 * corresponding registers may be reset to their
2173 * uninitialised initial values by a longjump.
2175 heapTopFst = heapFst + heapSize;
2176 heapTopSnd = heapSnd + heapSize;
2180 if (isNull(lastExprSaved))
2181 savedText = NUM_TEXT;
2186 for (i=NAMEMIN; i<nameHw; ++i) {
2187 mark(name(i).parent);
2189 mark(name(i).stgVar);
2192 end("Names", nameHw-NAMEMIN);
2195 for (i=MODMIN; i<moduleHw; ++i) {
2196 mark(module(i).tycons);
2197 mark(module(i).names);
2198 mark(module(i).classes);
2199 mark(module(i).exports);
2200 mark(module(i).qualImports);
2202 end("Modules", moduleHw-MODMIN);
2205 for (i=TYCMIN; i<tyconHw; ++i) {
2206 mark(tycon(i).defn);
2207 mark(tycon(i).kind);
2208 mark(tycon(i).what);
2210 end("Type constructors", tyconHw-TYCMIN);
2213 for (i=CLASSMIN; i<classHw; ++i) {
2214 mark(cclass(i).head);
2215 mark(cclass(i).kinds);
2216 mark(cclass(i).dsels);
2217 mark(cclass(i).supers);
2218 mark(cclass(i).members);
2219 mark(cclass(i).defaults);
2220 mark(cclass(i).instances);
2223 end("Classes", classHw-CLASSMIN);
2226 for (i=INSTMIN; i<instHw; ++i) {
2228 mark(inst(i).kinds);
2229 mark(inst(i).specifics);
2230 mark(inst(i).implements);
2232 end("Instances", instHw-INSTMIN);
2235 for (i=0; i<=sp; ++i)
2240 mark(lastExprSaved);
2243 end("Last expression", 3);
2248 end("C stack", stackRoots);
2253 case INSTALL : heapFst = heapAlloc(heapSize);
2254 heapSnd = heapAlloc(heapSize);
2256 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
2257 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
2262 heapTopFst = heapFst + heapSize;
2263 heapTopSnd = heapSnd + heapSize;
2264 for (i=1; i<heapSize; ++i) {
2268 snd(-heapSize) = NIL;
2275 marksSize = bitArraySize(heapSize);
2276 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
2277 ERRMSG(0) "Unable to allocate gc markspace"
2281 TABALLOC(text, char, NUM_TEXT)
2282 TABALLOC(tyconHash, Tycon, TYCONHSZ)
2283 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
2284 TABALLOC(nameHash, Name, NAMEHSZ)
2285 TABALLOC(tabName, struct strName, NUM_NAME)
2286 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
2287 TABALLOC(cellStack, Cell, NUM_STACK)
2288 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
2290 TABALLOC(tabExt, Text, NUM_EXT)
2295 nextNewText = NUM_TEXT;
2296 nextNewDText = (-1);
2297 lastExprSaved = NIL;
2298 savedText = NUM_TEXT;
2299 for (i=0; i<TEXTHSZ; ++i)
2300 textHash[i][0] = NOTEXT;
2306 for (i=0; i<TYCONHSZ; ++i)
2313 for (i=0; i<NAMEHSZ; ++i)
2324 tabInst = (struct strInst far *)
2325 farCalloc(NUM_INSTS,sizeof(struct strInst));
2328 ERRMSG(0) "Cannot allocate instance tables"
2338 /*-------------------------------------------------------------------------*/