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/06/07 17:22:49 $
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 name(nameHw).ghc_names = NIL;
419 module(currentModule).names=cons(nameHw,module(currentModule).names);
420 name(nameHw).nextNameHash = nameHash[h];
421 nameHash[h] = nameHw;
425 Name findName(t) /* Locate name in name table */
427 Name n = nameHash[nHash(t)];
429 while (nonNull(n) && name(n).text!=t)
430 n = name(n).nextNameHash;
434 Name addName(nm) /* Insert Name in name table - if */
435 Name nm; { /* no clash is caused */
436 Name oldnm = findName(name(nm).text);
439 module(currentModule).names=cons(nm,module(currentModule).names);
445 static Void local hashName(nm) /* Insert Name into hash table */
452 name(nm).nextNameHash = nameHash[h];
456 Name findQualName(id) /* Locate (possibly qualified) name*/
457 Cell id; { /* in name table */
459 internal("findQualName");
465 return findName(textOf(id));
467 Text t = qtextOf(id);
468 Module m = findQualifier(qmodOf(id));
470 if (isNull(m)) return NIL;
471 for(es=module(m).exports; nonNull(es); es=tl(es)) {
473 if (isName(e) && name(e).text==t)
475 else if (isPair(e) && DOTDOT==snd(e)) {
476 List subentities = NIL;
479 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
480 subentities = tycon(c).defn;
482 subentities = cclass(c).members;
483 for(; nonNull(subentities); subentities=tl(subentities)) {
484 if (!isName(hd(subentities)))
485 internal("findQualName3");
486 if (name(hd(subentities)).text == t)
487 return hd(subentities);
493 default : internal("findQualName2");
495 return 0; /* NOTREACHED */
499 Name nameFromStgVar ( StgVar v )
502 for (n = NAMEMIN; n < nameHw; n++)
503 if (name(n).stgVar == v) return n;
508 /* --------------------------------------------------------------------------
509 * Primitive functions:
510 * ------------------------------------------------------------------------*/
512 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
513 Text t; /* sets rep, not type */
516 Int rep; { /* Really AsmRep */
517 Name n = newName(t,NIL);
518 name(n).arity = arity;
519 name(n).number = cfunNo(no);
521 name(n).primop = (void*)rep;
526 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
531 Name n = newName(t,NIL);
532 name(n).arity = arity;
533 name(n).number = cfunNo(no);
539 Int sfunPos(s,c) /* Find position of field with */
540 Name s; /* selector s in constructor c. */
544 for (; nonNull(cns); cns=tl(cns))
546 return intOf(snd(hd(cns)));
548 return 0;/* NOTREACHED */
551 static List local insertName(nm,ns) /* insert name nm into sorted list */
556 String s = textToStr(name(nm).text);
558 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
559 if (hd(curr)==nm) /* just in case we get duplicates! */
565 tl(prev) = cons(nm,curr);
569 return cons(nm,curr);
572 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
573 String pat; /* to list of names ns */
574 List ns; { /* Null pattern matches every name */
575 Name nm; /* (Names with NIL type, or hidden */
577 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
578 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
579 String str = textToStr(name(nm).text);
580 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
581 ns = insertName(nm,ns);
585 List mns = module(currentModule).names;
586 for(; nonNull(mns); mns=tl(mns)) {
588 if (!inventedText(name(nm).text)) {
589 String str = textToStr(name(nm).text);
590 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
591 ns = insertName(nm,ns);
598 /* --------------------------------------------------------------------------
599 * A simple string matching routine
600 * `*' matches any sequence of zero or more characters
601 * `?' matches any single character exactly
602 * `@str' matches the string str exactly (ignoring any special chars)
603 * `\c' matches the character c only (ignoring special chars)
604 * c matches the character c only
605 * ------------------------------------------------------------------------*/
607 static Void local patternError(s) /* report error in pattern */
609 ERRMSG(0) "%s in pattern", s
613 static Bool local stringMatch(pat,str) /* match string against pattern */
619 case '\0' : return (*str=='\0');
622 if (stringMatch(pat+1,str))
627 case '?' : if (*str++=='\0')
632 case '[' : { Bool found = FALSE;
633 while (*++pat!='\0' && *pat!=']')
634 if (!found && ( pat[0] == *str ||
643 patternError("missing `]'");
651 case '\\' : if (*++pat == '\0')
652 patternError("extra trailing `\\'");
654 default : if (*pat++ != *str++)
660 /* --------------------------------------------------------------------------
661 * Storage of type classes, instances etc...:
662 * ------------------------------------------------------------------------*/
664 static Class classHw; /* next unused class */
665 static List classes; /* list of classes in current scope */
666 static Inst instHw; /* next unused instance record */
668 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
669 struct strInst far *tabInst; /* (pointer to) table of instances */
671 Class newClass(t) /* add new class to class table */
673 if (classHw-CLASSMIN >= NUM_CLASSES) {
674 ERRMSG(0) "Class storage space exhausted"
677 cclass(classHw).text = t;
678 cclass(classHw).arity = 0;
679 cclass(classHw).kinds = NIL;
680 cclass(classHw).head = NIL;
681 cclass(classHw).dcon = NIL;
682 cclass(classHw).supers = NIL;
683 cclass(classHw).dsels = NIL;
684 cclass(classHw).members = NIL;
685 cclass(classHw).dbuild = NIL;
686 cclass(classHw).defaults = NIL;
687 cclass(classHw).instances = NIL;
688 classes=cons(classHw,classes);
689 cclass(classHw).mod = currentModule;
690 module(currentModule).classes=cons(classHw,module(currentModule).classes);
694 Class classMax() { /* Return max Class in use ... */
695 return classHw; /* This is a bit ugly, but it's not*/
696 } /* worth a lot of effort right now */
698 Class findClass(t) /* look for named class in table */
702 for (cs=classes; nonNull(cs); cs=tl(cs)) {
704 if (cclass(cl).text==t)
710 Class addClass(c) /* Insert Class in class list */
711 Class c; { /* - if no clash caused */
712 Class oldc = findClass(cclass(c).text);
714 classes=cons(c,classes);
715 module(currentModule).classes=cons(c,module(currentModule).classes);
722 Class findQualClass(c) /* Look for (possibly qualified) */
723 Cell c; { /* class in class list */
724 if (!isQualIdent(c)) {
725 return findClass(textOf(c));
728 Module m = findQualifier(qmodOf(c));
732 for (es=module(m).exports; nonNull(es); es=tl(es)) {
734 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
741 Inst newInst() { /* Add new instance to table */
742 if (instHw-INSTMIN >= NUM_INSTS) {
743 ERRMSG(0) "Instance storage space exhausted"
746 inst(instHw).kinds = NIL;
747 inst(instHw).head = NIL;
748 inst(instHw).specifics = NIL;
749 inst(instHw).implements = NIL;
750 inst(instHw).builder = NIL;
751 inst(instHw).mod = currentModule;
757 extern Void printInst Args((Inst));
761 Class cl = inst(in).c;
762 Printf("%s-", textToStr(cclass(cl).text));
763 printType(stdout,inst(in).t);
765 #endif /* DEBUG_DICTS */
767 Inst findFirstInst(tc) /* look for 1st instance involving */
768 Tycon tc; { /* the type constructor tc */
769 return findNextInst(tc,INSTMIN-1);
772 Inst findNextInst(tc,in) /* look for next instance involving*/
773 Tycon tc; /* the type constructor tc */
774 Inst in; { /* starting after instance in */
775 while (++in < instHw) {
776 Cell pi = inst(in).head;
777 for (; isAp(pi); pi=fun(pi))
778 if (typeInvolves(arg(pi),tc))
784 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
785 Type ty; /* type constructor/tuple tc. */
788 || (isAp(ty) && (typeInvolves(fun(ty),tc)
789 || typeInvolves(arg(ty),tc)));
792 /* --------------------------------------------------------------------------
795 * Various parts of the system use a stack of cells. Most of the stack
796 * operations are defined as macros, expanded inline.
797 * ------------------------------------------------------------------------*/
799 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
800 StackPtr sp; /* stack pointer */
802 #if GIMME_STACK_DUMPS
804 #define UPPER_DISP 5 /* # display entries on top of stack */
805 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
807 Void hugsStackOverflow() { /* Report stack overflow */
809 extern Cell evalRoots[];
811 ERRMSG(0) "Control stack overflow" ETHEN
814 if (rootsp>=UPPER_DISP+LOWER_DISP) {
815 for (i=0; i<UPPER_DISP; i++) {
816 ERRTEXT "\nwhile evaluating: " ETHEN
817 ERREXPR(evalRoots[rootsp-i]);
819 ERRTEXT "\n..." ETHEN
820 for (i=LOWER_DISP-1; i>=0; i--) {
821 ERRTEXT "\nwhile evaluating: " ETHEN
822 ERREXPR(evalRoots[i]);
826 for (i=rootsp; i>=0; i--) {
827 ERRTEXT "\nwhile evaluating: " ETHEN
828 ERREXPR(evalRoots[i]);
836 #else /* !GIMME_STACK_DUMPS */
838 Void hugsStackOverflow() { /* Report stack overflow */
839 ERRMSG(0) "Control stack overflow"
843 #endif /* !GIMME_STACK_DUMPS */
845 /* --------------------------------------------------------------------------
848 * A Module represents a user defined module.
850 * Note: there are now two lookup mechanisms in the system:
852 * 1) The exports from a module are stored in a big list.
853 * We resolve qualified names, and import lists by linearly scanning
856 * 2) Unqualified imports and local definitions for the current module
857 * are stored in hash tables (tyconHash and nameHash) or linear lists
860 * ------------------------------------------------------------------------*/
862 static Module moduleHw; /* next unused Module */
863 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
864 Module currentModule; /* Module currently being processed*/
866 Bool isValidModule(m) /* is m a legitimate module id? */
868 return (MODMIN <= m && m < moduleHw);
871 Module newModule(t) /* add new module to module table */
873 if (moduleHw-MODMIN >= NUM_MODULE) {
874 ERRMSG(0) "Module storage space exhausted"
877 module(moduleHw).text = t; /* clear new module record */
878 module(moduleHw).qualImports = NIL;
879 module(moduleHw).exports = NIL;
880 module(moduleHw).tycons = NIL;
881 module(moduleHw).names = NIL;
882 module(moduleHw).classes = NIL;
883 module(moduleHw).oImage = NULL;
887 void ppModules ( void )
890 fflush(stderr); fflush(stdout);
891 printf ( "begin MODULES\n" );
892 for (i = moduleHw-1; i >= MODMIN; i--)
893 printf ( " %2d: %16s\n",
894 i-MODMIN, textToStr(module(i).text)
896 printf ( "end MODULES\n" );
897 fflush(stderr); fflush(stdout);
901 Module findModule(t) /* locate Module in module table */
904 for(m=MODMIN; m<moduleHw; ++m) {
905 if (module(m).text==t)
911 Module findModid(c) /* Find module by name or filename */
914 case STRCELL : { Script s = scriptThisFile(snd(c));
915 return (s==-1) ? NIL : moduleOfScript(s);
917 case CONIDCELL : return findModule(textOf(c));
918 default : internal("findModid");
920 assert(0); return 0; /* NOTREACHED */
923 static local Module findQualifier(t) /* locate Module in import list */
926 printf ( "findQualifier %s\n", textToStr(t));
927 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
928 if (textOf(fst(hd(ms)))==t)
932 if (module(currentModule).text==t)
933 return currentModule;
938 Void setCurrModule(m) /* set lookup tables for current module */
941 if (m!=currentModule) {
942 currentModule = m; /* This is the only assignment to currentModule */
943 for (i=0; i<TYCONHSZ; ++i)
945 mapProc(hashTycon,module(m).tycons);
946 for (i=0; i<NAMEHSZ; ++i)
948 mapProc(hashName,module(m).names);
949 classes = module(m).classes;
953 Name jrsFindQualName ( Text mn, Text sn )
958 for (m=MODMIN; m<moduleHw; m++)
959 if (module(m).text == mn) break;
960 if (m == moduleHw) return NIL;
962 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
963 if (name(hd(ns)).text == sn) return hd(ns);
968 /* --------------------------------------------------------------------------
969 * Script file storage:
971 * script files are read into the system one after another. The state of
972 * the stored data structures (except the garbage-collected heap) is recorded
973 * before reading a new script. In the event of being unable to read the
974 * script, or if otherwise requested, the system can be restored to its
975 * original state immediately before the file was read.
976 * ------------------------------------------------------------------------*/
978 typedef struct { /* record of storage state prior to */
979 Text file; /* reading script/module */
994 static Void local showUse(msg,val,mx)
997 Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1001 static Script scriptHw; /* next unused script number */
1002 static script scripts[NUM_SCRIPTS]; /* storage for script records */
1005 void ppScripts ( void )
1008 fflush(stderr); fflush(stdout);
1009 printf ( "begin SCRIPTS\n" );
1010 for (i = scriptHw-1; i >= 0; i--)
1011 printf ( " %2d: %16s tH=%d mH=%d yH=%d "
1012 "nH=%d cH=%d iH=%d nnS=%d,%d\n",
1013 i, textToStr(scripts[i].file),
1014 scripts[i].textHw, scripts[i].moduleHw,
1015 scripts[i].tyconHw, scripts[i].nameHw,
1016 scripts[i].classHw, scripts[i].instHw,
1017 scripts[i].nextNewText, scripts[i].nextNewDText
1019 printf ( "end SCRIPTS\n" );
1020 fflush(stderr); fflush(stdout);
1023 Script startNewScript(f) /* start new script, keeping record */
1024 String f; { /* of status for later restoration */
1025 if (scriptHw >= NUM_SCRIPTS) {
1026 ERRMSG(0) "Too many script files in use"
1029 #ifdef DEBUG_SHOWUSE
1030 showUse("Text", textHw, NUM_TEXT);
1031 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
1032 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
1033 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
1034 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
1035 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
1037 showUse("Ext", extHw-EXTMIN, NUM_EXT);
1040 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
1041 scripts[scriptHw].textHw = textHw;
1042 scripts[scriptHw].nextNewText = nextNewText;
1043 scripts[scriptHw].nextNewDText = nextNewDText;
1044 scripts[scriptHw].moduleHw = moduleHw;
1045 scripts[scriptHw].tyconHw = tyconHw;
1046 scripts[scriptHw].nameHw = nameHw;
1047 scripts[scriptHw].classHw = classHw;
1048 scripts[scriptHw].instHw = instHw;
1050 scripts[scriptHw].extHw = extHw;
1055 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1056 return (scriptHw==0);
1059 Bool moduleThisScript(m) /* Test if given module is defined */
1060 Module m; { /* in current script file */
1061 return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
1064 Module lastModule() { /* Return module in current script file */
1065 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1068 #define scriptThis(nm,t,tag) Script nm(x) \
1072 && x>=scripts[s].tag) \
1076 scriptThis(scriptThisName,Name,nameHw)
1077 scriptThis(scriptThisTycon,Tycon,tyconHw)
1078 scriptThis(scriptThisInst,Inst,instHw)
1079 scriptThis(scriptThisClass,Class,classHw)
1082 Module moduleOfScript(s)
1084 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1087 String fileOfModule(m)
1090 if (m == modulePrelude) {
1093 for(s=0; s<scriptHw; ++s) {
1094 if (scripts[s].moduleHw == m) {
1095 return textToStr(scripts[s].file);
1101 Script scriptThisFile(f)
1104 for (s=0; s < scriptHw; ++s) {
1105 if (scripts[s].file == f) {
1109 if (f == findText(STD_PRELUDE)) {
1115 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1116 Script sno; { /* to reading script sno */
1117 if (sno<scriptHw) { /* is there anything to restore? */
1119 textHw = scripts[sno].textHw;
1120 nextNewText = scripts[sno].nextNewText;
1121 nextNewDText = scripts[sno].nextNewDText;
1122 moduleHw = scripts[sno].moduleHw;
1123 tyconHw = scripts[sno].tyconHw;
1124 nameHw = scripts[sno].nameHw;
1125 classHw = scripts[sno].classHw;
1126 instHw = scripts[sno].instHw;
1128 dictHw = scripts[sno].dictHw;
1131 extHw = scripts[sno].extHw;
1135 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1136 if (module(i).objectFile) {
1137 printf("[bogus] closing objectFile for module %d\n",i);
1138 /*dlclose(module(i).objectFile);*/
1141 moduleHw = scripts[sno].moduleHw;
1143 for (i=0; i<TEXTHSZ; ++i) {
1145 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1146 && textHash[i][j]<textHw)
1149 textHash[i][j] = NOTEXT;
1153 for (i=0; i<TYCONHSZ; ++i) {
1156 for (i=0; i<NAMEHSZ; ++i) {
1160 for (i=CLASSMIN; i<classHw; i++) {
1161 List ins = cclass(i).instances;
1164 while (nonNull(ins)) {
1165 List temp = tl(ins);
1166 if (hd(ins)<instHw) {
1172 cclass(i).instances = rev(is);
1179 /* --------------------------------------------------------------------------
1182 * Provides a garbage collectable heap for storage of expressions etc.
1184 * Now incorporates a flat resource: A two-space collected extension of
1185 * the heap that provides storage for contiguous arrays of Cell storage,
1186 * cooperating with the garbage collection mechanisms for the main heap.
1187 * ------------------------------------------------------------------------*/
1189 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1190 Heap heapFst; /* array of fst component of pairs */
1191 Heap heapSnd; /* array of snd component of pairs */
1198 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1199 /* C stack; use with extreme care! */
1201 Int numGcs; /* number of garbage collections */
1202 Int cellsRecovered; /* number of cells recovered */
1204 static Cell freeList; /* free list of unused cells */
1205 static Cell lsave, rsave; /* save components of pair */
1209 static Int markCount, stackRoots;
1211 #define initStackRoots() stackRoots = 0
1212 #define recordStackRoot() stackRoots++
1225 #define start() markCount = 0
1226 #define end(thing,rs) \
1228 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1231 #define recordMark() markCount++
1233 #else /* !GC_STATISTICS */
1238 #define initStackRoots()
1239 #define recordStackRoot()
1242 #define end(thing,root)
1243 #define recordMark()
1245 #endif /* !GC_STATISTICS */
1247 Cell pair(l,r) /* Allocate pair (l, r) from */
1248 Cell l, r; { /* heap, garbage collecting first */
1249 Cell c = freeList; /* if necessary ... */
1261 freeList = snd(freeList);
1268 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1269 Cell dst, src; { /* both *MUST* be pairs */
1270 if (isPair(dst) && isPair(src)) {
1271 fst(dst) = fst(src);
1272 snd(dst) = snd(src);
1275 internal("overwrite");
1279 static Int marksSize;
1281 Cell markExpr(c) /* External interface to markCell */
1283 return isGenPair(c) ? markCell(c) : c;
1286 static Cell local markCell(c) /* Traverse part of graph marking */
1287 Cell c; { /* cells reachable from given root */
1288 /* markCell(c) is only called if c */
1290 { register int place = placeInSet(c);
1291 register int mask = maskInSet(c);
1292 if (marks[place]&mask)
1295 marks[place] |= mask;
1300 if (isGenPair(fst(c))) {
1301 fst(c) = markCell(fst(c));
1304 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1311 static Void local markSnd(c) /* Variant of markCell used to */
1312 Cell c; { /* update snd component of cell */
1313 Cell t; /* using tail recursion */
1315 ma: t = c; /* Keep pointer to original pair */
1320 { register int place = placeInSet(c);
1321 register int mask = maskInSet(c);
1322 if (marks[place]&mask)
1325 marks[place] |= mask;
1330 if (isGenPair(fst(c))) {
1331 fst(c) = markCell(fst(c));
1334 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1339 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1340 Cell n; { /* it was a cell ref, but don't */
1341 /* move cell so we don't have */
1342 /* to modify the stored value of n */
1349 Void garbageCollect() { /* Run garbage collector ... */
1350 Bool breakStat = breakOn(FALSE); /* disable break checking */
1356 jmp_buf regs; /* save registers on stack */
1360 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1363 everybody(MARK); /* Mark all components of system */
1365 gcScanning(); /* scan mark set */
1372 for (i=1; i<=heapSize; i++) {
1373 if ((marks[place] & mask) == 0) {
1380 if (++j == bitsPerWord) {
1387 gcRecovered(recovered);
1388 breakOn(breakStat); /* restore break trapping if nec. */
1392 /* can only return if freeList is nonempty on return. */
1393 if (recovered<minRecovery || isNull(freeList)) {
1394 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1397 cellsRecovered = recovered;
1400 /* --------------------------------------------------------------------------
1401 * Code for saving last expression entered:
1403 * This is a little tricky because some text values (e.g. strings or variable
1404 * names) may not be defined or have the same value when the expression is
1405 * recalled. These text values are therefore saved in the top portion of
1407 * ------------------------------------------------------------------------*/
1409 static Cell lastExprSaved; /* last expression to be saved */
1411 Void setLastExpr(e) /* save expression for later recall*/
1413 lastExprSaved = NIL; /* in case attempt to save fails */
1414 savedText = NUM_TEXT;
1415 lastExprSaved = lowLevelLastIn(e);
1418 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
1419 Cell c; { /* acyclic graph) for later recall */
1420 if (isPair(c)) { /* Duplicating any text strings */
1421 if (isBoxTag(fst(c))) /* in case these are lost at some */
1422 switch (fst(c)) { /* point before the expr is reused */
1428 case STRCELL : return pair(fst(c),saveText(textOf(c)));
1429 default : return pair(fst(c),snd(c));
1432 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
1436 return pair(EXTCOPY,saveText(extText(c)));
1442 Cell getLastExpr() { /* recover previously saved expr */
1443 return lowLevelLastOut(lastExprSaved);
1446 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
1447 Cell c; { /* except that Cells refering to */
1448 if (isPair(c)) { /* Text values are restored to */
1449 if (isBoxTag(fst(c))) /* appropriate values */
1456 case STRCELL : return pair(fst(c),
1457 findText(text+intValOf(c)));
1459 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
1461 default : return pair(fst(c),snd(c));
1464 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
1470 /* --------------------------------------------------------------------------
1471 * Miscellaneous operations on heap cells:
1472 * ------------------------------------------------------------------------*/
1474 /* Profiling suggests that the number of calls to whatIs() is typically */
1475 /* rather high. The recoded version below attempts to improve the average */
1476 /* performance for whatIs() using a binary search for part of the analysis */
1478 Cell whatIs(c) /* identify type of cell */
1481 register Cell fstc = fst(c);
1482 return isTag(fstc) ? fstc : AP;
1484 if (c<TUPMIN) return c;
1485 if (c>=INTMIN) return INTCELL;
1487 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
1489 else if (c>=INSTMIN) return INSTANCE;
1491 else if (c>=MODMIN) {if (c>=TYCMIN) return TYCON;
1492 else return MODULE;}
1493 else if (c>=OFFMIN) return OFFSET;
1495 else return (c>=EXTMIN) ?
1502 register Cell fstc = fst(c);
1503 return isTag(fstc) ? fstc : AP;
1505 if (c>=INTMIN) return INTCELL;
1506 if (c>=CHARMIN) return CHARCELL;
1507 if (c>=CLASSMIN) return CLASS;
1508 if (c>=INSTMIN) return INSTANCE;
1509 if (c>=NAMEMIN) return NAME;
1510 if (c>=TYCMIN) return TYCON;
1511 if (c>=MODMIN) return MODULE;
1512 if (c>=OFFMIN) return OFFSET;
1514 if (c>=EXTMIN) return EXT;
1516 if (c>=TUPMIN) return TUPLE;
1521 /* A very, very simple printer.
1522 * Output is uglier than from printExp - but the printer is more
1523 * robust and can be used on any data structure irrespective of
1526 Void print Args((Cell, Int));
1527 Void print(c, depth)
1532 #if 0 /* Not in this version of Hugs */
1533 } else if (isPair(c) && !isGenPair(c)) {
1534 extern Void printEvalCell Args((Cell, Int));
1535 printEvalCell(c,depth);
1538 Int tag = whatIs(c);
1542 print(fst(c), depth-1);
1544 print(snd(c), depth-1);
1548 Printf("free(%d)", c);
1551 Printf("int(%d)", intOf(c));
1554 Printf("bignum(%s)", bignumToString(c));
1557 Printf("char('%c')", charOf(c));
1560 Printf("ptr(%p)",ptrOf(c));
1563 Printf("class(%d)", c-CLASSMIN);
1564 if (CLASSMIN <= c && c < classHw) {
1565 Printf("=\"%s\"", textToStr(cclass(c).text));
1569 Printf("instance(%d)", c - INSTMIN);
1572 Printf("name(%d)", c-NAMEMIN);
1573 if (NAMEMIN <= c && c < nameHw) {
1574 Printf("=\"%s\"", textToStr(name(c).text));
1578 Printf("tycon(%d)", c-TYCMIN);
1579 if (TYCMIN <= c && c < tyconHw)
1580 Printf("=\"%s\"", textToStr(tycon(c).text));
1583 Printf("module(%d)", c - MODMIN);
1586 Printf("Offset %d", offsetOf(c));
1589 Printf("Tuple %d", tupleOf(c));
1593 print(snd(c),depth-1);
1597 print(snd(c),depth-1);
1601 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
1602 Printf("%d ", intOf(fst(snd(c))));
1603 print(snd(snd(c)),depth-1);
1605 print(snd(c),depth-1);
1622 Printf("{dict %d}",textOf(c));
1628 Printf("{id %s}",textToStr(textOf(c)));
1631 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
1635 print(fst(snd(c)),depth-1);
1637 print(snd(snd(c)),depth-1);
1642 print(snd(c),depth-1);
1647 print(snd(c),depth-1);
1652 print(fst(snd(c)),depth-1);
1654 print(snd(snd(c)),depth-1);
1659 print(fst(snd(c)),depth-1);
1661 print(snd(snd(c)),depth-1);
1665 Printf("FromQual(");
1666 print(fst(snd(c)),depth-1);
1668 print(snd(snd(c)),depth-1);
1672 Printf("StgVar%d=",-c);
1673 print(snd(c), depth-1);
1677 print(fst(snd(c)),depth-1);
1679 print(snd(snd(c)),depth-1);
1684 print(fst(snd(c)),depth-1);
1686 print(snd(snd(c)),depth-1);
1691 print(fst(snd(c)),depth-1);
1693 print(snd(snd(c)),depth-1);
1697 Printf("PrimCase(");
1698 print(fst(snd(c)),depth-1);
1700 print(snd(snd(c)),depth-1);
1704 if (isBoxTag(tag)) {
1705 Printf("Tag(%d)=%d", c, tag);
1706 } else if (isConTag(tag)) {
1707 Printf("%d@(%d,",c,tag);
1708 print(snd(c), depth-1);
1711 } else if (c == tag) {
1712 Printf("Tag(%d)", c);
1714 Printf("Tag(%d)=%d", c, tag);
1723 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
1724 Cell c; { /* also recognises DICTVAR cells */
1726 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
1729 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
1731 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
1734 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
1736 if (!isPair(c)) return FALSE;
1739 case VAROPCELL : return TRUE;
1741 case QUALIDENT : return isVar(snd(snd(c)));
1743 default : return FALSE;
1747 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
1749 if (!isPair(c)) return FALSE;
1752 case CONOPCELL : return TRUE;
1754 case QUALIDENT : return isCon(snd(snd(c)));
1756 default : return FALSE;
1760 Bool isQualIdent(c) /* is cell a qualified identifier? */
1762 return isPair(c) && (fst(c)==QUALIDENT);
1765 Bool isIdent(c) /* is cell an identifier? */
1767 if (!isPair(c)) return FALSE;
1772 case CONOPCELL : return TRUE;
1774 case QUALIDENT : return TRUE;
1776 default : return FALSE;
1780 Bool isInt(c) /* cell holds integer value? */
1782 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
1785 Int intOf(c) /* find integer value of cell? */
1789 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
1792 Cell mkInt(n) /* make cell representing integer */
1794 return (MINSMALLINT <= n && n <= MAXSMALLINT)
1799 #if SIZEOF_INTP == SIZEOF_INT
1800 typedef union {Int i; Ptr p;} IntOrPtr;
1806 return pair(PTRCELL,x.i);
1813 assert(fst(c) == PTRCELL);
1822 return pair(CPTRCELL,x.i);
1829 assert(fst(c) == CPTRCELL);
1833 #elif SIZEOF_INTP == 2*SIZEOF_INT
1834 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
1840 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
1847 assert(fst(c) == PTRCELL);
1848 x.i.i1 = intOf(fst(snd(c)));
1849 x.i.i2 = intOf(snd(snd(c)));
1853 #warning "type Addr not supported on this architecture - don't use it"
1857 ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
1864 ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
1869 String stringNegate( s )
1877 strcpy(&t[1],s); /* ToDo: use strncpy instead */
1882 /* --------------------------------------------------------------------------
1884 * ------------------------------------------------------------------------*/
1886 Int length(xs) /* calculate length of list xs */
1889 for (; nonNull(xs); ++n)
1894 List appendOnto(xs,ys) /* Destructively prepend xs onto */
1895 List xs, ys; { /* ys by modifying xs ... */
1900 while (nonNull(tl(zs)))
1907 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
1910 for (; nonNull(xs); xs=tl(xs))
1911 ys = cons(hd(xs),ys);
1915 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
1918 return revOnto(dupOnto(xs,NIL),ys);
1921 List dupList(xs) /* Duplicate spine of list xs */
1924 for (; nonNull(xs); xs=tl(xs))
1925 ys = cons(hd(xs),ys);
1929 List revOnto(xs,ys) /* Destructively reverse elements of*/
1930 List xs, ys; { /* list xs onto list ys... */
1933 while (nonNull(xs)) {
1942 Cell varIsMember(t,xs) /* Test if variable is a member of */
1943 Text t; /* given list of variables */
1945 for (; nonNull(xs); xs=tl(xs))
1946 if (t==textOf(hd(xs)))
1951 Name nameIsMember(t,ns) /* Test if name with text t is a */
1952 Text t; /* member of list of names xs */
1954 for (; nonNull(ns); ns=tl(ns))
1955 if (t==name(hd(ns)).text)
1960 Cell intIsMember(n,xs) /* Test if integer n is member of */
1961 Int n; /* given list of integers */
1963 for (; nonNull(xs); xs=tl(xs))
1964 if (n==intOf(hd(xs)))
1969 Cell cellIsMember(x,xs) /* Test for membership of specific */
1970 Cell x; /* cell x in list xs */
1972 for (; nonNull(xs); xs=tl(xs))
1978 Cell cellAssoc(c,xs) /* Lookup cell in association list */
1981 for (; nonNull(xs); xs=tl(xs))
1987 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
1988 Cell c; /* association lists */
1990 for (; nonNull(xs); xs=tl(xs))
1996 List replicate(n,x) /* create list of n copies of x */
2005 List diffList(from,take) /* list difference: from\take */
2006 List from, take; { /* result contains all elements of */
2007 List result = NIL; /* `from' not appearing in `take' */
2009 while (nonNull(from)) {
2010 List next = tl(from);
2011 if (!cellIsMember(hd(from),take)) {
2020 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2024 for(;nonNull(xs);xs=tl(xs)) {
2027 result=cons(x,result);
2033 List take(n,xs) /* destructively truncate list to */
2034 Int n; /* specified length */
2040 while (1<n-- && nonNull(xs))
2047 List splitAt(n,xs) /* drop n things from front of list*/
2056 Cell nth(n,xs) /* extract n'th element of list */
2059 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2066 List removeCell(x,xs) /* destructively remove cell from */
2071 return tl(xs); /* element at front of list */
2075 for (; nonNull(curr); prev=curr, curr=tl(prev))
2077 tl(prev) = tl(curr);
2078 return xs; /* element in middle of list */
2082 return xs; /* here if element not found */
2085 List nubList(xs) /* nuke dups in list */
2086 List xs; { /* non destructive */
2088 for (; nonNull(xs); xs=tl(xs))
2089 if (isNull(cellIsMember(hd(xs),outs)))
2090 outs = cons(hd(xs),outs);
2095 /* --------------------------------------------------------------------------
2096 * Operations on applications:
2097 * ------------------------------------------------------------------------*/
2099 Int argCount; /* number of args in application */
2101 Cell getHead(e) /* get head cell of application */
2102 Cell e; { /* set number of args in argCount */
2103 for (argCount=0; isAp(e); e=fun(e))
2108 List getArgs(e) /* get list of arguments in function*/
2109 Cell e; { /* application: */
2110 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2112 for (as=NIL; isAp(e); e=fun(e))
2113 as = cons(arg(e),as);
2117 Cell nthArg(n,e) /* return nth arg in application */
2118 Int n; /* of function to m args (m>=n) */
2119 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2120 for (n=numArgs(e)-n-1; n>0; n--)
2125 Int numArgs(e) /* find number of arguments to expr */
2128 for (n=0; isAp(e); e=fun(e))
2133 Cell applyToArgs(f,args) /* destructively apply list of args */
2134 Cell f; /* to function f */
2136 while (nonNull(args)) {
2137 Cell temp = tl(args);
2138 tl(args) = hd(args);
2147 /* --------------------------------------------------------------------------
2149 * ------------------------------------------------------------------------*/
2151 /*---------------------------------------------------------------------------
2152 * GreenCard entry points
2154 * GreenCard generated code accesses Hugs data structures and functions
2155 * (only) via these functions (which are stored in the virtual function
2157 *-------------------------------------------------------------------------*/
2161 static Cell makeTuple Args((Int));
2162 static Cell makeInt Args((Int));
2163 static Cell makeChar Args((Char));
2164 static Char CharOf Args((Cell));
2165 static Cell makeFloat Args((FloatPro));
2166 static Void* derefMallocPtr Args((Cell));
2167 static Cell* Fst Args((Cell));
2168 static Cell* Snd Args((Cell));
2170 static Cell makeTuple(n) Int n; { return mkTuple(n); }
2171 static Cell makeInt(n) Int n; { return mkInt(n); }
2172 static Cell makeChar(n) Char n; { return mkChar(n); }
2173 static Char CharOf(n) Cell n; { return charOf(n); }
2174 static Cell makeFloat(n) FloatPro n; { return mkFloat(n); }
2175 static Void* derefMallocPtr(n) Cell n; { return derefMP(n); }
2176 static Cell* Fst(n) Cell n; { return (Cell*)&fst(n); }
2177 static Cell* Snd(n) Cell n; { return (Cell*)&snd(n); }
2179 HugsAPI1* hugsAPI1() {
2180 static HugsAPI1 api;
2181 static Bool initialised = FALSE;
2183 api.nameTrue = nameTrue;
2184 api.nameFalse = nameFalse;
2185 api.nameNil = nameNil;
2186 api.nameCons = nameCons;
2187 api.nameJust = nameJust;
2188 api.nameNothing = nameNothing;
2189 api.nameLeft = nameLeft;
2190 api.nameRight = nameRight;
2191 api.nameUnit = nameUnit;
2192 api.nameIORun = nameIORun;
2193 api.makeInt = makeInt;
2194 api.makeChar = makeChar;
2195 api.CharOf = CharOf;
2196 api.makeFloat = makeFloat;
2197 api.makeTuple = makeTuple;
2199 api.mkMallocPtr = mkMallocPtr;
2200 api.derefMallocPtr = derefMallocPtr;
2201 api.mkStablePtr = mkStablePtr;
2202 api.derefStablePtr = derefStablePtr;
2203 api.freeStablePtr = freeStablePtr;
2205 api.evalWithNoError = evalWithNoError;
2206 api.evalFails = evalFails;
2207 api.whnfArgs = &whnfArgs;
2208 api.whnfHead = &whnfHead;
2209 api.whnfInt = &whnfInt;
2210 api.whnfFloat = &whnfFloat;
2211 api.garbageCollect = garbageCollect;
2212 api.stackOverflow = hugsStackOverflow;
2213 api.internal = internal;
2214 api.registerPrims = registerPrims;
2215 api.addPrimCfun = addPrimCfun;
2216 api.inventText = inventText;
2219 api.cellStack = cellStack;
2225 #endif /* GREENCARD */
2228 /* --------------------------------------------------------------------------
2230 * ------------------------------------------------------------------------*/
2233 static void far* safeFarCalloc Args((Int,Int));
2234 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
2235 Int n, s; { /* for non-null return */
2236 void far* tab = farCalloc(n,s);
2238 ERRMSG(0) "Cannot allocate run-time tables"
2243 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
2245 #define TABALLOC(v,t,n)
2253 case RESET : clearStack();
2255 /* the next 2 statements are particularly important
2256 * if you are using GLOBALfst or GLOBALsnd since the
2257 * corresponding registers may be reset to their
2258 * uninitialised initial values by a longjump.
2260 heapTopFst = heapFst + heapSize;
2261 heapTopSnd = heapSnd + heapSize;
2265 if (isNull(lastExprSaved))
2266 savedText = NUM_TEXT;
2271 for (i=NAMEMIN; i<nameHw; ++i) {
2272 mark(name(i).parent);
2274 mark(name(i).stgVar);
2276 mark(name(i).ghc_names);
2278 end("Names", nameHw-NAMEMIN);
2281 for (i=MODMIN; i<moduleHw; ++i) {
2282 mark(module(i).tycons);
2283 mark(module(i).names);
2284 mark(module(i).classes);
2285 mark(module(i).exports);
2286 mark(module(i).qualImports);
2288 end("Modules", moduleHw-MODMIN);
2291 for (i=TYCMIN; i<tyconHw; ++i) {
2292 mark(tycon(i).defn);
2293 mark(tycon(i).kind);
2294 mark(tycon(i).what);
2296 end("Type constructors", tyconHw-TYCMIN);
2299 for (i=CLASSMIN; i<classHw; ++i) {
2300 mark(cclass(i).head);
2301 mark(cclass(i).kinds);
2302 mark(cclass(i).dsels);
2303 mark(cclass(i).supers);
2304 mark(cclass(i).members);
2305 mark(cclass(i).defaults);
2306 mark(cclass(i).instances);
2309 end("Classes", classHw-CLASSMIN);
2312 for (i=INSTMIN; i<instHw; ++i) {
2314 mark(inst(i).kinds);
2315 mark(inst(i).specifics);
2316 mark(inst(i).implements);
2318 end("Instances", instHw-INSTMIN);
2321 for (i=0; i<=sp; ++i)
2326 mark(lastExprSaved);
2329 end("Last expression", 3);
2334 end("C stack", stackRoots);
2339 case INSTALL : heapFst = heapAlloc(heapSize);
2340 heapSnd = heapAlloc(heapSize);
2342 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
2343 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
2348 heapTopFst = heapFst + heapSize;
2349 heapTopSnd = heapSnd + heapSize;
2350 for (i=1; i<heapSize; ++i) {
2354 snd(-heapSize) = NIL;
2361 marksSize = bitArraySize(heapSize);
2362 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
2363 ERRMSG(0) "Unable to allocate gc markspace"
2367 TABALLOC(text, char, NUM_TEXT)
2368 TABALLOC(tyconHash, Tycon, TYCONHSZ)
2369 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
2370 TABALLOC(nameHash, Name, NAMEHSZ)
2371 TABALLOC(tabName, struct strName, NUM_NAME)
2372 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
2373 TABALLOC(cellStack, Cell, NUM_STACK)
2374 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
2376 TABALLOC(tabExt, Text, NUM_EXT)
2381 nextNewText = NUM_TEXT;
2382 nextNewDText = (-1);
2383 lastExprSaved = NIL;
2384 savedText = NUM_TEXT;
2385 for (i=0; i<TEXTHSZ; ++i)
2386 textHash[i][0] = NOTEXT;
2392 for (i=0; i<TYCONHSZ; ++i)
2399 for (i=0; i<NAMEHSZ; ++i)
2410 tabInst = (struct strInst far *)
2411 farCalloc(NUM_INSTS,sizeof(struct strInst));
2414 ERRMSG(0) "Cannot allocate instance tables"
2424 /*-------------------------------------------------------------------------*/