2 /* --------------------------------------------------------------------------
3 * Primitives for manipulating global data structures
5 * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
6 * Yale Haskell Group, and the Oregon Graduate Institute of Science and
7 * Technology, 1994-1999, All rights reserved. It is distributed as
8 * free software under the license in the file "License", which is
9 * included in the distribution.
11 * $RCSfile: storage.c,v $
13 * $Date: 2000/03/23 14:54:21 $
14 * ------------------------------------------------------------------------*/
16 #include "hugsbasictypes.h"
23 /*#define DEBUG_SHOWUSE*/
25 /* --------------------------------------------------------------------------
26 * local function prototypes:
27 * ------------------------------------------------------------------------*/
29 static Int local hash ( String );
30 static Int local saveText ( Text );
31 static Module local findQualifier ( Text );
32 static Void local hashTycon ( Tycon );
33 static List local insertTycon ( Tycon,List );
34 static Void local hashName ( Name );
35 static List local insertName ( Name,List );
36 static Void local patternError ( String );
37 static Bool local stringMatch ( String,String );
38 static Bool local typeInvolves ( Type,Type );
39 static Cell local markCell ( Cell );
40 static Void local markSnd ( Cell );
41 static Cell local lowLevelLastIn ( Cell );
42 static Cell local lowLevelLastOut ( Cell );
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 = TEXT_SIZE; /* 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 text[TEXT_SIZE]; /* 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 (isText(t)) /* standard char string */
85 return text + t - TEXT_BASE_ADDR;
86 if (isInventedDictVar(t)) {
88 t-INDVAR_BASE_ADDR); /* dictionary variable */
91 if (isInventedVar(t)) {
93 t-INVAR_BASE_ADDR); /* normal variable */
96 internal("textToStr");
99 String identToStr(v) /*find string corresp to given ident or qualified name*/
102 internal("identToStr");
108 case CONOPCELL : return text+textOf(v);
110 case QUALIDENT : { Text pos = textHw;
112 while (pos+1 < savedText && text[t]!=0) {
113 text[pos++] = text[t++];
115 if (pos+1 < savedText) {
119 while (pos+1 < savedText && text[t]!=0) {
120 text[pos++] = text[t++];
126 internal("identToStr2");
127 return 0; /* NOTREACHED */
130 Text inventText() { /* return new unused variable name */
131 if (nextNewText >= INVAR_BASE_ADDR+INVAR_MAX_AVAIL)
132 internal("inventText: too many invented variables");
133 return nextNewText++;
136 Text inventDictText() { /* return new unused dictvar name */
137 if (nextNewDText >= INDVAR_BASE_ADDR+INDVAR_MAX_AVAIL)
138 internal("inventDictText: too many invented variables");
139 return nextNewDText++;
142 Bool inventedText(t) /* Signal TRUE if text has been */
143 Text t; { /* generated internally */
144 return isInventedVar(t) || isInventedDictVar(t);
147 #define MAX_FIXLIT 100
148 Text fixLitText(t) /* fix literal text that might include \ */
150 String s = textToStr(t);
153 for(i = 0;i < MAX_FIXLIT-2 && *s;s++) {
159 if (i < MAX_FIXLIT-2) {
162 ERRMSG(0) "storage space exhausted for internal literal string"
165 return (findText(p));
169 static Int local hash(s) /* Simple hash function on strings */
173 for (v=((int)(*s))*8; *s; s++)
174 v += ((int)(*s))*(j++);
180 Text findText(s) /* Locate string in Text array */
184 Text textPos = textHash[h][hashno];
186 # define TryMatch { Text originalTextPos = textPos; \
188 for (t=s; *t==text[textPos]; textPos++,t++) \
190 return originalTextPos+TEXT_BASE_ADDR; \
192 # define Skip while (text[textPos++]) ;
194 while (textPos!=NOTEXT) {
196 if (++hashno<NUM_TEXTH) /* look in next hashtable entry */
197 textPos = textHash[h][hashno];
200 while (textPos < textHw) {
211 textPos = textHw; /* if not found, save in array */
212 if (textHw + (Int)strlen(s) + 1 > savedText) {
213 ERRMSG(0) "Character string storage space exhausted"
216 while ((text[textHw++] = *s++) != 0) {
218 if (hashno<NUM_TEXTH) { /* updating hash table as necessary */
219 textHash[h][hashno] = textPos;
220 if (hashno<NUM_TEXTH-1)
221 textHash[h][hashno+1] = NOTEXT;
224 return textPos+TEXT_BASE_ADDR;
227 static Int local saveText(t) /* Save text value in buffer */
228 Text t; { /* at top of text table */
229 String s = textToStr(t);
231 if (textHw + l + 1 > savedText) {
232 ERRMSG(0) "Character string storage space exhausted"
236 strcpy(text+savedText,s);
241 static int fromHexDigit ( char c )
244 case '0': case '1': case '2': case '3': case '4':
245 case '5': case '6': case '7': case '8': case '9':
247 case 'a': case 'A': return 10;
248 case 'b': case 'B': return 11;
249 case 'c': case 'C': return 12;
250 case 'd': case 'D': return 13;
251 case 'e': case 'E': return 14;
252 case 'f': case 'F': return 15;
258 /* returns findText (unZencode s) */
259 Text unZcodeThenFindText ( String s )
266 nn = 100 + 10 * strlen(s);
268 if (!p) internal ("unZcodeThenFindText: malloc failed");
273 if (n > nn-90) internal ("unZcodeThenFindText: result is too big");
274 if (*s != 'z' && *s != 'Z') {
279 if (!(*s)) goto parse_error;
281 case 'Z': p[n++] = 'Z'; break;
282 case 'C': p[n++] = ':'; break;
283 case 'L': p[n++] = '('; break;
284 case 'R': p[n++] = ')'; break;
285 case 'M': p[n++] = '['; break;
286 case 'N': p[n++] = ']'; break;
287 case 'z': p[n++] = 'z'; break;
288 case 'a': p[n++] = '&'; break;
289 case 'b': p[n++] = '|'; break;
290 case 'd': p[n++] = '$'; break;
291 case 'e': p[n++] = '='; break;
292 case 'g': p[n++] = '>'; break;
293 case 'h': p[n++] = '#'; break;
294 case 'i': p[n++] = '.'; break;
295 case 'l': p[n++] = '<'; break;
296 case 'm': p[n++] = '-'; break;
297 case 'n': p[n++] = '!'; break;
298 case 'p': p[n++] = '+'; break;
299 case 'q': p[n++] = '\\'; break;
300 case 'r': p[n++] = '\''; break;
301 case 's': p[n++] = '/'; break;
302 case 't': p[n++] = '*'; break;
303 case 'u': p[n++] = '^'; break;
304 case 'v': p[n++] = '%'; break;
306 if (!s[0] || !s[1]) goto parse_error;
307 if (fromHexDigit(s[0]) < 0 || fromHexDigit(s[1]) < 0) goto parse_error;
308 p[n++] = 16 * fromHexDigit(s[0]) + fromHexDigit(s[1]);
311 case '0': case '1': case '2': case '3': case '4':
312 case '5': case '6': case '7': case '8': case '9':
315 while (*s && isdigit((int)(*s))) {
316 i = 10 * i + (*s - '0');
319 if (*s != 'T') goto parse_error;
322 while (i > 0) { p[n++] = ','; i--; };
336 fprintf ( stderr, "\nstring = `%s'\n", s );
337 internal ( "unZcodeThenFindText: parse error on above string");
338 return NIL; /*notreached*/
342 Text enZcodeThenFindText ( String s )
347 char toHex[16] = "0123456789ABCDEF";
350 nn = 100 + 10 * strlen(s);
352 if (!p) internal ("enZcodeThenFindText: malloc failed");
356 if (n > nn-90) internal ("enZcodeThenFindText: result is too big");
359 && (isalnum((int)(*s)) || *s == '_')) {
367 while (*s && *s==',') { s++; tup++; };
368 if (*s != ')') internal("enZcodeThenFindText: invalid tuple type");
371 sprintf(num,"%d",tup);
372 p[n] = 0; strcat ( &(p[n]), num ); n += strlen(num);
377 case '(': p[n++] = 'Z'; p[n++] = 'L'; break;
378 case ')': p[n++] = 'Z'; p[n++] = 'R'; break;
379 case '[': p[n++] = 'Z'; p[n++] = 'M'; break;
380 case ']': p[n++] = 'Z'; p[n++] = 'N'; break;
381 case ':': p[n++] = 'Z'; p[n++] = 'C'; break;
382 case 'Z': p[n++] = 'Z'; p[n++] = 'Z'; break;
383 case 'z': p[n++] = 'z'; p[n++] = 'z'; break;
384 case '&': p[n++] = 'z'; p[n++] = 'a'; break;
385 case '|': p[n++] = 'z'; p[n++] = 'b'; break;
386 case '$': p[n++] = 'z'; p[n++] = 'd'; break;
387 case '=': p[n++] = 'z'; p[n++] = 'e'; break;
388 case '>': p[n++] = 'z'; p[n++] = 'g'; break;
389 case '#': p[n++] = 'z'; p[n++] = 'h'; break;
390 case '.': p[n++] = 'z'; p[n++] = 'i'; break;
391 case '<': p[n++] = 'z'; p[n++] = 'l'; break;
392 case '-': p[n++] = 'z'; p[n++] = 'm'; break;
393 case '!': p[n++] = 'z'; p[n++] = 'n'; break;
394 case '+': p[n++] = 'z'; p[n++] = 'p'; break;
395 case '\'': p[n++] = 'z'; p[n++] = 'q'; break;
396 case '\\': p[n++] = 'z'; p[n++] = 'r'; break;
397 case '/': p[n++] = 'z'; p[n++] = 's'; break;
398 case '*': p[n++] = 'z'; p[n++] = 't'; break;
399 case '^': p[n++] = 'z'; p[n++] = 'u'; break;
400 case '%': p[n++] = 'z'; p[n++] = 'v'; break;
401 default: s--; p[n++] = 'z'; p[n++] = 'x';
402 p[n++] = toHex[(int)(*s)/16];
403 p[n++] = toHex[(int)(*s)%16];
414 Text textOf ( Cell c )
428 fprintf(stderr, "\ntextOf: bad tag %d\n",wot );
429 internal("textOf: bad tag");
434 /* --------------------------------------------------------------------------
437 * Currently, the only attributes that we store for each Ext value is the
438 * corresponding Text label. At some later stage, we may decide to cache
439 * types, predicates, etc. here as a space saving gesture. Given that Text
440 * comparison is cheap, and that this is an experimental implementation, we
441 * will use a straightforward linear search to locate Ext values from their
442 * corresponding Text labels; a hashing scheme can be introduced later if
443 * this turns out to be a problem.
444 * ------------------------------------------------------------------------*/
447 Text DEFTABLE(tabExt,NUM_EXT); /* Storage for Ext names */
450 Ext mkExt(t) /* Allocate or find an Ext value */
456 if (extHw-EXTMIN >= NUM_EXT) {
457 ERRMSG(0) "Ext storage space exhausted"
466 /* --------------------------------------------------------------------------
467 * Expandable symbol tables. A template, which is instantiated for the name,
468 * tycon, class, instance and module tables. Also, potentially, TREX Exts.
469 * ------------------------------------------------------------------------*/
471 #define EXPANDABLE_SYMBOL_TABLE(type_name,struct_name, \
472 proc_name,free_proc_name, \
473 free_list,tab_name,tab_size,err_msg, \
474 TAB_INIT_SIZE,TAB_MAX_SIZE, \
477 struct struct_name* tab_name = NULL; \
479 static type_name free_list = TAB_BASE_ADDR-1; \
481 void free_proc_name ( type_name n ) \
483 assert(TAB_BASE_ADDR <= n); \
484 assert(n < TAB_BASE_ADDR+tab_size); \
485 assert(tab_name[n-TAB_BASE_ADDR].inUse); \
486 tab_name[n-TAB_BASE_ADDR].inUse = FALSE; \
487 /*tab_name[n-TAB_BASE_ADDR].nextFree = free_list; */ \
491 type_name proc_name ( void ) \
495 struct struct_name* newTab; \
496 struct struct_name* temp; \
498 if (free_list != TAB_BASE_ADDR-1) { \
499 type_name t = free_list; \
500 free_list = tab_name[free_list-TAB_BASE_ADDR].nextFree; \
501 assert (!(tab_name[t-TAB_BASE_ADDR].inUse)); \
502 tab_name[t-TAB_BASE_ADDR].inUse = TRUE; \
506 newSz = (tab_size == 0 ? TAB_INIT_SIZE : 2 * tab_size); \
507 if (newSz > TAB_MAX_SIZE) goto cant_allocate; \
508 newTab = malloc(newSz * sizeof(struct struct_name)); \
509 if (!newTab) goto cant_allocate; \
510 for (i = 0; i < tab_size; i++) \
511 newTab[i] = tab_name[i]; \
512 for (i = tab_size; i < newSz; i++) { \
513 newTab[i].inUse = FALSE; \
514 newTab[i].nextFree = i-1+TAB_BASE_ADDR; \
516 fprintf(stderr, "Expanding " #type_name \
517 "table to size %d\n", newSz ); \
518 newTab[tab_size].nextFree = TAB_BASE_ADDR-1; \
519 free_list = newSz-1+TAB_BASE_ADDR; \
523 if (temp) free(temp); \
533 EXPANDABLE_SYMBOL_TABLE(Name,strName,allocNewName,freeName,
534 nameFL,tabName,tabNameSz,
535 "Name storage space exhausted",
536 NAME_INIT_SIZE,NAME_MAX_SIZE,NAME_BASE_ADDR)
539 EXPANDABLE_SYMBOL_TABLE(Tycon,strTycon,allocNewTycon,freeTycon,
540 tyconFL,tabTycon,tabTyconSz,
541 "Type constructor storage space exhausted",
542 TYCON_INIT_SIZE,TYCON_MAX_SIZE,TYCON_BASE_ADDR)
545 EXPANDABLE_SYMBOL_TABLE(Class,strClass,allocNewClass,freeClass,
546 classFL,tabClass,tabClassSz,
547 "Class storage space exhausted",
548 CCLASS_INIT_SIZE,CCLASS_MAX_SIZE,CCLASS_BASE_ADDR)
551 EXPANDABLE_SYMBOL_TABLE(Inst,strInst,allocNewInst,freeInst,
552 instFL,tabInst,tabInstSz,
553 "Instance storage space exhausted",
554 INST_INIT_SIZE,INST_MAX_SIZE,INST_BASE_ADDR)
557 EXPANDABLE_SYMBOL_TABLE(Module,strModule,allocNewModule,freeModule,
558 moduleFL,tabModule,tabModuleSz,
559 "Module storage space exhausted",
560 MODULE_INIT_SIZE,MODULE_MAX_SIZE,MODULE_BASE_ADDR)
563 struct strName* generate_name_ref ( Cell nm )
566 nm -= NAME_BASE_ADDR;
567 assert(tabName[nm].inUse);
568 assert(isModule(tabName[nm].mod));
569 return & tabName[nm];
571 struct strTycon* generate_tycon_ref ( Cell tc )
573 assert(isTycon(tc) || isTuple(tc));
574 tc -= TYCON_BASE_ADDR;
575 assert(tabTycon[tc].inUse);
576 assert(isModule(tabTycon[tc].mod));
577 return & tabTycon[tc];
579 struct strClass* generate_cclass_ref ( Cell cl )
582 cl -= CCLASS_BASE_ADDR;
583 assert(tabClass[cl].inUse);
584 assert(isModule(tabClass[cl].mod));
585 return & tabClass[cl];
587 struct strInst* generate_inst_ref ( Cell in )
590 in -= INST_BASE_ADDR;
591 assert(tabInst[in].inUse);
592 assert(isModule(tabInst[in].mod));
593 return & tabInst[in];
595 struct strModule* generate_module_ref ( Cell mo )
597 assert(isModule(mo));
598 mo -= MODULE_BASE_ADDR;
599 assert(tabModule[mo].inUse);
600 return & tabModule[mo];
605 /* --------------------------------------------------------------------------
608 * A Tycon represents a user defined type constructor. Tycons are indexed
609 * by Text values ... a very simple hash function is used to improve lookup
610 * times. Tycon entries with the same hash code are chained together, with
611 * the most recent entry at the front of the list.
612 * ------------------------------------------------------------------------*/
614 #define TYCONHSZ 256 /* Size of Tycon hash table*/
615 //#define tHash(x) (((x)-TEXT_BASE_ADDR)%TYCONHSZ)/* Tycon hash function */
616 static int tHash(Text x)
619 assert(isText(x) || inventedText(x));
627 static Tycon tyconHash[TYCONHSZ]; /* Hash table storage */
630 assert (x >= 0 && x < TYCONHSZ);
633 Tycon newTycon ( Text t ) /* add new tycon to tycon table */
636 Tycon tc = allocNewTycon();
638 [tc-TYCON_BASE_ADDR].tuple = -1;
640 [tc-TYCON_BASE_ADDR].mod = currentModule;
641 tycon(tc).text = t; /* clear new tycon record */
642 tycon(tc).kind = NIL;
643 tycon(tc).defn = NIL;
644 tycon(tc).what = NIL;
645 tycon(tc).conToTag = NIL;
646 tycon(tc).tagToCon = NIL;
647 tycon(tc).itbl = NULL;
649 module(currentModule).tycons = cons(tc,module(currentModule).tycons);
650 tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
651 tyconHash[RC_T(h)] = tc;
655 Tycon findTycon(t) /* locate Tycon in tycon table */
657 Tycon tc = tyconHash[RC_T(tHash(t))];
658 assert(isTycon(tc) || isTuple(tc) || isNull(tc));
659 while (nonNull(tc) && tycon(tc).text!=t)
660 tc = tycon(tc).nextTyconHash;
664 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
667 assert(isTycon(tc) || isTuple(tc));
668 oldtc = findTycon(tycon(tc).text);
671 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
677 static Void local hashTycon(tc) /* Insert Tycon into hash table */
681 assert(isTycon(tc) || isTuple(tc));
682 {int i; for (i = 0; i < TYCONHSZ; i++)
683 assert (tyconHash[i] == 0
684 || isTycon(tyconHash[i])
685 || isTuple(tyconHash[i]));
689 tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
690 tyconHash[RC_T(h)] = tc;
693 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
695 if (!isPair(id)) internal("findQualTycon");
699 return findTycon(textOf(id));
701 Text t = qtextOf(id);
702 Module m = findQualifier(qmodOf(id));
704 if (isNull(m)) return NIL;
705 for(es=module(m).exports; nonNull(es); es=tl(es)) {
707 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
712 default : internal("findQualTycon2");
714 return NIL; /* NOTREACHED */
717 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
723 Tycon tc = newTycon(t);
725 tycon(tc).kind = kind;
726 tycon(tc).what = what;
727 tycon(tc).defn = defn;
728 tycon(tc).arity = ar;
732 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
737 String s = textToStr(tycon(tc).text);
739 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
740 if (hd(curr)==tc) /* just in case we get duplicates! */
746 tl(prev) = cons(tc,curr);
750 return cons(tc,curr);
753 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
754 String pat; /* to list of Tycons ts */
755 List ts; { /* Null pattern matches every tycon*/
756 Tycon tc; /* (Tycons with NIL kind excluded) */
757 for (tc = TYCON_BASE_ADDR;
758 tc < TYCON_BASE_ADDR+tabTyconSz; ++tc)
759 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
760 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
761 if (nonNull(tycon(tc).kind))
762 ts = insertTycon(tc,ts);
766 Text ghcTupleText_n ( Int n )
771 if (n < 0 || n >= 100) internal("ghcTupleText_n");
772 if (n == 1) internal("ghcTupleText_n==1");
774 for (i = 1; i <= n-1; i++) buf[x++] = ',';
777 return findText(buf);
780 Text ghcTupleText(tup)
783 assert(isTuple(tup));
785 return ghcTupleText_n ( tupleOf(tup) );
789 Tycon mkTuple ( Int n )
793 internal("mkTuple: request for tuple of unsupported size");
794 for (i = TYCON_BASE_ADDR;
795 i < TYCON_BASE_ADDR+tabTyconSz; i++)
796 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
797 if (tycon(i).tuple == n) return i;
798 internal("mkTuple: request for non-existent tuple");
802 /* --------------------------------------------------------------------------
805 * A Name represents a top level binding of a value to an identifier.
806 * Such values may be a constructor function, a member function in a
807 * class, a user-defined or primitive value/function.
809 * Names are indexed by Text values ... a very simple hash functions speeds
810 * access to the table of Names and Name entries with the same hash value
811 * are chained together, with the most recent entry at the front of the
813 * ------------------------------------------------------------------------*/
815 #define NAMEHSZ 256 /* Size of Name hash table */
816 //#define nHash(x) (((x)-TEXT_BASE_ADDR)%NAMEHSZ) /* hash fn :: Text->Int */
817 static int nHash(Text x)
819 assert(isText(x) || inventedText(x));
824 static Name nameHash[NAMEHSZ]; /* Hash table storage */
827 assert (x >= 0 && x < NAMEHSZ);
830 void hashSanity ( void )
833 for (i = 0; i < TYCONHSZ; i++) {
836 assert(isTycon(j) || isTuple(j));
837 j = tycon(j).nextTyconHash;
840 for (i = 0; i < NAMEHSZ; i++) {
844 j = name(j).nextNameHash;
849 Name newName ( Text t, Cell parent ) /* Add new name to name table */
852 Name nm = allocNewName();
854 [nm-NAME_BASE_ADDR].mod = currentModule;
855 name(nm).text = t; /* clear new name record */
857 name(nm).syntax = NO_SYNTAX;
858 name(nm).parent = parent;
860 name(nm).number = EXECNAME;
862 name(nm).stgVar = NIL;
863 name(nm).callconv = NIL;
865 name(nm).primop = NULL;
866 name(nm).itbl = NULL;
867 module(currentModule).names = cons(nm,module(currentModule).names);
868 name(nm).nextNameHash = nameHash[RC_N(h)];
869 nameHash[RC_N(h)] = nm;
873 Name findName(t) /* Locate name in name table */
875 Name n = nameHash[RC_N(nHash(t))];
877 assert(isName(n) || isNull(n));
878 while (nonNull(n) && name(n).text!=t)
879 n = name(n).nextNameHash;
883 Name addName(nm) /* Insert Name in name table - if */
884 Name nm; { /* no clash is caused */
887 oldnm = findName(name(nm).text);
890 module(currentModule).names=cons(nm,module(currentModule).names);
896 static Void local hashName(nm) /* Insert Name into hash table */
903 name(nm).nextNameHash = nameHash[RC_N(h)];
904 nameHash[RC_N(h)] = nm;
907 Name findQualName(id) /* Locate (possibly qualified) name*/
908 Cell id; { /* in name table */
910 internal("findQualName");
916 return findName(textOf(id));
918 Text t = qtextOf(id);
919 Module m = findQualifier(qmodOf(id));
921 if (isNull(m)) return NIL;
922 for(es=module(m).exports; nonNull(es); es=tl(es)) {
924 if (isName(e) && name(e).text==t)
926 else if (isPair(e) && DOTDOT==snd(e)) {
927 List subentities = NIL;
930 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
931 subentities = tycon(c).defn;
933 subentities = cclass(c).members;
934 for(; nonNull(subentities); subentities=tl(subentities)) {
935 if (!isName(hd(subentities)))
936 internal("findQualName3");
937 if (name(hd(subentities)).text == t)
938 return hd(subentities);
944 default : internal("findQualName2");
946 return 0; /* NOTREACHED */
950 Name nameFromStgVar ( StgVar v )
953 for (n = NAME_BASE_ADDR;
954 n < NAME_BASE_ADDR+tabNameSz; n++)
955 if (tabName[n-NAME_BASE_ADDR].inUse)
956 if (name(n).stgVar == v) return n;
960 void* getHugs_AsmObject_for ( char* s )
963 Text t = findText(s);
965 for (n = NAME_BASE_ADDR;
966 n < NAME_BASE_ADDR+tabNameSz; n++)
967 if (tabName[n-NAME_BASE_ADDR].inUse)
968 if (name(n).text == t) break;
969 if (n == NAME_BASE_ADDR+tabNameSz) {
970 fprintf ( stderr, "can't find `%s' in ...\n", s );
971 internal("getHugs_AsmObject_for(1)");
974 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
975 internal("getHugs_AsmObject_for(2)");
976 return ptrOf(stgVarInfo(v));
979 /* --------------------------------------------------------------------------
980 * Primitive functions:
981 * ------------------------------------------------------------------------*/
983 Module findFakeModule ( Text t )
985 Module m = findModule(t);
987 if (!module(m).fake) internal("findFakeModule");
990 module(m).fake = TRUE;
996 Name addWiredInBoxingTycon
997 ( String modNm, String typeNm, String constrNm,
1002 Text modT = findText(modNm);
1003 Text typeT = findText(typeNm);
1004 Text conT = findText(constrNm);
1005 Module m = findFakeModule(modT);
1008 n = newName(conT,NIL);
1010 name(n).number = cfunNo(0);
1012 name(n).primop = (void*)rep;
1014 t = newTycon(typeT);
1015 tycon(t).what = DATATYPE;
1016 tycon(t).kind = kind;
1021 Tycon addTupleTycon ( Int n )
1029 for (i = TYCON_BASE_ADDR;
1030 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1031 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
1032 if (tycon(i).tuple == n) return i;
1035 m = findFakeModule(findText(n==0 ? "PrelBase" : "PrelTup")); else
1036 m = findModule(findText("Prelude"));
1040 for (i = 0; i < n; i++) k = ap(STAR,k);
1041 t = newTycon(ghcTupleText_n(n));
1044 tycon(t).what = DATATYPE;
1047 /* maybe we want to do this for all n ? */
1048 nm = newName(ghcTupleText_n(n), t);
1049 name(nm).type = t; /* ummm ... for n > 0 */
1056 Tycon addWiredInEnumTycon ( String modNm, String typeNm,
1057 List /*of Text*/ constrs )
1061 Text modT = findText(modNm);
1062 Text typeT = findText(typeNm);
1063 Module m = findFakeModule(modT);
1066 t = newTycon(typeT);
1067 tycon(t).kind = STAR;
1068 tycon(t).what = DATATYPE;
1070 constrs = reverse(constrs);
1071 i = length(constrs);
1072 for (; nonNull(constrs); constrs=tl(constrs),i--) {
1073 Text conT = hd(constrs);
1074 Name con = newName(conT,t);
1075 name(con).number = cfunNo(i);
1077 name(con).parent = t;
1078 tycon(t).defn = cons(con, tycon(t).defn);
1084 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
1085 Text t; /* sets rep, not type */
1088 Int rep; { /* Really AsmRep */
1089 Name n = newName(t,NIL);
1090 name(n).arity = arity;
1091 name(n).number = cfunNo(no);
1093 name(n).primop = (void*)rep;
1098 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
1103 Name n = newName(t,NIL);
1104 name(n).arity = arity;
1105 name(n).number = cfunNo(no);
1106 name(n).type = type;
1111 Int sfunPos(s,c) /* Find position of field with */
1112 Name s; /* selector s in constructor c. */
1116 for (; nonNull(cns); cns=tl(cns))
1117 if (fst(hd(cns))==c)
1118 return intOf(snd(hd(cns)));
1119 internal("sfunPos");
1120 return 0;/* NOTREACHED */
1123 static List local insertName(nm,ns) /* insert name nm into sorted list */
1128 String s = textToStr(name(nm).text);
1130 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
1131 if (hd(curr)==nm) /* just in case we get duplicates! */
1136 if (nonNull(prev)) {
1137 tl(prev) = cons(nm,curr);
1141 return cons(nm,curr);
1144 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
1145 String pat; /* to list of names ns */
1146 List ns; { /* Null pattern matches every name */
1147 Name nm; /* (Names with NIL type, or hidden */
1148 /* or invented names are excluded) */
1150 for (nm = NAME_BASE_ADDR;
1151 nm < NAME_BASE_ADDR+tabNameSz; ++nm)
1152 if (tabName[nm-NAME_BASE_ADDR].inUse) {
1153 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
1154 String str = textToStr(name(nm).text);
1155 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1156 ns = insertName(nm,ns);
1161 List mns = module(currentModule).names;
1162 for(; nonNull(mns); mns=tl(mns)) {
1164 if (!inventedText(name(nm).text)) {
1165 String str = textToStr(name(nm).text);
1166 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1167 ns = insertName(nm,ns);
1174 /* --------------------------------------------------------------------------
1175 * A simple string matching routine
1176 * `*' matches any sequence of zero or more characters
1177 * `?' matches any single character exactly
1178 * `@str' matches the string str exactly (ignoring any special chars)
1179 * `\c' matches the character c only (ignoring special chars)
1180 * c matches the character c only
1181 * ------------------------------------------------------------------------*/
1183 static Void local patternError(s) /* report error in pattern */
1185 ERRMSG(0) "%s in pattern", s
1189 static Bool local stringMatch(pat,str) /* match string against pattern */
1195 case '\0' : return (*str=='\0');
1198 if (stringMatch(pat+1,str))
1203 case '?' : if (*str++=='\0')
1208 case '[' : { Bool found = FALSE;
1209 while (*++pat!='\0' && *pat!=']')
1210 if (!found && ( pat[0] == *str ||
1219 patternError("missing `]'");
1227 case '\\' : if (*++pat == '\0')
1228 patternError("extra trailing `\\'");
1230 default : if (*pat++ != *str++)
1236 /* --------------------------------------------------------------------------
1237 * Storage of type classes, instances etc...:
1238 * ------------------------------------------------------------------------*/
1240 static List classes; /* list of classes in current scope */
1242 Class newClass ( Text t ) /* add new class to class table */
1244 Class cl = allocNewClass();
1246 [cl-CCLASS_BASE_ADDR].mod = currentModule;
1247 cclass(cl).text = t;
1248 cclass(cl).arity = 0;
1249 cclass(cl).kinds = NIL;
1250 cclass(cl).head = NIL;
1251 cclass(cl).fds = NIL;
1252 cclass(cl).xfds = NIL;
1253 cclass(cl).dcon = NIL;
1254 cclass(cl).supers = NIL;
1255 cclass(cl).dsels = NIL;
1256 cclass(cl).members = NIL;
1257 cclass(cl).defaults = NIL;
1258 cclass(cl).instances = NIL;
1259 classes = cons(cl,classes);
1260 module(currentModule).classes
1261 = cons(cl,module(currentModule).classes);
1265 Class findClass(t) /* look for named class in table */
1269 for (cs=classes; nonNull(cs); cs=tl(cs)) {
1271 if (cclass(cl).text==t)
1277 Class addClass(c) /* Insert Class in class list */
1278 Class c; { /* - if no clash caused */
1280 assert(whatIs(c)==CLASS);
1281 oldc = findClass(cclass(c).text);
1283 classes=cons(c,classes);
1284 module(currentModule).classes=cons(c,module(currentModule).classes);
1291 Class findQualClass(c) /* Look for (possibly qualified) */
1292 Cell c; { /* class in class list */
1293 if (!isQualIdent(c)) {
1294 return findClass(textOf(c));
1296 Text t = qtextOf(c);
1297 Module m = findQualifier(qmodOf(c));
1301 for (es=module(m).exports; nonNull(es); es=tl(es)) {
1303 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
1310 Inst newInst() { /* Add new instance to table */
1311 Inst in = allocNewInst();
1313 [in-INST_BASE_ADDR].mod = currentModule;
1314 inst(in).kinds = NIL;
1315 inst(in).head = NIL;
1316 inst(in).specifics = NIL;
1317 inst(in).implements = NIL;
1318 inst(in).builder = NIL;
1323 extern Void printInst ( Inst));
1327 Class cl = inst(in).c;
1328 Printf("%s-", textToStr(cclass(cl).text));
1329 printType(stdout,inst(in).t);
1331 #endif /* DEBUG_DICTS */
1333 Inst findFirstInst(tc) /* look for 1st instance involving */
1334 Tycon tc; { /* the type constructor tc */
1335 return findNextInst(tc,INST_BASE_ADDR-1);
1338 Inst findNextInst(tc,in) /* look for next instance involving*/
1339 Tycon tc; /* the type constructor tc */
1340 Inst in; { /* starting after instance in */
1342 while (++in < INST_BASE_ADDR+tabInstSz) {
1343 if (!tabInst[in-INST_BASE_ADDR].inUse) continue;
1344 assert(isModule(inst(in).mod));
1346 for (; isAp(pi); pi=fun(pi))
1347 if (typeInvolves(arg(pi),tc))
1353 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1354 Type ty; /* type constructor/tuple tc. */
1357 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1358 || typeInvolves(arg(ty),tc)));
1362 /* Needed by finishGHCInstance to find classes, before the
1363 export list has been built -- so we can't use
1366 Class findQualClassWithoutConsultingExportList ( QualId q )
1376 t_class = textOf(q);
1379 t_class = qtextOf(q);
1382 for (cl = CCLASS_BASE_ADDR;
1383 cl < CCLASS_BASE_ADDR+tabClassSz; cl++) {
1384 if (tabClass[cl-CCLASS_BASE_ADDR].inUse)
1385 if (cclass(cl).text == t_class) {
1386 /* Class name is ok, but is this the right module? */
1387 if (isNull(t_mod) /* no module name specified */
1389 && t_mod == module(cclass(cl).mod).text)
1397 /* Same deal, except for Tycons. */
1398 Tycon findQualTyconWithoutConsultingExportList ( QualId q )
1408 t_tycon = textOf(q);
1411 t_tycon = qtextOf(q);
1414 for (tc = TYCON_BASE_ADDR;
1415 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1416 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1417 if (tycon(tc).text == t_tycon) {
1418 /* Tycon name is ok, but is this the right module? */
1419 if (isNull(t_mod) /* no module name specified */
1421 && t_mod == module(tycon(tc).mod).text)
1429 /* Same deal, except for Names. */
1430 Name findQualNameWithoutConsultingExportList ( QualId q )
1436 assert(isQVar(q) || isQCon(q));
1438 if (isCon(q) || isVar(q)) {
1443 t_name = qtextOf(q);
1446 for (nm = NAME_BASE_ADDR;
1447 nm < NAME_BASE_ADDR+tabNameSz; nm++) {
1448 if (tabName[nm-NAME_BASE_ADDR].inUse)
1449 if (name(nm).text == t_name) {
1450 /* Name is ok, but is this the right module? */
1451 if (isNull(t_mod) /* no module name specified */
1453 && t_mod == module(name(nm).mod).text)
1462 Tycon findTyconInAnyModule ( Text t )
1465 for (tc = TYCON_BASE_ADDR;
1466 tc < TYCON_BASE_ADDR+tabTyconSz; tc++)
1467 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1468 if (tycon(tc).text == t) return tc;
1472 Class findClassInAnyModule ( Text t )
1475 for (cc = CCLASS_BASE_ADDR;
1476 cc < CCLASS_BASE_ADDR+tabClassSz; cc++)
1477 if (tabClass[cc-CCLASS_BASE_ADDR].inUse)
1478 if (cclass(cc).text == t) return cc;
1482 Name findNameInAnyModule ( Text t )
1485 for (nm = NAME_BASE_ADDR;
1486 nm < NAME_BASE_ADDR+tabNameSz; nm++)
1487 if (tabName[nm-NAME_BASE_ADDR].inUse)
1488 if (name(nm).text == t) return nm;
1493 /* returns List of QualId */
1494 List getAllKnownTyconsAndClasses ( void )
1499 for (tc = TYCON_BASE_ADDR;
1500 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1501 if (tabTycon[tc-TYCON_BASE_ADDR].inUse) {
1502 /* almost certainly undue paranoia about duplicate avoidance */
1503 QualId q = mkQCon( module(tycon(tc).mod).text, tycon(tc).text );
1504 if (!qualidIsMember(q,xs))
1505 xs = cons ( q, xs );
1508 for (nw = CCLASS_BASE_ADDR;
1509 nw < CCLASS_BASE_ADDR+tabClassSz; nw++) {
1510 if (tabClass[nw-CCLASS_BASE_ADDR].inUse) {
1511 QualId q = mkQCon( module(cclass(nw).mod).text, cclass(nw).text );
1512 if (!qualidIsMember(q,xs))
1513 xs = cons ( q, xs );
1519 /* Purely for debugging. */
1520 void locateSymbolByName ( Text t )
1523 for (i = NAME_BASE_ADDR;
1524 i < NAME_BASE_ADDR+tabNameSz; i++)
1525 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).text == t)
1526 fprintf ( stderr, "name(%d)\n", i-NAME_BASE_ADDR);
1527 for (i = TYCON_BASE_ADDR;
1528 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1529 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).text == t)
1530 fprintf ( stderr, "tycon(%d)\n", i-TYCON_BASE_ADDR);
1531 for (i = CCLASS_BASE_ADDR;
1532 i < CCLASS_BASE_ADDR+tabClassSz; i++)
1533 if (tabClass[i-CCLASS_BASE_ADDR].inUse && cclass(i).text == t)
1534 fprintf ( stderr, "class(%d)\n", i-CCLASS_BASE_ADDR);
1537 /* --------------------------------------------------------------------------
1540 * Various parts of the system use a stack of cells. Most of the stack
1541 * operations are defined as macros, expanded inline.
1542 * ------------------------------------------------------------------------*/
1544 Cell cellStack[NUM_STACK]; /* Storage for cells on stack */
1545 StackPtr sp; /* stack pointer */
1547 Void hugsStackOverflow() { /* Report stack overflow */
1548 ERRMSG(0) "Control stack overflow"
1553 /* --------------------------------------------------------------------------
1556 * A Module represents a user defined module.
1558 * Note: there are now two lookup mechanisms in the system:
1560 * 1) The exports from a module are stored in a big list.
1561 * We resolve qualified names, and import lists by linearly scanning
1562 * through this list.
1564 * 2) Unqualified imports and local definitions for the current module
1565 * are stored in hash tables (tyconHash and nameHash) or linear lists
1568 * ------------------------------------------------------------------------*/
1570 Module currentModule; /* Module currently being processed*/
1572 Bool isValidModule(m) /* is m a legitimate module id? */
1577 Module newModule ( Text t ) /* add new module to module table */
1579 Module mod = allocNewModule();
1580 module(mod).text = t; /* clear new module record */
1582 module(mod).tycons = NIL;
1583 module(mod).names = NIL;
1584 module(mod).classes = NIL;
1585 module(mod).exports = NIL;
1586 module(mod).qualImports = NIL;
1587 module(mod).fake = FALSE;
1589 module(mod).tree = NIL;
1590 module(mod).completed = FALSE;
1591 module(mod).lastStamp = 0; /* ???? */
1593 module(mod).fromSrc = TRUE;
1594 module(mod).srcExt = findText("");
1595 module(mod).uses = NIL;
1597 module(mod).objName = findText("");
1598 module(mod).objSize = 0;
1600 module(mod).object = NULL;
1601 module(mod).objectExtras = NULL;
1602 module(mod).objectExtraNames = NIL;
1606 void nukeModule ( Module m )
1611 assert(isModule(m));
1612 fprintf(stderr, "NUKEMODULE `%s'\n", textToStr(module(m).text));
1613 oc = module(m).object;
1619 oc = module(m).objectExtras;
1626 for (i = NAME_BASE_ADDR; i < NAME_BASE_ADDR+tabNameSz; i++)
1627 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).mod == m) {
1628 if (name(i).itbl) free(name(i).itbl);
1629 name(i).itbl = NULL;
1633 for (i = TYCON_BASE_ADDR; i < TYCON_BASE_ADDR+tabTyconSz; i++)
1634 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).mod == m) {
1635 if (tycon(i).itbl) free(tycon(i).itbl);
1636 tycon(i).itbl = NULL;
1640 for (i = CCLASS_BASE_ADDR; i < CCLASS_BASE_ADDR+tabClassSz; i++)
1641 if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
1642 if (cclass(i).mod == m) {
1645 List /* Inst */ ins;
1646 List /* Inst */ ins2 = NIL;
1647 for (ins = cclass(i).instances; nonNull(ins); ins=tl(ins))
1648 if (inst(hd(ins)).mod != m)
1649 ins2 = cons(hd(ins),ins2);
1650 cclass(i).instances = ins2;
1655 for (i = INST_BASE_ADDR; i < INST_BASE_ADDR+tabInstSz; i++)
1656 if (tabInst[i-INST_BASE_ADDR].inUse && inst(i).mod == m)
1660 //for (i = 0; i < TYCONHSZ; i++) tyconHash[i] = 0;
1661 //for (i = 0; i < NAMEHSZ; i++) nameHash[i] = 0;
1666 void ppModules ( void )
1669 fflush(stderr); fflush(stdout);
1670 printf ( "begin MODULES\n" );
1671 for (i = MODULE_BASE_ADDR+tabModuleSz-1;
1672 i >= MODULE_BASE_ADDR; i--)
1673 if (tabModule[i-MODULE_BASE_ADDR].inUse)
1674 printf ( " %2d: %16s\n",
1675 i-MODULE_BASE_ADDR, textToStr(module(i).text)
1677 printf ( "end MODULES\n" );
1678 fflush(stderr); fflush(stdout);
1682 Module findModule(t) /* locate Module in module table */
1685 for(m = MODULE_BASE_ADDR;
1686 m < MODULE_BASE_ADDR+tabModuleSz; ++m) {
1687 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1688 if (module(m).text==t)
1694 Module findModid(c) /* Find module by name or filename */
1696 switch (whatIs(c)) {
1697 case STRCELL : internal("findModid-STRCELL unimp");
1698 case CONIDCELL : return findModule(textOf(c));
1699 default : internal("findModid");
1701 return NIL;/*NOTUSED*/
1704 static local Module findQualifier(t) /* locate Module in import list */
1707 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1708 if (textOf(fst(hd(ms)))==t)
1711 if (module(currentModule).text==t)
1712 return currentModule;
1716 Void setCurrModule(m) /* set lookup tables for current module */
1719 assert(isModule(m));
1720 fprintf(stderr, "SET CURR MODULE %s\n", textToStr(module(m).text));
1722 for (t = module(m).names; nonNull(t); t=tl(t))
1723 assert(isName(hd(t)));
1724 for (t = module(m).tycons; nonNull(t); t=tl(t))
1725 assert(isTycon(hd(t)) || isTuple(hd(t)));
1726 for (t = module(m).classes; nonNull(t); t=tl(t))
1727 assert(isClass(hd(t)));
1730 currentModule = m; /* This is the only assignment to currentModule */
1731 for (i=0; i<TYCONHSZ; ++i)
1732 tyconHash[RC_T(i)] = NIL;
1733 mapProc(hashTycon,module(m).tycons);
1734 for (i=0; i<NAMEHSZ; ++i)
1735 nameHash[RC_N(i)] = NIL;
1736 mapProc(hashName,module(m).names);
1737 classes = module(m).classes;
1741 Name jrsFindQualName ( Text mn, Text sn )
1746 for (m = MODULE_BASE_ADDR;
1747 m < MODULE_BASE_ADDR+tabModuleSz; m++)
1748 if (tabModule[m-MODULE_BASE_ADDR].inUse
1749 && module(m).text == mn) break;
1751 if (m == MODULE_BASE_ADDR+tabModuleSz) return NIL;
1753 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1754 if (name(hd(ns)).text == sn) return hd(ns);
1760 char* nameFromOPtr ( void* p )
1764 for (m = MODULE_BASE_ADDR;
1765 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1766 if (tabModule[m-MODULE_BASE_ADDR].inUse && module(m).object) {
1767 char* nm = ocLookupAddr ( module(m).object, p );
1772 /* A kludge to assist Win32 debugging; not actually necessary. */
1773 { char* nm = nameFromStaticOPtr(p);
1781 void* lookupOTabName ( Module m, char* sym )
1783 assert(isModule(m));
1784 if (module(m).object)
1785 return ocLookupSym ( module(m).object, sym );
1790 void* lookupOExtraTabName ( char* sym )
1794 for (m = MODULE_BASE_ADDR;
1795 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1796 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1797 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1798 void* ad = ocLookupSym ( oc, sym );
1806 OSectionKind lookupSection ( void* ad )
1813 for (m = MODULE_BASE_ADDR;
1814 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1815 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1816 if (module(m).object) {
1817 sect = ocLookupSection ( module(m).object, ad );
1818 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1821 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1822 sect = ocLookupSection ( oc, ad );
1823 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1828 return HUGS_SECTIONKIND_OTHER;
1832 /* --------------------------------------------------------------------------
1835 * Provides a garbage collectable heap for storage of expressions etc.
1837 * Now incorporates a flat resource: A two-space collected extension of
1838 * the heap that provides storage for contiguous arrays of Cell storage,
1839 * cooperating with the garbage collection mechanisms for the main heap.
1840 * ------------------------------------------------------------------------*/
1842 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1843 Heap heapFst; /* array of fst component of pairs */
1844 Heap heapSnd; /* array of snd component of pairs */
1851 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1852 /* C stack; use with extreme care! */
1854 Int numGcs; /* number of garbage collections */
1855 Int cellsRecovered; /* number of cells recovered */
1857 static Cell freeList; /* free list of unused cells */
1858 static Cell lsave, rsave; /* save components of pair */
1862 static Int markCount, stackRoots;
1864 #define initStackRoots() stackRoots = 0
1865 #define recordStackRoot() stackRoots++
1878 #define start() markCount = 0
1879 #define end(thing,rs) \
1881 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1884 #define recordMark() markCount++
1886 #else /* !GC_STATISTICS */
1891 #define initStackRoots()
1892 #define recordStackRoot()
1895 #define end(thing,root)
1896 #define recordMark()
1898 #endif /* !GC_STATISTICS */
1900 Cell pair(l,r) /* Allocate pair (l, r) from */
1901 Cell l, r; { /* heap, garbage collecting first */
1902 Cell c = freeList; /* if necessary ... */
1914 freeList = snd(freeList);
1922 static Int marksSize;
1924 Cell markExpr(c) /* External interface to markCell */
1926 return isGenPair(c) ? markCell(c) : c;
1929 static Cell local markCell(c) /* Traverse part of graph marking */
1930 Cell c; { /* cells reachable from given root */
1931 /* markCell(c) is only called if c */
1933 { register int place = placeInSet(c);
1934 register int mask = maskInSet(c);
1935 if (marks[place]&mask)
1938 marks[place] |= mask;
1943 /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1944 if (isGenPair(fst(c))) {
1946 fst(c) = markCell(fst(c));
1949 else if (isNull(fst(c)) || isTagPtr(fst(c))) {
1957 static Void local markSnd(c) /* Variant of markCell used to */
1958 Cell c; { /* update snd component of cell */
1959 Cell t; /* using tail recursion */
1961 ma: t = c; /* Keep pointer to original pair */
1966 { register int place = placeInSet(c);
1967 register int mask = maskInSet(c);
1968 if (marks[place]&mask)
1971 marks[place] |= mask;
1976 if (isGenPair(fst(c))) {
1977 fst(c) = markCell(fst(c));
1980 else if (isNull(fst(c)) || isTagPtr(fst(c)))
1985 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1986 Cell n; { /* it was a cell ref, but don't */
1987 /* move cell so we don't have */
1988 /* to modify the stored value of n */
1995 Void garbageCollect() { /* Run garbage collector ... */
1996 Bool breakStat = breakOn(FALSE); /* disable break checking */
2001 jmp_buf regs; /* save registers on stack */
2002 fprintf ( stderr, "wa-hey! garbage collection! too difficult! bye!\n" );
2007 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
2010 everybody(MARK); /* Mark all components of system */
2012 gcScanning(); /* scan mark set */
2019 for (i=1; i<=heapSize; i++) {
2020 if ((marks[place] & mask) == 0) {
2027 if (++j == bitsPerWord) {
2034 gcRecovered(recovered);
2035 breakOn(breakStat); /* restore break trapping if nec. */
2039 /* can only return if freeList is nonempty on return. */
2040 if (recovered<minRecovery || isNull(freeList)) {
2041 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
2044 cellsRecovered = recovered;
2047 /* --------------------------------------------------------------------------
2048 * Code for saving last expression entered:
2050 * This is a little tricky because some text values (e.g. strings or variable
2051 * names) may not be defined or have the same value when the expression is
2052 * recalled. These text values are therefore saved in the top portion of
2054 * ------------------------------------------------------------------------*/
2056 static Cell lastExprSaved; /* last expression to be saved */
2058 Void setLastExpr(e) /* save expression for later recall*/
2060 lastExprSaved = NIL; /* in case attempt to save fails */
2061 savedText = TEXT_SIZE;
2062 lastExprSaved = lowLevelLastIn(e);
2065 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
2066 Cell c; { /* acyclic graph) for later recall */
2067 if (isPair(c)) { /* Duplicating any text strings */
2068 if (isTagNonPtr(fst(c))) /* in case these are lost at some */
2069 switch (fst(c)) { /* point before the expr is reused */
2075 case STRCELL : return pair(fst(c),saveText(textOf(c)));
2076 default : return pair(fst(c),snd(c));
2079 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2083 return pair(EXTCOPY,saveText(extText(c)));
2089 Cell getLastExpr() { /* recover previously saved expr */
2090 return lowLevelLastOut(lastExprSaved);
2093 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
2094 Cell c; { /* except that Cells refering to */
2095 if (isPair(c)) { /* Text values are restored to */
2096 if (isTagNonPtr(fst(c))) /* appropriate values */
2103 case STRCELL : return pair(fst(c),
2104 findText(text+intValOf(c)));
2106 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
2108 default : return pair(fst(c),snd(c));
2111 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2117 /* --------------------------------------------------------------------------
2118 * Miscellaneous operations on heap cells:
2119 * ------------------------------------------------------------------------*/
2121 Cell whatIs ( register Cell c )
2124 register Cell fstc = fst(c);
2125 return isTag(fstc) ? fstc : AP;
2127 if (isOffset(c)) return OFFSET;
2128 if (isChar(c)) return CHARCELL;
2129 if (isInt(c)) return INTCELL;
2130 if (isName(c)) return NAME;
2131 if (isTycon(c)) return TYCON;
2132 if (isTuple(c)) return TUPLE;
2133 if (isClass(c)) return CLASS;
2134 if (isInst(c)) return INSTANCE;
2135 if (isModule(c)) return MODULE;
2136 if (isText(c)) return TEXTCELL;
2137 if (isInventedVar(c)) return INVAR;
2138 if (isInventedDictVar(c)) return INDVAR;
2139 if (isSpec(c)) return c;
2140 if (isNull(c)) return c;
2141 fprintf ( stderr, "whatIs: unknown %d\n", c );
2147 Cell whatIs(c) /* identify type of cell */
2150 register Cell fstc = fst(c);
2151 return isTag(fstc) ? fstc : AP;
2153 if (c<OFFMIN) return c;
2155 if (isExt(c)) return EXT;
2157 if (c>=INTMIN) return INTCELL;
2159 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
2161 else if (c>=INSTMIN) return INSTANCE;
2163 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
2164 else return MODULE;}
2165 else if (c>=OFFMIN) return OFFSET;
2167 else return (c>=EXTMIN) ?
2175 register Cell fstc = fst(c);
2176 return isTag(fstc) ? fstc : AP;
2178 if (c>=INTMIN) return INTCELL;
2179 if (c>=CHARMIN) return CHARCELL;
2180 if (c>=CLASSMIN) return CLASS;
2181 if (c>=INSTMIN) return INSTANCE;
2182 if (c>=NAMEMIN) return NAME;
2183 if (c>=TYCMIN) return TYCON;
2184 if (c>=MODMIN) return MODULE;
2185 if (c>=OFFMIN) return OFFSET;
2187 if (c>=EXTMIN) return EXT;
2189 if (c>=TUPMIN) return TUPLE;
2195 /* A very, very simple printer.
2196 * Output is uglier than from printExp - but the printer is more
2197 * robust and can be used on any data structure irrespective of
2200 Void print ( Cell c, Int depth )
2205 else if (isNull(c)) {
2208 else if (isTagPtr(c)) {
2209 Printf("TagP(%d)", c);
2211 else if (isTagNonPtr(c)) {
2212 Printf("TagNP(%d)", c);
2214 else if (isSpec(c)) {
2215 Printf("TagS(%d)", c);
2217 else if (isText(c)) {
2218 Printf("text(%d)=\"%s\"",c-TEXT_BASE_ADDR,textToStr(c));
2220 else if (isInventedVar(c)) {
2221 Printf("invented(%d)", c-INVAR_BASE_ADDR);
2223 else if (isInventedDictVar(c)) {
2224 Printf("inventedDict(%d)",c-INDVAR_BASE_ADDR);
2227 Int tag = whatIs(c);
2231 print(fst(c), depth-1);
2233 print(snd(c), depth-1);
2237 Printf("free(%d)", c);
2240 Printf("int(%d)", intOf(c));
2243 Printf("bignum(%s)", bignumToString(c));
2246 Printf("char('%c')", charOf(c));
2249 Printf("ptr(%p)",ptrOf(c));
2252 Printf("class(%d)", c-CCLASS_BASE_ADDR);
2253 Printf("=\"%s\"", textToStr(cclass(c).text));
2256 Printf("instance(%d)", c - INST_BASE_ADDR);
2259 Printf("name(%d)", c-NAME_BASE_ADDR);
2260 Printf("=\"%s\"", textToStr(name(c).text));
2263 Printf("tycon(%d)", c-TYCON_BASE_ADDR);
2264 Printf("=\"%s\"", textToStr(tycon(c).text));
2267 Printf("module(%d)", c - MODULE_BASE_ADDR);
2268 Printf("=\"%s\"", textToStr(module(c).text));
2271 Printf("Offset %d", offsetOf(c));
2274 Printf("%s", textToStr(ghcTupleText(c)));
2278 print(snd(c),depth-1);
2282 print(snd(c),depth-1);
2286 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2287 Printf("%d ", intOf(fst(snd(c))));
2288 print(snd(snd(c)),depth-1);
2290 print(snd(c),depth-1);
2304 Printf("{dict %d}",textOf(c));
2310 Printf("{id %s}",textToStr(textOf(c)));
2314 Printf("{ip %s}",textToStr(textOf(c)));
2317 Printf("?%s",textToStr(textOf(c)));
2321 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2325 print(fst(snd(c)),depth-1);
2327 print(snd(snd(c)),depth-1);
2332 print(snd(c),depth-1);
2337 print(snd(c),depth-1);
2342 print(fst(snd(c)),depth-1);
2344 print(snd(snd(c)),depth-1);
2349 print(fst(snd(c)),depth-1);
2351 print(snd(snd(c)),depth-1);
2355 Printf("FromQual(");
2356 print(fst(snd(c)),depth-1);
2358 print(snd(snd(c)),depth-1);
2362 Printf("StgVar%d=",-c);
2363 print(snd(c), depth-1);
2367 print(fst(snd(c)),depth-1);
2369 print(snd(snd(c)),depth-1);
2374 print(fst(snd(c)),depth-1);
2376 print(snd(snd(c)),depth-1);
2381 print(fst(snd(c)),depth-1);
2383 print(snd(snd(c)),depth-1);
2387 Printf("PrimCase(");
2388 print(fst(snd(c)),depth-1);
2390 print(snd(snd(c)),depth-1);
2395 print(snd(c),depth-1);
2399 Printf("(UNBOXEDTUP,");
2400 print(snd(c),depth-1);
2405 print(zfst(c),depth-1);
2407 print(zsnd(c),depth-1);
2411 Printf("<ZTriple ");
2412 print(zfst3(c),depth-1);
2414 print(zsnd3(c),depth-1);
2416 print(zthd3(c),depth-1);
2421 print(snd(c),depth-1);
2425 if (isTagNonPtr(tag)) {
2426 Printf("(TagNP=%d,%d)", c, tag);
2427 } else if (isTagPtr(tag)) {
2428 Printf("(TagP=%d,",tag);
2429 print(snd(c), depth-1);
2432 } else if (c == tag) {
2433 Printf("Tag(%d)", c);
2435 Printf("Tag(%d)=%d", c, tag);
2444 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2445 Cell c; { /* also recognises DICTVAR cells */
2447 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2450 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2452 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2455 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2457 if (!isPair(c)) return FALSE;
2460 case VAROPCELL : return TRUE;
2462 case QUALIDENT : return isVar(snd(snd(c)));
2464 default : return FALSE;
2468 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2470 if (!isPair(c)) return FALSE;
2473 case CONOPCELL : return TRUE;
2475 case QUALIDENT : return isCon(snd(snd(c)));
2477 default : return FALSE;
2481 Bool isQualIdent(c) /* is cell a qualified identifier? */
2483 return isPair(c) && (fst(c)==QUALIDENT);
2486 Bool eqQualIdent ( QualId c1, QualId c2 )
2488 assert(isQualIdent(c1));
2489 if (!isQualIdent(c2)) {
2490 assert(isQualIdent(c2));
2492 return qmodOf(c1)==qmodOf(c2) &&
2493 qtextOf(c1)==qtextOf(c2);
2496 Bool isIdent(c) /* is cell an identifier? */
2498 if (!isPair(c)) return FALSE;
2503 case CONOPCELL : return TRUE;
2505 case QUALIDENT : return TRUE;
2507 default : return FALSE;
2511 Bool isInt(c) /* cell holds integer value? */
2513 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2516 Int intOf(c) /* find integer value of cell? */
2519 return isPair(c) ? (Int)(snd(c)) : (Int)(c-SMALL_INT_ZERO);
2522 Cell mkInt(n) /* make cell representing integer */
2524 return (SMALL_INT_MIN <= SMALL_INT_ZERO+n &&
2525 SMALL_INT_ZERO+n <= SMALL_INT_MAX)
2530 #if SIZEOF_VOID_P == SIZEOF_INT
2532 typedef union {Int i; Ptr p;} IntOrPtr;
2539 return pair(PTRCELL,x.i);
2546 assert(fst(c) == PTRCELL);
2556 return pair(CPTRCELL,x.i);
2563 assert(fst(c) == CPTRCELL);
2568 #elif SIZEOF_VOID_P == 2*SIZEOF_INT
2570 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2577 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2584 assert(fst(c) == PTRCELL);
2585 x.i.i1 = intOf(fst(snd(c)));
2586 x.i.i2 = intOf(snd(snd(c)));
2595 return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2602 assert(fst(c) == CPTRCELL);
2603 x.i.i1 = intOf(fst(snd(c)));
2604 x.i.i2 = intOf(snd(snd(c)));
2610 #error "Can't implement mkPtr/ptrOf on this architecture."
2615 String stringNegate( s )
2623 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2628 /* --------------------------------------------------------------------------
2630 * ------------------------------------------------------------------------*/
2632 Int length(xs) /* calculate length of list xs */
2635 for (; nonNull(xs); ++n)
2640 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2641 List xs, ys; { /* ys by modifying xs ... */
2646 while (nonNull(tl(zs)))
2653 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2656 for (; nonNull(xs); xs=tl(xs))
2657 ys = cons(hd(xs),ys);
2661 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2664 return revOnto(dupOnto(xs,NIL),ys);
2667 List dupList(xs) /* Duplicate spine of list xs */
2670 for (; nonNull(xs); xs=tl(xs))
2671 ys = cons(hd(xs),ys);
2675 List revOnto(xs,ys) /* Destructively reverse elements of*/
2676 List xs, ys; { /* list xs onto list ys... */
2679 while (nonNull(xs)) {
2688 QualId qualidIsMember ( QualId q, List xs )
2690 for (; nonNull(xs); xs=tl(xs)) {
2691 if (eqQualIdent(q, hd(xs)))
2697 Cell varIsMember(t,xs) /* Test if variable is a member of */
2698 Text t; /* given list of variables */
2700 for (; nonNull(xs); xs=tl(xs))
2701 if (t==textOf(hd(xs)))
2706 Name nameIsMember(t,ns) /* Test if name with text t is a */
2707 Text t; /* member of list of names xs */
2709 for (; nonNull(ns); ns=tl(ns))
2710 if (t==name(hd(ns)).text)
2715 Cell intIsMember(n,xs) /* Test if integer n is member of */
2716 Int n; /* given list of integers */
2718 for (; nonNull(xs); xs=tl(xs))
2719 if (n==intOf(hd(xs)))
2724 Cell cellIsMember(x,xs) /* Test for membership of specific */
2725 Cell x; /* cell x in list xs */
2727 for (; nonNull(xs); xs=tl(xs))
2733 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2736 for (; nonNull(xs); xs=tl(xs))
2742 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2743 Cell c; /* association lists */
2745 for (; nonNull(xs); xs=tl(xs))
2751 List replicate(n,x) /* create list of n copies of x */
2760 List diffList(from,take) /* list difference: from\take */
2761 List from, take; { /* result contains all elements of */
2762 List result = NIL; /* `from' not appearing in `take' */
2764 while (nonNull(from)) {
2765 List next = tl(from);
2766 if (!cellIsMember(hd(from),take)) {
2775 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2779 for(;nonNull(xs);xs=tl(xs)) {
2782 result=cons(x,result);
2788 List take(n,xs) /* destructively truncate list to */
2789 Int n; /* specified length */
2795 while (1<n-- && nonNull(xs))
2802 List splitAt(n,xs) /* drop n things from front of list*/
2811 Cell nth(n,xs) /* extract n'th element of list */
2814 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2821 List removeCell(x,xs) /* destructively remove cell from */
2826 return tl(xs); /* element at front of list */
2830 for (; nonNull(curr); prev=curr, curr=tl(prev))
2832 tl(prev) = tl(curr);
2833 return xs; /* element in middle of list */
2837 return xs; /* here if element not found */
2840 List nubList(xs) /* nuke dups in list */
2841 List xs; { /* non destructive */
2843 for (; nonNull(xs); xs=tl(xs))
2844 if (isNull(cellIsMember(hd(xs),outs)))
2845 outs = cons(hd(xs),outs);
2851 /* --------------------------------------------------------------------------
2852 * Tagged tuples (experimental)
2853 * ------------------------------------------------------------------------*/
2855 static void z_tag_check ( Cell x, int tag, char* caller )
2859 sprintf(buf,"z_tag_check(%s): null\n", caller);
2862 if (whatIs(x) != tag) {
2864 "z_tag_check(%s): tag was %d, expected %d\n",
2865 caller, whatIs(x), tag );
2870 Cell zpair ( Cell x1, Cell x2 )
2871 { return ap(ZTUP2,ap(x1,x2)); }
2872 Cell zfst ( Cell zpair )
2873 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2874 Cell zsnd ( Cell zpair )
2875 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2877 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2878 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2879 Cell zfst3 ( Cell zpair )
2880 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2881 Cell zsnd3 ( Cell zpair )
2882 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2883 Cell zthd3 ( Cell zpair )
2884 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2886 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2887 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2888 Cell zsel14 ( Cell zpair )
2889 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2890 Cell zsel24 ( Cell zpair )
2891 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2892 Cell zsel34 ( Cell zpair )
2893 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2894 Cell zsel44 ( Cell zpair )
2895 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2897 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2898 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2899 Cell zsel15 ( Cell zpair )
2900 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2901 Cell zsel25 ( Cell zpair )
2902 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2903 Cell zsel35 ( Cell zpair )
2904 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2905 Cell zsel45 ( Cell zpair )
2906 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2907 Cell zsel55 ( Cell zpair )
2908 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2911 Cell unap ( int tag, Cell c )
2914 if (whatIs(c) != tag) {
2915 sprintf(buf, "unap: specified %d, actual %d\n",
2922 /* --------------------------------------------------------------------------
2923 * Operations on applications:
2924 * ------------------------------------------------------------------------*/
2926 Int argCount; /* number of args in application */
2928 Cell getHead(e) /* get head cell of application */
2929 Cell e; { /* set number of args in argCount */
2930 for (argCount=0; isAp(e); e=fun(e))
2935 List getArgs(e) /* get list of arguments in function*/
2936 Cell e; { /* application: */
2937 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2939 for (as=NIL; isAp(e); e=fun(e))
2940 as = cons(arg(e),as);
2944 Cell nthArg(n,e) /* return nth arg in application */
2945 Int n; /* of function to m args (m>=n) */
2946 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2947 for (n=numArgs(e)-n-1; n>0; n--)
2952 Int numArgs(e) /* find number of arguments to expr */
2955 for (n=0; isAp(e); e=fun(e))
2960 Cell applyToArgs(f,args) /* destructively apply list of args */
2961 Cell f; /* to function f */
2963 while (nonNull(args)) {
2964 Cell temp = tl(args);
2965 tl(args) = hd(args);
2973 /* --------------------------------------------------------------------------
2975 * ------------------------------------------------------------------------*/
2977 static String maybeModuleStr ( Module m )
2979 if (isModule(m)) return textToStr(module(m).text); else return "??";
2982 static String maybeNameStr ( Name n )
2984 if (isName(n)) return textToStr(name(n).text); else return "??";
2987 static String maybeTyconStr ( Tycon t )
2989 if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
2992 static String maybeClassStr ( Class c )
2994 if (isClass(c)) return textToStr(cclass(c).text); else return "??";
2997 static String maybeText ( Text t )
2999 if (isNull(t)) return "(nil)";
3000 return textToStr(t);
3003 static void print100 ( Int x )
3005 print ( x, 100); printf("\n");
3008 void dumpTycon ( Int t )
3010 if (isTycon(TYCON_BASE_ADDR+t) && !isTycon(t)) t += TYCON_BASE_ADDR;
3012 printf ( "dumpTycon %d: not a tycon\n", t);
3016 printf ( " text: %s\n", textToStr(tycon(t).text) );
3017 printf ( " line: %d\n", tycon(t).line );
3018 printf ( " mod: %s\n", maybeModuleStr(tycon(t).mod));
3019 printf ( " tuple: %d\n", tycon(t).tuple);
3020 printf ( " arity: %d\n", tycon(t).arity);
3021 printf ( " kind: "); print100(tycon(t).kind);
3022 printf ( " what: %d\n", tycon(t).what);
3023 printf ( " defn: "); print100(tycon(t).defn);
3024 printf ( " cToT: %d %s\n", tycon(t).conToTag,
3025 maybeNameStr(tycon(t).conToTag));
3026 printf ( " tToC: %d %s\n", tycon(t).tagToCon,
3027 maybeNameStr(tycon(t).tagToCon));
3028 printf ( " itbl: %p\n", tycon(t).itbl);
3029 printf ( " nextTH: %d %s\n", tycon(t).nextTyconHash,
3030 maybeTyconStr(tycon(t).nextTyconHash));
3034 void dumpName ( Int n )
3036 if (isName(NAME_BASE_ADDR+n) && !isName(n)) n += NAME_BASE_ADDR;
3038 printf ( "dumpName %d: not a name\n", n);
3042 printf ( " text: %s\n", textToStr(name(n).text) );
3043 printf ( " line: %d\n", name(n).line );
3044 printf ( " mod: %s\n", maybeModuleStr(name(n).mod));
3045 printf ( " syntax: %d\n", name(n).syntax );
3046 printf ( " parent: %d\n", name(n).parent );
3047 printf ( " arity: %d\n", name(n).arity );
3048 printf ( " number: %d\n", name(n).number );
3049 printf ( " type: "); print100(name(n).type);
3050 printf ( " defn: %d\n", name(n).defn );
3051 printf ( " stgVar: "); print100(name(n).stgVar);
3052 printf ( " cconv: %d\n", name(n).callconv );
3053 printf ( " primop: %p\n", name(n).primop );
3054 printf ( " itbl: %p\n", name(n).itbl );
3055 printf ( " nextNH: %d\n", name(n).nextNameHash );
3060 void dumpClass ( Int c )
3062 if (isClass(CCLASS_BASE_ADDR+c) && !isClass(c)) c += CCLASS_BASE_ADDR;
3064 printf ( "dumpClass %d: not a class\n", c);
3068 printf ( " text: %s\n", textToStr(cclass(c).text) );
3069 printf ( " line: %d\n", cclass(c).line );
3070 printf ( " mod: %s\n", maybeModuleStr(cclass(c).mod));
3071 printf ( " arity: %d\n", cclass(c).arity );
3072 printf ( " level: %d\n", cclass(c).level );
3073 printf ( " kinds: "); print100( cclass(c).kinds );
3074 printf ( " fds: %d\n", cclass(c).fds );
3075 printf ( " xfds: %d\n", cclass(c).xfds );
3076 printf ( " head: "); print100( cclass(c).head );
3077 printf ( " dcon: "); print100( cclass(c).dcon );
3078 printf ( " supers: "); print100( cclass(c).supers );
3079 printf ( " #supers: %d\n", cclass(c).numSupers );
3080 printf ( " dsels: "); print100( cclass(c).dsels );
3081 printf ( " members: "); print100( cclass(c).members );
3082 printf ( "#members: %d\n", cclass(c).numMembers );
3083 printf ( "defaults: "); print100( cclass(c).defaults );
3084 printf ( " insts: "); print100( cclass(c).instances );
3089 void dumpInst ( Int i )
3091 if (isInst(INST_BASE_ADDR+i) && !isInst(i)) i += INST_BASE_ADDR;
3093 printf ( "dumpInst %d: not an instance\n", i);
3097 printf ( " class: %s\n", maybeClassStr(inst(i).c) );
3098 printf ( " line: %d\n", inst(i).line );
3099 printf ( " mod: %s\n", maybeModuleStr(inst(i).mod));
3100 printf ( " kinds: "); print100( inst(i).kinds );
3101 printf ( " head: "); print100( inst(i).head );
3102 printf ( " specs: "); print100( inst(i).specifics );
3103 printf ( " #specs: %d\n", inst(i).numSpecifics );
3104 printf ( " impls: "); print100( inst(i).implements );
3105 printf ( " builder: %s\n", maybeNameStr( inst(i).builder ) );
3110 /* --------------------------------------------------------------------------
3112 * ------------------------------------------------------------------------*/
3119 case POSTPREL: break;
3121 case RESET : clearStack();
3123 /* the next 2 statements are particularly important
3124 * if you are using GLOBALfst or GLOBALsnd since the
3125 * corresponding registers may be reset to their
3126 * uninitialised initial values by a longjump.
3128 heapTopFst = heapFst + heapSize;
3129 heapTopSnd = heapSnd + heapSize;
3133 if (isNull(lastExprSaved))
3134 savedText = TEXT_SIZE;
3139 for (i = NAME_BASE_ADDR;
3140 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3141 if (tabName[i-NAME_BASE_ADDR].inUse) {
3142 mark(name(i).parent);
3144 mark(name(i).stgVar);
3148 end("Names", nameHw-NAMEMIN);
3151 for (i = MODULE_BASE_ADDR;
3152 i < MODULE_BASE_ADDR+tabModuleSz; ++i) {
3153 if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3154 mark(module(i).tycons);
3155 mark(module(i).names);
3156 mark(module(i).classes);
3157 mark(module(i).exports);
3158 mark(module(i).qualImports);
3159 mark(module(i).objectExtraNames);
3164 mark(targetModules);
3165 end("Modules", moduleHw-MODMIN);
3168 for (i = TYCON_BASE_ADDR;
3169 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3170 if (tabTycon[i-TYCON_BASE_ADDR].inUse) {
3171 mark(tycon(i).defn);
3172 mark(tycon(i).kind);
3173 mark(tycon(i).what);
3176 end("Type constructors", tyconHw-TYCMIN);
3179 for (i = CCLASS_BASE_ADDR;
3180 i < CCLASS_BASE_ADDR+tabClassSz; ++i) {
3181 if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3182 mark(cclass(i).head);
3183 mark(cclass(i).kinds);
3184 mark(cclass(i).fds);
3185 mark(cclass(i).xfds);
3186 mark(cclass(i).dsels);
3187 mark(cclass(i).supers);
3188 mark(cclass(i).members);
3189 mark(cclass(i).defaults);
3190 mark(cclass(i).instances);
3194 end("Classes", classHw-CLASSMIN);
3197 for (i = INST_BASE_ADDR;
3198 i < INST_BASE_ADDR+tabInstSz; ++i) {
3199 if (tabInst[i-INST_BASE_ADDR].inUse) {
3201 mark(inst(i).kinds);
3202 mark(inst(i).specifics);
3203 mark(inst(i).implements);
3206 end("Instances", instHw-INSTMIN);
3209 for (i=0; i<=sp; ++i)
3214 mark(lastExprSaved);
3217 end("Last expression", 3);
3222 end("C stack", stackRoots);
3227 case PREPREL : heapFst = heapAlloc(heapSize);
3228 heapSnd = heapAlloc(heapSize);
3230 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3231 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3236 heapTopFst = heapFst + heapSize;
3237 heapTopSnd = heapSnd + heapSize;
3238 for (i=1; i<heapSize; ++i) {
3242 snd(-heapSize) = NIL;
3249 marksSize = bitArraySize(heapSize);
3250 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3251 ERRMSG(0) "Unable to allocate gc markspace"
3258 nextNewText = INVAR_BASE_ADDR;
3259 nextNewDText = INDVAR_BASE_ADDR;
3260 lastExprSaved = NIL;
3261 savedText = TEXT_SIZE;
3263 for (i=0; i<TEXTHSZ; ++i) textHash[i][0] = NOTEXT;
3264 for (i=0; i<TYCONHSZ; ++i) tyconHash[RC_T(i)] = NIL;
3265 for (i=0; i<NAMEHSZ; ++i) nameHash[RC_N(i)] = NIL;
3271 /*-------------------------------------------------------------------------*/