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/04/04 11:24:48 $
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 textToStr(textOf(v));
110 case QUALIDENT : { String qmod = textToStr(qmodOf(v));
111 String qtext = textToStr(qtextOf(v));
114 while (pos+1 < savedText && *qmod!=0) {
115 text[pos++] = *qmod++;
117 if (pos+1 < savedText) {
120 while (pos+1 < savedText && *qtext!=0) {
121 text[pos++] = *qtext++;
127 internal("identToStr2");
128 return 0; /* NOTREACHED */
131 Text inventText() { /* return new unused variable name */
132 if (nextNewText >= INVAR_BASE_ADDR+INVAR_MAX_AVAIL)
133 internal("inventText: too many invented variables");
134 return nextNewText++;
137 Text inventDictText() { /* return new unused dictvar name */
138 if (nextNewDText >= INDVAR_BASE_ADDR+INDVAR_MAX_AVAIL)
139 internal("inventDictText: too many invented variables");
140 return nextNewDText++;
143 Bool inventedText(t) /* Signal TRUE if text has been */
144 Text t; { /* generated internally */
145 return isInventedVar(t) || isInventedDictVar(t);
148 #define MAX_FIXLIT 100
149 Text fixLitText(t) /* fix literal text that might include \ */
151 String s = textToStr(t);
154 for(i = 0;i < MAX_FIXLIT-2 && *s;s++) {
160 if (i < MAX_FIXLIT-2) {
163 ERRMSG(0) "storage space exhausted for internal literal string"
166 return (findText(p));
170 static Int local hash(s) /* Simple hash function on strings */
174 for (v=((int)(*s))*8; *s; s++)
175 v += ((int)(*s))*(j++);
181 Text findText(s) /* Locate string in Text array */
185 Text textPos = textHash[h][hashno];
187 # define TryMatch { Text originalTextPos = textPos; \
189 for (t=s; *t==text[textPos]; textPos++,t++) \
191 return originalTextPos+TEXT_BASE_ADDR; \
193 # define Skip while (text[textPos++]) ;
195 while (textPos!=NOTEXT) {
197 if (++hashno<NUM_TEXTH) /* look in next hashtable entry */
198 textPos = textHash[h][hashno];
201 while (textPos < textHw) {
212 textPos = textHw; /* if not found, save in array */
213 if (textHw + (Int)strlen(s) + 1 > savedText) {
214 ERRMSG(0) "Character string storage space exhausted"
217 while ((text[textHw++] = *s++) != 0) {
219 if (hashno<NUM_TEXTH) { /* updating hash table as necessary */
220 textHash[h][hashno] = textPos;
221 if (hashno<NUM_TEXTH-1)
222 textHash[h][hashno+1] = NOTEXT;
225 return textPos+TEXT_BASE_ADDR;
228 static Int local saveText(t) /* Save text value in buffer */
229 Text t; { /* at top of text table */
230 String s = textToStr(t);
232 if (textHw + l + 1 > savedText) {
233 ERRMSG(0) "Character string storage space exhausted"
237 strcpy(text+savedText,s);
242 static int fromHexDigit ( char c )
245 case '0': case '1': case '2': case '3': case '4':
246 case '5': case '6': case '7': case '8': case '9':
248 case 'a': case 'A': return 10;
249 case 'b': case 'B': return 11;
250 case 'c': case 'C': return 12;
251 case 'd': case 'D': return 13;
252 case 'e': case 'E': return 14;
253 case 'f': case 'F': return 15;
259 /* returns findText (unZencode s) */
260 Text unZcodeThenFindText ( String s )
267 nn = 100 + 10 * strlen(s);
269 if (!p) internal ("unZcodeThenFindText: malloc failed");
274 if (n > nn-90) internal ("unZcodeThenFindText: result is too big");
275 if (*s != 'z' && *s != 'Z') {
280 if (!(*s)) goto parse_error;
282 case 'Z': p[n++] = 'Z'; break;
283 case 'C': p[n++] = ':'; break;
284 case 'L': p[n++] = '('; break;
285 case 'R': p[n++] = ')'; break;
286 case 'M': p[n++] = '['; break;
287 case 'N': p[n++] = ']'; break;
288 case 'z': p[n++] = 'z'; break;
289 case 'a': p[n++] = '&'; break;
290 case 'b': p[n++] = '|'; break;
291 case 'd': p[n++] = '$'; break;
292 case 'e': p[n++] = '='; break;
293 case 'g': p[n++] = '>'; break;
294 case 'h': p[n++] = '#'; break;
295 case 'i': p[n++] = '.'; break;
296 case 'l': p[n++] = '<'; break;
297 case 'm': p[n++] = '-'; break;
298 case 'n': p[n++] = '!'; break;
299 case 'p': p[n++] = '+'; break;
300 case 'q': p[n++] = '\\'; break;
301 case 'r': p[n++] = '\''; break;
302 case 's': p[n++] = '/'; break;
303 case 't': p[n++] = '*'; break;
304 case 'u': p[n++] = '^'; break;
305 case 'v': p[n++] = '%'; break;
307 if (!s[0] || !s[1]) goto parse_error;
308 if (fromHexDigit(s[0]) < 0 || fromHexDigit(s[1]) < 0) goto parse_error;
309 p[n++] = 16 * fromHexDigit(s[0]) + fromHexDigit(s[1]);
312 case '0': case '1': case '2': case '3': case '4':
313 case '5': case '6': case '7': case '8': case '9':
316 while (*s && isdigit((int)(*s))) {
317 i = 10 * i + (*s - '0');
320 if (*s != 'T') goto parse_error;
323 while (i > 0) { p[n++] = ','; i--; };
337 fprintf ( stderr, "\nstring = `%s'\n", s );
338 internal ( "unZcodeThenFindText: parse error on above string");
339 return NIL; /*notreached*/
343 Text enZcodeThenFindText ( String s )
348 char toHex[16] = "0123456789ABCDEF";
351 nn = 100 + 10 * strlen(s);
353 if (!p) internal ("enZcodeThenFindText: malloc failed");
357 if (n > nn-90) internal ("enZcodeThenFindText: result is too big");
360 && (isalnum((int)(*s)) || *s == '_')) {
368 while (*s && *s==',') { s++; tup++; };
369 if (*s != ')') internal("enZcodeThenFindText: invalid tuple type");
372 sprintf(num,"%d",tup);
373 p[n] = 0; strcat ( &(p[n]), num ); n += strlen(num);
378 case '(': p[n++] = 'Z'; p[n++] = 'L'; break;
379 case ')': p[n++] = 'Z'; p[n++] = 'R'; break;
380 case '[': p[n++] = 'Z'; p[n++] = 'M'; break;
381 case ']': p[n++] = 'Z'; p[n++] = 'N'; break;
382 case ':': p[n++] = 'Z'; p[n++] = 'C'; break;
383 case 'Z': p[n++] = 'Z'; p[n++] = 'Z'; break;
384 case 'z': p[n++] = 'z'; p[n++] = 'z'; break;
385 case '&': p[n++] = 'z'; p[n++] = 'a'; break;
386 case '|': p[n++] = 'z'; p[n++] = 'b'; break;
387 case '$': p[n++] = 'z'; p[n++] = 'd'; break;
388 case '=': p[n++] = 'z'; p[n++] = 'e'; break;
389 case '>': p[n++] = 'z'; p[n++] = 'g'; break;
390 case '#': p[n++] = 'z'; p[n++] = 'h'; break;
391 case '.': p[n++] = 'z'; p[n++] = 'i'; break;
392 case '<': p[n++] = 'z'; p[n++] = 'l'; break;
393 case '-': p[n++] = 'z'; p[n++] = 'm'; break;
394 case '!': p[n++] = 'z'; p[n++] = 'n'; break;
395 case '+': p[n++] = 'z'; p[n++] = 'p'; break;
396 case '\'': p[n++] = 'z'; p[n++] = 'q'; break;
397 case '\\': p[n++] = 'z'; p[n++] = 'r'; break;
398 case '/': p[n++] = 'z'; p[n++] = 's'; break;
399 case '*': p[n++] = 'z'; p[n++] = 't'; break;
400 case '^': p[n++] = 'z'; p[n++] = 'u'; break;
401 case '%': p[n++] = 'z'; p[n++] = 'v'; break;
402 default: s--; p[n++] = 'z'; p[n++] = 'x';
403 p[n++] = toHex[(int)(*s)/16];
404 p[n++] = toHex[(int)(*s)%16];
415 Text textOf ( Cell c )
429 fprintf(stderr, "\ntextOf: bad tag %d\n",wot );
430 internal("textOf: bad tag");
435 /* --------------------------------------------------------------------------
438 * Currently, the only attributes that we store for each Ext value is the
439 * corresponding Text label. At some later stage, we may decide to cache
440 * types, predicates, etc. here as a space saving gesture. Given that Text
441 * comparison is cheap, and that this is an experimental implementation, we
442 * will use a straightforward linear search to locate Ext values from their
443 * corresponding Text labels; a hashing scheme can be introduced later if
444 * this turns out to be a problem.
445 * ------------------------------------------------------------------------*/
448 Text DEFTABLE(tabExt,NUM_EXT); /* Storage for Ext names */
451 Ext mkExt(t) /* Allocate or find an Ext value */
457 if (extHw-EXTMIN >= NUM_EXT) {
458 ERRMSG(0) "Ext storage space exhausted"
467 /* --------------------------------------------------------------------------
468 * Expandable symbol tables. A template, which is instantiated for the name,
469 * tycon, class, instance and module tables. Also, potentially, TREX Exts.
470 * ------------------------------------------------------------------------*/
472 #define EXPANDABLE_SYMBOL_TABLE(type_name,struct_name, \
473 proc_name,free_proc_name, \
474 free_list,tab_name,tab_size,err_msg, \
475 TAB_INIT_SIZE,TAB_MAX_SIZE, \
478 struct struct_name* tab_name = NULL; \
480 static type_name free_list = TAB_BASE_ADDR-1; \
482 void free_proc_name ( type_name n ) \
484 assert(TAB_BASE_ADDR <= n); \
485 assert(n < TAB_BASE_ADDR+tab_size); \
486 assert(tab_name[n-TAB_BASE_ADDR].inUse); \
487 tab_name[n-TAB_BASE_ADDR].inUse = FALSE; \
488 /*tab_name[n-TAB_BASE_ADDR].nextFree = free_list; */ \
492 type_name proc_name ( void ) \
496 struct struct_name* newTab; \
497 struct struct_name* temp; \
499 if (free_list != TAB_BASE_ADDR-1) { \
500 type_name t = free_list; \
501 free_list = tab_name[free_list-TAB_BASE_ADDR].nextFree; \
502 assert (!(tab_name[t-TAB_BASE_ADDR].inUse)); \
503 tab_name[t-TAB_BASE_ADDR].inUse = TRUE; \
507 newSz = (tab_size == 0 ? TAB_INIT_SIZE : 2 * tab_size); \
508 if (newSz > TAB_MAX_SIZE) goto cant_allocate; \
509 newTab = malloc(newSz * sizeof(struct struct_name)); \
510 if (!newTab) goto cant_allocate; \
511 for (i = 0; i < tab_size; i++) \
512 newTab[i] = tab_name[i]; \
513 for (i = tab_size; i < newSz; i++) { \
514 newTab[i].inUse = FALSE; \
515 newTab[i].nextFree = i-1+TAB_BASE_ADDR; \
517 /* fprintf(stderr, "Expanding " #type_name \
518 "table to size %d\n", newSz );*/ \
519 newTab[tab_size].nextFree = TAB_BASE_ADDR-1; \
520 free_list = newSz-1+TAB_BASE_ADDR; \
524 if (temp) free(temp); \
534 EXPANDABLE_SYMBOL_TABLE(Name,strName,allocNewName,freeName,
535 nameFL,tabName,tabNameSz,
536 "Name storage space exhausted",
537 NAME_INIT_SIZE,NAME_MAX_SIZE,NAME_BASE_ADDR)
540 EXPANDABLE_SYMBOL_TABLE(Tycon,strTycon,allocNewTycon,freeTycon,
541 tyconFL,tabTycon,tabTyconSz,
542 "Type constructor storage space exhausted",
543 TYCON_INIT_SIZE,TYCON_MAX_SIZE,TYCON_BASE_ADDR)
546 EXPANDABLE_SYMBOL_TABLE(Class,strClass,allocNewClass,freeClass,
547 classFL,tabClass,tabClassSz,
548 "Class storage space exhausted",
549 CCLASS_INIT_SIZE,CCLASS_MAX_SIZE,CCLASS_BASE_ADDR)
552 EXPANDABLE_SYMBOL_TABLE(Inst,strInst,allocNewInst,freeInst,
553 instFL,tabInst,tabInstSz,
554 "Instance storage space exhausted",
555 INST_INIT_SIZE,INST_MAX_SIZE,INST_BASE_ADDR)
558 EXPANDABLE_SYMBOL_TABLE(Module,strModule,allocNewModule,freeModule,
559 moduleFL,tabModule,tabModuleSz,
560 "Module storage space exhausted",
561 MODULE_INIT_SIZE,MODULE_MAX_SIZE,MODULE_BASE_ADDR)
564 struct strName* generate_name_ref ( Cell nm )
567 nm -= NAME_BASE_ADDR;
568 assert(tabName[nm].inUse);
569 assert(isModule(tabName[nm].mod));
570 return & tabName[nm];
572 struct strTycon* generate_tycon_ref ( Cell tc )
574 assert(isTycon(tc) || isTuple(tc));
575 tc -= TYCON_BASE_ADDR;
576 assert(tabTycon[tc].inUse);
577 assert(isModule(tabTycon[tc].mod));
578 return & tabTycon[tc];
580 struct strClass* generate_cclass_ref ( Cell cl )
583 cl -= CCLASS_BASE_ADDR;
584 assert(tabClass[cl].inUse);
585 assert(isModule(tabClass[cl].mod));
586 return & tabClass[cl];
588 struct strInst* generate_inst_ref ( Cell in )
591 in -= INST_BASE_ADDR;
592 assert(tabInst[in].inUse);
593 assert(isModule(tabInst[in].mod));
594 return & tabInst[in];
596 struct strModule* generate_module_ref ( Cell mo )
598 assert(isModule(mo));
599 mo -= MODULE_BASE_ADDR;
600 assert(tabModule[mo].inUse);
601 return & tabModule[mo];
606 /* --------------------------------------------------------------------------
609 * A Tycon represents a user defined type constructor. Tycons are indexed
610 * by Text values ... a very simple hash function is used to improve lookup
611 * times. Tycon entries with the same hash code are chained together, with
612 * the most recent entry at the front of the list.
613 * ------------------------------------------------------------------------*/
615 #define TYCONHSZ 256 /* Size of Tycon hash table*/
616 //#define tHash(x) (((x)-TEXT_BASE_ADDR)%TYCONHSZ)/* Tycon hash function */
617 static int tHash(Text x)
620 assert(isText(x) || inventedText(x));
628 static Tycon tyconHash[TYCONHSZ]; /* Hash table storage */
631 assert (x >= 0 && x < TYCONHSZ);
634 Tycon newTycon ( Text t ) /* add new tycon to tycon table */
637 Tycon tc = allocNewTycon();
639 [tc-TYCON_BASE_ADDR].tuple = -1;
641 [tc-TYCON_BASE_ADDR].mod = currentModule;
642 tycon(tc).text = t; /* clear new tycon record */
643 tycon(tc).kind = NIL;
644 tycon(tc).defn = NIL;
645 tycon(tc).what = NIL;
646 tycon(tc).conToTag = NIL;
647 tycon(tc).tagToCon = NIL;
648 tycon(tc).itbl = NULL;
650 module(currentModule).tycons = cons(tc,module(currentModule).tycons);
651 tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
652 tyconHash[RC_T(h)] = tc;
656 Tycon findTycon(t) /* locate Tycon in tycon table */
658 Tycon tc = tyconHash[RC_T(tHash(t))];
659 assert(isTycon(tc) || isTuple(tc) || isNull(tc));
660 while (nonNull(tc) && tycon(tc).text!=t)
661 tc = tycon(tc).nextTyconHash;
665 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
668 assert(isTycon(tc) || isTuple(tc));
669 oldtc = findTycon(tycon(tc).text);
672 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
678 static Void local hashTycon(tc) /* Insert Tycon into hash table */
682 assert(isTycon(tc) || isTuple(tc));
683 {int i; for (i = 0; i < TYCONHSZ; i++)
684 assert (tyconHash[i] == 0
685 || isTycon(tyconHash[i])
686 || isTuple(tyconHash[i]));
690 tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
691 tyconHash[RC_T(h)] = tc;
694 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
696 if (!isPair(id)) internal("findQualTycon");
700 return findTycon(textOf(id));
702 Text t = qtextOf(id);
703 Module m = findQualifier(qmodOf(id));
705 if (isNull(m)) return NIL;
706 for(es=module(m).exports; nonNull(es); es=tl(es)) {
708 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
713 default : internal("findQualTycon2");
715 return NIL; /* NOTREACHED */
718 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
724 Tycon tc = newTycon(t);
726 tycon(tc).kind = kind;
727 tycon(tc).what = what;
728 tycon(tc).defn = defn;
729 tycon(tc).arity = ar;
733 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
738 String s = textToStr(tycon(tc).text);
740 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
741 if (hd(curr)==tc) /* just in case we get duplicates! */
747 tl(prev) = cons(tc,curr);
751 return cons(tc,curr);
754 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
755 String pat; /* to list of Tycons ts */
756 List ts; { /* Null pattern matches every tycon*/
757 Tycon tc; /* (Tycons with NIL kind excluded) */
758 for (tc = TYCON_BASE_ADDR;
759 tc < TYCON_BASE_ADDR+tabTyconSz; ++tc)
760 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
761 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
762 if (nonNull(tycon(tc).kind))
763 ts = insertTycon(tc,ts);
767 Text ghcTupleText_n ( Int n )
772 if (n < 0 || n >= 100) internal("ghcTupleText_n");
773 if (n == 1) internal("ghcTupleText_n==1");
775 for (i = 1; i <= n-1; i++) buf[x++] = ',';
778 return findText(buf);
781 Text ghcTupleText(tup)
784 assert(isTuple(tup));
786 return ghcTupleText_n ( tupleOf(tup) );
790 Tycon mkTuple ( Int n )
794 internal("mkTuple: request for tuple of unsupported size");
795 for (i = TYCON_BASE_ADDR;
796 i < TYCON_BASE_ADDR+tabTyconSz; i++)
797 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
798 if (tycon(i).tuple == n) return i;
799 internal("mkTuple: request for non-existent tuple");
803 /* --------------------------------------------------------------------------
806 * A Name represents a top level binding of a value to an identifier.
807 * Such values may be a constructor function, a member function in a
808 * class, a user-defined or primitive value/function.
810 * Names are indexed by Text values ... a very simple hash functions speeds
811 * access to the table of Names and Name entries with the same hash value
812 * are chained together, with the most recent entry at the front of the
814 * ------------------------------------------------------------------------*/
816 #define NAMEHSZ 256 /* Size of Name hash table */
817 //#define nHash(x) (((x)-TEXT_BASE_ADDR)%NAMEHSZ) /* hash fn :: Text->Int */
818 static int nHash(Text x)
820 assert(isText(x) || inventedText(x));
825 static Name nameHash[NAMEHSZ]; /* Hash table storage */
828 assert (x >= 0 && x < NAMEHSZ);
831 void hashSanity ( void )
834 for (i = 0; i < TYCONHSZ; i++) {
837 assert(isTycon(j) || isTuple(j));
838 j = tycon(j).nextTyconHash;
841 for (i = 0; i < NAMEHSZ; i++) {
845 j = name(j).nextNameHash;
850 Name newName ( Text t, Cell parent ) /* Add new name to name table */
853 Name nm = allocNewName();
855 [nm-NAME_BASE_ADDR].mod = currentModule;
856 name(nm).text = t; /* clear new name record */
858 name(nm).syntax = NO_SYNTAX;
859 name(nm).parent = parent;
861 name(nm).number = EXECNAME;
863 name(nm).stgVar = NIL;
864 name(nm).callconv = NIL;
866 name(nm).primop = NULL;
867 name(nm).itbl = NULL;
868 module(currentModule).names = cons(nm,module(currentModule).names);
869 name(nm).nextNameHash = nameHash[RC_N(h)];
870 nameHash[RC_N(h)] = nm;
874 Name findName(t) /* Locate name in name table */
876 Name n = nameHash[RC_N(nHash(t))];
878 assert(isName(n) || isNull(n));
879 while (nonNull(n) && name(n).text!=t)
880 n = name(n).nextNameHash;
884 Name addName(nm) /* Insert Name in name table - if */
885 Name nm; { /* no clash is caused */
888 oldnm = findName(name(nm).text);
891 module(currentModule).names=cons(nm,module(currentModule).names);
897 static Void local hashName(nm) /* Insert Name into hash table */
904 name(nm).nextNameHash = nameHash[RC_N(h)];
905 nameHash[RC_N(h)] = nm;
908 Name findQualName(id) /* Locate (possibly qualified) name*/
909 Cell id; { /* in name table */
911 internal("findQualName");
917 return findName(textOf(id));
919 Text t = qtextOf(id);
920 Module m = findQualifier(qmodOf(id));
922 if (isNull(m)) return NIL;
923 for(es=module(m).exports; nonNull(es); es=tl(es)) {
925 if (isName(e) && name(e).text==t)
927 else if (isPair(e) && DOTDOT==snd(e)) {
928 List subentities = NIL;
931 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
932 subentities = tycon(c).defn;
934 subentities = cclass(c).members;
935 for(; nonNull(subentities); subentities=tl(subentities)) {
936 if (!isName(hd(subentities)))
937 internal("findQualName3");
938 if (name(hd(subentities)).text == t)
939 return hd(subentities);
945 default : internal("findQualName2");
947 return 0; /* NOTREACHED */
951 Name nameFromStgVar ( StgVar v )
954 for (n = NAME_BASE_ADDR;
955 n < NAME_BASE_ADDR+tabNameSz; n++)
956 if (tabName[n-NAME_BASE_ADDR].inUse)
957 if (name(n).stgVar == v) return n;
961 void* getHugs_AsmObject_for ( char* s )
964 Text t = findText(s);
966 for (n = NAME_BASE_ADDR;
967 n < NAME_BASE_ADDR+tabNameSz; n++)
968 if (tabName[n-NAME_BASE_ADDR].inUse)
969 if (name(n).text == t) break;
970 if (n == NAME_BASE_ADDR+tabNameSz) {
971 fprintf ( stderr, "can't find `%s' in ...\n", s );
972 internal("getHugs_AsmObject_for(1)");
975 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
976 internal("getHugs_AsmObject_for(2)");
977 return ptrOf(stgVarInfo(v));
980 /* --------------------------------------------------------------------------
981 * Primitive functions:
982 * ------------------------------------------------------------------------*/
984 Module findFakeModule ( Text t )
986 Module m = findModule(t);
988 if (!module(m).fake) internal("findFakeModule");
991 module(m).fake = TRUE;
997 Name addWiredInBoxingTycon
998 ( String modNm, String typeNm, String constrNm,
1003 Text modT = findText(modNm);
1004 Text typeT = findText(typeNm);
1005 Text conT = findText(constrNm);
1006 Module m = findFakeModule(modT);
1009 n = newName(conT,NIL);
1011 name(n).number = cfunNo(0);
1013 name(n).primop = (void*)rep;
1015 t = newTycon(typeT);
1016 tycon(t).what = DATATYPE;
1017 tycon(t).kind = kind;
1022 Tycon addTupleTycon ( Int n )
1030 for (i = TYCON_BASE_ADDR;
1031 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1032 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
1033 if (tycon(i).tuple == n) return i;
1036 m = findFakeModule(findText(n==0 ? "PrelBase" : "PrelTup")); else
1037 m = findModule(findText("PrimPrel"));
1041 for (i = 0; i < n; i++) k = ap(STAR,k);
1042 t = newTycon(ghcTupleText_n(n));
1045 tycon(t).what = DATATYPE;
1048 /* maybe we want to do this for all n ? */
1049 nm = newName(ghcTupleText_n(n), t);
1050 name(nm).type = t; /* ummm ... for n > 0 */
1057 Tycon addWiredInEnumTycon ( String modNm, String typeNm,
1058 List /*of Text*/ constrs )
1062 Text modT = findText(modNm);
1063 Text typeT = findText(typeNm);
1064 Module m = findFakeModule(modT);
1067 t = newTycon(typeT);
1068 tycon(t).kind = STAR;
1069 tycon(t).what = DATATYPE;
1071 constrs = reverse(constrs);
1072 i = length(constrs);
1073 for (; nonNull(constrs); constrs=tl(constrs),i--) {
1074 Text conT = hd(constrs);
1075 Name con = newName(conT,t);
1076 name(con).number = cfunNo(i);
1078 name(con).parent = t;
1079 tycon(t).defn = cons(con, tycon(t).defn);
1085 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
1086 Text t; /* sets rep, not type */
1089 Int rep; { /* Really AsmRep */
1090 Name n = newName(t,NIL);
1091 name(n).arity = arity;
1092 name(n).number = cfunNo(no);
1094 name(n).primop = (void*)rep;
1099 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
1104 Name n = newName(t,NIL);
1105 name(n).arity = arity;
1106 name(n).number = cfunNo(no);
1107 name(n).type = type;
1112 Int sfunPos(s,c) /* Find position of field with */
1113 Name s; /* selector s in constructor c. */
1117 for (; nonNull(cns); cns=tl(cns))
1118 if (fst(hd(cns))==c)
1119 return intOf(snd(hd(cns)));
1120 internal("sfunPos");
1121 return 0;/* NOTREACHED */
1124 static List local insertName(nm,ns) /* insert name nm into sorted list */
1129 String s = textToStr(name(nm).text);
1131 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
1132 if (hd(curr)==nm) /* just in case we get duplicates! */
1137 if (nonNull(prev)) {
1138 tl(prev) = cons(nm,curr);
1142 return cons(nm,curr);
1145 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
1146 String pat; /* to list of names ns */
1147 List ns; { /* Null pattern matches every name */
1148 Name nm; /* (Names with NIL type, or hidden */
1149 /* or invented names are excluded) */
1151 for (nm = NAME_BASE_ADDR;
1152 nm < NAME_BASE_ADDR+tabNameSz; ++nm)
1153 if (tabName[nm-NAME_BASE_ADDR].inUse) {
1154 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
1155 String str = textToStr(name(nm).text);
1156 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1157 ns = insertName(nm,ns);
1162 List mns = module(currentModule).names;
1163 for(; nonNull(mns); mns=tl(mns)) {
1165 if (!inventedText(name(nm).text)) {
1166 String str = textToStr(name(nm).text);
1167 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1168 ns = insertName(nm,ns);
1175 /* --------------------------------------------------------------------------
1176 * A simple string matching routine
1177 * `*' matches any sequence of zero or more characters
1178 * `?' matches any single character exactly
1179 * `@str' matches the string str exactly (ignoring any special chars)
1180 * `\c' matches the character c only (ignoring special chars)
1181 * c matches the character c only
1182 * ------------------------------------------------------------------------*/
1184 static Void local patternError(s) /* report error in pattern */
1186 ERRMSG(0) "%s in pattern", s
1190 static Bool local stringMatch(pat,str) /* match string against pattern */
1196 case '\0' : return (*str=='\0');
1199 if (stringMatch(pat+1,str))
1204 case '?' : if (*str++=='\0')
1209 case '[' : { Bool found = FALSE;
1210 while (*++pat!='\0' && *pat!=']')
1211 if (!found && ( pat[0] == *str ||
1220 patternError("missing `]'");
1228 case '\\' : if (*++pat == '\0')
1229 patternError("extra trailing `\\'");
1231 default : if (*pat++ != *str++)
1237 /* --------------------------------------------------------------------------
1238 * Storage of type classes, instances etc...:
1239 * ------------------------------------------------------------------------*/
1241 static List classes; /* list of classes in current scope */
1243 Class newClass ( Text t ) /* add new class to class table */
1245 Class cl = allocNewClass();
1247 [cl-CCLASS_BASE_ADDR].mod = currentModule;
1248 cclass(cl).text = t;
1249 cclass(cl).arity = 0;
1250 cclass(cl).kinds = NIL;
1251 cclass(cl).head = NIL;
1252 cclass(cl).fds = NIL;
1253 cclass(cl).xfds = NIL;
1254 cclass(cl).dcon = NIL;
1255 cclass(cl).supers = NIL;
1256 cclass(cl).dsels = NIL;
1257 cclass(cl).members = NIL;
1258 cclass(cl).defaults = NIL;
1259 cclass(cl).instances = NIL;
1260 classes = cons(cl,classes);
1261 module(currentModule).classes
1262 = cons(cl,module(currentModule).classes);
1266 Class findClass(t) /* look for named class in table */
1270 for (cs=classes; nonNull(cs); cs=tl(cs)) {
1272 if (cclass(cl).text==t)
1278 Class addClass(c) /* Insert Class in class list */
1279 Class c; { /* - if no clash caused */
1281 assert(whatIs(c)==CLASS);
1282 oldc = findClass(cclass(c).text);
1284 classes=cons(c,classes);
1285 module(currentModule).classes=cons(c,module(currentModule).classes);
1292 Class findQualClass(c) /* Look for (possibly qualified) */
1293 Cell c; { /* class in class list */
1294 if (!isQualIdent(c)) {
1295 return findClass(textOf(c));
1297 Text t = qtextOf(c);
1298 Module m = findQualifier(qmodOf(c));
1302 for (es=module(m).exports; nonNull(es); es=tl(es)) {
1304 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
1311 Inst newInst() { /* Add new instance to table */
1312 Inst in = allocNewInst();
1314 [in-INST_BASE_ADDR].mod = currentModule;
1315 inst(in).kinds = NIL;
1316 inst(in).head = NIL;
1317 inst(in).specifics = NIL;
1318 inst(in).implements = NIL;
1319 inst(in).builder = NIL;
1324 extern Void printInst ( Inst));
1328 Class cl = inst(in).c;
1329 Printf("%s-", textToStr(cclass(cl).text));
1330 printType(stdout,inst(in).t);
1332 #endif /* DEBUG_DICTS */
1334 Inst findFirstInst(tc) /* look for 1st instance involving */
1335 Tycon tc; { /* the type constructor tc */
1336 return findNextInst(tc,INST_BASE_ADDR-1);
1339 Inst findNextInst(tc,in) /* look for next instance involving*/
1340 Tycon tc; /* the type constructor tc */
1341 Inst in; { /* starting after instance in */
1343 while (++in < INST_BASE_ADDR+tabInstSz) {
1344 if (!tabInst[in-INST_BASE_ADDR].inUse) continue;
1345 assert(isModule(inst(in).mod));
1347 for (; isAp(pi); pi=fun(pi))
1348 if (typeInvolves(arg(pi),tc))
1354 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1355 Type ty; /* type constructor/tuple tc. */
1358 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1359 || typeInvolves(arg(ty),tc)));
1363 /* Needed by finishGHCInstance to find classes, before the
1364 export list has been built -- so we can't use
1367 Class findQualClassWithoutConsultingExportList ( QualId q )
1377 t_class = textOf(q);
1380 t_class = qtextOf(q);
1383 for (cl = CCLASS_BASE_ADDR;
1384 cl < CCLASS_BASE_ADDR+tabClassSz; cl++) {
1385 if (tabClass[cl-CCLASS_BASE_ADDR].inUse)
1386 if (cclass(cl).text == t_class) {
1387 /* Class name is ok, but is this the right module? */
1388 if (isNull(t_mod) /* no module name specified */
1390 && t_mod == module(cclass(cl).mod).text)
1398 /* Same deal, except for Tycons. */
1399 Tycon findQualTyconWithoutConsultingExportList ( QualId q )
1409 t_tycon = textOf(q);
1412 t_tycon = qtextOf(q);
1415 for (tc = TYCON_BASE_ADDR;
1416 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1417 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1418 if (tycon(tc).text == t_tycon) {
1419 /* Tycon name is ok, but is this the right module? */
1420 if (isNull(t_mod) /* no module name specified */
1422 && t_mod == module(tycon(tc).mod).text)
1430 /* Same deal, except for Names. */
1431 Name findQualNameWithoutConsultingExportList ( QualId q )
1437 assert(isQVar(q) || isQCon(q));
1439 if (isCon(q) || isVar(q)) {
1444 t_name = qtextOf(q);
1447 for (nm = NAME_BASE_ADDR;
1448 nm < NAME_BASE_ADDR+tabNameSz; nm++) {
1449 if (tabName[nm-NAME_BASE_ADDR].inUse)
1450 if (name(nm).text == t_name) {
1451 /* Name is ok, but is this the right module? */
1452 if (isNull(t_mod) /* no module name specified */
1454 && t_mod == module(name(nm).mod).text)
1463 Tycon findTyconInAnyModule ( Text t )
1466 for (tc = TYCON_BASE_ADDR;
1467 tc < TYCON_BASE_ADDR+tabTyconSz; tc++)
1468 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1469 if (tycon(tc).text == t) return tc;
1473 Class findClassInAnyModule ( Text t )
1476 for (cc = CCLASS_BASE_ADDR;
1477 cc < CCLASS_BASE_ADDR+tabClassSz; cc++)
1478 if (tabClass[cc-CCLASS_BASE_ADDR].inUse)
1479 if (cclass(cc).text == t) return cc;
1483 Name findNameInAnyModule ( Text t )
1486 for (nm = NAME_BASE_ADDR;
1487 nm < NAME_BASE_ADDR+tabNameSz; nm++)
1488 if (tabName[nm-NAME_BASE_ADDR].inUse)
1489 if (name(nm).text == t) return nm;
1494 /* returns List of QualId */
1495 List getAllKnownTyconsAndClasses ( void )
1500 for (tc = TYCON_BASE_ADDR;
1501 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1502 if (tabTycon[tc-TYCON_BASE_ADDR].inUse) {
1503 /* almost certainly undue paranoia about duplicate avoidance */
1504 QualId q = mkQCon( module(tycon(tc).mod).text, tycon(tc).text );
1505 if (!qualidIsMember(q,xs))
1506 xs = cons ( q, xs );
1509 for (nw = CCLASS_BASE_ADDR;
1510 nw < CCLASS_BASE_ADDR+tabClassSz; nw++) {
1511 if (tabClass[nw-CCLASS_BASE_ADDR].inUse) {
1512 QualId q = mkQCon( module(cclass(nw).mod).text, cclass(nw).text );
1513 if (!qualidIsMember(q,xs))
1514 xs = cons ( q, xs );
1520 /* Purely for debugging. */
1521 void locateSymbolByName ( Text t )
1524 for (i = NAME_BASE_ADDR;
1525 i < NAME_BASE_ADDR+tabNameSz; i++)
1526 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).text == t)
1527 fprintf ( stderr, "name(%d)\n", i-NAME_BASE_ADDR);
1528 for (i = TYCON_BASE_ADDR;
1529 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1530 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).text == t)
1531 fprintf ( stderr, "tycon(%d)\n", i-TYCON_BASE_ADDR);
1532 for (i = CCLASS_BASE_ADDR;
1533 i < CCLASS_BASE_ADDR+tabClassSz; i++)
1534 if (tabClass[i-CCLASS_BASE_ADDR].inUse && cclass(i).text == t)
1535 fprintf ( stderr, "class(%d)\n", i-CCLASS_BASE_ADDR);
1538 /* --------------------------------------------------------------------------
1541 * Various parts of the system use a stack of cells. Most of the stack
1542 * operations are defined as macros, expanded inline.
1543 * ------------------------------------------------------------------------*/
1545 Cell cellStack[NUM_STACK]; /* Storage for cells on stack */
1546 StackPtr sp; /* stack pointer */
1548 Void hugsStackOverflow() { /* Report stack overflow */
1549 ERRMSG(0) "Control stack overflow"
1554 /* --------------------------------------------------------------------------
1557 * A Module represents a user defined module.
1559 * Note: there are now two lookup mechanisms in the system:
1561 * 1) The exports from a module are stored in a big list.
1562 * We resolve qualified names, and import lists by linearly scanning
1563 * through this list.
1565 * 2) Unqualified imports and local definitions for the current module
1566 * are stored in hash tables (tyconHash and nameHash) or linear lists
1569 * ------------------------------------------------------------------------*/
1571 Module currentModule; /* Module currently being processed*/
1573 Bool isValidModule(m) /* is m a legitimate module id? */
1578 Module newModule ( Text t ) /* add new module to module table */
1580 Module mod = allocNewModule();
1581 module(mod).text = t; /* clear new module record */
1583 module(mod).tycons = NIL;
1584 module(mod).names = NIL;
1585 module(mod).classes = NIL;
1586 module(mod).exports = NIL;
1587 module(mod).qualImports = NIL;
1588 module(mod).fake = FALSE;
1590 module(mod).tree = NIL;
1591 module(mod).completed = FALSE;
1592 module(mod).lastStamp = 0; /* ???? */
1594 module(mod).fromSrc = TRUE;
1595 module(mod).srcExt = findText("");
1596 module(mod).uses = NIL;
1598 module(mod).objName = findText("");
1599 module(mod).objSize = 0;
1601 module(mod).object = NULL;
1602 module(mod).objectExtras = NULL;
1603 module(mod).objectExtraNames = NIL;
1607 void nukeModule ( Module m )
1612 assert(isModule(m));
1613 /*fprintf(stderr, "NUKEMODULE `%s'\n", textToStr(module(m).text)); */
1614 oc = module(m).object;
1620 oc = module(m).objectExtras;
1627 for (i = NAME_BASE_ADDR; i < NAME_BASE_ADDR+tabNameSz; i++)
1628 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).mod == m) {
1629 if (name(i).itbl) free(name(i).itbl);
1630 name(i).itbl = NULL;
1634 for (i = TYCON_BASE_ADDR; i < TYCON_BASE_ADDR+tabTyconSz; i++)
1635 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).mod == m) {
1636 if (tycon(i).itbl) free(tycon(i).itbl);
1637 tycon(i).itbl = NULL;
1641 for (i = CCLASS_BASE_ADDR; i < CCLASS_BASE_ADDR+tabClassSz; i++)
1642 if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
1643 if (cclass(i).mod == m) {
1646 List /* Inst */ ins;
1647 List /* Inst */ ins2 = NIL;
1648 for (ins = cclass(i).instances; nonNull(ins); ins=tl(ins))
1649 if (inst(hd(ins)).mod != m)
1650 ins2 = cons(hd(ins),ins2);
1651 cclass(i).instances = ins2;
1656 for (i = INST_BASE_ADDR; i < INST_BASE_ADDR+tabInstSz; i++)
1657 if (tabInst[i-INST_BASE_ADDR].inUse && inst(i).mod == m)
1661 //for (i = 0; i < TYCONHSZ; i++) tyconHash[i] = 0;
1662 //for (i = 0; i < NAMEHSZ; i++) nameHash[i] = 0;
1667 void ppModules ( void )
1670 fflush(stderr); fflush(stdout);
1671 printf ( "begin MODULES\n" );
1672 for (i = MODULE_BASE_ADDR+tabModuleSz-1;
1673 i >= MODULE_BASE_ADDR; i--)
1674 if (tabModule[i-MODULE_BASE_ADDR].inUse)
1675 printf ( " %2d: %16s\n",
1676 i-MODULE_BASE_ADDR, textToStr(module(i).text)
1678 printf ( "end MODULES\n" );
1679 fflush(stderr); fflush(stdout);
1683 Module findModule(t) /* locate Module in module table */
1686 for(m = MODULE_BASE_ADDR;
1687 m < MODULE_BASE_ADDR+tabModuleSz; ++m) {
1688 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1689 if (module(m).text==t)
1695 Module findModid(c) /* Find module by name or filename */
1697 switch (whatIs(c)) {
1698 case STRCELL : internal("findModid-STRCELL unimp");
1699 case CONIDCELL : return findModule(textOf(c));
1700 default : internal("findModid");
1702 return NIL;/*NOTUSED*/
1705 static local Module findQualifier(t) /* locate Module in import list */
1708 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1709 if (textOf(fst(hd(ms)))==t)
1712 if (module(currentModule).text==t)
1713 return currentModule;
1717 Void setCurrModule(m) /* set lookup tables for current module */
1720 assert(isModule(m));
1721 /* fprintf(stderr, "SET CURR MODULE %s %d\n", textToStr(module(m).text),m); */
1723 for (t = module(m).names; nonNull(t); t=tl(t))
1724 assert(isName(hd(t)));
1725 for (t = module(m).tycons; nonNull(t); t=tl(t))
1726 assert(isTycon(hd(t)) || isTuple(hd(t)));
1727 for (t = module(m).classes; nonNull(t); t=tl(t))
1728 assert(isClass(hd(t)));
1731 currentModule = m; /* This is the only assignment to currentModule */
1732 for (i=0; i<TYCONHSZ; ++i)
1733 tyconHash[RC_T(i)] = NIL;
1734 mapProc(hashTycon,module(m).tycons);
1735 for (i=0; i<NAMEHSZ; ++i)
1736 nameHash[RC_N(i)] = NIL;
1737 mapProc(hashName,module(m).names);
1738 classes = module(m).classes;
1742 Name jrsFindQualName ( Text mn, Text sn )
1747 for (m = MODULE_BASE_ADDR;
1748 m < MODULE_BASE_ADDR+tabModuleSz; m++)
1749 if (tabModule[m-MODULE_BASE_ADDR].inUse
1750 && module(m).text == mn) break;
1752 if (m == MODULE_BASE_ADDR+tabModuleSz) return NIL;
1754 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1755 if (name(hd(ns)).text == sn) return hd(ns);
1761 char* nameFromOPtr ( void* p )
1765 for (m = MODULE_BASE_ADDR;
1766 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1767 if (tabModule[m-MODULE_BASE_ADDR].inUse && module(m).object) {
1768 char* nm = ocLookupAddr ( module(m).object, p );
1773 /* A kludge to assist Win32 debugging; not actually necessary. */
1774 { char* nm = nameFromStaticOPtr(p);
1782 void* lookupOTabName ( Module m, char* sym )
1784 assert(isModule(m));
1785 if (module(m).object)
1786 return ocLookupSym ( module(m).object, sym );
1791 void* lookupOExtraTabName ( char* sym )
1795 for (m = MODULE_BASE_ADDR;
1796 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1797 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1798 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1799 void* ad = ocLookupSym ( oc, sym );
1807 OSectionKind lookupSection ( void* ad )
1814 for (m = MODULE_BASE_ADDR;
1815 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1816 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1817 if (module(m).object) {
1818 sect = ocLookupSection ( module(m).object, ad );
1819 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1822 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1823 sect = ocLookupSection ( oc, ad );
1824 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1829 return HUGS_SECTIONKIND_OTHER;
1833 /* --------------------------------------------------------------------------
1836 * Provides a garbage collectable heap for storage of expressions etc.
1838 * Now incorporates a flat resource: A two-space collected extension of
1839 * the heap that provides storage for contiguous arrays of Cell storage,
1840 * cooperating with the garbage collection mechanisms for the main heap.
1841 * ------------------------------------------------------------------------*/
1843 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1844 Heap heapFst; /* array of fst component of pairs */
1845 Heap heapSnd; /* array of snd component of pairs */
1852 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1853 /* C stack; use with extreme care! */
1855 Int numGcs; /* number of garbage collections */
1856 Int cellsRecovered; /* number of cells recovered */
1858 static Cell freeList; /* free list of unused cells */
1859 static Cell lsave, rsave; /* save components of pair */
1863 static Int markCount, stackRoots;
1865 #define initStackRoots() stackRoots = 0
1866 #define recordStackRoot() stackRoots++
1879 #define start() markCount = 0
1880 #define end(thing,rs) \
1882 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1885 #define recordMark() markCount++
1887 #else /* !GC_STATISTICS */
1892 #define initStackRoots()
1893 #define recordStackRoot()
1896 #define end(thing,root)
1897 #define recordMark()
1899 #endif /* !GC_STATISTICS */
1901 Cell pair(l,r) /* Allocate pair (l, r) from */
1902 Cell l, r; { /* heap, garbage collecting first */
1903 Cell c = freeList; /* if necessary ... */
1915 freeList = snd(freeList);
1923 static Int marksSize;
1925 Cell markExpr(c) /* External interface to markCell */
1927 return isGenPair(c) ? markCell(c) : c;
1930 static Cell local markCell(c) /* Traverse part of graph marking */
1931 Cell c; { /* cells reachable from given root */
1932 /* markCell(c) is only called if c */
1934 { register int place = placeInSet(c);
1935 register int mask = maskInSet(c);
1936 if (marks[place]&mask)
1939 marks[place] |= mask;
1944 /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1945 if (isGenPair(fst(c))) {
1947 fst(c) = markCell(fst(c));
1950 else if (isNull(fst(c)) || isTagPtr(fst(c))) {
1958 static Void local markSnd(c) /* Variant of markCell used to */
1959 Cell c; { /* update snd component of cell */
1960 Cell t; /* using tail recursion */
1962 ma: t = c; /* Keep pointer to original pair */
1967 { register int place = placeInSet(c);
1968 register int mask = maskInSet(c);
1969 if (marks[place]&mask)
1972 marks[place] |= mask;
1977 if (isGenPair(fst(c))) {
1978 fst(c) = markCell(fst(c));
1981 else if (isNull(fst(c)) || isTagPtr(fst(c)))
1986 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1987 Cell n; { /* it was a cell ref, but don't */
1988 /* move cell so we don't have */
1989 /* to modify the stored value of n */
1996 Void garbageCollect() { /* Run garbage collector ... */
1997 /* disable break checking */
2002 jmp_buf regs; /* save registers on stack */
2003 HugsBreakAction oldBrk
2004 = setBreakAction ( HugsIgnoreBreak );
2005 fprintf ( stderr, "wa-hey! garbage collection! too difficult! bye!\n" );
2010 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
2013 everybody(MARK); /* Mark all components of system */
2015 gcScanning(); /* scan mark set */
2022 for (i=1; i<=heapSize; i++) {
2023 if ((marks[place] & mask) == 0) {
2030 if (++j == bitsPerWord) {
2037 gcRecovered(recovered);
2038 setBreakAction ( oldBrk );
2042 /* can only return if freeList is nonempty on return. */
2043 if (recovered<minRecovery || isNull(freeList)) {
2044 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
2047 cellsRecovered = recovered;
2050 /* --------------------------------------------------------------------------
2051 * Code for saving last expression entered:
2053 * This is a little tricky because some text values (e.g. strings or variable
2054 * names) may not be defined or have the same value when the expression is
2055 * recalled. These text values are therefore saved in the top portion of
2057 * ------------------------------------------------------------------------*/
2059 static Cell lastExprSaved; /* last expression to be saved */
2061 Void setLastExpr(e) /* save expression for later recall*/
2063 lastExprSaved = NIL; /* in case attempt to save fails */
2064 savedText = TEXT_SIZE;
2065 lastExprSaved = lowLevelLastIn(e);
2068 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
2069 Cell c; { /* acyclic graph) for later recall */
2070 if (isPair(c)) { /* Duplicating any text strings */
2071 if (isTagNonPtr(fst(c))) /* in case these are lost at some */
2072 switch (fst(c)) { /* point before the expr is reused */
2078 case STRCELL : return pair(fst(c),saveText(textOf(c)));
2079 default : return pair(fst(c),snd(c));
2082 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2086 return pair(EXTCOPY,saveText(extText(c)));
2092 Cell getLastExpr() { /* recover previously saved expr */
2093 return lowLevelLastOut(lastExprSaved);
2096 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
2097 Cell c; { /* except that Cells refering to */
2098 if (isPair(c)) { /* Text values are restored to */
2099 if (isTagNonPtr(fst(c))) /* appropriate values */
2106 case STRCELL : return pair(fst(c),
2107 findText(text+intValOf(c)));
2109 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
2111 default : return pair(fst(c),snd(c));
2114 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2120 /* --------------------------------------------------------------------------
2121 * Miscellaneous operations on heap cells:
2122 * ------------------------------------------------------------------------*/
2124 Cell whatIs ( register Cell c )
2127 register Cell fstc = fst(c);
2128 return isTag(fstc) ? fstc : AP;
2130 if (isOffset(c)) return OFFSET;
2131 if (isChar(c)) return CHARCELL;
2132 if (isInt(c)) return INTCELL;
2133 if (isName(c)) return NAME;
2134 if (isTycon(c)) return TYCON;
2135 if (isTuple(c)) return TUPLE;
2136 if (isClass(c)) return CLASS;
2137 if (isInst(c)) return INSTANCE;
2138 if (isModule(c)) return MODULE;
2139 if (isText(c)) return TEXTCELL;
2140 if (isInventedVar(c)) return INVAR;
2141 if (isInventedDictVar(c)) return INDVAR;
2142 if (isSpec(c)) return c;
2143 if (isNull(c)) return c;
2144 fprintf ( stderr, "whatIs: unknown %d\n", c );
2150 Cell whatIs(c) /* identify type of cell */
2153 register Cell fstc = fst(c);
2154 return isTag(fstc) ? fstc : AP;
2156 if (c<OFFMIN) return c;
2158 if (isExt(c)) return EXT;
2160 if (c>=INTMIN) return INTCELL;
2162 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
2164 else if (c>=INSTMIN) return INSTANCE;
2166 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
2167 else return MODULE;}
2168 else if (c>=OFFMIN) return OFFSET;
2170 else return (c>=EXTMIN) ?
2178 register Cell fstc = fst(c);
2179 return isTag(fstc) ? fstc : AP;
2181 if (c>=INTMIN) return INTCELL;
2182 if (c>=CHARMIN) return CHARCELL;
2183 if (c>=CLASSMIN) return CLASS;
2184 if (c>=INSTMIN) return INSTANCE;
2185 if (c>=NAMEMIN) return NAME;
2186 if (c>=TYCMIN) return TYCON;
2187 if (c>=MODMIN) return MODULE;
2188 if (c>=OFFMIN) return OFFSET;
2190 if (c>=EXTMIN) return EXT;
2192 if (c>=TUPMIN) return TUPLE;
2198 /* A very, very simple printer.
2199 * Output is uglier than from printExp - but the printer is more
2200 * robust and can be used on any data structure irrespective of
2203 Void print ( Cell c, Int depth )
2208 else if (isNull(c)) {
2211 else if (isTagPtr(c)) {
2212 Printf("TagP(%d)", c);
2214 else if (isTagNonPtr(c)) {
2215 Printf("TagNP(%d)", c);
2217 else if (isSpec(c)) {
2218 Printf("TagS(%d)", c);
2220 else if (isText(c)) {
2221 Printf("text(%d)=\"%s\"",c-TEXT_BASE_ADDR,textToStr(c));
2223 else if (isInventedVar(c)) {
2224 Printf("invented(%d)", c-INVAR_BASE_ADDR);
2226 else if (isInventedDictVar(c)) {
2227 Printf("inventedDict(%d)",c-INDVAR_BASE_ADDR);
2230 Int tag = whatIs(c);
2234 print(fst(c), depth-1);
2236 print(snd(c), depth-1);
2240 Printf("free(%d)", c);
2243 Printf("int(%d)", intOf(c));
2246 Printf("bignum(%s)", bignumToString(c));
2249 Printf("char('%c')", charOf(c));
2252 Printf("ptr(%p)",ptrOf(c));
2255 Printf("class(%d)", c-CCLASS_BASE_ADDR);
2256 Printf("=\"%s\"", textToStr(cclass(c).text));
2259 Printf("instance(%d)", c - INST_BASE_ADDR);
2262 Printf("name(%d)", c-NAME_BASE_ADDR);
2263 Printf("=\"%s\"", textToStr(name(c).text));
2266 Printf("tycon(%d)", c-TYCON_BASE_ADDR);
2267 Printf("=\"%s\"", textToStr(tycon(c).text));
2270 Printf("module(%d)", c - MODULE_BASE_ADDR);
2271 Printf("=\"%s\"", textToStr(module(c).text));
2274 Printf("Offset %d", offsetOf(c));
2277 Printf("%s", textToStr(ghcTupleText(c)));
2281 print(snd(c),depth-1);
2285 print(snd(c),depth-1);
2289 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2290 Printf("%d ", intOf(fst(snd(c))));
2291 print(snd(snd(c)),depth-1);
2293 print(snd(c),depth-1);
2307 Printf("{dict %d}",textOf(c));
2313 Printf("{id %s}",textToStr(textOf(c)));
2317 Printf("{ip %s}",textToStr(textOf(c)));
2320 Printf("?%s",textToStr(textOf(c)));
2324 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2328 print(fst(snd(c)),depth-1);
2330 print(snd(snd(c)),depth-1);
2335 print(snd(c),depth-1);
2340 print(snd(c),depth-1);
2345 print(fst(snd(c)),depth-1);
2347 print(snd(snd(c)),depth-1);
2352 print(fst(snd(c)),depth-1);
2354 print(snd(snd(c)),depth-1);
2358 Printf("FromQual(");
2359 print(fst(snd(c)),depth-1);
2361 print(snd(snd(c)),depth-1);
2365 Printf("StgVar%d=",-c);
2366 print(snd(c), depth-1);
2370 print(fst(snd(c)),depth-1);
2372 print(snd(snd(c)),depth-1);
2377 print(fst(snd(c)),depth-1);
2379 print(snd(snd(c)),depth-1);
2384 print(fst(snd(c)),depth-1);
2386 print(snd(snd(c)),depth-1);
2390 Printf("PrimCase(");
2391 print(fst(snd(c)),depth-1);
2393 print(snd(snd(c)),depth-1);
2398 print(snd(c),depth-1);
2402 Printf("(UNBOXEDTUP,");
2403 print(snd(c),depth-1);
2408 print(zfst(c),depth-1);
2410 print(zsnd(c),depth-1);
2414 Printf("<ZTriple ");
2415 print(zfst3(c),depth-1);
2417 print(zsnd3(c),depth-1);
2419 print(zthd3(c),depth-1);
2424 print(snd(c),depth-1);
2428 if (isTagNonPtr(tag)) {
2429 Printf("(TagNP=%d,%d)", c, tag);
2430 } else if (isTagPtr(tag)) {
2431 Printf("(TagP=%d,",tag);
2432 print(snd(c), depth-1);
2435 } else if (c == tag) {
2436 Printf("Tag(%d)", c);
2438 Printf("Tag(%d)=%d", c, tag);
2447 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2448 Cell c; { /* also recognises DICTVAR cells */
2450 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2453 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2455 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2458 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2460 if (!isPair(c)) return FALSE;
2463 case VAROPCELL : return TRUE;
2465 case QUALIDENT : return isVar(snd(snd(c)));
2467 default : return FALSE;
2471 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2473 if (!isPair(c)) return FALSE;
2476 case CONOPCELL : return TRUE;
2478 case QUALIDENT : return isCon(snd(snd(c)));
2480 default : return FALSE;
2484 Bool isQualIdent(c) /* is cell a qualified identifier? */
2486 return isPair(c) && (fst(c)==QUALIDENT);
2489 Bool eqQualIdent ( QualId c1, QualId c2 )
2491 assert(isQualIdent(c1));
2492 if (!isQualIdent(c2)) {
2493 assert(isQualIdent(c2));
2495 return qmodOf(c1)==qmodOf(c2) &&
2496 qtextOf(c1)==qtextOf(c2);
2499 Bool isIdent(c) /* is cell an identifier? */
2501 if (!isPair(c)) return FALSE;
2506 case CONOPCELL : return TRUE;
2508 case QUALIDENT : return TRUE;
2510 default : return FALSE;
2514 Bool isInt(c) /* cell holds integer value? */
2516 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2519 Int intOf(c) /* find integer value of cell? */
2522 return isPair(c) ? (Int)(snd(c)) : (Int)(c-SMALL_INT_ZERO);
2525 Cell mkInt(n) /* make cell representing integer */
2527 return (SMALL_INT_MIN <= SMALL_INT_ZERO+n &&
2528 SMALL_INT_ZERO+n <= SMALL_INT_MAX)
2533 #if SIZEOF_VOID_P == SIZEOF_INT
2535 typedef union {Int i; Ptr p;} IntOrPtr;
2542 return pair(PTRCELL,x.i);
2549 assert(fst(c) == PTRCELL);
2559 return pair(CPTRCELL,x.i);
2566 assert(fst(c) == CPTRCELL);
2571 #elif SIZEOF_VOID_P == 2*SIZEOF_INT
2573 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2580 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2587 assert(fst(c) == PTRCELL);
2588 x.i.i1 = intOf(fst(snd(c)));
2589 x.i.i2 = intOf(snd(snd(c)));
2598 return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2605 assert(fst(c) == CPTRCELL);
2606 x.i.i1 = intOf(fst(snd(c)));
2607 x.i.i2 = intOf(snd(snd(c)));
2613 #error "Can't implement mkPtr/ptrOf on this architecture."
2618 String stringNegate( s )
2626 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2631 /* --------------------------------------------------------------------------
2633 * ------------------------------------------------------------------------*/
2635 Int length(xs) /* calculate length of list xs */
2638 for (; nonNull(xs); ++n)
2643 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2644 List xs, ys; { /* ys by modifying xs ... */
2649 while (nonNull(tl(zs)))
2656 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2659 for (; nonNull(xs); xs=tl(xs))
2660 ys = cons(hd(xs),ys);
2664 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2667 return revOnto(dupOnto(xs,NIL),ys);
2670 List dupList(xs) /* Duplicate spine of list xs */
2673 for (; nonNull(xs); xs=tl(xs))
2674 ys = cons(hd(xs),ys);
2678 List revOnto(xs,ys) /* Destructively reverse elements of*/
2679 List xs, ys; { /* list xs onto list ys... */
2682 while (nonNull(xs)) {
2691 QualId qualidIsMember ( QualId q, List xs )
2693 for (; nonNull(xs); xs=tl(xs)) {
2694 if (eqQualIdent(q, hd(xs)))
2700 Cell varIsMember(t,xs) /* Test if variable is a member of */
2701 Text t; /* given list of variables */
2703 for (; nonNull(xs); xs=tl(xs))
2704 if (t==textOf(hd(xs)))
2709 Name nameIsMember(t,ns) /* Test if name with text t is a */
2710 Text t; /* member of list of names xs */
2712 for (; nonNull(ns); ns=tl(ns))
2713 if (t==name(hd(ns)).text)
2718 Cell intIsMember(n,xs) /* Test if integer n is member of */
2719 Int n; /* given list of integers */
2721 for (; nonNull(xs); xs=tl(xs))
2722 if (n==intOf(hd(xs)))
2727 Cell cellIsMember(x,xs) /* Test for membership of specific */
2728 Cell x; /* cell x in list xs */
2730 for (; nonNull(xs); xs=tl(xs))
2736 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2739 for (; nonNull(xs); xs=tl(xs))
2745 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2746 Cell c; /* association lists */
2748 for (; nonNull(xs); xs=tl(xs))
2754 List replicate(n,x) /* create list of n copies of x */
2763 List diffList(from,take) /* list difference: from\take */
2764 List from, take; { /* result contains all elements of */
2765 List result = NIL; /* `from' not appearing in `take' */
2767 while (nonNull(from)) {
2768 List next = tl(from);
2769 if (!cellIsMember(hd(from),take)) {
2778 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2782 for(;nonNull(xs);xs=tl(xs)) {
2785 result=cons(x,result);
2791 List take(n,xs) /* destructively truncate list to */
2792 Int n; /* specified length */
2798 while (1<n-- && nonNull(xs))
2805 List splitAt(n,xs) /* drop n things from front of list*/
2814 Cell nth(n,xs) /* extract n'th element of list */
2817 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2824 List removeCell(x,xs) /* destructively remove cell from */
2829 return tl(xs); /* element at front of list */
2833 for (; nonNull(curr); prev=curr, curr=tl(prev))
2835 tl(prev) = tl(curr);
2836 return xs; /* element in middle of list */
2840 return xs; /* here if element not found */
2843 List nubList(xs) /* nuke dups in list */
2844 List xs; { /* non destructive */
2846 for (; nonNull(xs); xs=tl(xs))
2847 if (isNull(cellIsMember(hd(xs),outs)))
2848 outs = cons(hd(xs),outs);
2854 /* --------------------------------------------------------------------------
2855 * Tagged tuples (experimental)
2856 * ------------------------------------------------------------------------*/
2858 static void z_tag_check ( Cell x, int tag, char* caller )
2862 sprintf(buf,"z_tag_check(%s): null\n", caller);
2865 if (whatIs(x) != tag) {
2867 "z_tag_check(%s): tag was %d, expected %d\n",
2868 caller, whatIs(x), tag );
2873 Cell zpair ( Cell x1, Cell x2 )
2874 { return ap(ZTUP2,ap(x1,x2)); }
2875 Cell zfst ( Cell zpair )
2876 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2877 Cell zsnd ( Cell zpair )
2878 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2880 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2881 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2882 Cell zfst3 ( Cell zpair )
2883 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2884 Cell zsnd3 ( Cell zpair )
2885 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2886 Cell zthd3 ( Cell zpair )
2887 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2889 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2890 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2891 Cell zsel14 ( Cell zpair )
2892 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2893 Cell zsel24 ( Cell zpair )
2894 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2895 Cell zsel34 ( Cell zpair )
2896 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2897 Cell zsel44 ( Cell zpair )
2898 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2900 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2901 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2902 Cell zsel15 ( Cell zpair )
2903 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2904 Cell zsel25 ( Cell zpair )
2905 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2906 Cell zsel35 ( Cell zpair )
2907 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2908 Cell zsel45 ( Cell zpair )
2909 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2910 Cell zsel55 ( Cell zpair )
2911 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2914 Cell unap ( int tag, Cell c )
2917 if (whatIs(c) != tag) {
2918 sprintf(buf, "unap: specified %d, actual %d\n",
2925 /* --------------------------------------------------------------------------
2926 * Operations on applications:
2927 * ------------------------------------------------------------------------*/
2929 Int argCount; /* number of args in application */
2931 Cell getHead(e) /* get head cell of application */
2932 Cell e; { /* set number of args in argCount */
2933 for (argCount=0; isAp(e); e=fun(e))
2938 List getArgs(e) /* get list of arguments in function*/
2939 Cell e; { /* application: */
2940 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2942 for (as=NIL; isAp(e); e=fun(e))
2943 as = cons(arg(e),as);
2947 Cell nthArg(n,e) /* return nth arg in application */
2948 Int n; /* of function to m args (m>=n) */
2949 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2950 for (n=numArgs(e)-n-1; n>0; n--)
2955 Int numArgs(e) /* find number of arguments to expr */
2958 for (n=0; isAp(e); e=fun(e))
2963 Cell applyToArgs(f,args) /* destructively apply list of args */
2964 Cell f; /* to function f */
2966 while (nonNull(args)) {
2967 Cell temp = tl(args);
2968 tl(args) = hd(args);
2976 /* --------------------------------------------------------------------------
2978 * ------------------------------------------------------------------------*/
2980 static String maybeModuleStr ( Module m )
2982 if (isModule(m)) return textToStr(module(m).text); else return "??";
2985 static String maybeNameStr ( Name n )
2987 if (isName(n)) return textToStr(name(n).text); else return "??";
2990 static String maybeTyconStr ( Tycon t )
2992 if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
2995 static String maybeClassStr ( Class c )
2997 if (isClass(c)) return textToStr(cclass(c).text); else return "??";
3000 static String maybeText ( Text t )
3002 if (isNull(t)) return "(nil)";
3003 return textToStr(t);
3006 static void print100 ( Int x )
3008 print ( x, 100); printf("\n");
3011 void dumpTycon ( Int t )
3013 if (isTycon(TYCON_BASE_ADDR+t) && !isTycon(t)) t += TYCON_BASE_ADDR;
3015 printf ( "dumpTycon %d: not a tycon\n", t);
3019 printf ( " text: %s\n", textToStr(tycon(t).text) );
3020 printf ( " line: %d\n", tycon(t).line );
3021 printf ( " mod: %s\n", maybeModuleStr(tycon(t).mod));
3022 printf ( " tuple: %d\n", tycon(t).tuple);
3023 printf ( " arity: %d\n", tycon(t).arity);
3024 printf ( " kind: "); print100(tycon(t).kind);
3025 printf ( " what: %d\n", tycon(t).what);
3026 printf ( " defn: "); print100(tycon(t).defn);
3027 printf ( " cToT: %d %s\n", tycon(t).conToTag,
3028 maybeNameStr(tycon(t).conToTag));
3029 printf ( " tToC: %d %s\n", tycon(t).tagToCon,
3030 maybeNameStr(tycon(t).tagToCon));
3031 printf ( " itbl: %p\n", tycon(t).itbl);
3032 printf ( " nextTH: %d %s\n", tycon(t).nextTyconHash,
3033 maybeTyconStr(tycon(t).nextTyconHash));
3037 void dumpName ( Int n )
3039 if (isName(NAME_BASE_ADDR+n) && !isName(n)) n += NAME_BASE_ADDR;
3041 printf ( "dumpName %d: not a name\n", n);
3045 printf ( " text: %s\n", textToStr(name(n).text) );
3046 printf ( " line: %d\n", name(n).line );
3047 printf ( " mod: %s\n", maybeModuleStr(name(n).mod));
3048 printf ( " syntax: %d\n", name(n).syntax );
3049 printf ( " parent: %d\n", name(n).parent );
3050 printf ( " arity: %d\n", name(n).arity );
3051 printf ( " number: %d\n", name(n).number );
3052 printf ( " type: "); print100(name(n).type);
3053 printf ( " defn: %d\n", name(n).defn );
3054 printf ( " stgVar: "); print100(name(n).stgVar);
3055 printf ( " cconv: %d\n", name(n).callconv );
3056 printf ( " primop: %p\n", name(n).primop );
3057 printf ( " itbl: %p\n", name(n).itbl );
3058 printf ( " nextNH: %d\n", name(n).nextNameHash );
3063 void dumpClass ( Int c )
3065 if (isClass(CCLASS_BASE_ADDR+c) && !isClass(c)) c += CCLASS_BASE_ADDR;
3067 printf ( "dumpClass %d: not a class\n", c);
3071 printf ( " text: %s\n", textToStr(cclass(c).text) );
3072 printf ( " line: %d\n", cclass(c).line );
3073 printf ( " mod: %s\n", maybeModuleStr(cclass(c).mod));
3074 printf ( " arity: %d\n", cclass(c).arity );
3075 printf ( " level: %d\n", cclass(c).level );
3076 printf ( " kinds: "); print100( cclass(c).kinds );
3077 printf ( " fds: %d\n", cclass(c).fds );
3078 printf ( " xfds: %d\n", cclass(c).xfds );
3079 printf ( " head: "); print100( cclass(c).head );
3080 printf ( " dcon: "); print100( cclass(c).dcon );
3081 printf ( " supers: "); print100( cclass(c).supers );
3082 printf ( " #supers: %d\n", cclass(c).numSupers );
3083 printf ( " dsels: "); print100( cclass(c).dsels );
3084 printf ( " members: "); print100( cclass(c).members );
3085 printf ( "#members: %d\n", cclass(c).numMembers );
3086 printf ( "defaults: "); print100( cclass(c).defaults );
3087 printf ( " insts: "); print100( cclass(c).instances );
3092 void dumpInst ( Int i )
3094 if (isInst(INST_BASE_ADDR+i) && !isInst(i)) i += INST_BASE_ADDR;
3096 printf ( "dumpInst %d: not an instance\n", i);
3100 printf ( " class: %s\n", maybeClassStr(inst(i).c) );
3101 printf ( " line: %d\n", inst(i).line );
3102 printf ( " mod: %s\n", maybeModuleStr(inst(i).mod));
3103 printf ( " kinds: "); print100( inst(i).kinds );
3104 printf ( " head: "); print100( inst(i).head );
3105 printf ( " specs: "); print100( inst(i).specifics );
3106 printf ( " #specs: %d\n", inst(i).numSpecifics );
3107 printf ( " impls: "); print100( inst(i).implements );
3108 printf ( " builder: %s\n", maybeNameStr( inst(i).builder ) );
3113 /* --------------------------------------------------------------------------
3115 * ------------------------------------------------------------------------*/
3122 case POSTPREL: break;
3124 case RESET : clearStack();
3126 /* the next 2 statements are particularly important
3127 * if you are using GLOBALfst or GLOBALsnd since the
3128 * corresponding registers may be reset to their
3129 * uninitialised initial values by a longjump.
3131 heapTopFst = heapFst + heapSize;
3132 heapTopSnd = heapSnd + heapSize;
3136 if (isNull(lastExprSaved))
3137 savedText = TEXT_SIZE;
3142 for (i = NAME_BASE_ADDR;
3143 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3144 if (tabName[i-NAME_BASE_ADDR].inUse) {
3145 mark(name(i).parent);
3147 mark(name(i).stgVar);
3151 end("Names", nameHw-NAMEMIN);
3154 for (i = MODULE_BASE_ADDR;
3155 i < MODULE_BASE_ADDR+tabModuleSz; ++i) {
3156 if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3157 mark(module(i).tycons);
3158 mark(module(i).names);
3159 mark(module(i).classes);
3160 mark(module(i).exports);
3161 mark(module(i).qualImports);
3162 mark(module(i).objectExtraNames);
3167 mark(targetModules);
3168 end("Modules", moduleHw-MODMIN);
3171 for (i = TYCON_BASE_ADDR;
3172 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3173 if (tabTycon[i-TYCON_BASE_ADDR].inUse) {
3174 mark(tycon(i).defn);
3175 mark(tycon(i).kind);
3176 mark(tycon(i).what);
3179 end("Type constructors", tyconHw-TYCMIN);
3182 for (i = CCLASS_BASE_ADDR;
3183 i < CCLASS_BASE_ADDR+tabClassSz; ++i) {
3184 if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3185 mark(cclass(i).head);
3186 mark(cclass(i).kinds);
3187 mark(cclass(i).fds);
3188 mark(cclass(i).xfds);
3189 mark(cclass(i).dsels);
3190 mark(cclass(i).supers);
3191 mark(cclass(i).members);
3192 mark(cclass(i).defaults);
3193 mark(cclass(i).instances);
3197 end("Classes", classHw-CLASSMIN);
3200 for (i = INST_BASE_ADDR;
3201 i < INST_BASE_ADDR+tabInstSz; ++i) {
3202 if (tabInst[i-INST_BASE_ADDR].inUse) {
3204 mark(inst(i).kinds);
3205 mark(inst(i).specifics);
3206 mark(inst(i).implements);
3209 end("Instances", instHw-INSTMIN);
3212 for (i=0; i<=sp; ++i)
3217 mark(lastExprSaved);
3220 end("Last expression", 3);
3225 end("C stack", stackRoots);
3230 case PREPREL : heapFst = heapAlloc(heapSize);
3231 heapSnd = heapAlloc(heapSize);
3233 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3234 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3239 heapTopFst = heapFst + heapSize;
3240 heapTopSnd = heapSnd + heapSize;
3241 for (i=1; i<heapSize; ++i) {
3245 snd(-heapSize) = NIL;
3252 marksSize = bitArraySize(heapSize);
3253 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3254 ERRMSG(0) "Unable to allocate gc markspace"
3261 nextNewText = INVAR_BASE_ADDR;
3262 nextNewDText = INDVAR_BASE_ADDR;
3263 lastExprSaved = NIL;
3264 savedText = TEXT_SIZE;
3266 for (i=0; i<TEXTHSZ; ++i) textHash[i][0] = NOTEXT;
3267 for (i=0; i<TYCONHSZ; ++i) tyconHash[RC_T(i)] = NIL;
3268 for (i=0; i<NAMEHSZ; ++i) nameHash[RC_N(i)] = NIL;
3274 /*-------------------------------------------------------------------------*/