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/05 10:25:08 $
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).hasStrict = FALSE;
864 name(nm).stgVar = NIL;
865 name(nm).callconv = NIL;
867 name(nm).primop = NULL;
868 name(nm).itbl = NULL;
869 module(currentModule).names = cons(nm,module(currentModule).names);
870 name(nm).nextNameHash = nameHash[RC_N(h)];
871 nameHash[RC_N(h)] = nm;
875 Name findName(t) /* Locate name in name table */
877 Name n = nameHash[RC_N(nHash(t))];
879 assert(isName(n) || isNull(n));
880 while (nonNull(n) && name(n).text!=t)
881 n = name(n).nextNameHash;
885 Name addName(nm) /* Insert Name in name table - if */
886 Name nm; { /* no clash is caused */
889 oldnm = findName(name(nm).text);
892 module(currentModule).names=cons(nm,module(currentModule).names);
898 static Void local hashName(nm) /* Insert Name into hash table */
905 name(nm).nextNameHash = nameHash[RC_N(h)];
906 nameHash[RC_N(h)] = nm;
909 Name findQualName(id) /* Locate (possibly qualified) name*/
910 Cell id; { /* in name table */
912 internal("findQualName");
918 return findName(textOf(id));
920 Text t = qtextOf(id);
921 Module m = findQualifier(qmodOf(id));
923 if (isNull(m)) return NIL;
924 for(es=module(m).exports; nonNull(es); es=tl(es)) {
926 if (isName(e) && name(e).text==t)
928 else if (isPair(e) && DOTDOT==snd(e)) {
929 List subentities = NIL;
932 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
933 subentities = tycon(c).defn;
935 subentities = cclass(c).members;
936 for(; nonNull(subentities); subentities=tl(subentities)) {
937 if (!isName(hd(subentities)))
938 internal("findQualName3");
939 if (name(hd(subentities)).text == t)
940 return hd(subentities);
946 default : internal("findQualName2");
948 return 0; /* NOTREACHED */
952 Name nameFromStgVar ( StgVar v )
955 for (n = NAME_BASE_ADDR;
956 n < NAME_BASE_ADDR+tabNameSz; n++)
957 if (tabName[n-NAME_BASE_ADDR].inUse)
958 if (name(n).stgVar == v) return n;
962 void* getHugs_AsmObject_for ( char* s )
965 Text t = findText(s);
967 for (n = NAME_BASE_ADDR;
968 n < NAME_BASE_ADDR+tabNameSz; n++)
969 if (tabName[n-NAME_BASE_ADDR].inUse)
970 if (name(n).text == t) break;
971 if (n == NAME_BASE_ADDR+tabNameSz) {
972 fprintf ( stderr, "can't find `%s' in ...\n", s );
973 internal("getHugs_AsmObject_for(1)");
976 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
977 internal("getHugs_AsmObject_for(2)");
978 return ptrOf(stgVarInfo(v));
981 /* --------------------------------------------------------------------------
982 * Primitive functions:
983 * ------------------------------------------------------------------------*/
985 Module findFakeModule ( Text t )
987 Module m = findModule(t);
989 if (!module(m).fake) internal("findFakeModule");
992 module(m).fake = TRUE;
998 Name addWiredInBoxingTycon
999 ( String modNm, String typeNm, String constrNm,
1000 Int rep, Kind kind )
1004 Text modT = findText(modNm);
1005 Text typeT = findText(typeNm);
1006 Text conT = findText(constrNm);
1007 Module m = findFakeModule(modT);
1010 n = newName(conT,NIL);
1012 name(n).number = cfunNo(0);
1014 name(n).primop = (void*)rep;
1016 t = newTycon(typeT);
1017 tycon(t).what = DATATYPE;
1018 tycon(t).kind = kind;
1023 Tycon addTupleTycon ( Int n )
1031 for (i = TYCON_BASE_ADDR;
1032 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1033 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
1034 if (tycon(i).tuple == n) return i;
1037 m = findFakeModule(findText(n==0 ? "PrelBase" : "PrelTup")); else
1038 m = findModule(findText("PrimPrel"));
1042 for (i = 0; i < n; i++) k = ap(STAR,k);
1043 t = newTycon(ghcTupleText_n(n));
1046 tycon(t).what = DATATYPE;
1049 /* maybe we want to do this for all n ? */
1050 nm = newName(ghcTupleText_n(n), t);
1051 name(nm).type = t; /* ummm ... for n > 0 */
1058 Tycon addWiredInEnumTycon ( String modNm, String typeNm,
1059 List /*of Text*/ constrs )
1063 Text modT = findText(modNm);
1064 Text typeT = findText(typeNm);
1065 Module m = findFakeModule(modT);
1068 t = newTycon(typeT);
1069 tycon(t).kind = STAR;
1070 tycon(t).what = DATATYPE;
1072 constrs = reverse(constrs);
1073 i = length(constrs);
1074 for (; nonNull(constrs); constrs=tl(constrs),i--) {
1075 Text conT = hd(constrs);
1076 Name con = newName(conT,t);
1077 name(con).number = cfunNo(i);
1079 name(con).parent = t;
1080 tycon(t).defn = cons(con, tycon(t).defn);
1086 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
1087 Text t; /* sets rep, not type */
1090 Int rep; { /* Really AsmRep */
1091 Name n = newName(t,NIL);
1092 name(n).arity = arity;
1093 name(n).number = cfunNo(no);
1095 name(n).primop = (void*)rep;
1100 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
1105 Name n = newName(t,NIL);
1106 name(n).arity = arity;
1107 name(n).number = cfunNo(no);
1108 name(n).type = type;
1113 Int sfunPos(s,c) /* Find position of field with */
1114 Name s; /* selector s in constructor c. */
1118 for (; nonNull(cns); cns=tl(cns))
1119 if (fst(hd(cns))==c)
1120 return intOf(snd(hd(cns)));
1121 internal("sfunPos");
1122 return 0;/* NOTREACHED */
1125 static List local insertName(nm,ns) /* insert name nm into sorted list */
1130 String s = textToStr(name(nm).text);
1132 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
1133 if (hd(curr)==nm) /* just in case we get duplicates! */
1138 if (nonNull(prev)) {
1139 tl(prev) = cons(nm,curr);
1143 return cons(nm,curr);
1146 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
1147 String pat; /* to list of names ns */
1148 List ns; { /* Null pattern matches every name */
1149 Name nm; /* (Names with NIL type, or hidden */
1150 /* or invented names are excluded) */
1152 for (nm = NAME_BASE_ADDR;
1153 nm < NAME_BASE_ADDR+tabNameSz; ++nm)
1154 if (tabName[nm-NAME_BASE_ADDR].inUse) {
1155 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
1156 String str = textToStr(name(nm).text);
1157 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1158 ns = insertName(nm,ns);
1163 List mns = module(currentModule).names;
1164 for(; nonNull(mns); mns=tl(mns)) {
1166 if (!inventedText(name(nm).text)) {
1167 String str = textToStr(name(nm).text);
1168 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1169 ns = insertName(nm,ns);
1176 /* --------------------------------------------------------------------------
1177 * A simple string matching routine
1178 * `*' matches any sequence of zero or more characters
1179 * `?' matches any single character exactly
1180 * `@str' matches the string str exactly (ignoring any special chars)
1181 * `\c' matches the character c only (ignoring special chars)
1182 * c matches the character c only
1183 * ------------------------------------------------------------------------*/
1185 static Void local patternError(s) /* report error in pattern */
1187 ERRMSG(0) "%s in pattern", s
1191 static Bool local stringMatch(pat,str) /* match string against pattern */
1197 case '\0' : return (*str=='\0');
1200 if (stringMatch(pat+1,str))
1205 case '?' : if (*str++=='\0')
1210 case '[' : { Bool found = FALSE;
1211 while (*++pat!='\0' && *pat!=']')
1212 if (!found && ( pat[0] == *str ||
1221 patternError("missing `]'");
1229 case '\\' : if (*++pat == '\0')
1230 patternError("extra trailing `\\'");
1232 default : if (*pat++ != *str++)
1238 /* --------------------------------------------------------------------------
1239 * Storage of type classes, instances etc...:
1240 * ------------------------------------------------------------------------*/
1242 static List classes; /* list of classes in current scope */
1244 Class newClass ( Text t ) /* add new class to class table */
1246 Class cl = allocNewClass();
1248 [cl-CCLASS_BASE_ADDR].mod = currentModule;
1249 cclass(cl).text = t;
1250 cclass(cl).arity = 0;
1251 cclass(cl).kinds = NIL;
1252 cclass(cl).head = NIL;
1253 cclass(cl).fds = NIL;
1254 cclass(cl).xfds = NIL;
1255 cclass(cl).dcon = NIL;
1256 cclass(cl).supers = NIL;
1257 cclass(cl).dsels = NIL;
1258 cclass(cl).members = NIL;
1259 cclass(cl).defaults = NIL;
1260 cclass(cl).instances = NIL;
1261 classes = cons(cl,classes);
1262 module(currentModule).classes
1263 = cons(cl,module(currentModule).classes);
1267 Class findClass(t) /* look for named class in table */
1271 for (cs=classes; nonNull(cs); cs=tl(cs)) {
1273 if (cclass(cl).text==t)
1279 Class addClass(c) /* Insert Class in class list */
1280 Class c; { /* - if no clash caused */
1282 assert(whatIs(c)==CLASS);
1283 oldc = findClass(cclass(c).text);
1285 classes=cons(c,classes);
1286 module(currentModule).classes=cons(c,module(currentModule).classes);
1293 Class findQualClass(c) /* Look for (possibly qualified) */
1294 Cell c; { /* class in class list */
1295 if (!isQualIdent(c)) {
1296 return findClass(textOf(c));
1298 Text t = qtextOf(c);
1299 Module m = findQualifier(qmodOf(c));
1303 for (es=module(m).exports; nonNull(es); es=tl(es)) {
1305 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
1312 Inst newInst() { /* Add new instance to table */
1313 Inst in = allocNewInst();
1315 [in-INST_BASE_ADDR].mod = currentModule;
1316 inst(in).kinds = NIL;
1317 inst(in).head = NIL;
1318 inst(in).specifics = NIL;
1319 inst(in).implements = NIL;
1320 inst(in).builder = NIL;
1325 extern Void printInst ( Inst));
1329 Class cl = inst(in).c;
1330 Printf("%s-", textToStr(cclass(cl).text));
1331 printType(stdout,inst(in).t);
1333 #endif /* DEBUG_DICTS */
1335 Inst findFirstInst(tc) /* look for 1st instance involving */
1336 Tycon tc; { /* the type constructor tc */
1337 return findNextInst(tc,INST_BASE_ADDR-1);
1340 Inst findNextInst(tc,in) /* look for next instance involving*/
1341 Tycon tc; /* the type constructor tc */
1342 Inst in; { /* starting after instance in */
1344 while (++in < INST_BASE_ADDR+tabInstSz) {
1345 if (!tabInst[in-INST_BASE_ADDR].inUse) continue;
1346 assert(isModule(inst(in).mod));
1348 for (; isAp(pi); pi=fun(pi))
1349 if (typeInvolves(arg(pi),tc))
1355 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1356 Type ty; /* type constructor/tuple tc. */
1359 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1360 || typeInvolves(arg(ty),tc)));
1364 /* Needed by finishGHCInstance to find classes, before the
1365 export list has been built -- so we can't use
1368 Class findQualClassWithoutConsultingExportList ( QualId q )
1378 t_class = textOf(q);
1381 t_class = qtextOf(q);
1384 for (cl = CCLASS_BASE_ADDR;
1385 cl < CCLASS_BASE_ADDR+tabClassSz; cl++) {
1386 if (tabClass[cl-CCLASS_BASE_ADDR].inUse)
1387 if (cclass(cl).text == t_class) {
1388 /* Class name is ok, but is this the right module? */
1389 if (isNull(t_mod) /* no module name specified */
1391 && t_mod == module(cclass(cl).mod).text)
1399 /* Same deal, except for Tycons. */
1400 Tycon findQualTyconWithoutConsultingExportList ( QualId q )
1410 t_tycon = textOf(q);
1413 t_tycon = qtextOf(q);
1416 for (tc = TYCON_BASE_ADDR;
1417 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1418 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1419 if (tycon(tc).text == t_tycon) {
1420 /* Tycon name is ok, but is this the right module? */
1421 if (isNull(t_mod) /* no module name specified */
1423 && t_mod == module(tycon(tc).mod).text)
1431 /* Same deal, except for Names. */
1432 Name findQualNameWithoutConsultingExportList ( QualId q )
1438 assert(isQVar(q) || isQCon(q));
1440 if (isCon(q) || isVar(q)) {
1445 t_name = qtextOf(q);
1448 for (nm = NAME_BASE_ADDR;
1449 nm < NAME_BASE_ADDR+tabNameSz; nm++) {
1450 if (tabName[nm-NAME_BASE_ADDR].inUse)
1451 if (name(nm).text == t_name) {
1452 /* Name is ok, but is this the right module? */
1453 if (isNull(t_mod) /* no module name specified */
1455 && t_mod == module(name(nm).mod).text)
1464 Tycon findTyconInAnyModule ( Text t )
1467 for (tc = TYCON_BASE_ADDR;
1468 tc < TYCON_BASE_ADDR+tabTyconSz; tc++)
1469 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1470 if (tycon(tc).text == t) return tc;
1474 Class findClassInAnyModule ( Text t )
1477 for (cc = CCLASS_BASE_ADDR;
1478 cc < CCLASS_BASE_ADDR+tabClassSz; cc++)
1479 if (tabClass[cc-CCLASS_BASE_ADDR].inUse)
1480 if (cclass(cc).text == t) return cc;
1484 Name findNameInAnyModule ( Text t )
1487 for (nm = NAME_BASE_ADDR;
1488 nm < NAME_BASE_ADDR+tabNameSz; nm++)
1489 if (tabName[nm-NAME_BASE_ADDR].inUse)
1490 if (name(nm).text == t) return nm;
1495 /* returns List of QualId */
1496 List getAllKnownTyconsAndClasses ( void )
1501 for (tc = TYCON_BASE_ADDR;
1502 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1503 if (tabTycon[tc-TYCON_BASE_ADDR].inUse) {
1504 /* almost certainly undue paranoia about duplicate avoidance */
1505 QualId q = mkQCon( module(tycon(tc).mod).text, tycon(tc).text );
1506 if (!qualidIsMember(q,xs))
1507 xs = cons ( q, xs );
1510 for (nw = CCLASS_BASE_ADDR;
1511 nw < CCLASS_BASE_ADDR+tabClassSz; nw++) {
1512 if (tabClass[nw-CCLASS_BASE_ADDR].inUse) {
1513 QualId q = mkQCon( module(cclass(nw).mod).text, cclass(nw).text );
1514 if (!qualidIsMember(q,xs))
1515 xs = cons ( q, xs );
1521 /* Purely for debugging. */
1522 void locateSymbolByName ( Text t )
1525 for (i = NAME_BASE_ADDR;
1526 i < NAME_BASE_ADDR+tabNameSz; i++)
1527 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).text == t)
1528 fprintf ( stderr, "name(%d)\n", i-NAME_BASE_ADDR);
1529 for (i = TYCON_BASE_ADDR;
1530 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1531 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).text == t)
1532 fprintf ( stderr, "tycon(%d)\n", i-TYCON_BASE_ADDR);
1533 for (i = CCLASS_BASE_ADDR;
1534 i < CCLASS_BASE_ADDR+tabClassSz; i++)
1535 if (tabClass[i-CCLASS_BASE_ADDR].inUse && cclass(i).text == t)
1536 fprintf ( stderr, "class(%d)\n", i-CCLASS_BASE_ADDR);
1539 /* --------------------------------------------------------------------------
1542 * Various parts of the system use a stack of cells. Most of the stack
1543 * operations are defined as macros, expanded inline.
1544 * ------------------------------------------------------------------------*/
1546 Cell cellStack[NUM_STACK]; /* Storage for cells on stack */
1547 StackPtr sp; /* stack pointer */
1549 Void hugsStackOverflow() { /* Report stack overflow */
1550 ERRMSG(0) "Control stack overflow"
1555 /* --------------------------------------------------------------------------
1558 * A Module represents a user defined module.
1560 * Note: there are now two lookup mechanisms in the system:
1562 * 1) The exports from a module are stored in a big list.
1563 * We resolve qualified names, and import lists by linearly scanning
1564 * through this list.
1566 * 2) Unqualified imports and local definitions for the current module
1567 * are stored in hash tables (tyconHash and nameHash) or linear lists
1570 * ------------------------------------------------------------------------*/
1572 Module currentModule; /* Module currently being processed*/
1574 Bool isValidModule(m) /* is m a legitimate module id? */
1579 Module newModule ( Text t ) /* add new module to module table */
1581 Module mod = allocNewModule();
1582 module(mod).text = t; /* clear new module record */
1584 module(mod).tycons = NIL;
1585 module(mod).names = NIL;
1586 module(mod).classes = NIL;
1587 module(mod).exports = NIL;
1588 module(mod).qualImports = NIL;
1589 module(mod).fake = FALSE;
1591 module(mod).tree = NIL;
1592 module(mod).completed = FALSE;
1593 module(mod).lastStamp = 0; /* ???? */
1595 module(mod).mode = NIL;
1596 module(mod).srcExt = findText("");
1597 module(mod).uses = NIL;
1599 module(mod).objName = findText("");
1600 module(mod).objSize = 0;
1602 module(mod).object = NULL;
1603 module(mod).objectExtras = NULL;
1604 module(mod).objectExtraNames = NIL;
1608 void nukeModule ( Module m )
1613 assert(isModule(m));
1614 /*fprintf(stderr, "NUKEMODULE `%s'\n", textToStr(module(m).text)); */
1615 oc = module(m).object;
1621 oc = module(m).objectExtras;
1628 for (i = NAME_BASE_ADDR; i < NAME_BASE_ADDR+tabNameSz; i++)
1629 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).mod == m) {
1630 if (name(i).itbl) free(name(i).itbl);
1631 name(i).itbl = NULL;
1635 for (i = TYCON_BASE_ADDR; i < TYCON_BASE_ADDR+tabTyconSz; i++)
1636 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).mod == m) {
1637 if (tycon(i).itbl) free(tycon(i).itbl);
1638 tycon(i).itbl = NULL;
1642 for (i = CCLASS_BASE_ADDR; i < CCLASS_BASE_ADDR+tabClassSz; i++)
1643 if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
1644 if (cclass(i).mod == m) {
1647 List /* Inst */ ins;
1648 List /* Inst */ ins2 = NIL;
1649 for (ins = cclass(i).instances; nonNull(ins); ins=tl(ins))
1650 if (inst(hd(ins)).mod != m)
1651 ins2 = cons(hd(ins),ins2);
1652 cclass(i).instances = ins2;
1657 for (i = INST_BASE_ADDR; i < INST_BASE_ADDR+tabInstSz; i++)
1658 if (tabInst[i-INST_BASE_ADDR].inUse && inst(i).mod == m)
1662 //for (i = 0; i < TYCONHSZ; i++) tyconHash[i] = 0;
1663 //for (i = 0; i < NAMEHSZ; i++) nameHash[i] = 0;
1668 void ppModules ( void )
1671 fflush(stderr); fflush(stdout);
1672 printf ( "begin MODULES\n" );
1673 for (i = MODULE_BASE_ADDR+tabModuleSz-1;
1674 i >= MODULE_BASE_ADDR; i--)
1675 if (tabModule[i-MODULE_BASE_ADDR].inUse)
1676 printf ( " %2d: %16s\n",
1677 i-MODULE_BASE_ADDR, textToStr(module(i).text)
1679 printf ( "end MODULES\n" );
1680 fflush(stderr); fflush(stdout);
1684 Module findModule(t) /* locate Module in module table */
1687 for(m = MODULE_BASE_ADDR;
1688 m < MODULE_BASE_ADDR+tabModuleSz; ++m) {
1689 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1690 if (module(m).text==t)
1696 Module findModid(c) /* Find module by name or filename */
1698 switch (whatIs(c)) {
1699 case STRCELL : internal("findModid-STRCELL unimp");
1700 case CONIDCELL : return findModule(textOf(c));
1701 default : internal("findModid");
1703 return NIL;/*NOTUSED*/
1706 static local Module findQualifier(t) /* locate Module in import list */
1709 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1710 if (textOf(fst(hd(ms)))==t)
1713 if (module(currentModule).text==t)
1714 return currentModule;
1718 Void setCurrModule(m) /* set lookup tables for current module */
1721 assert(isModule(m));
1722 /* fprintf(stderr, "SET CURR MODULE %s %d\n", textToStr(module(m).text),m); */
1724 for (t = module(m).names; nonNull(t); t=tl(t))
1725 assert(isName(hd(t)));
1726 for (t = module(m).tycons; nonNull(t); t=tl(t))
1727 assert(isTycon(hd(t)) || isTuple(hd(t)));
1728 for (t = module(m).classes; nonNull(t); t=tl(t))
1729 assert(isClass(hd(t)));
1732 currentModule = m; /* This is the only assignment to currentModule */
1733 for (i=0; i<TYCONHSZ; ++i)
1734 tyconHash[RC_T(i)] = NIL;
1735 mapProc(hashTycon,module(m).tycons);
1736 for (i=0; i<NAMEHSZ; ++i)
1737 nameHash[RC_N(i)] = NIL;
1738 mapProc(hashName,module(m).names);
1739 classes = module(m).classes;
1743 Name jrsFindQualName ( Text mn, Text sn )
1748 for (m = MODULE_BASE_ADDR;
1749 m < MODULE_BASE_ADDR+tabModuleSz; m++)
1750 if (tabModule[m-MODULE_BASE_ADDR].inUse
1751 && module(m).text == mn) break;
1753 if (m == MODULE_BASE_ADDR+tabModuleSz) return NIL;
1755 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1756 if (name(hd(ns)).text == sn) return hd(ns);
1762 char* nameFromOPtr ( void* p )
1766 for (m = MODULE_BASE_ADDR;
1767 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1768 if (tabModule[m-MODULE_BASE_ADDR].inUse && module(m).object) {
1769 char* nm = ocLookupAddr ( module(m).object, p );
1774 /* A kludge to assist Win32 debugging; not actually necessary. */
1775 { char* nm = nameFromStaticOPtr(p);
1783 void* lookupOTabName ( Module m, char* sym )
1785 assert(isModule(m));
1786 if (module(m).object)
1787 return ocLookupSym ( module(m).object, sym );
1792 void* lookupOExtraTabName ( char* sym )
1796 for (m = MODULE_BASE_ADDR;
1797 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1798 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1799 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1800 void* ad = ocLookupSym ( oc, sym );
1808 OSectionKind lookupSection ( void* ad )
1815 for (m = MODULE_BASE_ADDR;
1816 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1817 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1818 if (module(m).object) {
1819 sect = ocLookupSection ( module(m).object, ad );
1820 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1823 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1824 sect = ocLookupSection ( oc, ad );
1825 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1830 return HUGS_SECTIONKIND_OTHER;
1834 /* --------------------------------------------------------------------------
1837 * Provides a garbage collectable heap for storage of expressions etc.
1839 * Now incorporates a flat resource: A two-space collected extension of
1840 * the heap that provides storage for contiguous arrays of Cell storage,
1841 * cooperating with the garbage collection mechanisms for the main heap.
1842 * ------------------------------------------------------------------------*/
1844 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1845 Heap heapFst; /* array of fst component of pairs */
1846 Heap heapSnd; /* array of snd component of pairs */
1853 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1854 /* C stack; use with extreme care! */
1856 Int numGcs; /* number of garbage collections */
1857 Int cellsRecovered; /* number of cells recovered */
1859 static Cell freeList; /* free list of unused cells */
1860 static Cell lsave, rsave; /* save components of pair */
1864 static Int markCount, stackRoots;
1866 #define initStackRoots() stackRoots = 0
1867 #define recordStackRoot() stackRoots++
1880 #define start() markCount = 0
1881 #define end(thing,rs) \
1883 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1886 #define recordMark() markCount++
1888 #else /* !GC_STATISTICS */
1893 #define initStackRoots()
1894 #define recordStackRoot()
1897 #define end(thing,root)
1898 #define recordMark()
1900 #endif /* !GC_STATISTICS */
1902 Cell pair(l,r) /* Allocate pair (l, r) from */
1903 Cell l, r; { /* heap, garbage collecting first */
1904 Cell c = freeList; /* if necessary ... */
1916 freeList = snd(freeList);
1924 static Int marksSize;
1926 Cell markExpr(c) /* External interface to markCell */
1928 return isGenPair(c) ? markCell(c) : c;
1931 static Cell local markCell(c) /* Traverse part of graph marking */
1932 Cell c; { /* cells reachable from given root */
1933 /* markCell(c) is only called if c */
1935 { register int place = placeInSet(c);
1936 register int mask = maskInSet(c);
1937 if (marks[place]&mask)
1940 marks[place] |= mask;
1945 /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1946 if (isGenPair(fst(c))) {
1948 fst(c) = markCell(fst(c));
1951 else if (isNull(fst(c)) || isTagPtr(fst(c))) {
1959 static Void local markSnd(c) /* Variant of markCell used to */
1960 Cell c; { /* update snd component of cell */
1961 Cell t; /* using tail recursion */
1963 ma: t = c; /* Keep pointer to original pair */
1968 { register int place = placeInSet(c);
1969 register int mask = maskInSet(c);
1970 if (marks[place]&mask)
1973 marks[place] |= mask;
1978 if (isGenPair(fst(c))) {
1979 fst(c) = markCell(fst(c));
1982 else if (isNull(fst(c)) || isTagPtr(fst(c)))
1987 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1988 Cell n; { /* it was a cell ref, but don't */
1989 /* move cell so we don't have */
1990 /* to modify the stored value of n */
1997 Void garbageCollect() { /* Run garbage collector ... */
1998 /* disable break checking */
2003 jmp_buf regs; /* save registers on stack */
2004 HugsBreakAction oldBrk
2005 = setBreakAction ( HugsIgnoreBreak );
2006 fprintf ( stderr, "wa-hey! garbage collection! too difficult! bye!\n" );
2011 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
2014 everybody(MARK); /* Mark all components of system */
2016 gcScanning(); /* scan mark set */
2023 for (i=1; i<=heapSize; i++) {
2024 if ((marks[place] & mask) == 0) {
2031 if (++j == bitsPerWord) {
2038 gcRecovered(recovered);
2039 setBreakAction ( oldBrk );
2043 /* can only return if freeList is nonempty on return. */
2044 if (recovered<minRecovery || isNull(freeList)) {
2045 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
2048 cellsRecovered = recovered;
2051 /* --------------------------------------------------------------------------
2052 * Code for saving last expression entered:
2054 * This is a little tricky because some text values (e.g. strings or variable
2055 * names) may not be defined or have the same value when the expression is
2056 * recalled. These text values are therefore saved in the top portion of
2058 * ------------------------------------------------------------------------*/
2060 static Cell lastExprSaved; /* last expression to be saved */
2062 Void setLastExpr(e) /* save expression for later recall*/
2064 lastExprSaved = NIL; /* in case attempt to save fails */
2065 savedText = TEXT_SIZE;
2066 lastExprSaved = lowLevelLastIn(e);
2069 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
2070 Cell c; { /* acyclic graph) for later recall */
2071 if (isPair(c)) { /* Duplicating any text strings */
2072 if (isTagNonPtr(fst(c))) /* in case these are lost at some */
2073 switch (fst(c)) { /* point before the expr is reused */
2079 case STRCELL : return pair(fst(c),saveText(textOf(c)));
2080 default : return pair(fst(c),snd(c));
2083 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2087 return pair(EXTCOPY,saveText(extText(c)));
2093 Cell getLastExpr() { /* recover previously saved expr */
2094 return lowLevelLastOut(lastExprSaved);
2097 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
2098 Cell c; { /* except that Cells refering to */
2099 if (isPair(c)) { /* Text values are restored to */
2100 if (isTagNonPtr(fst(c))) /* appropriate values */
2107 case STRCELL : return pair(fst(c),
2108 findText(text+intValOf(c)));
2110 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
2112 default : return pair(fst(c),snd(c));
2115 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2121 /* --------------------------------------------------------------------------
2122 * Miscellaneous operations on heap cells:
2123 * ------------------------------------------------------------------------*/
2125 Cell whatIs ( register Cell c )
2128 register Cell fstc = fst(c);
2129 return isTag(fstc) ? fstc : AP;
2131 if (isOffset(c)) return OFFSET;
2132 if (isChar(c)) return CHARCELL;
2133 if (isInt(c)) return INTCELL;
2134 if (isName(c)) return NAME;
2135 if (isTycon(c)) return TYCON;
2136 if (isTuple(c)) return TUPLE;
2137 if (isClass(c)) return CLASS;
2138 if (isInst(c)) return INSTANCE;
2139 if (isModule(c)) return MODULE;
2140 if (isText(c)) return TEXTCELL;
2141 if (isInventedVar(c)) return INVAR;
2142 if (isInventedDictVar(c)) return INDVAR;
2143 if (isSpec(c)) return c;
2144 if (isNull(c)) return c;
2145 fprintf ( stderr, "whatIs: unknown %d\n", c );
2151 Cell whatIs(c) /* identify type of cell */
2154 register Cell fstc = fst(c);
2155 return isTag(fstc) ? fstc : AP;
2157 if (c<OFFMIN) return c;
2159 if (isExt(c)) return EXT;
2161 if (c>=INTMIN) return INTCELL;
2163 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
2165 else if (c>=INSTMIN) return INSTANCE;
2167 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
2168 else return MODULE;}
2169 else if (c>=OFFMIN) return OFFSET;
2171 else return (c>=EXTMIN) ?
2179 register Cell fstc = fst(c);
2180 return isTag(fstc) ? fstc : AP;
2182 if (c>=INTMIN) return INTCELL;
2183 if (c>=CHARMIN) return CHARCELL;
2184 if (c>=CLASSMIN) return CLASS;
2185 if (c>=INSTMIN) return INSTANCE;
2186 if (c>=NAMEMIN) return NAME;
2187 if (c>=TYCMIN) return TYCON;
2188 if (c>=MODMIN) return MODULE;
2189 if (c>=OFFMIN) return OFFSET;
2191 if (c>=EXTMIN) return EXT;
2193 if (c>=TUPMIN) return TUPLE;
2199 /* A very, very simple printer.
2200 * Output is uglier than from printExp - but the printer is more
2201 * robust and can be used on any data structure irrespective of
2204 Void print ( Cell c, Int depth )
2209 else if (isNull(c)) {
2212 else if (isTagPtr(c)) {
2213 Printf("TagP(%d)", c);
2215 else if (isTagNonPtr(c)) {
2216 Printf("TagNP(%d)", c);
2218 else if (isSpec(c)) {
2219 Printf("TagS(%d)", c);
2221 else if (isText(c)) {
2222 Printf("text(%d)=\"%s\"",c-TEXT_BASE_ADDR,textToStr(c));
2224 else if (isInventedVar(c)) {
2225 Printf("invented(%d)", c-INVAR_BASE_ADDR);
2227 else if (isInventedDictVar(c)) {
2228 Printf("inventedDict(%d)",c-INDVAR_BASE_ADDR);
2231 Int tag = whatIs(c);
2235 print(fst(c), depth-1);
2237 print(snd(c), depth-1);
2241 Printf("free(%d)", c);
2244 Printf("int(%d)", intOf(c));
2247 Printf("bignum(%s)", bignumToString(c));
2250 Printf("char('%c')", charOf(c));
2253 Printf("ptr(%p)",ptrOf(c));
2256 Printf("class(%d)", c-CCLASS_BASE_ADDR);
2257 Printf("=\"%s\"", textToStr(cclass(c).text));
2260 Printf("instance(%d)", c - INST_BASE_ADDR);
2263 Printf("name(%d)", c-NAME_BASE_ADDR);
2264 Printf("=\"%s\"", textToStr(name(c).text));
2267 Printf("tycon(%d)", c-TYCON_BASE_ADDR);
2268 Printf("=\"%s\"", textToStr(tycon(c).text));
2271 Printf("module(%d)", c - MODULE_BASE_ADDR);
2272 Printf("=\"%s\"", textToStr(module(c).text));
2275 Printf("Offset %d", offsetOf(c));
2278 Printf("%s", textToStr(ghcTupleText(c)));
2282 print(snd(c),depth-1);
2286 print(snd(c),depth-1);
2290 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2291 Printf("%d ", intOf(fst(snd(c))));
2292 print(snd(snd(c)),depth-1);
2294 print(snd(c),depth-1);
2308 Printf("{dict %d}",textOf(c));
2314 Printf("{id %s}",textToStr(textOf(c)));
2318 Printf("{ip %s}",textToStr(textOf(c)));
2321 Printf("?%s",textToStr(textOf(c)));
2325 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2329 print(fst(snd(c)),depth-1);
2331 print(snd(snd(c)),depth-1);
2336 print(snd(c),depth-1);
2341 print(snd(c),depth-1);
2346 print(fst(snd(c)),depth-1);
2348 print(snd(snd(c)),depth-1);
2353 print(fst(snd(c)),depth-1);
2355 print(snd(snd(c)),depth-1);
2359 Printf("FromQual(");
2360 print(fst(snd(c)),depth-1);
2362 print(snd(snd(c)),depth-1);
2366 Printf("StgVar%d=",-c);
2367 print(snd(c), depth-1);
2371 print(fst(snd(c)),depth-1);
2373 print(snd(snd(c)),depth-1);
2378 print(fst(snd(c)),depth-1);
2380 print(snd(snd(c)),depth-1);
2385 print(fst(snd(c)),depth-1);
2387 print(snd(snd(c)),depth-1);
2391 Printf("PrimCase(");
2392 print(fst(snd(c)),depth-1);
2394 print(snd(snd(c)),depth-1);
2399 print(snd(c),depth-1);
2403 Printf("(UNBOXEDTUP,");
2404 print(snd(c),depth-1);
2409 print(zfst(c),depth-1);
2411 print(zsnd(c),depth-1);
2415 Printf("<ZTriple ");
2416 print(zfst3(c),depth-1);
2418 print(zsnd3(c),depth-1);
2420 print(zthd3(c),depth-1);
2425 print(snd(c),depth-1);
2429 if (isTagNonPtr(tag)) {
2430 Printf("(TagNP=%d,%d)", c, tag);
2431 } else if (isTagPtr(tag)) {
2432 Printf("(TagP=%d,",tag);
2433 print(snd(c), depth-1);
2436 } else if (c == tag) {
2437 Printf("Tag(%d)", c);
2439 Printf("Tag(%d)=%d", c, tag);
2448 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2449 Cell c; { /* also recognises DICTVAR cells */
2451 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2454 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2456 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2459 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2461 if (!isPair(c)) return FALSE;
2464 case VAROPCELL : return TRUE;
2466 case QUALIDENT : return isVar(snd(snd(c)));
2468 default : return FALSE;
2472 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2474 if (!isPair(c)) return FALSE;
2477 case CONOPCELL : return TRUE;
2479 case QUALIDENT : return isCon(snd(snd(c)));
2481 default : return FALSE;
2485 Bool isQualIdent(c) /* is cell a qualified identifier? */
2487 return isPair(c) && (fst(c)==QUALIDENT);
2490 Bool eqQualIdent ( QualId c1, QualId c2 )
2492 assert(isQualIdent(c1));
2493 if (!isQualIdent(c2)) {
2494 assert(isQualIdent(c2));
2496 return qmodOf(c1)==qmodOf(c2) &&
2497 qtextOf(c1)==qtextOf(c2);
2500 Bool isIdent(c) /* is cell an identifier? */
2502 if (!isPair(c)) return FALSE;
2507 case CONOPCELL : return TRUE;
2509 case QUALIDENT : return TRUE;
2511 default : return FALSE;
2515 Bool isInt(c) /* cell holds integer value? */
2517 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2520 Int intOf(c) /* find integer value of cell? */
2523 return isPair(c) ? (Int)(snd(c)) : (Int)(c-SMALL_INT_ZERO);
2526 Cell mkInt(n) /* make cell representing integer */
2528 return (SMALL_INT_MIN <= SMALL_INT_ZERO+n &&
2529 SMALL_INT_ZERO+n <= SMALL_INT_MAX)
2534 #if SIZEOF_VOID_P == SIZEOF_INT
2536 typedef union {Int i; Ptr p;} IntOrPtr;
2543 return pair(PTRCELL,x.i);
2550 assert(fst(c) == PTRCELL);
2560 return pair(CPTRCELL,x.i);
2567 assert(fst(c) == CPTRCELL);
2572 #elif SIZEOF_VOID_P == 2*SIZEOF_INT
2574 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2581 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2588 assert(fst(c) == PTRCELL);
2589 x.i.i1 = intOf(fst(snd(c)));
2590 x.i.i2 = intOf(snd(snd(c)));
2599 return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2606 assert(fst(c) == CPTRCELL);
2607 x.i.i1 = intOf(fst(snd(c)));
2608 x.i.i2 = intOf(snd(snd(c)));
2614 #error "Can't implement mkPtr/ptrOf on this architecture."
2619 String stringNegate( s )
2627 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2632 /* --------------------------------------------------------------------------
2634 * ------------------------------------------------------------------------*/
2636 Int length(xs) /* calculate length of list xs */
2639 for (; nonNull(xs); ++n)
2644 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2645 List xs, ys; { /* ys by modifying xs ... */
2650 while (nonNull(tl(zs)))
2657 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2660 for (; nonNull(xs); xs=tl(xs))
2661 ys = cons(hd(xs),ys);
2665 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2668 return revOnto(dupOnto(xs,NIL),ys);
2671 List dupList(xs) /* Duplicate spine of list xs */
2674 for (; nonNull(xs); xs=tl(xs))
2675 ys = cons(hd(xs),ys);
2679 List revOnto(xs,ys) /* Destructively reverse elements of*/
2680 List xs, ys; { /* list xs onto list ys... */
2683 while (nonNull(xs)) {
2692 QualId qualidIsMember ( QualId q, List xs )
2694 for (; nonNull(xs); xs=tl(xs)) {
2695 if (eqQualIdent(q, hd(xs)))
2701 Cell varIsMember(t,xs) /* Test if variable is a member of */
2702 Text t; /* given list of variables */
2704 for (; nonNull(xs); xs=tl(xs))
2705 if (t==textOf(hd(xs)))
2710 Name nameIsMember(t,ns) /* Test if name with text t is a */
2711 Text t; /* member of list of names xs */
2713 for (; nonNull(ns); ns=tl(ns))
2714 if (t==name(hd(ns)).text)
2719 Cell intIsMember(n,xs) /* Test if integer n is member of */
2720 Int n; /* given list of integers */
2722 for (; nonNull(xs); xs=tl(xs))
2723 if (n==intOf(hd(xs)))
2728 Cell cellIsMember(x,xs) /* Test for membership of specific */
2729 Cell x; /* cell x in list xs */
2731 for (; nonNull(xs); xs=tl(xs))
2737 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2740 for (; nonNull(xs); xs=tl(xs))
2746 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2747 Cell c; /* association lists */
2749 for (; nonNull(xs); xs=tl(xs))
2755 List replicate(n,x) /* create list of n copies of x */
2764 List diffList(from,take) /* list difference: from\take */
2765 List from, take; { /* result contains all elements of */
2766 List result = NIL; /* `from' not appearing in `take' */
2768 while (nonNull(from)) {
2769 List next = tl(from);
2770 if (!cellIsMember(hd(from),take)) {
2779 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2783 for(;nonNull(xs);xs=tl(xs)) {
2786 result=cons(x,result);
2792 List take(n,xs) /* destructively truncate list to */
2793 Int n; /* specified length */
2799 while (1<n-- && nonNull(xs))
2806 List splitAt(n,xs) /* drop n things from front of list*/
2815 Cell nth(n,xs) /* extract n'th element of list */
2818 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2825 List removeCell(x,xs) /* destructively remove cell from */
2830 return tl(xs); /* element at front of list */
2834 for (; nonNull(curr); prev=curr, curr=tl(prev))
2836 tl(prev) = tl(curr);
2837 return xs; /* element in middle of list */
2841 return xs; /* here if element not found */
2844 List nubList(xs) /* nuke dups in list */
2845 List xs; { /* non destructive */
2847 for (; nonNull(xs); xs=tl(xs))
2848 if (isNull(cellIsMember(hd(xs),outs)))
2849 outs = cons(hd(xs),outs);
2855 /* --------------------------------------------------------------------------
2856 * Tagged tuples (experimental)
2857 * ------------------------------------------------------------------------*/
2859 static void z_tag_check ( Cell x, int tag, char* caller )
2863 sprintf(buf,"z_tag_check(%s): null\n", caller);
2866 if (whatIs(x) != tag) {
2868 "z_tag_check(%s): tag was %d, expected %d\n",
2869 caller, whatIs(x), tag );
2874 Cell zpair ( Cell x1, Cell x2 )
2875 { return ap(ZTUP2,ap(x1,x2)); }
2876 Cell zfst ( Cell zpair )
2877 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2878 Cell zsnd ( Cell zpair )
2879 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2881 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2882 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2883 Cell zfst3 ( Cell zpair )
2884 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2885 Cell zsnd3 ( Cell zpair )
2886 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2887 Cell zthd3 ( Cell zpair )
2888 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2890 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2891 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2892 Cell zsel14 ( Cell zpair )
2893 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2894 Cell zsel24 ( Cell zpair )
2895 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2896 Cell zsel34 ( Cell zpair )
2897 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2898 Cell zsel44 ( Cell zpair )
2899 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2901 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2902 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2903 Cell zsel15 ( Cell zpair )
2904 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2905 Cell zsel25 ( Cell zpair )
2906 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2907 Cell zsel35 ( Cell zpair )
2908 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2909 Cell zsel45 ( Cell zpair )
2910 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2911 Cell zsel55 ( Cell zpair )
2912 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2915 Cell unap ( int tag, Cell c )
2918 if (whatIs(c) != tag) {
2919 sprintf(buf, "unap: specified %d, actual %d\n",
2926 /* --------------------------------------------------------------------------
2927 * Operations on applications:
2928 * ------------------------------------------------------------------------*/
2930 Int argCount; /* number of args in application */
2932 Cell getHead(e) /* get head cell of application */
2933 Cell e; { /* set number of args in argCount */
2934 for (argCount=0; isAp(e); e=fun(e))
2939 List getArgs(e) /* get list of arguments in function*/
2940 Cell e; { /* application: */
2941 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2943 for (as=NIL; isAp(e); e=fun(e))
2944 as = cons(arg(e),as);
2948 Cell nthArg(n,e) /* return nth arg in application */
2949 Int n; /* of function to m args (m>=n) */
2950 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2951 for (n=numArgs(e)-n-1; n>0; n--)
2956 Int numArgs(e) /* find number of arguments to expr */
2959 for (n=0; isAp(e); e=fun(e))
2964 Cell applyToArgs(f,args) /* destructively apply list of args */
2965 Cell f; /* to function f */
2967 while (nonNull(args)) {
2968 Cell temp = tl(args);
2969 tl(args) = hd(args);
2977 /* --------------------------------------------------------------------------
2979 * ------------------------------------------------------------------------*/
2981 static String maybeModuleStr ( Module m )
2983 if (isModule(m)) return textToStr(module(m).text); else return "??";
2986 static String maybeNameStr ( Name n )
2988 if (isName(n)) return textToStr(name(n).text); else return "??";
2991 static String maybeTyconStr ( Tycon t )
2993 if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
2996 static String maybeClassStr ( Class c )
2998 if (isClass(c)) return textToStr(cclass(c).text); else return "??";
3001 static String maybeText ( Text t )
3003 if (isNull(t)) return "(nil)";
3004 return textToStr(t);
3007 static void print100 ( Int x )
3009 print ( x, 100); printf("\n");
3012 void dumpTycon ( Int t )
3014 if (isTycon(TYCON_BASE_ADDR+t) && !isTycon(t)) t += TYCON_BASE_ADDR;
3016 printf ( "dumpTycon %d: not a tycon\n", t);
3020 printf ( " text: %s\n", textToStr(tycon(t).text) );
3021 printf ( " line: %d\n", tycon(t).line );
3022 printf ( " mod: %s\n", maybeModuleStr(tycon(t).mod));
3023 printf ( " tuple: %d\n", tycon(t).tuple);
3024 printf ( " arity: %d\n", tycon(t).arity);
3025 printf ( " kind: "); print100(tycon(t).kind);
3026 printf ( " what: %d\n", tycon(t).what);
3027 printf ( " defn: "); print100(tycon(t).defn);
3028 printf ( " cToT: %d %s\n", tycon(t).conToTag,
3029 maybeNameStr(tycon(t).conToTag));
3030 printf ( " tToC: %d %s\n", tycon(t).tagToCon,
3031 maybeNameStr(tycon(t).tagToCon));
3032 printf ( " itbl: %p\n", tycon(t).itbl);
3033 printf ( " nextTH: %d %s\n", tycon(t).nextTyconHash,
3034 maybeTyconStr(tycon(t).nextTyconHash));
3038 void dumpName ( Int n )
3040 if (isName(NAME_BASE_ADDR+n) && !isName(n)) n += NAME_BASE_ADDR;
3042 printf ( "dumpName %d: not a name\n", n);
3046 printf ( " text: %s\n", textToStr(name(n).text) );
3047 printf ( " line: %d\n", name(n).line );
3048 printf ( " mod: %s\n", maybeModuleStr(name(n).mod));
3049 printf ( " syntax: %d\n", name(n).syntax );
3050 printf ( " parent: %d\n", name(n).parent );
3051 printf ( " arity: %d\n", name(n).arity );
3052 printf ( " number: %d\n", name(n).number );
3053 printf ( " type: "); print100(name(n).type);
3054 printf ( " defn: %d\n", name(n).defn );
3055 printf ( " stgVar: "); print100(name(n).stgVar);
3056 printf ( " cconv: %d\n", name(n).callconv );
3057 printf ( " primop: %p\n", name(n).primop );
3058 printf ( " itbl: %p\n", name(n).itbl );
3059 printf ( " nextNH: %d\n", name(n).nextNameHash );
3064 void dumpClass ( Int c )
3066 if (isClass(CCLASS_BASE_ADDR+c) && !isClass(c)) c += CCLASS_BASE_ADDR;
3068 printf ( "dumpClass %d: not a class\n", c);
3072 printf ( " text: %s\n", textToStr(cclass(c).text) );
3073 printf ( " line: %d\n", cclass(c).line );
3074 printf ( " mod: %s\n", maybeModuleStr(cclass(c).mod));
3075 printf ( " arity: %d\n", cclass(c).arity );
3076 printf ( " level: %d\n", cclass(c).level );
3077 printf ( " kinds: "); print100( cclass(c).kinds );
3078 printf ( " fds: %d\n", cclass(c).fds );
3079 printf ( " xfds: %d\n", cclass(c).xfds );
3080 printf ( " head: "); print100( cclass(c).head );
3081 printf ( " dcon: "); print100( cclass(c).dcon );
3082 printf ( " supers: "); print100( cclass(c).supers );
3083 printf ( " #supers: %d\n", cclass(c).numSupers );
3084 printf ( " dsels: "); print100( cclass(c).dsels );
3085 printf ( " members: "); print100( cclass(c).members );
3086 printf ( "#members: %d\n", cclass(c).numMembers );
3087 printf ( "defaults: "); print100( cclass(c).defaults );
3088 printf ( " insts: "); print100( cclass(c).instances );
3093 void dumpInst ( Int i )
3095 if (isInst(INST_BASE_ADDR+i) && !isInst(i)) i += INST_BASE_ADDR;
3097 printf ( "dumpInst %d: not an instance\n", i);
3101 printf ( " class: %s\n", maybeClassStr(inst(i).c) );
3102 printf ( " line: %d\n", inst(i).line );
3103 printf ( " mod: %s\n", maybeModuleStr(inst(i).mod));
3104 printf ( " kinds: "); print100( inst(i).kinds );
3105 printf ( " head: "); print100( inst(i).head );
3106 printf ( " specs: "); print100( inst(i).specifics );
3107 printf ( " #specs: %d\n", inst(i).numSpecifics );
3108 printf ( " impls: "); print100( inst(i).implements );
3109 printf ( " builder: %s\n", maybeNameStr( inst(i).builder ) );
3114 /* --------------------------------------------------------------------------
3116 * ------------------------------------------------------------------------*/
3123 case POSTPREL: break;
3125 case RESET : clearStack();
3127 /* the next 2 statements are particularly important
3128 * if you are using GLOBALfst or GLOBALsnd since the
3129 * corresponding registers may be reset to their
3130 * uninitialised initial values by a longjump.
3132 heapTopFst = heapFst + heapSize;
3133 heapTopSnd = heapSnd + heapSize;
3137 if (isNull(lastExprSaved))
3138 savedText = TEXT_SIZE;
3143 for (i = NAME_BASE_ADDR;
3144 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3145 if (tabName[i-NAME_BASE_ADDR].inUse) {
3146 mark(name(i).parent);
3148 mark(name(i).stgVar);
3152 end("Names", nameHw-NAMEMIN);
3155 for (i = MODULE_BASE_ADDR;
3156 i < MODULE_BASE_ADDR+tabModuleSz; ++i) {
3157 if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3158 mark(module(i).tycons);
3159 mark(module(i).names);
3160 mark(module(i).classes);
3161 mark(module(i).exports);
3162 mark(module(i).qualImports);
3163 mark(module(i).objectExtraNames);
3168 mark(targetModules);
3169 end("Modules", moduleHw-MODMIN);
3172 for (i = TYCON_BASE_ADDR;
3173 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3174 if (tabTycon[i-TYCON_BASE_ADDR].inUse) {
3175 mark(tycon(i).defn);
3176 mark(tycon(i).kind);
3177 mark(tycon(i).what);
3180 end("Type constructors", tyconHw-TYCMIN);
3183 for (i = CCLASS_BASE_ADDR;
3184 i < CCLASS_BASE_ADDR+tabClassSz; ++i) {
3185 if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3186 mark(cclass(i).head);
3187 mark(cclass(i).kinds);
3188 mark(cclass(i).fds);
3189 mark(cclass(i).xfds);
3190 mark(cclass(i).dsels);
3191 mark(cclass(i).supers);
3192 mark(cclass(i).members);
3193 mark(cclass(i).defaults);
3194 mark(cclass(i).instances);
3198 end("Classes", classHw-CLASSMIN);
3201 for (i = INST_BASE_ADDR;
3202 i < INST_BASE_ADDR+tabInstSz; ++i) {
3203 if (tabInst[i-INST_BASE_ADDR].inUse) {
3205 mark(inst(i).kinds);
3206 mark(inst(i).specifics);
3207 mark(inst(i).implements);
3210 end("Instances", instHw-INSTMIN);
3213 for (i=0; i<=sp; ++i)
3218 mark(lastExprSaved);
3221 end("Last expression", 3);
3226 end("C stack", stackRoots);
3231 case PREPREL : heapFst = heapAlloc(heapSize);
3232 heapSnd = heapAlloc(heapSize);
3234 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3235 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3240 heapTopFst = heapFst + heapSize;
3241 heapTopSnd = heapSnd + heapSize;
3242 for (i=1; i<heapSize; ++i) {
3246 snd(-heapSize) = NIL;
3253 marksSize = bitArraySize(heapSize);
3254 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3255 ERRMSG(0) "Unable to allocate gc markspace"
3262 nextNewText = INVAR_BASE_ADDR;
3263 nextNewDText = INDVAR_BASE_ADDR;
3264 lastExprSaved = NIL;
3265 savedText = TEXT_SIZE;
3267 for (i=0; i<TEXTHSZ; ++i) textHash[i][0] = NOTEXT;
3268 for (i=0; i<TYCONHSZ; ++i) tyconHash[RC_T(i)] = NIL;
3269 for (i=0; i<NAMEHSZ; ++i) nameHash[RC_N(i)] = NIL;
3275 /*-------------------------------------------------------------------------*/