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/05/09 09:11:40 $
14 * ------------------------------------------------------------------------*/
16 #include "hugsbasictypes.h"
25 /*#define DEBUG_SHOWUSE*/
27 /* --------------------------------------------------------------------------
28 * local function prototypes:
29 * ------------------------------------------------------------------------*/
31 static Int local hash ( String );
32 static Int local saveText ( Text );
33 static Module local findQualifier ( Text );
34 static Void local hashTycon ( Tycon );
35 static List local insertTycon ( Tycon,List );
36 static Void local hashName ( Name );
37 static List local insertName ( Name,List );
38 static Void local patternError ( String );
39 static Bool local stringMatch ( String,String );
40 static Bool local typeInvolves ( Type,Type );
41 static Cell local markCell ( Cell );
42 static Void local markSnd ( Cell );
43 static Cell local lowLevelLastIn ( Cell );
44 static Cell local lowLevelLastOut ( Cell );
47 /* --------------------------------------------------------------------------
50 * provides storage for the characters making up identifier and symbol
51 * names, string literals, character constants etc...
53 * All character strings are stored in a large character array, with textHw
54 * pointing to the next free position. Lookup in the array is improved using
55 * a hash table. Internally, text strings are represented by integer offsets
56 * from the beginning of the array to the string in question.
58 * Where memory permits, the use of multiple hashtables gives a significant
59 * increase in performance, particularly when large source files are used.
61 * Each string in the array is terminated by a zero byte. No string is
62 * stored more than once, so that it is safe to test equality of strings by
63 * comparing the corresponding offsets.
65 * Special text values (beyond the range of the text array table) are used
66 * to generate unique `new variable names' as required.
68 * The same text storage is also used to hold text values stored in a saved
69 * expression. This grows downwards from the top of the text table (and is
70 * not included in the hash table).
71 * ------------------------------------------------------------------------*/
73 #define TEXTHSZ 512 /* Size of Text hash table */
74 #define NOTEXT ((Text)(~0)) /* Empty bucket in Text hash table */
75 static Text textHw; /* Next unused position */
76 static Text savedText = TEXT_SIZE; /* Start of saved portion of text */
77 static Text nextNewText; /* Next new text value */
78 static Text nextNewDText; /* Next new dict text value */
79 static char text[TEXT_SIZE]; /* Storage of character strings */
80 static Text textHash[TEXTHSZ][NUM_TEXTH]; /* Hash table storage */
82 String textToStr(t) /* find string corresp to given Text*/
84 static char newVar[16];
86 if (isText(t)) /* standard char string */
87 return text + t - TEXT_BASE_ADDR;
88 if (isInventedDictVar(t)) {
90 t-INDVAR_BASE_ADDR); /* dictionary variable */
93 if (isInventedVar(t)) {
95 t-INVAR_BASE_ADDR); /* normal variable */
98 internal("textToStr");
101 String identToStr(v) /*find string corresp to given ident or qualified name*/
104 internal("identToStr");
110 case CONOPCELL : return textToStr(textOf(v));
112 case QUALIDENT : { String qmod = textToStr(qmodOf(v));
113 String qtext = textToStr(qtextOf(v));
116 while (pos+1 < savedText && *qmod!=0) {
117 text[pos++] = *qmod++;
119 if (pos+1 < savedText) {
122 while (pos+1 < savedText && *qtext!=0) {
123 text[pos++] = *qtext++;
129 internal("identToStr2");
130 return 0; /* NOTREACHED */
133 Text inventText() { /* return new unused variable name */
134 if (nextNewText >= INVAR_BASE_ADDR+INVAR_MAX_AVAIL)
135 internal("inventText: too many invented variables");
136 return nextNewText++;
139 Text inventDictText() { /* return new unused dictvar name */
140 if (nextNewDText >= INDVAR_BASE_ADDR+INDVAR_MAX_AVAIL)
141 internal("inventDictText: too many invented variables");
142 return nextNewDText++;
145 Bool inventedText(t) /* Signal TRUE if text has been */
146 Text t; { /* generated internally */
147 return isInventedVar(t) || isInventedDictVar(t);
150 #define MAX_FIXLIT 100
151 Text fixLitText(t) /* fix literal text that might include \ */
153 String s = textToStr(t);
156 for(i = 0;i < MAX_FIXLIT-2 && *s;s++) {
162 if (i < MAX_FIXLIT-2) {
165 ERRMSG(0) "storage space exhausted for internal literal string"
168 return (findText(p));
172 static Int local hash(s) /* Simple hash function on strings */
176 for (v=((int)(*s))*8; *s; s++)
177 v += ((int)(*s))*(j++);
183 Text findText(s) /* Locate string in Text array */
187 Text textPos = textHash[h][hashno];
189 # define TryMatch { Text originalTextPos = textPos; \
191 for (t=s; *t==text[textPos]; textPos++,t++) \
193 return originalTextPos+TEXT_BASE_ADDR; \
195 # define Skip while (text[textPos++]) ;
197 while (textPos!=NOTEXT) {
199 if (++hashno<NUM_TEXTH) /* look in next hashtable entry */
200 textPos = textHash[h][hashno];
203 while (textPos < textHw) {
214 textPos = textHw; /* if not found, save in array */
215 if (textHw + (Int)strlen(s) + 1 > savedText) {
216 ERRMSG(0) "Character string storage space exhausted"
219 while ((text[textHw++] = *s++) != 0) {
221 if (hashno<NUM_TEXTH) { /* updating hash table as necessary */
222 textHash[h][hashno] = textPos;
223 if (hashno<NUM_TEXTH-1)
224 textHash[h][hashno+1] = NOTEXT;
227 return textPos+TEXT_BASE_ADDR;
230 static Int local saveText(t) /* Save text value in buffer */
231 Text t; { /* at top of text table */
232 String s = textToStr(t);
234 if (textHw + l + 1 > savedText) {
235 ERRMSG(0) "Character string storage space exhausted"
239 strcpy(text+savedText,s);
244 static int fromHexDigit ( char c )
247 case '0': case '1': case '2': case '3': case '4':
248 case '5': case '6': case '7': case '8': case '9':
250 case 'a': case 'A': return 10;
251 case 'b': case 'B': return 11;
252 case 'c': case 'C': return 12;
253 case 'd': case 'D': return 13;
254 case 'e': case 'E': return 14;
255 case 'f': case 'F': return 15;
261 /* returns findText (unZencode s) */
262 Text unZcodeThenFindText ( String s )
269 nn = 100 + 10 * strlen(s);
271 if (!p) internal ("unZcodeThenFindText: malloc failed");
276 if (n > nn-90) internal ("unZcodeThenFindText: result is too big");
277 if (*s != 'z' && *s != 'Z') {
282 if (!(*s)) goto parse_error;
284 case 'Z': p[n++] = 'Z'; break;
285 case 'C': p[n++] = ':'; break;
286 case 'L': p[n++] = '('; break;
287 case 'R': p[n++] = ')'; break;
288 case 'M': p[n++] = '['; break;
289 case 'N': p[n++] = ']'; break;
290 case 'z': p[n++] = 'z'; break;
291 case 'a': p[n++] = '&'; break;
292 case 'b': p[n++] = '|'; break;
293 case 'd': p[n++] = '$'; break;
294 case 'e': p[n++] = '='; break;
295 case 'g': p[n++] = '>'; break;
296 case 'h': p[n++] = '#'; break;
297 case 'i': p[n++] = '.'; break;
298 case 'l': p[n++] = '<'; break;
299 case 'm': p[n++] = '-'; break;
300 case 'n': p[n++] = '!'; break;
301 case 'p': p[n++] = '+'; break;
302 case 'q': p[n++] = '\\'; break;
303 case 'r': p[n++] = '\''; break;
304 case 's': p[n++] = '/'; break;
305 case 't': p[n++] = '*'; break;
306 case 'u': p[n++] = '^'; break;
307 case 'v': p[n++] = '%'; break;
309 if (!s[0] || !s[1]) goto parse_error;
310 if (fromHexDigit(s[0]) < 0 || fromHexDigit(s[1]) < 0) goto parse_error;
311 p[n++] = 16 * fromHexDigit(s[0]) + fromHexDigit(s[1]);
314 case '0': case '1': case '2': case '3': case '4':
315 case '5': case '6': case '7': case '8': case '9':
318 while (*s && isdigit((int)(*s))) {
319 i = 10 * i + (*s - '0');
322 if (*s != 'T') goto parse_error;
325 while (i > 0) { p[n++] = ','; i--; };
339 fprintf ( stderr, "\nstring = `%s'\n", s );
340 internal ( "unZcodeThenFindText: parse error on above string");
341 return NIL; /*notreached*/
345 Text enZcodeThenFindText ( String s )
350 char toHex[16] = "0123456789ABCDEF";
353 nn = 100 + 10 * strlen(s);
355 if (!p) internal ("enZcodeThenFindText: malloc failed");
359 if (n > nn-90) internal ("enZcodeThenFindText: result is too big");
362 && (isalnum((int)(*s)) || *s == '_')) {
370 while (*s && *s==',') { s++; tup++; };
371 if (*s != ')') internal("enZcodeThenFindText: invalid tuple type");
374 sprintf(num,"%d",tup);
375 p[n] = 0; strcat ( &(p[n]), num ); n += strlen(num);
380 case '(': p[n++] = 'Z'; p[n++] = 'L'; break;
381 case ')': p[n++] = 'Z'; p[n++] = 'R'; break;
382 case '[': p[n++] = 'Z'; p[n++] = 'M'; break;
383 case ']': p[n++] = 'Z'; p[n++] = 'N'; break;
384 case ':': p[n++] = 'Z'; p[n++] = 'C'; break;
385 case 'Z': p[n++] = 'Z'; p[n++] = 'Z'; break;
386 case 'z': p[n++] = 'z'; p[n++] = 'z'; break;
387 case '&': p[n++] = 'z'; p[n++] = 'a'; break;
388 case '|': p[n++] = 'z'; p[n++] = 'b'; break;
389 case '$': p[n++] = 'z'; p[n++] = 'd'; break;
390 case '=': p[n++] = 'z'; p[n++] = 'e'; break;
391 case '>': p[n++] = 'z'; p[n++] = 'g'; break;
392 case '#': p[n++] = 'z'; p[n++] = 'h'; break;
393 case '.': p[n++] = 'z'; p[n++] = 'i'; break;
394 case '<': p[n++] = 'z'; p[n++] = 'l'; break;
395 case '-': p[n++] = 'z'; p[n++] = 'm'; break;
396 case '!': p[n++] = 'z'; p[n++] = 'n'; break;
397 case '+': p[n++] = 'z'; p[n++] = 'p'; break;
398 case '\'': p[n++] = 'z'; p[n++] = 'q'; break;
399 case '\\': p[n++] = 'z'; p[n++] = 'r'; break;
400 case '/': p[n++] = 'z'; p[n++] = 's'; break;
401 case '*': p[n++] = 'z'; p[n++] = 't'; break;
402 case '^': p[n++] = 'z'; p[n++] = 'u'; break;
403 case '%': p[n++] = 'z'; p[n++] = 'v'; break;
404 default: s--; p[n++] = 'z'; p[n++] = 'x';
405 p[n++] = toHex[(int)(*s)/16];
406 p[n++] = toHex[(int)(*s)%16];
417 Text textOf ( Cell c )
431 fprintf(stderr, "\ntextOf: bad tag %d\n",wot );
432 internal("textOf: bad tag");
437 /* --------------------------------------------------------------------------
440 * Currently, the only attributes that we store for each Ext value is the
441 * corresponding Text label. At some later stage, we may decide to cache
442 * types, predicates, etc. here as a space saving gesture. Given that Text
443 * comparison is cheap, and that this is an experimental implementation, we
444 * will use a straightforward linear search to locate Ext values from their
445 * corresponding Text labels; a hashing scheme can be introduced later if
446 * this turns out to be a problem.
447 * ------------------------------------------------------------------------*/
450 Text DEFTABLE(tabExt,NUM_EXT); /* Storage for Ext names */
453 Ext mkExt(t) /* Allocate or find an Ext value */
459 if (extHw-EXTMIN >= NUM_EXT) {
460 ERRMSG(0) "Ext storage space exhausted"
469 /* --------------------------------------------------------------------------
470 * Expandable symbol tables. A template, which is instantiated for the name,
471 * tycon, class, instance and module tables. Also, potentially, TREX Exts.
472 * ------------------------------------------------------------------------*/
474 #ifdef DEBUG_STORAGE_EXTRA
475 static Bool debugStorageExtra = TRUE;
477 static Bool debugStorageExtra = FALSE;
481 #define EXPANDABLE_SYMBOL_TABLE(type_name,struct_name, \
482 proc_name,free_proc_name, \
483 free_list,tab_name,tab_size,err_msg, \
484 TAB_INIT_SIZE,TAB_MAX_SIZE, \
487 struct struct_name* tab_name = NULL; \
489 static type_name free_list = TAB_BASE_ADDR-1; \
491 void free_proc_name ( type_name n ) \
493 assert(TAB_BASE_ADDR <= n); \
494 assert(n < TAB_BASE_ADDR+tab_size); \
495 assert(tab_name[n-TAB_BASE_ADDR].inUse); \
496 tab_name[n-TAB_BASE_ADDR].inUse = FALSE; \
497 if (!debugStorageExtra) { \
498 tab_name[n-TAB_BASE_ADDR].nextFree = free_list; \
503 type_name proc_name ( void ) \
507 struct struct_name* newTab; \
508 struct struct_name* temp; \
510 if (free_list != TAB_BASE_ADDR-1) { \
511 type_name t = free_list; \
512 free_list = tab_name[free_list-TAB_BASE_ADDR].nextFree; \
513 assert (!(tab_name[t-TAB_BASE_ADDR].inUse)); \
514 tab_name[t-TAB_BASE_ADDR].inUse = TRUE; \
518 newSz = (tab_size == 0 ? TAB_INIT_SIZE : 2 * tab_size); \
519 if (newSz > TAB_MAX_SIZE) goto cant_allocate; \
520 newTab = malloc(newSz * sizeof(struct struct_name)); \
521 if (!newTab) goto cant_allocate; \
522 for (i = 0; i < tab_size; i++) \
523 newTab[i] = tab_name[i]; \
524 for (i = tab_size; i < newSz; i++) { \
525 newTab[i].inUse = FALSE; \
526 newTab[i].nextFree = i-1+TAB_BASE_ADDR; \
528 if (0 && debugStorageExtra) \
529 fprintf(stderr, "Expanding " #type_name \
530 "table to size %d\n", newSz ); \
531 newTab[tab_size].nextFree = TAB_BASE_ADDR-1; \
532 free_list = newSz-1+TAB_BASE_ADDR; \
536 if (temp) free(temp); \
546 EXPANDABLE_SYMBOL_TABLE(Name,strName,allocNewName,freeName,
547 nameFL,tabName,tabNameSz,
548 "Name storage space exhausted",
549 NAME_INIT_SIZE,NAME_MAX_SIZE,NAME_BASE_ADDR)
552 EXPANDABLE_SYMBOL_TABLE(Tycon,strTycon,allocNewTycon,freeTycon,
553 tyconFL,tabTycon,tabTyconSz,
554 "Type constructor storage space exhausted",
555 TYCON_INIT_SIZE,TYCON_MAX_SIZE,TYCON_BASE_ADDR)
558 EXPANDABLE_SYMBOL_TABLE(Class,strClass,allocNewClass,freeClass,
559 classFL,tabClass,tabClassSz,
560 "Class storage space exhausted",
561 CCLASS_INIT_SIZE,CCLASS_MAX_SIZE,CCLASS_BASE_ADDR)
564 EXPANDABLE_SYMBOL_TABLE(Inst,strInst,allocNewInst,freeInst,
565 instFL,tabInst,tabInstSz,
566 "Instance storage space exhausted",
567 INST_INIT_SIZE,INST_MAX_SIZE,INST_BASE_ADDR)
570 EXPANDABLE_SYMBOL_TABLE(Module,strModule,allocNewModule,freeModule,
571 moduleFL,tabModule,tabModuleSz,
572 "Module storage space exhausted",
573 MODULE_INIT_SIZE,MODULE_MAX_SIZE,MODULE_BASE_ADDR)
576 struct strName* generate_name_ref ( Cell nm )
579 nm -= NAME_BASE_ADDR;
580 assert(tabName[nm].inUse);
581 assert(isModule(tabName[nm].mod));
582 return & tabName[nm];
584 struct strTycon* generate_tycon_ref ( Cell tc )
586 assert(isTycon(tc) || isTuple(tc));
587 tc -= TYCON_BASE_ADDR;
588 assert(tabTycon[tc].inUse);
589 assert(isModule(tabTycon[tc].mod));
590 return & tabTycon[tc];
592 struct strClass* generate_cclass_ref ( Cell cl )
595 cl -= CCLASS_BASE_ADDR;
596 assert(tabClass[cl].inUse);
597 assert(isModule(tabClass[cl].mod));
598 return & tabClass[cl];
600 struct strInst* generate_inst_ref ( Cell in )
603 in -= INST_BASE_ADDR;
604 assert(tabInst[in].inUse);
605 assert(isModule(tabInst[in].mod));
606 return & tabInst[in];
608 struct strModule* generate_module_ref ( Cell mo )
610 assert(isModule(mo));
611 mo -= MODULE_BASE_ADDR;
612 assert(tabModule[mo].inUse);
613 return & tabModule[mo];
618 /* --------------------------------------------------------------------------
621 * A Tycon represents a user defined type constructor. Tycons are indexed
622 * by Text values ... a very simple hash function is used to improve lookup
623 * times. Tycon entries with the same hash code are chained together, with
624 * the most recent entry at the front of the list.
625 * ------------------------------------------------------------------------*/
627 #define TYCONHSZ 256 /* Size of Tycon hash table*/
628 static Tycon tyconHash[TYCONHSZ]; /* Hash table storage */
630 static int tHash(Text x)
633 assert(isText(x) || inventedText(x));
642 static int RC_T ( int x )
644 assert (x >= 0 && x < TYCONHSZ);
648 Tycon newTycon ( Text t ) /* add new tycon to tycon table */
651 Tycon tc = allocNewTycon();
653 [tc-TYCON_BASE_ADDR].tuple = -1;
655 [tc-TYCON_BASE_ADDR].mod = currentModule;
656 tycon(tc).text = t; /* clear new tycon record */
657 tycon(tc).kind = NIL;
658 tycon(tc).defn = NIL;
659 tycon(tc).what = NIL;
660 tycon(tc).conToTag = NIL;
661 tycon(tc).tagToCon = NIL;
662 tycon(tc).itbl = NULL;
664 tycon(tc).closure = NIL;
665 module(currentModule).tycons = cons(tc,module(currentModule).tycons);
666 tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
667 tyconHash[RC_T(h)] = tc;
671 Tycon findTycon(t) /* locate Tycon in tycon table */
673 Tycon tc = tyconHash[RC_T(tHash(t))];
674 assert(isTycon(tc) || isTuple(tc) || isNull(tc));
675 while (nonNull(tc) && tycon(tc).text!=t)
676 tc = tycon(tc).nextTyconHash;
680 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
683 assert(isTycon(tc) || isTuple(tc));
684 oldtc = findTycon(tycon(tc).text);
687 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
693 static Void local hashTycon(tc) /* Insert Tycon into hash table */
697 assert(isTycon(tc) || isTuple(tc));
698 {int i; for (i = 0; i < TYCONHSZ; i++)
699 assert (tyconHash[i] == 0
700 || isTycon(tyconHash[i])
701 || isTuple(tyconHash[i]));
705 tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
706 tyconHash[RC_T(h)] = tc;
709 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
711 if (!isPair(id)) internal("findQualTycon");
715 return findTycon(textOf(id));
717 Text t = qtextOf(id);
718 Module m = findQualifier(qmodOf(id));
720 if (isNull(m)) return NIL;
721 for(es=module(m).exports; nonNull(es); es=tl(es)) {
723 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
728 default : internal("findQualTycon2");
730 return NIL; /* NOTREACHED */
733 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
739 Tycon tc = newTycon(t);
741 tycon(tc).kind = kind;
742 tycon(tc).what = what;
743 tycon(tc).defn = defn;
744 tycon(tc).arity = ar;
748 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
753 String s = textToStr(tycon(tc).text);
755 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
756 if (hd(curr)==tc) /* just in case we get duplicates! */
762 tl(prev) = cons(tc,curr);
766 return cons(tc,curr);
769 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
770 String pat; /* to list of Tycons ts */
771 List ts; { /* Null pattern matches every tycon*/
772 Tycon tc; /* (Tycons with NIL kind excluded) */
773 for (tc = TYCON_BASE_ADDR;
774 tc < TYCON_BASE_ADDR+tabTyconSz; ++tc)
775 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
776 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
777 if (nonNull(tycon(tc).kind))
778 ts = insertTycon(tc,ts);
782 Text ghcTupleText_n ( Int n )
787 if (n < 0 || n >= 100) internal("ghcTupleText_n");
788 if (n == 1) internal("ghcTupleText_n==1");
790 for (i = 1; i <= n-1; i++) buf[x++] = ',';
793 return findText(buf);
796 Text ghcTupleText(tup)
799 assert(isTuple(tup));
801 return ghcTupleText_n ( tupleOf(tup) );
805 Tycon mkTuple ( Int n )
809 internal("mkTuple: request for tuple of unsupported size");
810 for (i = TYCON_BASE_ADDR;
811 i < TYCON_BASE_ADDR+tabTyconSz; i++)
812 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
813 if (tycon(i).tuple == n) return i;
814 internal("mkTuple: request for non-existent tuple");
818 /* --------------------------------------------------------------------------
821 * A Name represents a top level binding of a value to an identifier.
822 * Such values may be a constructor function, a member function in a
823 * class, a user-defined or primitive value/function.
825 * Names are indexed by Text values ... a very simple hash functions speeds
826 * access to the table of Names and Name entries with the same hash value
827 * are chained together, with the most recent entry at the front of the
829 * ------------------------------------------------------------------------*/
831 #define NAMEHSZ 256 /* Size of Name hash table */
832 static Name nameHash[NAMEHSZ]; /* Hash table storage */
834 static int nHash(Text x)
836 assert(isText(x) || inventedText(x));
844 assert (x >= 0 && x < NAMEHSZ);
848 void hashSanity ( void )
851 for (i = 0; i < TYCONHSZ; i++) {
854 assert(isTycon(j) || isTuple(j));
855 j = tycon(j).nextTyconHash;
858 for (i = 0; i < NAMEHSZ; i++) {
862 j = name(j).nextNameHash;
867 Name newName ( Text t, Cell parent ) /* Add new name to name table */
870 Name nm = allocNewName();
872 [nm-NAME_BASE_ADDR].mod = currentModule;
873 name(nm).text = t; /* clear new name record */
875 name(nm).syntax = NO_SYNTAX;
876 name(nm).parent = parent;
878 name(nm).number = EXECNAME;
880 name(nm).hasStrict = FALSE;
881 name(nm).callconv = NIL;
883 name(nm).primop = NULL;
884 name(nm).itbl = NULL;
885 name(nm).closure = NIL;
886 module(currentModule).names = cons(nm,module(currentModule).names);
887 name(nm).nextNameHash = nameHash[RC_N(h)];
888 nameHash[RC_N(h)] = nm;
892 Name findName(t) /* Locate name in name table */
894 Name n = nameHash[RC_N(nHash(t))];
895 assert(isText(t) || isInventedVar(t) || isInventedDictVar(t));
896 assert(isName(n) || isNull(n));
897 while (nonNull(n) && name(n).text!=t)
898 n = name(n).nextNameHash;
902 Name addName(nm) /* Insert Name in name table - if */
903 Name nm; { /* no clash is caused */
906 oldnm = findName(name(nm).text);
909 module(currentModule).names=cons(nm,module(currentModule).names);
915 static Void local hashName(nm) /* Insert Name into hash table */
922 name(nm).nextNameHash = nameHash[RC_N(h)];
923 nameHash[RC_N(h)] = nm;
926 Name findQualName(id) /* Locate (possibly qualified) name*/
927 Cell id; { /* in name table */
929 internal("findQualName");
935 return findName(textOf(id));
937 Text t = qtextOf(id);
938 Module m = findQualifier(qmodOf(id));
940 if (isNull(m)) return NIL;
941 for(es=module(m).exports; nonNull(es); es=tl(es)) {
943 if (isName(e) && name(e).text==t)
945 else if (isPair(e) && DOTDOT==snd(e)) {
946 List subentities = NIL;
949 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
950 subentities = tycon(c).defn;
952 subentities = cclass(c).members;
953 for(; nonNull(subentities); subentities=tl(subentities)) {
954 if (!isName(hd(subentities)))
955 internal("findQualName3");
956 if (name(hd(subentities)).text == t)
957 return hd(subentities);
963 default : internal("findQualName2");
965 return 0; /* NOTREACHED */
969 void* /* StgClosure* */ getHugs_BCO_cptr_for ( char* s )
971 Text t = findText(s);
973 for (n = NAME_BASE_ADDR;
974 n < NAME_BASE_ADDR+tabNameSz; n++)
975 if (tabName[n-NAME_BASE_ADDR].inUse && name(n).text == t)
977 if (n == NAME_BASE_ADDR+tabNameSz) {
978 fprintf ( stderr, "can't find `%s' in ...\n", s );
979 internal("getHugs_BCO_cptr_for(1)");
981 if (!isCPtr(name(n).closure))
982 internal("getHugs_BCO_cptr_for(2)");
983 return cptrOf(name(n).closure);
986 /* --------------------------------------------------------------------------
987 * Primitive functions:
988 * ------------------------------------------------------------------------*/
990 Module findFakeModule ( Text t )
992 Module m = findModule(t);
994 if (!module(m).fake) internal("findFakeModule");
997 module(m).fake = TRUE;
1003 Name addWiredInBoxingTycon
1004 ( String modNm, String typeNm, String constrNm,
1005 Int rep, Kind kind )
1009 Text modT = findText(modNm);
1010 Text typeT = findText(typeNm);
1011 Text conT = findText(constrNm);
1012 Module m = findFakeModule(modT);
1015 n = newName(conT,NIL);
1017 name(n).number = cfunNo(0);
1019 name(n).primop = (void*)rep;
1021 t = newTycon(typeT);
1022 tycon(t).what = DATATYPE;
1023 tycon(t).kind = kind;
1028 Tycon addTupleTycon ( Int n )
1036 for (i = TYCON_BASE_ADDR;
1037 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1038 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
1039 if (tycon(i).tuple == n) return i;
1042 m = findFakeModule(findText(n==0 ? "PrelBase" : "PrelTup")); else
1043 m = findModule(findText("PrelPrim"));
1047 for (i = 0; i < n; i++) k = ap(STAR,k);
1048 t = newTycon(ghcTupleText_n(n));
1051 tycon(t).what = DATATYPE;
1054 /* maybe we want to do this for all n ? */
1055 nm = newName(ghcTupleText_n(n), t);
1056 name(nm).type = t; /* ummm ... for n > 0 */
1063 Tycon addWiredInEnumTycon ( String modNm, String typeNm,
1064 List /*of Text*/ constrs )
1068 Text modT = findText(modNm);
1069 Text typeT = findText(typeNm);
1070 Module m = findFakeModule(modT);
1073 t = newTycon(typeT);
1074 tycon(t).kind = STAR;
1075 tycon(t).what = DATATYPE;
1077 constrs = reverse(constrs);
1078 i = length(constrs);
1079 for (; nonNull(constrs); constrs=tl(constrs),i--) {
1080 Text conT = hd(constrs);
1081 Name con = newName(conT,t);
1082 name(con).number = cfunNo(i);
1084 name(con).parent = t;
1085 tycon(t).defn = cons(con, tycon(t).defn);
1091 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
1092 Text t; /* sets rep, not type */
1095 Int rep; { /* Really AsmRep */
1096 Name n = newName(t,NIL);
1097 name(n).arity = arity;
1098 name(n).number = cfunNo(no);
1100 name(n).primop = (void*)rep;
1105 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
1110 Name n = newName(t,NIL);
1111 name(n).arity = arity;
1112 name(n).number = cfunNo(no);
1113 name(n).type = type;
1118 Int sfunPos(s,c) /* Find position of field with */
1119 Name s; /* selector s in constructor c. */
1123 for (; nonNull(cns); cns=tl(cns))
1124 if (fst(hd(cns))==c)
1125 return intOf(snd(hd(cns)));
1126 internal("sfunPos");
1127 return 0;/* NOTREACHED */
1130 static List local insertName(nm,ns) /* insert name nm into sorted list */
1135 String s = textToStr(name(nm).text);
1137 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
1138 if (hd(curr)==nm) /* just in case we get duplicates! */
1143 if (nonNull(prev)) {
1144 tl(prev) = cons(nm,curr);
1148 return cons(nm,curr);
1151 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
1152 String pat; /* to list of names ns */
1153 List ns; { /* Null pattern matches every name */
1154 Name nm; /* (Names with NIL type, or hidden */
1155 /* or invented names are excluded) */
1157 for (nm = NAME_BASE_ADDR;
1158 nm < NAME_BASE_ADDR+tabNameSz; ++nm)
1159 if (tabName[nm-NAME_BASE_ADDR].inUse) {
1160 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
1161 String str = textToStr(name(nm).text);
1162 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1163 ns = insertName(nm,ns);
1168 List mns = module(currentModule).names;
1169 for(; nonNull(mns); mns=tl(mns)) {
1171 if (!inventedText(name(nm).text)) {
1172 String str = textToStr(name(nm).text);
1173 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1174 ns = insertName(nm,ns);
1181 /* --------------------------------------------------------------------------
1182 * A simple string matching routine
1183 * `*' matches any sequence of zero or more characters
1184 * `?' matches any single character exactly
1185 * `@str' matches the string str exactly (ignoring any special chars)
1186 * `\c' matches the character c only (ignoring special chars)
1187 * c matches the character c only
1188 * ------------------------------------------------------------------------*/
1190 static Void local patternError(s) /* report error in pattern */
1192 ERRMSG(0) "%s in pattern", s
1196 static Bool local stringMatch(pat,str) /* match string against pattern */
1202 case '\0' : return (*str=='\0');
1205 if (stringMatch(pat+1,str))
1210 case '?' : if (*str++=='\0')
1215 case '[' : { Bool found = FALSE;
1216 while (*++pat!='\0' && *pat!=']')
1217 if (!found && ( pat[0] == *str ||
1226 patternError("missing `]'");
1234 case '\\' : if (*++pat == '\0')
1235 patternError("extra trailing `\\'");
1237 default : if (*pat++ != *str++)
1243 /* --------------------------------------------------------------------------
1244 * Storage of type classes, instances etc...:
1245 * ------------------------------------------------------------------------*/
1247 static List classes; /* list of classes in current scope */
1249 Class newClass ( Text t ) /* add new class to class table */
1251 Class cl = allocNewClass();
1253 [cl-CCLASS_BASE_ADDR].mod = currentModule;
1254 cclass(cl).text = t;
1255 cclass(cl).arity = 0;
1256 cclass(cl).kinds = NIL;
1257 cclass(cl).head = NIL;
1258 cclass(cl).fds = NIL;
1259 cclass(cl).xfds = NIL;
1260 cclass(cl).dcon = NIL;
1261 cclass(cl).supers = NIL;
1262 cclass(cl).dsels = NIL;
1263 cclass(cl).members = NIL;
1264 cclass(cl).defaults = NIL;
1265 cclass(cl).instances = NIL;
1266 classes = cons(cl,classes);
1267 module(currentModule).classes
1268 = cons(cl,module(currentModule).classes);
1272 Class findClass(t) /* look for named class in table */
1276 for (cs=classes; nonNull(cs); cs=tl(cs)) {
1278 if (cclass(cl).text==t)
1284 Class addClass(c) /* Insert Class in class list */
1285 Class c; { /* - if no clash caused */
1287 assert(whatIs(c)==CLASS);
1288 oldc = findClass(cclass(c).text);
1290 classes=cons(c,classes);
1291 module(currentModule).classes=cons(c,module(currentModule).classes);
1298 Class findQualClass(c) /* Look for (possibly qualified) */
1299 Cell c; { /* class in class list */
1300 if (!isQualIdent(c)) {
1301 return findClass(textOf(c));
1303 Text t = qtextOf(c);
1304 Module m = findQualifier(qmodOf(c));
1308 for (es=module(m).exports; nonNull(es); es=tl(es)) {
1310 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
1317 Inst newInst() { /* Add new instance to table */
1318 Inst in = allocNewInst();
1320 [in-INST_BASE_ADDR].mod = currentModule;
1321 inst(in).kinds = NIL;
1322 inst(in).head = NIL;
1323 inst(in).specifics = NIL;
1324 inst(in).numSpecifics = 0;
1325 inst(in).implements = NIL;
1326 inst(in).builder = NIL;
1331 extern Void printInst ( Inst));
1335 Class cl = inst(in).c;
1336 Printf("%s-", textToStr(cclass(cl).text));
1337 printType(stdout,inst(in).t);
1339 #endif /* DEBUG_DICTS */
1341 Inst findFirstInst(tc) /* look for 1st instance involving */
1342 Tycon tc; { /* the type constructor tc */
1343 return findNextInst(tc,INST_BASE_ADDR-1);
1346 Inst findNextInst(tc,in) /* look for next instance involving*/
1347 Tycon tc; /* the type constructor tc */
1348 Inst in; { /* starting after instance in */
1350 while (++in < INST_BASE_ADDR+tabInstSz) {
1351 if (!tabInst[in-INST_BASE_ADDR].inUse) continue;
1352 assert(isModule(inst(in).mod));
1354 for (; isAp(pi); pi=fun(pi))
1355 if (typeInvolves(arg(pi),tc))
1361 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1362 Type ty; /* type constructor/tuple tc. */
1365 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1366 || typeInvolves(arg(ty),tc)));
1370 /* Needed by finishGHCInstance to find classes, before the
1371 export list has been built -- so we can't use
1374 Class findQualClassWithoutConsultingExportList ( QualId q )
1384 t_class = textOf(q);
1387 t_class = qtextOf(q);
1390 for (cl = CCLASS_BASE_ADDR;
1391 cl < CCLASS_BASE_ADDR+tabClassSz; cl++) {
1392 if (tabClass[cl-CCLASS_BASE_ADDR].inUse)
1393 if (cclass(cl).text == t_class) {
1394 /* Class name is ok, but is this the right module? */
1395 if (isNull(t_mod) /* no module name specified */
1397 && t_mod == module(cclass(cl).mod).text)
1405 /* Same deal, except for Tycons. */
1406 Tycon findQualTyconWithoutConsultingExportList ( QualId q )
1416 t_tycon = textOf(q);
1419 t_tycon = qtextOf(q);
1422 for (tc = TYCON_BASE_ADDR;
1423 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1424 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1425 if (tycon(tc).text == t_tycon) {
1426 /* Tycon name is ok, but is this the right module? */
1427 if (isNull(t_mod) /* no module name specified */
1429 && t_mod == module(tycon(tc).mod).text)
1437 /* Same deal, except for Names. */
1438 Name findQualNameWithoutConsultingExportList ( QualId q )
1444 assert(isQVar(q) || isQCon(q));
1446 if (isCon(q) || isVar(q)) {
1451 t_name = qtextOf(q);
1454 for (nm = NAME_BASE_ADDR;
1455 nm < NAME_BASE_ADDR+tabNameSz; nm++) {
1456 if (tabName[nm-NAME_BASE_ADDR].inUse)
1457 if (name(nm).text == t_name) {
1458 /* Name is ok, but is this the right module? */
1459 if (isNull(t_mod) /* no module name specified */
1461 && t_mod == module(name(nm).mod).text)
1470 Tycon findTyconInAnyModule ( Text t )
1473 for (tc = TYCON_BASE_ADDR;
1474 tc < TYCON_BASE_ADDR+tabTyconSz; tc++)
1475 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1476 if (tycon(tc).text == t) return tc;
1480 Class findClassInAnyModule ( Text t )
1483 for (cc = CCLASS_BASE_ADDR;
1484 cc < CCLASS_BASE_ADDR+tabClassSz; cc++)
1485 if (tabClass[cc-CCLASS_BASE_ADDR].inUse)
1486 if (cclass(cc).text == t) return cc;
1490 Name findNameInAnyModule ( Text t )
1493 for (nm = NAME_BASE_ADDR;
1494 nm < NAME_BASE_ADDR+tabNameSz; nm++)
1495 if (tabName[nm-NAME_BASE_ADDR].inUse)
1496 if (name(nm).text == t) return nm;
1501 /* returns List of QualId */
1502 List getAllKnownTyconsAndClasses ( void )
1507 for (tc = TYCON_BASE_ADDR;
1508 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1509 if (tabTycon[tc-TYCON_BASE_ADDR].inUse) {
1510 /* almost certainly undue paranoia about duplicate avoidance */
1511 QualId q = mkQCon( module(tycon(tc).mod).text, tycon(tc).text );
1512 if (!qualidIsMember(q,xs))
1513 xs = cons ( q, xs );
1516 for (nw = CCLASS_BASE_ADDR;
1517 nw < CCLASS_BASE_ADDR+tabClassSz; nw++) {
1518 if (tabClass[nw-CCLASS_BASE_ADDR].inUse) {
1519 QualId q = mkQCon( module(cclass(nw).mod).text, cclass(nw).text );
1520 if (!qualidIsMember(q,xs))
1521 xs = cons ( q, xs );
1527 Int numQualifiers ( Type t )
1529 if (isPolyType(t)) t = monotypeOf(t);
1531 return length ( fst(snd(t)) ); else
1536 /* Purely for debugging. */
1537 void locateSymbolByName ( Text t )
1540 for (i = NAME_BASE_ADDR;
1541 i < NAME_BASE_ADDR+tabNameSz; i++)
1542 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).text == t)
1543 fprintf ( stderr, "name(%d)\n", i-NAME_BASE_ADDR);
1544 for (i = TYCON_BASE_ADDR;
1545 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1546 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).text == t)
1547 fprintf ( stderr, "tycon(%d)\n", i-TYCON_BASE_ADDR);
1548 for (i = CCLASS_BASE_ADDR;
1549 i < CCLASS_BASE_ADDR+tabClassSz; i++)
1550 if (tabClass[i-CCLASS_BASE_ADDR].inUse && cclass(i).text == t)
1551 fprintf ( stderr, "class(%d)\n", i-CCLASS_BASE_ADDR);
1554 /* --------------------------------------------------------------------------
1557 * Various parts of the system use a stack of cells. Most of the stack
1558 * operations are defined as macros, expanded inline.
1559 * ------------------------------------------------------------------------*/
1561 Cell cellStack[NUM_STACK]; /* Storage for cells on stack */
1562 StackPtr sp; /* stack pointer */
1564 Void hugsStackOverflow() { /* Report stack overflow */
1565 ERRMSG(0) "Control stack overflow"
1570 /* --------------------------------------------------------------------------
1573 * A Module represents a user defined module.
1575 * Note: there are now two lookup mechanisms in the system:
1577 * 1) The exports from a module are stored in a big list.
1578 * We resolve qualified names, and import lists by linearly scanning
1579 * through this list.
1581 * 2) Unqualified imports and local definitions for the current module
1582 * are stored in hash tables (tyconHash and nameHash) or linear lists
1585 * ------------------------------------------------------------------------*/
1587 Module currentModule; /* Module currently being processed*/
1589 Bool isValidModule(m) /* is m a legitimate module id? */
1594 Module newModule ( Text t ) /* add new module to module table */
1596 Module mod = allocNewModule();
1597 module(mod).text = t; /* clear new module record */
1599 module(mod).tycons = NIL;
1600 module(mod).names = NIL;
1601 module(mod).classes = NIL;
1602 module(mod).exports = NIL;
1603 module(mod).qualImports = NIL;
1604 module(mod).codeList = NIL;
1605 module(mod).fake = FALSE;
1607 module(mod).tree = NIL;
1608 module(mod).completed = FALSE;
1609 module(mod).lastStamp = 0; /* ???? */
1611 module(mod).mode = NIL;
1612 module(mod).srcExt = findText("");
1613 module(mod).uses = NIL;
1615 module(mod).objName = findText("");
1616 module(mod).objSize = 0;
1618 module(mod).object = NULL;
1619 module(mod).objectExtras = NULL;
1620 module(mod).objectExtraNames = NIL;
1625 Bool nukeModule_needs_major_gc = TRUE;
1627 void nukeModule ( Module m )
1633 if (!isModule(m)) internal("nukeModule");
1635 /* fprintf ( stderr, "NUKE MODULE %s\n", textToStr(module(m).text) ); */
1637 /* see comment in compiler.c about this,
1638 and interaction with info tables */
1639 if (nukeModule_needs_major_gc) {
1640 /* fprintf ( stderr, "doing major GC in nukeModule\n"); */
1641 /* performMajorGC(); */
1642 nukeModule_needs_major_gc = FALSE;
1645 oc = module(m).object;
1651 oc = module(m).objectExtras;
1658 for (i = NAME_BASE_ADDR; i < NAME_BASE_ADDR+tabNameSz; i++)
1659 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).mod == m) {
1661 module(name(i).mod).mode == FM_SOURCE) {
1664 name(i).itbl = NULL;
1665 name(i).closure = NIL;
1669 for (i = TYCON_BASE_ADDR; i < TYCON_BASE_ADDR+tabTyconSz; i++)
1670 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).mod == m) {
1671 if (tycon(i).itbl &&
1672 module(tycon(i).mod).mode == FM_SOURCE) {
1673 free(tycon(i).itbl);
1675 tycon(i).itbl = NULL;
1679 for (i = CCLASS_BASE_ADDR; i < CCLASS_BASE_ADDR+tabClassSz; i++)
1680 if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
1681 if (cclass(i).mod == m) {
1684 List /* Inst */ ins;
1685 List /* Inst */ ins2 = NIL;
1686 for (ins = cclass(i).instances; nonNull(ins); ins=tl(ins))
1687 if (inst(hd(ins)).mod != m)
1688 ins2 = cons(hd(ins),ins2);
1689 cclass(i).instances = ins2;
1694 for (i = INST_BASE_ADDR; i < INST_BASE_ADDR+tabInstSz; i++)
1695 if (tabInst[i-INST_BASE_ADDR].inUse && inst(i).mod == m)
1699 //for (i = 0; i < TYCONHSZ; i++) tyconHash[i] = 0;
1700 //for (i = 0; i < NAMEHSZ; i++) nameHash[i] = 0;
1705 void ppModules ( void )
1708 fflush(stderr); fflush(stdout);
1709 printf ( "begin MODULES\n" );
1710 for (i = MODULE_BASE_ADDR+tabModuleSz-1;
1711 i >= MODULE_BASE_ADDR; i--)
1712 if (tabModule[i-MODULE_BASE_ADDR].inUse)
1713 printf ( " %2d: %16s\n",
1714 i-MODULE_BASE_ADDR, textToStr(module(i).text)
1716 printf ( "end MODULES\n" );
1717 fflush(stderr); fflush(stdout);
1721 Module findModule(t) /* locate Module in module table */
1724 for(m = MODULE_BASE_ADDR;
1725 m < MODULE_BASE_ADDR+tabModuleSz; ++m) {
1726 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1727 if (module(m).text==t)
1733 Module findModid(c) /* Find module by name or filename */
1735 switch (whatIs(c)) {
1736 case STRCELL : internal("findModid-STRCELL unimp");
1737 case CONIDCELL : return findModule(textOf(c));
1738 default : internal("findModid");
1740 return NIL;/*NOTUSED*/
1743 static local Module findQualifier(t) /* locate Module in import list */
1746 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1747 if (textOf(fst(hd(ms)))==t)
1750 if (module(currentModule).text==t)
1751 return currentModule;
1755 Void setCurrModule(m) /* set lookup tables for current module */
1758 assert(isModule(m));
1759 /* fprintf(stderr, "SET CURR MODULE %s %d\n", textToStr(module(m).text),m); */
1761 for (t = module(m).names; nonNull(t); t=tl(t))
1762 assert(isName(hd(t)));
1763 for (t = module(m).tycons; nonNull(t); t=tl(t))
1764 assert(isTycon(hd(t)) || isTuple(hd(t)));
1765 for (t = module(m).classes; nonNull(t); t=tl(t))
1766 assert(isClass(hd(t)));
1769 currentModule = m; /* This is the only assignment to currentModule */
1770 for (i=0; i<TYCONHSZ; ++i)
1771 tyconHash[RC_T(i)] = NIL;
1772 mapProc(hashTycon,module(m).tycons);
1773 for (i=0; i<NAMEHSZ; ++i)
1774 nameHash[RC_N(i)] = NIL;
1775 mapProc(hashName,module(m).names);
1776 classes = module(m).classes;
1780 void addToCodeList ( Module m, Cell c )
1782 assert(isName(c) || isTuple(c));
1783 if (nonNull(getNameOrTupleClosure(c)))
1784 module(m).codeList = cons ( c, module(m).codeList );
1785 /* fprintf ( stderr, "addToCodeList %s %s\n",
1786 textToStr(module(m).text),
1787 textToStr( isTuple(c) ? tycon(c).text : name(c).text ) );
1791 Cell getNameOrTupleClosure ( Cell c )
1793 if (isName(c)) return name(c).closure;
1794 else if (isTuple(c)) return tycon(c).closure;
1795 else internal("getNameOrTupleClosure");
1798 void setNameOrTupleClosure ( Cell c, Cell closure )
1800 if (isName(c)) name(c).closure = closure;
1801 else if (isTuple(c)) tycon(c).closure = closure;
1802 else internal("setNameOrTupleClosure");
1805 /* This function is used in ghc/rts/Assembler.c. */
1806 void* /* StgClosure* */ getNameOrTupleClosureCPtr ( Cell c )
1808 return cptrOf(getNameOrTupleClosure(c));
1811 /* used in codegen.c */
1812 void setNameOrTupleClosureCPtr ( Cell c, void* /* StgClosure* */ cptr )
1814 if (isName(c)) name(c).closure = mkCPtr(cptr);
1815 else if (isTuple(c)) tycon(c).closure = mkCPtr(cptr);
1816 else internal("setNameOrTupleClosureCPtr");
1821 Name jrsFindQualName ( Text mn, Text sn )
1826 for (m = MODULE_BASE_ADDR;
1827 m < MODULE_BASE_ADDR+tabModuleSz; m++)
1828 if (tabModule[m-MODULE_BASE_ADDR].inUse
1829 && module(m).text == mn) break;
1831 if (m == MODULE_BASE_ADDR+tabModuleSz) return NIL;
1833 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1834 if (name(hd(ns)).text == sn) return hd(ns);
1840 char* nameFromOPtr ( void* p )
1844 for (m = MODULE_BASE_ADDR;
1845 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1846 if (tabModule[m-MODULE_BASE_ADDR].inUse && module(m).object) {
1847 char* nm = ocLookupAddr ( module(m).object, p );
1852 /* A kludge to assist Win32 debugging; not actually necessary. */
1853 { char* nm = nameFromStaticOPtr(p);
1861 void* lookupOTabName ( Module m, char* sym )
1863 assert(isModule(m));
1864 if (module(m).object)
1865 return ocLookupSym ( module(m).object, sym );
1870 void* lookupOExtraTabName ( char* sym )
1874 for (m = MODULE_BASE_ADDR;
1875 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1876 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1877 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1878 void* ad = ocLookupSym ( oc, sym );
1886 /* Only call this if in dire straits; searches every object symtab
1887 in the system -- so is therefore slow.
1889 void* lookupOTabNameAbsolutelyEverywhere ( char* sym )
1894 for (m = MODULE_BASE_ADDR;
1895 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1896 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1897 if (module(m).object) {
1898 ad = ocLookupSym ( module(m).object, sym );
1901 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1902 ad = ocLookupSym ( oc, sym );
1911 OSectionKind lookupSection ( void* ad )
1918 for (m = MODULE_BASE_ADDR;
1919 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1920 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1921 if (module(m).object) {
1922 sect = ocLookupSection ( module(m).object, ad );
1923 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1926 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1927 sect = ocLookupSection ( oc, ad );
1928 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1933 return HUGS_SECTIONKIND_OTHER;
1937 /* Called by the evaluator's GC to tell Hugs to mark stuff in the
1940 void markHugsObjects( void )
1945 for ( nm = NAME_BASE_ADDR;
1946 nm < NAME_BASE_ADDR+tabNameSz; ++nm ) {
1947 if (tabName[nm-NAME_BASE_ADDR].inUse) {
1948 Cell cl = name(nm).closure;
1951 snd(cl) = (Cell)MarkRoot ( (StgClosure*)(snd(cl)) );
1956 for ( tc = TYCON_BASE_ADDR;
1957 tc < TYCON_BASE_ADDR+tabTyconSz; ++tc ) {
1958 if (tabTycon[tc-TYCON_BASE_ADDR].inUse) {
1959 Cell cl = tycon(tc).closure;
1962 snd(cl) = (Cell)MarkRoot ( (StgClosure*)(snd(cl)) );
1970 /* --------------------------------------------------------------------------
1973 * Provides a garbage collectable heap for storage of expressions etc.
1975 * Now incorporates a flat resource: A two-space collected extension of
1976 * the heap that provides storage for contiguous arrays of Cell storage,
1977 * cooperating with the garbage collection mechanisms for the main heap.
1978 * ------------------------------------------------------------------------*/
1980 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1981 Heap heapFst; /* array of fst component of pairs */
1982 Heap heapSnd; /* array of snd component of pairs */
1985 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1986 /* C stack; use with extreme care! */
1989 Int numGcs; /* number of garbage collections */
1990 Int cellsRecovered; /* number of cells recovered */
1992 static Cell freeList; /* free list of unused cells */
1993 static Cell lsave, rsave; /* save components of pair */
1997 static Int markCount, stackRoots;
1999 #define initStackRoots() stackRoots = 0
2000 #define recordStackRoot() stackRoots++
2013 #define start() markCount = 0
2014 #define end(thing,rs) \
2016 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
2019 #define recordMark() markCount++
2021 #else /* !GC_STATISTICS */
2026 #define initStackRoots()
2027 #define recordStackRoot()
2030 #define end(thing,root)
2031 #define recordMark()
2033 #endif /* !GC_STATISTICS */
2035 Cell pair(l,r) /* Allocate pair (l, r) from */
2036 Cell l, r; { /* heap, garbage collecting first */
2037 Cell c = freeList; /* if necessary ... */
2048 freeList = snd(freeList);
2056 static Int marksSize;
2058 void mark ( Cell root )
2061 Cell mstack[NUM_MSTACK];
2065 mstack[++msp] = root;
2068 if (msp > msp_max) msp_max = msp;
2070 if (!isGenPair(c)) continue;
2071 if (fst(c)==FREECELL) continue;
2073 register int place = placeInSet(c);
2074 register int mask = maskInSet(c);
2075 if (!(marks[place]&mask)) {
2076 marks[place] |= mask;
2077 if (msp >= NUM_MSTACK-5) {
2079 "hugs: fatal stack overflow during GC. "
2080 "Increase NUM_MSTACK.\n" );
2083 mstack[++msp] = fst(c);
2084 mstack[++msp] = snd(c);
2088 // fprintf(stderr, "%d ",msp_max);
2092 Void garbageCollect() { /* Run garbage collector ... */
2093 /* disable break checking */
2098 jmp_buf regs; /* save registers on stack */
2099 HugsBreakAction oldBrk
2100 = setBreakAction ( HugsIgnoreBreak );
2106 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
2109 everybody(MARK); /* Mark all components of system */
2111 gcScanning(); /* scan mark set */
2118 for (i=1; i<=heapSize; i++) {
2119 if ((marks[place] & mask) == 0) {
2126 if (++j == bitsPerWord) {
2133 gcRecovered(recovered);
2134 setBreakAction ( oldBrk );
2138 #if defined(DEBUG_STORAGE) || defined(DEBUG_STORAGE_EXTRA)
2139 /* fprintf(stderr, "\n--- GC recovered %d\n",recovered ); */
2142 /* can only return if freeList is nonempty on return. */
2143 if (recovered<minRecovery || isNull(freeList)) {
2144 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
2147 cellsRecovered = recovered;
2150 /* --------------------------------------------------------------------------
2151 * Code for saving last expression entered:
2153 * This is a little tricky because some text values (e.g. strings or variable
2154 * names) may not be defined or have the same value when the expression is
2155 * recalled. These text values are therefore saved in the top portion of
2157 * ------------------------------------------------------------------------*/
2159 static Cell lastExprSaved; /* last expression to be saved */
2161 Void setLastExpr(e) /* save expression for later recall*/
2163 lastExprSaved = NIL; /* in case attempt to save fails */
2164 savedText = TEXT_SIZE;
2165 lastExprSaved = lowLevelLastIn(e);
2168 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
2169 Cell c; { /* acyclic graph) for later recall */
2170 if (isPair(c)) { /* Duplicating any text strings */
2171 if (isTagNonPtr(fst(c))) /* in case these are lost at some */
2172 switch (fst(c)) { /* point before the expr is reused */
2178 case STRCELL : return pair(fst(c),saveText(textOf(c)));
2179 default : return pair(fst(c),snd(c));
2182 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2186 return pair(EXTCOPY,saveText(extText(c)));
2192 Cell getLastExpr() { /* recover previously saved expr */
2193 return lowLevelLastOut(lastExprSaved);
2196 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
2197 Cell c; { /* except that Cells refering to */
2198 if (isPair(c)) { /* Text values are restored to */
2199 if (isTagNonPtr(fst(c))) /* appropriate values */
2206 case STRCELL : return pair(fst(c),
2207 findText(text+intValOf(c)));
2209 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
2211 default : return pair(fst(c),snd(c));
2214 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2220 /* --------------------------------------------------------------------------
2221 * Miscellaneous operations on heap cells:
2222 * ------------------------------------------------------------------------*/
2224 /* Reordered 2 May 00 to have most common options first. */
2225 Cell whatIs ( register Cell c )
2228 register Cell fstc = fst(c);
2229 return isTag(fstc) ? fstc : AP;
2231 if (isTycon(c)) return TYCON;
2232 if (isOffset(c)) return OFFSET;
2233 if (isName(c)) return NAME;
2234 if (isInt(c)) return INTCELL;
2235 if (isTuple(c)) return TUPLE;
2236 if (isSpec(c)) return c;
2237 if (isClass(c)) return CLASS;
2238 if (isChar(c)) return CHARCELL;
2239 if (isNull(c)) return c;
2240 if (isInst(c)) return INSTANCE;
2241 if (isModule(c)) return MODULE;
2242 if (isText(c)) return TEXTCELL;
2243 if (isInventedVar(c)) return INVAR;
2244 if (isInventedDictVar(c)) return INDVAR;
2245 fprintf ( stderr, "whatIs: unknown %d\n", c );
2251 /* A very, very simple printer.
2252 * Output is uglier than from printExp - but the printer is more
2253 * robust and can be used on any data structure irrespective of
2256 Void print ( Cell c, Int depth )
2261 else if (isNull(c)) {
2264 else if (isTagPtr(c)) {
2265 Printf("TagP(%d)", c);
2267 else if (isTagNonPtr(c)) {
2268 Printf("TagNP(%d)", c);
2270 else if (isSpec(c) && c != STAR) {
2271 Printf("TagS(%d)", c);
2273 else if (isText(c)) {
2274 Printf("text(%d)=\"%s\"",c-TEXT_BASE_ADDR,textToStr(c));
2276 else if (isInventedVar(c)) {
2277 Printf("invented(%d)", c-INVAR_BASE_ADDR);
2279 else if (isInventedDictVar(c)) {
2280 Printf("inventedDict(%d)",c-INDVAR_BASE_ADDR);
2283 Int tag = whatIs(c);
2287 print(fst(c), depth-1);
2289 print(snd(c), depth-1);
2293 Printf("free(%d)", c);
2296 Printf("int(%d)", intOf(c));
2299 Printf("bignum(%s)", bignumToString(c));
2302 Printf("char('%c')", charOf(c));
2305 Printf("strcell(\"%s\")",textToStr(snd(c)));
2308 Printf("mptr(%p)",mptrOf(c));
2311 Printf("cptr(%p)",cptrOf(c));
2314 Printf("addr(%p)",addrOf(c));
2317 Printf("class(%d)", c-CCLASS_BASE_ADDR);
2318 Printf("=\"%s\"", textToStr(cclass(c).text));
2321 Printf("instance(%d)", c - INST_BASE_ADDR);
2324 Printf("name(%d)", c-NAME_BASE_ADDR);
2325 Printf("=\"%s\"", textToStr(name(c).text));
2328 Printf("tycon(%d)", c-TYCON_BASE_ADDR);
2329 Printf("=\"%s\"", textToStr(tycon(c).text));
2332 Printf("module(%d)", c - MODULE_BASE_ADDR);
2333 Printf("=\"%s\"", textToStr(module(c).text));
2336 Printf("Offset %d", offsetOf(c));
2339 Printf("%s", textToStr(ghcTupleText(c)));
2343 print(snd(c),depth-1);
2347 print(snd(c),depth-1);
2351 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2352 Printf("%d ", intOf(fst(snd(c))));
2353 print(snd(snd(c)),depth-1);
2355 print(snd(c),depth-1);
2369 Printf("{dict %d}",textOf(c));
2375 Printf("{id %s}",textToStr(textOf(c)));
2379 Printf("{ip %s}",textToStr(textOf(c)));
2382 Printf("?%s",textToStr(textOf(c)));
2386 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2390 print(fst(snd(c)),depth-1);
2392 print(snd(snd(c)),depth-1);
2397 print(snd(c),depth-1);
2402 print(snd(c),depth-1);
2407 print(fst(snd(c)),depth-1);
2409 print(snd(snd(c)),depth-1);
2414 print(fst(snd(c)),depth-1);
2416 print(snd(snd(c)),depth-1);
2420 Printf("FromQual(");
2421 print(fst(snd(c)),depth-1);
2423 print(snd(snd(c)),depth-1);
2427 Printf("StgVar%d=",-c);
2428 print(snd(c), depth-1);
2432 print(fst(snd(c)),depth-1);
2434 print(snd(snd(c)),depth-1);
2439 print(fst(snd(c)),depth-1);
2441 print(snd(snd(c)),depth-1);
2446 print(fst(snd(c)),depth-1);
2448 print(snd(snd(c)),depth-1);
2452 Printf("PrimCase(");
2453 print(fst(snd(c)),depth-1);
2455 print(snd(snd(c)),depth-1);
2460 print(snd(c),depth-1);
2464 Printf("(UNBOXEDTUP,");
2465 print(snd(c),depth-1);
2470 print(zfst(c),depth-1);
2472 print(zsnd(c),depth-1);
2476 Printf("<ZTriple ");
2477 print(zfst3(c),depth-1);
2479 print(zsnd3(c),depth-1);
2481 print(zthd3(c),depth-1);
2486 print(snd(c),depth-1);
2490 if (isTagNonPtr(tag)) {
2491 Printf("(TagNP=%d,%d)", c, tag);
2492 } else if (isTagPtr(tag)) {
2493 Printf("(TagP=%d,",tag);
2494 print(snd(c), depth-1);
2497 } else if (c == tag) {
2498 Printf("Tag(%d)", c);
2500 Printf("Tag(%d)=%d", c, tag);
2509 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2510 Cell c; { /* also recognises DICTVAR cells */
2512 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2515 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2517 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2520 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2522 if (!isPair(c)) return FALSE;
2525 case VAROPCELL : return TRUE;
2527 case QUALIDENT : return isVar(snd(snd(c)));
2529 default : return FALSE;
2533 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2535 if (!isPair(c)) return FALSE;
2538 case CONOPCELL : return TRUE;
2540 case QUALIDENT : return isCon(snd(snd(c)));
2542 default : return FALSE;
2546 Bool isQualIdent(c) /* is cell a qualified identifier? */
2548 return isPair(c) && (fst(c)==QUALIDENT);
2551 Bool eqQualIdent ( QualId c1, QualId c2 )
2553 assert(isQualIdent(c1));
2554 if (!isQualIdent(c2)) {
2555 assert(isQualIdent(c2));
2557 return qmodOf(c1)==qmodOf(c2) &&
2558 qtextOf(c1)==qtextOf(c2);
2561 Bool isIdent(c) /* is cell an identifier? */
2563 if (!isPair(c)) return FALSE;
2568 case CONOPCELL : return TRUE;
2570 case QUALIDENT : return TRUE;
2572 default : return FALSE;
2576 Bool isInt(c) /* cell holds integer value? */
2578 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2581 Int intOf(c) /* find integer value of cell? */
2584 return isPair(c) ? (Int)(snd(c)) : (Int)(c-SMALL_INT_ZERO);
2587 Cell mkInt(n) /* make cell representing integer */
2589 return (SMALL_INT_MIN <= SMALL_INT_ZERO+n &&
2590 SMALL_INT_ZERO+n <= SMALL_INT_MAX)
2595 #if SIZEOF_VOID_P == SIZEOF_INT
2597 typedef union {Int i; Ptr p;} IntOrPtr;
2604 return pair(ADDRCELL,x.i);
2611 assert(fst(c) == ADDRCELL);
2621 return pair(MPTRCELL,x.i);
2628 assert(fst(c) == MPTRCELL);
2638 return pair(CPTRCELL,x.i);
2645 assert(fst(c) == CPTRCELL);
2650 #elif SIZEOF_VOID_P == 2*SIZEOF_INT
2652 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2659 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2666 assert(fst(c) == PTRCELL);
2667 x.i.i1 = intOf(fst(snd(c)));
2668 x.i.i2 = intOf(snd(snd(c)));
2677 return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2684 assert(fst(c) == CPTRCELL);
2685 x.i.i1 = intOf(fst(snd(c)));
2686 x.i.i2 = intOf(snd(snd(c)));
2692 #error "Can't implement mkPtr/ptrOf on this architecture."
2697 String stringNegate( s )
2705 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2710 /* --------------------------------------------------------------------------
2712 * ------------------------------------------------------------------------*/
2714 Int length(xs) /* calculate length of list xs */
2717 for (; nonNull(xs); ++n)
2722 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2723 List xs, ys; { /* ys by modifying xs ... */
2728 while (nonNull(tl(zs)))
2735 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2738 for (; nonNull(xs); xs=tl(xs))
2739 ys = cons(hd(xs),ys);
2743 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2746 return revOnto(dupOnto(xs,NIL),ys);
2749 List dupList(xs) /* Duplicate spine of list xs */
2752 for (; nonNull(xs); xs=tl(xs))
2753 ys = cons(hd(xs),ys);
2757 List revOnto(xs,ys) /* Destructively reverse elements of*/
2758 List xs, ys; { /* list xs onto list ys... */
2761 while (nonNull(xs)) {
2770 QualId qualidIsMember ( QualId q, List xs )
2772 for (; nonNull(xs); xs=tl(xs)) {
2773 if (eqQualIdent(q, hd(xs)))
2779 Cell varIsMember(t,xs) /* Test if variable is a member of */
2780 Text t; /* given list of variables */
2782 assert(isText(t) || isInventedVar(t) || isInventedDictVar(t));
2783 for (; nonNull(xs); xs=tl(xs))
2784 if (t==textOf(hd(xs)))
2789 Name nameIsMember(t,ns) /* Test if name with text t is a */
2790 Text t; /* member of list of names xs */
2792 for (; nonNull(ns); ns=tl(ns))
2793 if (t==name(hd(ns)).text)
2798 Cell intIsMember(n,xs) /* Test if integer n is member of */
2799 Int n; /* given list of integers */
2801 for (; nonNull(xs); xs=tl(xs))
2802 if (n==intOf(hd(xs)))
2807 Cell cellIsMember(x,xs) /* Test for membership of specific */
2808 Cell x; /* cell x in list xs */
2810 for (; nonNull(xs); xs=tl(xs))
2816 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2819 for (; nonNull(xs); xs=tl(xs))
2825 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2826 Cell c; /* association lists */
2828 for (; nonNull(xs); xs=tl(xs))
2834 List replicate(n,x) /* create list of n copies of x */
2843 List diffList(from,take) /* list difference: from\take */
2844 List from, take; { /* result contains all elements of */
2845 List result = NIL; /* `from' not appearing in `take' */
2847 while (nonNull(from)) {
2848 List next = tl(from);
2849 if (!cellIsMember(hd(from),take)) {
2858 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2862 for(;nonNull(xs);xs=tl(xs)) {
2865 result=cons(x,result);
2871 List take(n,xs) /* destructively truncate list to */
2872 Int n; /* specified length */
2878 while (1<n-- && nonNull(xs))
2885 List splitAt(n,xs) /* drop n things from front of list*/
2894 Cell nth(n,xs) /* extract n'th element of list */
2897 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2904 List removeCell(x,xs) /* destructively remove cell from */
2909 return tl(xs); /* element at front of list */
2913 for (; nonNull(curr); prev=curr, curr=tl(prev))
2915 tl(prev) = tl(curr);
2916 return xs; /* element in middle of list */
2920 return xs; /* here if element not found */
2923 List nubList(xs) /* nuke dups in list */
2924 List xs; { /* non destructive */
2926 for (; nonNull(xs); xs=tl(xs))
2927 if (isNull(cellIsMember(hd(xs),outs)))
2928 outs = cons(hd(xs),outs);
2934 /* --------------------------------------------------------------------------
2935 * Tagged tuples (experimental)
2936 * ------------------------------------------------------------------------*/
2938 static void z_tag_check ( Cell x, int tag, char* caller )
2942 sprintf(buf,"z_tag_check(%s): null\n", caller);
2945 if (whatIs(x) != tag) {
2947 "z_tag_check(%s): tag was %d, expected %d\n",
2948 caller, whatIs(x), tag );
2953 Cell zpair ( Cell x1, Cell x2 )
2954 { return ap(ZTUP2,ap(x1,x2)); }
2955 Cell zfst ( Cell zpair )
2956 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2957 Cell zsnd ( Cell zpair )
2958 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2960 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2961 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2962 Cell zfst3 ( Cell zpair )
2963 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2964 Cell zsnd3 ( Cell zpair )
2965 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2966 Cell zthd3 ( Cell zpair )
2967 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2969 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2970 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2971 Cell zsel14 ( Cell zpair )
2972 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2973 Cell zsel24 ( Cell zpair )
2974 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2975 Cell zsel34 ( Cell zpair )
2976 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2977 Cell zsel44 ( Cell zpair )
2978 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2980 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2981 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2982 Cell zsel15 ( Cell zpair )
2983 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2984 Cell zsel25 ( Cell zpair )
2985 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2986 Cell zsel35 ( Cell zpair )
2987 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2988 Cell zsel45 ( Cell zpair )
2989 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2990 Cell zsel55 ( Cell zpair )
2991 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2994 Cell unap ( int tag, Cell c )
2997 if (whatIs(c) != tag) {
2998 sprintf(buf, "unap: specified %d, actual %d\n",
3005 /* --------------------------------------------------------------------------
3006 * Operations on applications:
3007 * ------------------------------------------------------------------------*/
3009 Int argCount; /* number of args in application */
3011 Cell getHead(e) /* get head cell of application */
3012 Cell e; { /* set number of args in argCount */
3013 for (argCount=0; isAp(e); e=fun(e))
3018 List getArgs(e) /* get list of arguments in function*/
3019 Cell e; { /* application: */
3020 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
3022 for (as=NIL; isAp(e); e=fun(e))
3023 as = cons(arg(e),as);
3027 Cell nthArg(n,e) /* return nth arg in application */
3028 Int n; /* of function to m args (m>=n) */
3029 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
3030 for (n=numArgs(e)-n-1; n>0; n--)
3035 Int numArgs(e) /* find number of arguments to expr */
3038 for (n=0; isAp(e); e=fun(e))
3043 Cell applyToArgs(f,args) /* destructively apply list of args */
3044 Cell f; /* to function f */
3046 while (nonNull(args)) {
3047 Cell temp = tl(args);
3048 tl(args) = hd(args);
3056 /* --------------------------------------------------------------------------
3058 * ------------------------------------------------------------------------*/
3060 /* Given the address of an info table, find the constructor/tuple
3061 that it belongs to, and return the name. Only needed for debugging.
3063 char* lookupHugsItblName ( void* v )
3066 for (i = TYCON_BASE_ADDR;
3067 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3068 if (tabTycon[i-TYCON_BASE_ADDR].inUse
3069 && tycon(i).itbl == v)
3070 return textToStr(tycon(i).text);
3072 for (i = NAME_BASE_ADDR;
3073 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3074 if (tabName[i-NAME_BASE_ADDR].inUse
3075 && name(i).itbl == v)
3076 return textToStr(name(i).text);
3081 static String maybeModuleStr ( Module m )
3083 if (isModule(m)) return textToStr(module(m).text); else return "??";
3086 static String maybeNameStr ( Name n )
3088 if (isName(n)) return textToStr(name(n).text); else return "??";
3091 static String maybeTyconStr ( Tycon t )
3093 if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
3096 static String maybeClassStr ( Class c )
3098 if (isClass(c)) return textToStr(cclass(c).text); else return "??";
3101 static String maybeText ( Text t )
3103 if (isNull(t)) return "(nil)";
3104 return textToStr(t);
3107 static void print100 ( Int x )
3109 print ( x, 100); printf("\n");
3112 void dumpTycon ( Int t )
3114 if (isTycon(TYCON_BASE_ADDR+t) && !isTycon(t)) t += TYCON_BASE_ADDR;
3116 printf ( "dumpTycon %d: not a tycon\n", t);
3120 printf ( " text: %s\n", textToStr(tycon(t).text) );
3121 printf ( " line: %d\n", tycon(t).line );
3122 printf ( " mod: %s\n", maybeModuleStr(tycon(t).mod));
3123 printf ( " tuple: %d\n", tycon(t).tuple);
3124 printf ( " arity: %d\n", tycon(t).arity);
3125 printf ( " kind: "); print100(tycon(t).kind);
3126 printf ( " what: %d\n", tycon(t).what);
3127 printf ( " defn: "); print100(tycon(t).defn);
3128 printf ( " cToT: %d %s\n", tycon(t).conToTag,
3129 maybeNameStr(tycon(t).conToTag));
3130 printf ( " tToC: %d %s\n", tycon(t).tagToCon,
3131 maybeNameStr(tycon(t).tagToCon));
3132 printf ( " itbl: %p\n", tycon(t).itbl);
3133 printf ( " nextTH: %d %s\n", tycon(t).nextTyconHash,
3134 maybeTyconStr(tycon(t).nextTyconHash));
3138 void dumpName ( Int n )
3140 if (isName(NAME_BASE_ADDR+n) && !isName(n)) n += NAME_BASE_ADDR;
3142 printf ( "dumpName %d: not a name\n", n);
3146 printf ( " text: %s\n", textToStr(name(n).text) );
3147 printf ( " line: %d\n", name(n).line );
3148 printf ( " mod: %s\n", maybeModuleStr(name(n).mod));
3149 printf ( " syntax: %d\n", name(n).syntax );
3150 printf ( " parent: %d\n", name(n).parent );
3151 printf ( " arity: %d\n", name(n).arity );
3152 printf ( " number: %d\n", name(n).number );
3153 printf ( " type: "); print100(name(n).type);
3154 printf ( " defn: %d\n", name(n).defn );
3155 printf ( " cconv: %d\n", name(n).callconv );
3156 printf ( " primop: %p\n", name(n).primop );
3157 printf ( " itbl: %p\n", name(n).itbl );
3158 printf ( " closure: %d\n", name(n).closure );
3159 printf ( " nextNH: %d\n", name(n).nextNameHash );
3164 void dumpClass ( Int c )
3166 if (isClass(CCLASS_BASE_ADDR+c) && !isClass(c)) c += CCLASS_BASE_ADDR;
3168 printf ( "dumpClass %d: not a class\n", c);
3172 printf ( " text: %s\n", textToStr(cclass(c).text) );
3173 printf ( " line: %d\n", cclass(c).line );
3174 printf ( " mod: %s\n", maybeModuleStr(cclass(c).mod));
3175 printf ( " arity: %d\n", cclass(c).arity );
3176 printf ( " level: %d\n", cclass(c).level );
3177 printf ( " kinds: "); print100( cclass(c).kinds );
3178 printf ( " fds: %d\n", cclass(c).fds );
3179 printf ( " xfds: %d\n", cclass(c).xfds );
3180 printf ( " head: "); print100( cclass(c).head );
3181 printf ( " dcon: "); print100( cclass(c).dcon );
3182 printf ( " supers: "); print100( cclass(c).supers );
3183 printf ( " #supers: %d\n", cclass(c).numSupers );
3184 printf ( " dsels: "); print100( cclass(c).dsels );
3185 printf ( " members: "); print100( cclass(c).members );
3186 printf ( "#members: %d\n", cclass(c).numMembers );
3187 printf ( "defaults: "); print100( cclass(c).defaults );
3188 printf ( " insts: "); print100( cclass(c).instances );
3193 void dumpInst ( Int i )
3195 if (isInst(INST_BASE_ADDR+i) && !isInst(i)) i += INST_BASE_ADDR;
3197 printf ( "dumpInst %d: not an instance\n", i);
3201 printf ( " class: %s\n", maybeClassStr(inst(i).c) );
3202 printf ( " line: %d\n", inst(i).line );
3203 printf ( " mod: %s\n", maybeModuleStr(inst(i).mod));
3204 printf ( " kinds: "); print100( inst(i).kinds );
3205 printf ( " head: "); print100( inst(i).head );
3206 printf ( " specs: "); print100( inst(i).specifics );
3207 printf ( " #specs: %d\n", inst(i).numSpecifics );
3208 printf ( " impls: "); print100( inst(i).implements );
3209 printf ( " builder: %s\n", maybeNameStr( inst(i).builder ) );
3214 /* --------------------------------------------------------------------------
3216 * ------------------------------------------------------------------------*/
3223 case POSTPREL: break;
3225 case RESET : clearStack();
3227 /* the next 2 statements are particularly important
3228 * if you are using GLOBALfst or GLOBALsnd since the
3229 * corresponding registers may be reset to their
3230 * uninitialised initial values by a longjump.
3232 heapTopFst = heapFst + heapSize;
3233 heapTopSnd = heapSnd + heapSize;
3237 if (isNull(lastExprSaved))
3238 savedText = TEXT_SIZE;
3243 for (i = NAME_BASE_ADDR;
3244 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3245 if (tabName[i-NAME_BASE_ADDR].inUse) {
3246 mark(name(i).parent);
3249 mark(name(i).closure);
3252 end("Names", nameHw-NAMEMIN);
3255 for (i = MODULE_BASE_ADDR;
3256 i < MODULE_BASE_ADDR+tabModuleSz; ++i) {
3257 if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3258 mark(module(i).tycons);
3259 mark(module(i).names);
3260 mark(module(i).classes);
3261 mark(module(i).exports);
3262 mark(module(i).qualImports);
3263 mark(module(i).codeList);
3264 mark(module(i).tree);
3265 mark(module(i).uses);
3266 mark(module(i).objectExtraNames);
3271 mark(targetModules);
3272 end("Modules", moduleHw-MODMIN);
3275 for (i = TYCON_BASE_ADDR;
3276 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3277 if (tabTycon[i-TYCON_BASE_ADDR].inUse) {
3278 mark(tycon(i).kind);
3279 mark(tycon(i).what);
3280 mark(tycon(i).defn);
3281 mark(tycon(i).closure);
3284 end("Type constructors", tyconHw-TYCMIN);
3287 for (i = CCLASS_BASE_ADDR;
3288 i < CCLASS_BASE_ADDR+tabClassSz; ++i) {
3289 if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
3290 mark(cclass(i).kinds);
3291 mark(cclass(i).fds);
3292 mark(cclass(i).xfds);
3293 mark(cclass(i).head);
3294 mark(cclass(i).supers);
3295 mark(cclass(i).dsels);
3296 mark(cclass(i).members);
3297 mark(cclass(i).defaults);
3298 mark(cclass(i).instances);
3302 end("Classes", classHw-CLASSMIN);
3305 for (i = INST_BASE_ADDR;
3306 i < INST_BASE_ADDR+tabInstSz; ++i) {
3307 if (tabInst[i-INST_BASE_ADDR].inUse) {
3308 mark(inst(i).kinds);
3310 mark(inst(i).specifics);
3311 mark(inst(i).implements);
3314 end("Instances", instHw-INSTMIN);
3317 for (i=0; i<=sp; ++i)
3322 mark(lastExprSaved);
3325 end("Last expression", 3);
3330 end("C stack", stackRoots);
3335 case PREPREL : heapFst = heapAlloc(heapSize);
3336 heapSnd = heapAlloc(heapSize);
3338 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3339 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3344 heapTopFst = heapFst + heapSize;
3345 heapTopSnd = heapSnd + heapSize;
3346 for (i=1; i<heapSize; ++i) {
3350 snd(-heapSize) = NIL;
3357 marksSize = bitArraySize(heapSize);
3358 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3359 ERRMSG(0) "Unable to allocate gc markspace"
3366 nextNewText = INVAR_BASE_ADDR;
3367 nextNewDText = INDVAR_BASE_ADDR;
3368 lastExprSaved = NIL;
3369 savedText = TEXT_SIZE;
3371 for (i=0; i<TEXTHSZ; ++i) textHash[i][0] = NOTEXT;
3372 for (i=0; i<TYCONHSZ; ++i) tyconHash[RC_T(i)] = NIL;
3373 for (i=0; i<NAMEHSZ; ++i) nameHash[RC_N(i)] = NIL;
3379 /*-------------------------------------------------------------------------*/