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/27 16:35:29 $
14 * ------------------------------------------------------------------------*/
16 #include "hugsbasictypes.h"
24 /*#define DEBUG_SHOWUSE*/
26 /* --------------------------------------------------------------------------
27 * local function prototypes:
28 * ------------------------------------------------------------------------*/
30 static Int local hash ( String );
31 static Int local saveText ( Text );
32 static Module local findQualifier ( Text );
33 static Void local hashTycon ( Tycon );
34 static List local insertTycon ( Tycon,List );
35 static Void local hashName ( Name );
36 static List local insertName ( Name,List );
37 static Void local patternError ( String );
38 static Bool local stringMatch ( String,String );
39 static Bool local typeInvolves ( Type,Type );
40 static Cell local markCell ( Cell );
41 static Void local markSnd ( Cell );
42 static Cell local lowLevelLastIn ( Cell );
43 static Cell local lowLevelLastOut ( Cell );
46 /* --------------------------------------------------------------------------
49 * provides storage for the characters making up identifier and symbol
50 * names, string literals, character constants etc...
52 * All character strings are stored in a large character array, with textHw
53 * pointing to the next free position. Lookup in the array is improved using
54 * a hash table. Internally, text strings are represented by integer offsets
55 * from the beginning of the array to the string in question.
57 * Where memory permits, the use of multiple hashtables gives a significant
58 * increase in performance, particularly when large source files are used.
60 * Each string in the array is terminated by a zero byte. No string is
61 * stored more than once, so that it is safe to test equality of strings by
62 * comparing the corresponding offsets.
64 * Special text values (beyond the range of the text array table) are used
65 * to generate unique `new variable names' as required.
67 * The same text storage is also used to hold text values stored in a saved
68 * expression. This grows downwards from the top of the text table (and is
69 * not included in the hash table).
70 * ------------------------------------------------------------------------*/
72 #define TEXTHSZ 512 /* Size of Text hash table */
73 #define NOTEXT ((Text)(~0)) /* Empty bucket in Text hash table */
74 static Text textHw; /* Next unused position */
75 static Text savedText = TEXT_SIZE; /* Start of saved portion of text */
76 static Text nextNewText; /* Next new text value */
77 static Text nextNewDText; /* Next new dict text value */
78 static char text[TEXT_SIZE]; /* Storage of character strings */
79 static Text textHash[TEXTHSZ][NUM_TEXTH]; /* Hash table storage */
81 String textToStr(t) /* find string corresp to given Text*/
83 static char newVar[16];
85 if (isText(t)) /* standard char string */
86 return text + t - TEXT_BASE_ADDR;
87 if (isInventedDictVar(t)) {
89 t-INDVAR_BASE_ADDR); /* dictionary variable */
92 if (isInventedVar(t)) {
94 t-INVAR_BASE_ADDR); /* normal variable */
97 internal("textToStr");
100 String identToStr(v) /*find string corresp to given ident or qualified name*/
103 internal("identToStr");
109 case CONOPCELL : return textToStr(textOf(v));
111 case QUALIDENT : { String qmod = textToStr(qmodOf(v));
112 String qtext = textToStr(qtextOf(v));
115 while (pos+1 < savedText && *qmod!=0) {
116 text[pos++] = *qmod++;
118 if (pos+1 < savedText) {
121 while (pos+1 < savedText && *qtext!=0) {
122 text[pos++] = *qtext++;
128 internal("identToStr2");
129 return 0; /* NOTREACHED */
132 Text inventText() { /* return new unused variable name */
133 if (nextNewText >= INVAR_BASE_ADDR+INVAR_MAX_AVAIL)
134 internal("inventText: too many invented variables");
135 return nextNewText++;
138 Text inventDictText() { /* return new unused dictvar name */
139 if (nextNewDText >= INDVAR_BASE_ADDR+INDVAR_MAX_AVAIL)
140 internal("inventDictText: too many invented variables");
141 return nextNewDText++;
144 Bool inventedText(t) /* Signal TRUE if text has been */
145 Text t; { /* generated internally */
146 return isInventedVar(t) || isInventedDictVar(t);
149 #define MAX_FIXLIT 100
150 Text fixLitText(t) /* fix literal text that might include \ */
152 String s = textToStr(t);
155 for(i = 0;i < MAX_FIXLIT-2 && *s;s++) {
161 if (i < MAX_FIXLIT-2) {
164 ERRMSG(0) "storage space exhausted for internal literal string"
167 return (findText(p));
171 static Int local hash(s) /* Simple hash function on strings */
175 for (v=((int)(*s))*8; *s; s++)
176 v += ((int)(*s))*(j++);
182 Text findText(s) /* Locate string in Text array */
186 Text textPos = textHash[h][hashno];
188 # define TryMatch { Text originalTextPos = textPos; \
190 for (t=s; *t==text[textPos]; textPos++,t++) \
192 return originalTextPos+TEXT_BASE_ADDR; \
194 # define Skip while (text[textPos++]) ;
196 while (textPos!=NOTEXT) {
198 if (++hashno<NUM_TEXTH) /* look in next hashtable entry */
199 textPos = textHash[h][hashno];
202 while (textPos < textHw) {
213 textPos = textHw; /* if not found, save in array */
214 if (textHw + (Int)strlen(s) + 1 > savedText) {
215 ERRMSG(0) "Character string storage space exhausted"
218 while ((text[textHw++] = *s++) != 0) {
220 if (hashno<NUM_TEXTH) { /* updating hash table as necessary */
221 textHash[h][hashno] = textPos;
222 if (hashno<NUM_TEXTH-1)
223 textHash[h][hashno+1] = NOTEXT;
226 return textPos+TEXT_BASE_ADDR;
229 static Int local saveText(t) /* Save text value in buffer */
230 Text t; { /* at top of text table */
231 String s = textToStr(t);
233 if (textHw + l + 1 > savedText) {
234 ERRMSG(0) "Character string storage space exhausted"
238 strcpy(text+savedText,s);
243 static int fromHexDigit ( char c )
246 case '0': case '1': case '2': case '3': case '4':
247 case '5': case '6': case '7': case '8': case '9':
249 case 'a': case 'A': return 10;
250 case 'b': case 'B': return 11;
251 case 'c': case 'C': return 12;
252 case 'd': case 'D': return 13;
253 case 'e': case 'E': return 14;
254 case 'f': case 'F': return 15;
260 /* returns findText (unZencode s) */
261 Text unZcodeThenFindText ( String s )
268 nn = 100 + 10 * strlen(s);
270 if (!p) internal ("unZcodeThenFindText: malloc failed");
275 if (n > nn-90) internal ("unZcodeThenFindText: result is too big");
276 if (*s != 'z' && *s != 'Z') {
281 if (!(*s)) goto parse_error;
283 case 'Z': p[n++] = 'Z'; break;
284 case 'C': p[n++] = ':'; break;
285 case 'L': p[n++] = '('; break;
286 case 'R': p[n++] = ')'; break;
287 case 'M': p[n++] = '['; break;
288 case 'N': p[n++] = ']'; break;
289 case 'z': p[n++] = 'z'; break;
290 case 'a': p[n++] = '&'; break;
291 case 'b': p[n++] = '|'; break;
292 case 'd': p[n++] = '$'; break;
293 case 'e': p[n++] = '='; break;
294 case 'g': p[n++] = '>'; break;
295 case 'h': p[n++] = '#'; break;
296 case 'i': p[n++] = '.'; break;
297 case 'l': p[n++] = '<'; break;
298 case 'm': p[n++] = '-'; break;
299 case 'n': p[n++] = '!'; break;
300 case 'p': p[n++] = '+'; break;
301 case 'q': p[n++] = '\\'; break;
302 case 'r': p[n++] = '\''; break;
303 case 's': p[n++] = '/'; break;
304 case 't': p[n++] = '*'; break;
305 case 'u': p[n++] = '^'; break;
306 case 'v': p[n++] = '%'; break;
308 if (!s[0] || !s[1]) goto parse_error;
309 if (fromHexDigit(s[0]) < 0 || fromHexDigit(s[1]) < 0) goto parse_error;
310 p[n++] = 16 * fromHexDigit(s[0]) + fromHexDigit(s[1]);
313 case '0': case '1': case '2': case '3': case '4':
314 case '5': case '6': case '7': case '8': case '9':
317 while (*s && isdigit((int)(*s))) {
318 i = 10 * i + (*s - '0');
321 if (*s != 'T') goto parse_error;
324 while (i > 0) { p[n++] = ','; i--; };
338 fprintf ( stderr, "\nstring = `%s'\n", s );
339 internal ( "unZcodeThenFindText: parse error on above string");
340 return NIL; /*notreached*/
344 Text enZcodeThenFindText ( String s )
349 char toHex[16] = "0123456789ABCDEF";
352 nn = 100 + 10 * strlen(s);
354 if (!p) internal ("enZcodeThenFindText: malloc failed");
358 if (n > nn-90) internal ("enZcodeThenFindText: result is too big");
361 && (isalnum((int)(*s)) || *s == '_')) {
369 while (*s && *s==',') { s++; tup++; };
370 if (*s != ')') internal("enZcodeThenFindText: invalid tuple type");
373 sprintf(num,"%d",tup);
374 p[n] = 0; strcat ( &(p[n]), num ); n += strlen(num);
379 case '(': p[n++] = 'Z'; p[n++] = 'L'; break;
380 case ')': p[n++] = 'Z'; p[n++] = 'R'; break;
381 case '[': p[n++] = 'Z'; p[n++] = 'M'; break;
382 case ']': p[n++] = 'Z'; p[n++] = 'N'; break;
383 case ':': p[n++] = 'Z'; p[n++] = 'C'; break;
384 case 'Z': p[n++] = 'Z'; p[n++] = 'Z'; break;
385 case 'z': p[n++] = 'z'; p[n++] = 'z'; break;
386 case '&': p[n++] = 'z'; p[n++] = 'a'; break;
387 case '|': p[n++] = 'z'; p[n++] = 'b'; break;
388 case '$': p[n++] = 'z'; p[n++] = 'd'; break;
389 case '=': p[n++] = 'z'; p[n++] = 'e'; break;
390 case '>': p[n++] = 'z'; p[n++] = 'g'; break;
391 case '#': p[n++] = 'z'; p[n++] = 'h'; break;
392 case '.': p[n++] = 'z'; p[n++] = 'i'; break;
393 case '<': p[n++] = 'z'; p[n++] = 'l'; break;
394 case '-': p[n++] = 'z'; p[n++] = 'm'; break;
395 case '!': p[n++] = 'z'; p[n++] = 'n'; break;
396 case '+': p[n++] = 'z'; p[n++] = 'p'; break;
397 case '\'': p[n++] = 'z'; p[n++] = 'q'; break;
398 case '\\': p[n++] = 'z'; p[n++] = 'r'; break;
399 case '/': p[n++] = 'z'; p[n++] = 's'; break;
400 case '*': p[n++] = 'z'; p[n++] = 't'; break;
401 case '^': p[n++] = 'z'; p[n++] = 'u'; break;
402 case '%': p[n++] = 'z'; p[n++] = 'v'; break;
403 default: s--; p[n++] = 'z'; p[n++] = 'x';
404 p[n++] = toHex[(int)(*s)/16];
405 p[n++] = toHex[(int)(*s)%16];
416 Text textOf ( Cell c )
430 fprintf(stderr, "\ntextOf: bad tag %d\n",wot );
431 internal("textOf: bad tag");
436 /* --------------------------------------------------------------------------
439 * Currently, the only attributes that we store for each Ext value is the
440 * corresponding Text label. At some later stage, we may decide to cache
441 * types, predicates, etc. here as a space saving gesture. Given that Text
442 * comparison is cheap, and that this is an experimental implementation, we
443 * will use a straightforward linear search to locate Ext values from their
444 * corresponding Text labels; a hashing scheme can be introduced later if
445 * this turns out to be a problem.
446 * ------------------------------------------------------------------------*/
449 Text DEFTABLE(tabExt,NUM_EXT); /* Storage for Ext names */
452 Ext mkExt(t) /* Allocate or find an Ext value */
458 if (extHw-EXTMIN >= NUM_EXT) {
459 ERRMSG(0) "Ext storage space exhausted"
468 /* --------------------------------------------------------------------------
469 * Expandable symbol tables. A template, which is instantiated for the name,
470 * tycon, class, instance and module tables. Also, potentially, TREX Exts.
471 * ------------------------------------------------------------------------*/
473 #ifdef DEBUG_STORAGE_EXTRA
474 static Bool debugStorageExtra = TRUE;
476 static Bool debugStorageExtra = FALSE;
480 #define EXPANDABLE_SYMBOL_TABLE(type_name,struct_name, \
481 proc_name,free_proc_name, \
482 free_list,tab_name,tab_size,err_msg, \
483 TAB_INIT_SIZE,TAB_MAX_SIZE, \
486 struct struct_name* tab_name = NULL; \
488 static type_name free_list = TAB_BASE_ADDR-1; \
490 void free_proc_name ( type_name n ) \
492 assert(TAB_BASE_ADDR <= n); \
493 assert(n < TAB_BASE_ADDR+tab_size); \
494 assert(tab_name[n-TAB_BASE_ADDR].inUse); \
495 tab_name[n-TAB_BASE_ADDR].inUse = FALSE; \
496 if (!debugStorageExtra) { \
497 tab_name[n-TAB_BASE_ADDR].nextFree = free_list; \
502 type_name proc_name ( void ) \
506 struct struct_name* newTab; \
507 struct struct_name* temp; \
509 if (free_list != TAB_BASE_ADDR-1) { \
510 type_name t = free_list; \
511 free_list = tab_name[free_list-TAB_BASE_ADDR].nextFree; \
512 assert (!(tab_name[t-TAB_BASE_ADDR].inUse)); \
513 tab_name[t-TAB_BASE_ADDR].inUse = TRUE; \
517 newSz = (tab_size == 0 ? TAB_INIT_SIZE : 2 * tab_size); \
518 if (newSz > TAB_MAX_SIZE) goto cant_allocate; \
519 newTab = malloc(newSz * sizeof(struct struct_name)); \
520 if (!newTab) goto cant_allocate; \
521 for (i = 0; i < tab_size; i++) \
522 newTab[i] = tab_name[i]; \
523 for (i = tab_size; i < newSz; i++) { \
524 newTab[i].inUse = FALSE; \
525 newTab[i].nextFree = i-1+TAB_BASE_ADDR; \
527 if (0 && debugStorageExtra) \
528 fprintf(stderr, "Expanding " #type_name \
529 "table to size %d\n", newSz ); \
530 newTab[tab_size].nextFree = TAB_BASE_ADDR-1; \
531 free_list = newSz-1+TAB_BASE_ADDR; \
535 if (temp) free(temp); \
545 EXPANDABLE_SYMBOL_TABLE(Name,strName,allocNewName,freeName,
546 nameFL,tabName,tabNameSz,
547 "Name storage space exhausted",
548 NAME_INIT_SIZE,NAME_MAX_SIZE,NAME_BASE_ADDR)
551 EXPANDABLE_SYMBOL_TABLE(Tycon,strTycon,allocNewTycon,freeTycon,
552 tyconFL,tabTycon,tabTyconSz,
553 "Type constructor storage space exhausted",
554 TYCON_INIT_SIZE,TYCON_MAX_SIZE,TYCON_BASE_ADDR)
557 EXPANDABLE_SYMBOL_TABLE(Class,strClass,allocNewClass,freeClass,
558 classFL,tabClass,tabClassSz,
559 "Class storage space exhausted",
560 CCLASS_INIT_SIZE,CCLASS_MAX_SIZE,CCLASS_BASE_ADDR)
563 EXPANDABLE_SYMBOL_TABLE(Inst,strInst,allocNewInst,freeInst,
564 instFL,tabInst,tabInstSz,
565 "Instance storage space exhausted",
566 INST_INIT_SIZE,INST_MAX_SIZE,INST_BASE_ADDR)
569 EXPANDABLE_SYMBOL_TABLE(Module,strModule,allocNewModule,freeModule,
570 moduleFL,tabModule,tabModuleSz,
571 "Module storage space exhausted",
572 MODULE_INIT_SIZE,MODULE_MAX_SIZE,MODULE_BASE_ADDR)
575 struct strName* generate_name_ref ( Cell nm )
578 nm -= NAME_BASE_ADDR;
579 assert(tabName[nm].inUse);
580 assert(isModule(tabName[nm].mod));
581 return & tabName[nm];
583 struct strTycon* generate_tycon_ref ( Cell tc )
585 assert(isTycon(tc) || isTuple(tc));
586 tc -= TYCON_BASE_ADDR;
587 assert(tabTycon[tc].inUse);
588 assert(isModule(tabTycon[tc].mod));
589 return & tabTycon[tc];
591 struct strClass* generate_cclass_ref ( Cell cl )
594 cl -= CCLASS_BASE_ADDR;
595 assert(tabClass[cl].inUse);
596 assert(isModule(tabClass[cl].mod));
597 return & tabClass[cl];
599 struct strInst* generate_inst_ref ( Cell in )
602 in -= INST_BASE_ADDR;
603 assert(tabInst[in].inUse);
604 assert(isModule(tabInst[in].mod));
605 return & tabInst[in];
607 struct strModule* generate_module_ref ( Cell mo )
609 assert(isModule(mo));
610 mo -= MODULE_BASE_ADDR;
611 assert(tabModule[mo].inUse);
612 return & tabModule[mo];
617 /* --------------------------------------------------------------------------
620 * A Tycon represents a user defined type constructor. Tycons are indexed
621 * by Text values ... a very simple hash function is used to improve lookup
622 * times. Tycon entries with the same hash code are chained together, with
623 * the most recent entry at the front of the list.
624 * ------------------------------------------------------------------------*/
626 #define TYCONHSZ 256 /* Size of Tycon hash table*/
627 static Tycon tyconHash[TYCONHSZ]; /* Hash table storage */
629 static int tHash(Text x)
632 assert(isText(x) || inventedText(x));
641 static int RC_T ( int x )
643 assert (x >= 0 && x < TYCONHSZ);
647 Tycon newTycon ( Text t ) /* add new tycon to tycon table */
650 Tycon tc = allocNewTycon();
652 [tc-TYCON_BASE_ADDR].tuple = -1;
654 [tc-TYCON_BASE_ADDR].mod = currentModule;
655 tycon(tc).text = t; /* clear new tycon record */
656 tycon(tc).kind = NIL;
657 tycon(tc).defn = NIL;
658 tycon(tc).what = NIL;
659 tycon(tc).conToTag = NIL;
660 tycon(tc).tagToCon = NIL;
661 tycon(tc).itbl = NULL;
663 tycon(tc).closure = NIL;
664 module(currentModule).tycons = cons(tc,module(currentModule).tycons);
665 tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
666 tyconHash[RC_T(h)] = tc;
670 Tycon findTycon(t) /* locate Tycon in tycon table */
672 Tycon tc = tyconHash[RC_T(tHash(t))];
673 assert(isTycon(tc) || isTuple(tc) || isNull(tc));
674 while (nonNull(tc) && tycon(tc).text!=t)
675 tc = tycon(tc).nextTyconHash;
679 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
682 assert(isTycon(tc) || isTuple(tc));
683 oldtc = findTycon(tycon(tc).text);
686 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
692 static Void local hashTycon(tc) /* Insert Tycon into hash table */
696 assert(isTycon(tc) || isTuple(tc));
697 {int i; for (i = 0; i < TYCONHSZ; i++)
698 assert (tyconHash[i] == 0
699 || isTycon(tyconHash[i])
700 || isTuple(tyconHash[i]));
704 tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
705 tyconHash[RC_T(h)] = tc;
708 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
710 if (!isPair(id)) internal("findQualTycon");
714 return findTycon(textOf(id));
716 Text t = qtextOf(id);
717 Module m = findQualifier(qmodOf(id));
719 if (isNull(m)) return NIL;
720 for(es=module(m).exports; nonNull(es); es=tl(es)) {
722 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
727 default : internal("findQualTycon2");
729 return NIL; /* NOTREACHED */
732 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
738 Tycon tc = newTycon(t);
740 tycon(tc).kind = kind;
741 tycon(tc).what = what;
742 tycon(tc).defn = defn;
743 tycon(tc).arity = ar;
747 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
752 String s = textToStr(tycon(tc).text);
754 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
755 if (hd(curr)==tc) /* just in case we get duplicates! */
761 tl(prev) = cons(tc,curr);
765 return cons(tc,curr);
768 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
769 String pat; /* to list of Tycons ts */
770 List ts; { /* Null pattern matches every tycon*/
771 Tycon tc; /* (Tycons with NIL kind excluded) */
772 for (tc = TYCON_BASE_ADDR;
773 tc < TYCON_BASE_ADDR+tabTyconSz; ++tc)
774 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
775 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
776 if (nonNull(tycon(tc).kind))
777 ts = insertTycon(tc,ts);
781 Text ghcTupleText_n ( Int n )
786 if (n < 0 || n >= 100) internal("ghcTupleText_n");
787 if (n == 1) internal("ghcTupleText_n==1");
789 for (i = 1; i <= n-1; i++) buf[x++] = ',';
792 return findText(buf);
795 Text ghcTupleText(tup)
798 assert(isTuple(tup));
800 return ghcTupleText_n ( tupleOf(tup) );
804 Tycon mkTuple ( Int n )
808 internal("mkTuple: request for tuple of unsupported size");
809 for (i = TYCON_BASE_ADDR;
810 i < TYCON_BASE_ADDR+tabTyconSz; i++)
811 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
812 if (tycon(i).tuple == n) return i;
813 internal("mkTuple: request for non-existent tuple");
817 /* --------------------------------------------------------------------------
820 * A Name represents a top level binding of a value to an identifier.
821 * Such values may be a constructor function, a member function in a
822 * class, a user-defined or primitive value/function.
824 * Names are indexed by Text values ... a very simple hash functions speeds
825 * access to the table of Names and Name entries with the same hash value
826 * are chained together, with the most recent entry at the front of the
828 * ------------------------------------------------------------------------*/
830 #define NAMEHSZ 256 /* Size of Name hash table */
831 static Name nameHash[NAMEHSZ]; /* Hash table storage */
833 static int nHash(Text x)
835 assert(isText(x) || inventedText(x));
843 assert (x >= 0 && x < NAMEHSZ);
847 void hashSanity ( void )
850 for (i = 0; i < TYCONHSZ; i++) {
853 assert(isTycon(j) || isTuple(j));
854 j = tycon(j).nextTyconHash;
857 for (i = 0; i < NAMEHSZ; i++) {
861 j = name(j).nextNameHash;
866 Name newName ( Text t, Cell parent ) /* Add new name to name table */
869 Name nm = allocNewName();
871 [nm-NAME_BASE_ADDR].mod = currentModule;
872 name(nm).text = t; /* clear new name record */
874 name(nm).syntax = NO_SYNTAX;
875 name(nm).parent = parent;
877 name(nm).number = EXECNAME;
879 name(nm).hasStrict = FALSE;
880 name(nm).callconv = NIL;
882 name(nm).primop = NULL;
883 name(nm).itbl = NULL;
884 name(nm).closure = NIL;
885 module(currentModule).names = cons(nm,module(currentModule).names);
886 name(nm).nextNameHash = nameHash[RC_N(h)];
887 nameHash[RC_N(h)] = nm;
891 Name findName(t) /* Locate name in name table */
893 Name n = nameHash[RC_N(nHash(t))];
894 assert(isText(t) || isInventedVar(t) || isInventedDictVar(t));
895 assert(isName(n) || isNull(n));
896 while (nonNull(n) && name(n).text!=t)
897 n = name(n).nextNameHash;
901 Name addName(nm) /* Insert Name in name table - if */
902 Name nm; { /* no clash is caused */
905 oldnm = findName(name(nm).text);
908 module(currentModule).names=cons(nm,module(currentModule).names);
914 static Void local hashName(nm) /* Insert Name into hash table */
921 name(nm).nextNameHash = nameHash[RC_N(h)];
922 nameHash[RC_N(h)] = nm;
925 Name findQualName(id) /* Locate (possibly qualified) name*/
926 Cell id; { /* in name table */
928 internal("findQualName");
934 return findName(textOf(id));
936 Text t = qtextOf(id);
937 Module m = findQualifier(qmodOf(id));
939 if (isNull(m)) return NIL;
940 for(es=module(m).exports; nonNull(es); es=tl(es)) {
942 if (isName(e) && name(e).text==t)
944 else if (isPair(e) && DOTDOT==snd(e)) {
945 List subentities = NIL;
948 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
949 subentities = tycon(c).defn;
951 subentities = cclass(c).members;
952 for(; nonNull(subentities); subentities=tl(subentities)) {
953 if (!isName(hd(subentities)))
954 internal("findQualName3");
955 if (name(hd(subentities)).text == t)
956 return hd(subentities);
962 default : internal("findQualName2");
964 return 0; /* NOTREACHED */
968 void* /* StgClosure* */ getHugs_BCO_cptr_for ( char* s )
970 Text t = findText(s);
972 for (n = NAME_BASE_ADDR;
973 n < NAME_BASE_ADDR+tabNameSz; n++)
974 if (tabName[n-NAME_BASE_ADDR].inUse && name(n).text == t)
976 if (n == NAME_BASE_ADDR+tabNameSz) {
977 fprintf ( stderr, "can't find `%s' in ...\n", s );
978 internal("getHugs_BCO_cptr_for(1)");
980 if (!isCPtr(name(n).closure))
981 internal("getHugs_BCO_cptr_for(2)");
982 return cptrOf(name(n).closure);
985 /* --------------------------------------------------------------------------
986 * Primitive functions:
987 * ------------------------------------------------------------------------*/
989 Module findFakeModule ( Text t )
991 Module m = findModule(t);
993 if (!module(m).fake) internal("findFakeModule");
996 module(m).fake = TRUE;
1002 Name addWiredInBoxingTycon
1003 ( String modNm, String typeNm, String constrNm,
1004 Int rep, Kind kind )
1008 Text modT = findText(modNm);
1009 Text typeT = findText(typeNm);
1010 Text conT = findText(constrNm);
1011 Module m = findFakeModule(modT);
1014 n = newName(conT,NIL);
1016 name(n).number = cfunNo(0);
1018 name(n).primop = (void*)rep;
1020 t = newTycon(typeT);
1021 tycon(t).what = DATATYPE;
1022 tycon(t).kind = kind;
1027 Tycon addTupleTycon ( Int n )
1035 for (i = TYCON_BASE_ADDR;
1036 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1037 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
1038 if (tycon(i).tuple == n) return i;
1041 m = findFakeModule(findText(n==0 ? "PrelBase" : "PrelTup")); else
1042 m = findModule(findText("PrelPrim"));
1046 for (i = 0; i < n; i++) k = ap(STAR,k);
1047 t = newTycon(ghcTupleText_n(n));
1050 tycon(t).what = DATATYPE;
1053 /* maybe we want to do this for all n ? */
1054 nm = newName(ghcTupleText_n(n), t);
1055 name(nm).type = t; /* ummm ... for n > 0 */
1062 Tycon addWiredInEnumTycon ( String modNm, String typeNm,
1063 List /*of Text*/ constrs )
1067 Text modT = findText(modNm);
1068 Text typeT = findText(typeNm);
1069 Module m = findFakeModule(modT);
1072 t = newTycon(typeT);
1073 tycon(t).kind = STAR;
1074 tycon(t).what = DATATYPE;
1076 constrs = reverse(constrs);
1077 i = length(constrs);
1078 for (; nonNull(constrs); constrs=tl(constrs),i--) {
1079 Text conT = hd(constrs);
1080 Name con = newName(conT,t);
1081 name(con).number = cfunNo(i);
1083 name(con).parent = t;
1084 tycon(t).defn = cons(con, tycon(t).defn);
1090 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
1091 Text t; /* sets rep, not type */
1094 Int rep; { /* Really AsmRep */
1095 Name n = newName(t,NIL);
1096 name(n).arity = arity;
1097 name(n).number = cfunNo(no);
1099 name(n).primop = (void*)rep;
1104 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
1109 Name n = newName(t,NIL);
1110 name(n).arity = arity;
1111 name(n).number = cfunNo(no);
1112 name(n).type = type;
1117 Int sfunPos(s,c) /* Find position of field with */
1118 Name s; /* selector s in constructor c. */
1122 for (; nonNull(cns); cns=tl(cns))
1123 if (fst(hd(cns))==c)
1124 return intOf(snd(hd(cns)));
1125 internal("sfunPos");
1126 return 0;/* NOTREACHED */
1129 static List local insertName(nm,ns) /* insert name nm into sorted list */
1134 String s = textToStr(name(nm).text);
1136 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
1137 if (hd(curr)==nm) /* just in case we get duplicates! */
1142 if (nonNull(prev)) {
1143 tl(prev) = cons(nm,curr);
1147 return cons(nm,curr);
1150 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
1151 String pat; /* to list of names ns */
1152 List ns; { /* Null pattern matches every name */
1153 Name nm; /* (Names with NIL type, or hidden */
1154 /* or invented names are excluded) */
1156 for (nm = NAME_BASE_ADDR;
1157 nm < NAME_BASE_ADDR+tabNameSz; ++nm)
1158 if (tabName[nm-NAME_BASE_ADDR].inUse) {
1159 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
1160 String str = textToStr(name(nm).text);
1161 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1162 ns = insertName(nm,ns);
1167 List mns = module(currentModule).names;
1168 for(; nonNull(mns); mns=tl(mns)) {
1170 if (!inventedText(name(nm).text)) {
1171 String str = textToStr(name(nm).text);
1172 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1173 ns = insertName(nm,ns);
1180 /* --------------------------------------------------------------------------
1181 * A simple string matching routine
1182 * `*' matches any sequence of zero or more characters
1183 * `?' matches any single character exactly
1184 * `@str' matches the string str exactly (ignoring any special chars)
1185 * `\c' matches the character c only (ignoring special chars)
1186 * c matches the character c only
1187 * ------------------------------------------------------------------------*/
1189 static Void local patternError(s) /* report error in pattern */
1191 ERRMSG(0) "%s in pattern", s
1195 static Bool local stringMatch(pat,str) /* match string against pattern */
1201 case '\0' : return (*str=='\0');
1204 if (stringMatch(pat+1,str))
1209 case '?' : if (*str++=='\0')
1214 case '[' : { Bool found = FALSE;
1215 while (*++pat!='\0' && *pat!=']')
1216 if (!found && ( pat[0] == *str ||
1225 patternError("missing `]'");
1233 case '\\' : if (*++pat == '\0')
1234 patternError("extra trailing `\\'");
1236 default : if (*pat++ != *str++)
1242 /* --------------------------------------------------------------------------
1243 * Storage of type classes, instances etc...:
1244 * ------------------------------------------------------------------------*/
1246 static List classes; /* list of classes in current scope */
1248 Class newClass ( Text t ) /* add new class to class table */
1250 Class cl = allocNewClass();
1252 [cl-CCLASS_BASE_ADDR].mod = currentModule;
1253 cclass(cl).text = t;
1254 cclass(cl).arity = 0;
1255 cclass(cl).kinds = NIL;
1256 cclass(cl).head = NIL;
1257 cclass(cl).fds = NIL;
1258 cclass(cl).xfds = NIL;
1259 cclass(cl).dcon = NIL;
1260 cclass(cl).supers = NIL;
1261 cclass(cl).dsels = NIL;
1262 cclass(cl).members = NIL;
1263 cclass(cl).defaults = NIL;
1264 cclass(cl).instances = NIL;
1265 classes = cons(cl,classes);
1266 module(currentModule).classes
1267 = cons(cl,module(currentModule).classes);
1271 Class findClass(t) /* look for named class in table */
1275 for (cs=classes; nonNull(cs); cs=tl(cs)) {
1277 if (cclass(cl).text==t)
1283 Class addClass(c) /* Insert Class in class list */
1284 Class c; { /* - if no clash caused */
1286 assert(whatIs(c)==CLASS);
1287 oldc = findClass(cclass(c).text);
1289 classes=cons(c,classes);
1290 module(currentModule).classes=cons(c,module(currentModule).classes);
1297 Class findQualClass(c) /* Look for (possibly qualified) */
1298 Cell c; { /* class in class list */
1299 if (!isQualIdent(c)) {
1300 return findClass(textOf(c));
1302 Text t = qtextOf(c);
1303 Module m = findQualifier(qmodOf(c));
1307 for (es=module(m).exports; nonNull(es); es=tl(es)) {
1309 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
1316 Inst newInst() { /* Add new instance to table */
1317 Inst in = allocNewInst();
1319 [in-INST_BASE_ADDR].mod = currentModule;
1320 inst(in).kinds = NIL;
1321 inst(in).head = NIL;
1322 inst(in).specifics = NIL;
1323 inst(in).numSpecifics = 0;
1324 inst(in).implements = NIL;
1325 inst(in).builder = NIL;
1330 extern Void printInst ( Inst));
1334 Class cl = inst(in).c;
1335 Printf("%s-", textToStr(cclass(cl).text));
1336 printType(stdout,inst(in).t);
1338 #endif /* DEBUG_DICTS */
1340 Inst findFirstInst(tc) /* look for 1st instance involving */
1341 Tycon tc; { /* the type constructor tc */
1342 return findNextInst(tc,INST_BASE_ADDR-1);
1345 Inst findNextInst(tc,in) /* look for next instance involving*/
1346 Tycon tc; /* the type constructor tc */
1347 Inst in; { /* starting after instance in */
1349 while (++in < INST_BASE_ADDR+tabInstSz) {
1350 if (!tabInst[in-INST_BASE_ADDR].inUse) continue;
1351 assert(isModule(inst(in).mod));
1353 for (; isAp(pi); pi=fun(pi))
1354 if (typeInvolves(arg(pi),tc))
1360 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1361 Type ty; /* type constructor/tuple tc. */
1364 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1365 || typeInvolves(arg(ty),tc)));
1369 /* Needed by finishGHCInstance to find classes, before the
1370 export list has been built -- so we can't use
1373 Class findQualClassWithoutConsultingExportList ( QualId q )
1383 t_class = textOf(q);
1386 t_class = qtextOf(q);
1389 for (cl = CCLASS_BASE_ADDR;
1390 cl < CCLASS_BASE_ADDR+tabClassSz; cl++) {
1391 if (tabClass[cl-CCLASS_BASE_ADDR].inUse)
1392 if (cclass(cl).text == t_class) {
1393 /* Class name is ok, but is this the right module? */
1394 if (isNull(t_mod) /* no module name specified */
1396 && t_mod == module(cclass(cl).mod).text)
1404 /* Same deal, except for Tycons. */
1405 Tycon findQualTyconWithoutConsultingExportList ( QualId q )
1415 t_tycon = textOf(q);
1418 t_tycon = qtextOf(q);
1421 for (tc = TYCON_BASE_ADDR;
1422 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1423 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1424 if (tycon(tc).text == t_tycon) {
1425 /* Tycon name is ok, but is this the right module? */
1426 if (isNull(t_mod) /* no module name specified */
1428 && t_mod == module(tycon(tc).mod).text)
1436 /* Same deal, except for Names. */
1437 Name findQualNameWithoutConsultingExportList ( QualId q )
1443 assert(isQVar(q) || isQCon(q));
1445 if (isCon(q) || isVar(q)) {
1450 t_name = qtextOf(q);
1453 for (nm = NAME_BASE_ADDR;
1454 nm < NAME_BASE_ADDR+tabNameSz; nm++) {
1455 if (tabName[nm-NAME_BASE_ADDR].inUse)
1456 if (name(nm).text == t_name) {
1457 /* Name is ok, but is this the right module? */
1458 if (isNull(t_mod) /* no module name specified */
1460 && t_mod == module(name(nm).mod).text)
1469 Tycon findTyconInAnyModule ( Text t )
1472 for (tc = TYCON_BASE_ADDR;
1473 tc < TYCON_BASE_ADDR+tabTyconSz; tc++)
1474 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1475 if (tycon(tc).text == t) return tc;
1479 Class findClassInAnyModule ( Text t )
1482 for (cc = CCLASS_BASE_ADDR;
1483 cc < CCLASS_BASE_ADDR+tabClassSz; cc++)
1484 if (tabClass[cc-CCLASS_BASE_ADDR].inUse)
1485 if (cclass(cc).text == t) return cc;
1489 Name findNameInAnyModule ( Text t )
1492 for (nm = NAME_BASE_ADDR;
1493 nm < NAME_BASE_ADDR+tabNameSz; nm++)
1494 if (tabName[nm-NAME_BASE_ADDR].inUse)
1495 if (name(nm).text == t) return nm;
1500 /* returns List of QualId */
1501 List getAllKnownTyconsAndClasses ( void )
1506 for (tc = TYCON_BASE_ADDR;
1507 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1508 if (tabTycon[tc-TYCON_BASE_ADDR].inUse) {
1509 /* almost certainly undue paranoia about duplicate avoidance */
1510 QualId q = mkQCon( module(tycon(tc).mod).text, tycon(tc).text );
1511 if (!qualidIsMember(q,xs))
1512 xs = cons ( q, xs );
1515 for (nw = CCLASS_BASE_ADDR;
1516 nw < CCLASS_BASE_ADDR+tabClassSz; nw++) {
1517 if (tabClass[nw-CCLASS_BASE_ADDR].inUse) {
1518 QualId q = mkQCon( module(cclass(nw).mod).text, cclass(nw).text );
1519 if (!qualidIsMember(q,xs))
1520 xs = cons ( q, xs );
1526 Int numQualifiers ( Type t )
1528 if (isPolyType(t)) t = monotypeOf(t);
1530 return length ( fst(snd(t)) ); else
1535 /* Purely for debugging. */
1536 void locateSymbolByName ( Text t )
1539 for (i = NAME_BASE_ADDR;
1540 i < NAME_BASE_ADDR+tabNameSz; i++)
1541 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).text == t)
1542 fprintf ( stderr, "name(%d)\n", i-NAME_BASE_ADDR);
1543 for (i = TYCON_BASE_ADDR;
1544 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1545 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).text == t)
1546 fprintf ( stderr, "tycon(%d)\n", i-TYCON_BASE_ADDR);
1547 for (i = CCLASS_BASE_ADDR;
1548 i < CCLASS_BASE_ADDR+tabClassSz; i++)
1549 if (tabClass[i-CCLASS_BASE_ADDR].inUse && cclass(i).text == t)
1550 fprintf ( stderr, "class(%d)\n", i-CCLASS_BASE_ADDR);
1553 /* --------------------------------------------------------------------------
1556 * Various parts of the system use a stack of cells. Most of the stack
1557 * operations are defined as macros, expanded inline.
1558 * ------------------------------------------------------------------------*/
1560 Cell cellStack[NUM_STACK]; /* Storage for cells on stack */
1561 StackPtr sp; /* stack pointer */
1563 Void hugsStackOverflow() { /* Report stack overflow */
1564 ERRMSG(0) "Control stack overflow"
1569 /* --------------------------------------------------------------------------
1572 * A Module represents a user defined module.
1574 * Note: there are now two lookup mechanisms in the system:
1576 * 1) The exports from a module are stored in a big list.
1577 * We resolve qualified names, and import lists by linearly scanning
1578 * through this list.
1580 * 2) Unqualified imports and local definitions for the current module
1581 * are stored in hash tables (tyconHash and nameHash) or linear lists
1584 * ------------------------------------------------------------------------*/
1586 Module currentModule; /* Module currently being processed*/
1588 Bool isValidModule(m) /* is m a legitimate module id? */
1593 Module newModule ( Text t ) /* add new module to module table */
1595 Module mod = allocNewModule();
1596 module(mod).text = t; /* clear new module record */
1598 module(mod).tycons = NIL;
1599 module(mod).names = NIL;
1600 module(mod).classes = NIL;
1601 module(mod).exports = NIL;
1602 module(mod).qualImports = NIL;
1603 module(mod).codeList = NIL;
1604 module(mod).fake = FALSE;
1606 module(mod).tree = NIL;
1607 module(mod).completed = FALSE;
1608 module(mod).lastStamp = 0; /* ???? */
1610 module(mod).mode = NIL;
1611 module(mod).srcExt = findText("");
1612 module(mod).uses = NIL;
1614 module(mod).objName = findText("");
1615 module(mod).objSize = 0;
1617 module(mod).object = NULL;
1618 module(mod).objectExtras = NULL;
1619 module(mod).objectExtraNames = NIL;
1624 Bool nukeModule_needs_major_gc = TRUE;
1626 void nukeModule ( Module m )
1632 if (!isModule(m)) internal("nukeModule");
1634 /* fprintf ( stderr, "NUKE MODULE %s\n", textToStr(module(m).text) ); */
1636 /* see comment in compiler.c about this,
1637 and interaction with info tables */
1638 if (nukeModule_needs_major_gc) {
1639 /* fprintf ( stderr, "doing major GC in nukeModule\n"); */
1640 /* performMajorGC(); */
1641 nukeModule_needs_major_gc = FALSE;
1644 oc = module(m).object;
1650 oc = module(m).objectExtras;
1657 for (i = NAME_BASE_ADDR; i < NAME_BASE_ADDR+tabNameSz; i++)
1658 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).mod == m) {
1660 module(name(i).mod).mode == FM_SOURCE) {
1663 name(i).itbl = NULL;
1664 name(i).closure = NIL;
1668 for (i = TYCON_BASE_ADDR; i < TYCON_BASE_ADDR+tabTyconSz; i++)
1669 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).mod == m) {
1670 if (tycon(i).itbl &&
1671 module(tycon(i).mod).mode == FM_SOURCE) {
1672 free(tycon(i).itbl);
1674 tycon(i).itbl = NULL;
1678 for (i = CCLASS_BASE_ADDR; i < CCLASS_BASE_ADDR+tabClassSz; i++)
1679 if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
1680 if (cclass(i).mod == m) {
1683 List /* Inst */ ins;
1684 List /* Inst */ ins2 = NIL;
1685 for (ins = cclass(i).instances; nonNull(ins); ins=tl(ins))
1686 if (inst(hd(ins)).mod != m)
1687 ins2 = cons(hd(ins),ins2);
1688 cclass(i).instances = ins2;
1693 for (i = INST_BASE_ADDR; i < INST_BASE_ADDR+tabInstSz; i++)
1694 if (tabInst[i-INST_BASE_ADDR].inUse && inst(i).mod == m)
1698 //for (i = 0; i < TYCONHSZ; i++) tyconHash[i] = 0;
1699 //for (i = 0; i < NAMEHSZ; i++) nameHash[i] = 0;
1704 void ppModules ( void )
1707 fflush(stderr); fflush(stdout);
1708 printf ( "begin MODULES\n" );
1709 for (i = MODULE_BASE_ADDR+tabModuleSz-1;
1710 i >= MODULE_BASE_ADDR; i--)
1711 if (tabModule[i-MODULE_BASE_ADDR].inUse)
1712 printf ( " %2d: %16s\n",
1713 i-MODULE_BASE_ADDR, textToStr(module(i).text)
1715 printf ( "end MODULES\n" );
1716 fflush(stderr); fflush(stdout);
1720 Module findModule(t) /* locate Module in module table */
1723 for(m = MODULE_BASE_ADDR;
1724 m < MODULE_BASE_ADDR+tabModuleSz; ++m) {
1725 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1726 if (module(m).text==t)
1732 Module findModid(c) /* Find module by name or filename */
1734 switch (whatIs(c)) {
1735 case STRCELL : internal("findModid-STRCELL unimp");
1736 case CONIDCELL : return findModule(textOf(c));
1737 default : internal("findModid");
1739 return NIL;/*NOTUSED*/
1742 static local Module findQualifier(t) /* locate Module in import list */
1745 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1746 if (textOf(fst(hd(ms)))==t)
1749 if (module(currentModule).text==t)
1750 return currentModule;
1754 Void setCurrModule(m) /* set lookup tables for current module */
1757 assert(isModule(m));
1758 /* fprintf(stderr, "SET CURR MODULE %s %d\n", textToStr(module(m).text),m); */
1760 for (t = module(m).names; nonNull(t); t=tl(t))
1761 assert(isName(hd(t)));
1762 for (t = module(m).tycons; nonNull(t); t=tl(t))
1763 assert(isTycon(hd(t)) || isTuple(hd(t)));
1764 for (t = module(m).classes; nonNull(t); t=tl(t))
1765 assert(isClass(hd(t)));
1768 currentModule = m; /* This is the only assignment to currentModule */
1769 for (i=0; i<TYCONHSZ; ++i)
1770 tyconHash[RC_T(i)] = NIL;
1771 mapProc(hashTycon,module(m).tycons);
1772 for (i=0; i<NAMEHSZ; ++i)
1773 nameHash[RC_N(i)] = NIL;
1774 mapProc(hashName,module(m).names);
1775 classes = module(m).classes;
1779 void addToCodeList ( Module m, Cell c )
1781 assert(isName(c) || isTuple(c));
1782 if (nonNull(getNameOrTupleClosure(c)))
1783 module(m).codeList = cons ( c, module(m).codeList );
1784 /* fprintf ( stderr, "addToCodeList %s %s\n",
1785 textToStr(module(m).text),
1786 textToStr( isTuple(c) ? tycon(c).text : name(c).text ) );
1790 Cell getNameOrTupleClosure ( Cell c )
1792 if (isName(c)) return name(c).closure;
1793 else if (isTuple(c)) return tycon(c).closure;
1794 else internal("getNameOrTupleClosure");
1797 void setNameOrTupleClosure ( Cell c, Cell closure )
1799 if (isName(c)) name(c).closure = closure;
1800 else if (isTuple(c)) tycon(c).closure = closure;
1801 else internal("setNameOrTupleClosure");
1804 /* This function is used in ghc/rts/Assembler.c. */
1805 void* /* StgClosure* */ getNameOrTupleClosureCPtr ( Cell c )
1807 return cptrOf(getNameOrTupleClosure(c));
1810 /* used in codegen.c */
1811 void setNameOrTupleClosureCPtr ( Cell c, void* /* StgClosure* */ cptr )
1813 if (isName(c)) name(c).closure = mkCPtr(cptr);
1814 else if (isTuple(c)) tycon(c).closure = mkCPtr(cptr);
1815 else internal("setNameOrTupleClosureCPtr");
1820 Name jrsFindQualName ( Text mn, Text sn )
1825 for (m = MODULE_BASE_ADDR;
1826 m < MODULE_BASE_ADDR+tabModuleSz; m++)
1827 if (tabModule[m-MODULE_BASE_ADDR].inUse
1828 && module(m).text == mn) break;
1830 if (m == MODULE_BASE_ADDR+tabModuleSz) return NIL;
1832 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1833 if (name(hd(ns)).text == sn) return hd(ns);
1839 char* nameFromOPtr ( void* p )
1843 for (m = MODULE_BASE_ADDR;
1844 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1845 if (tabModule[m-MODULE_BASE_ADDR].inUse && module(m).object) {
1846 char* nm = ocLookupAddr ( module(m).object, p );
1851 /* A kludge to assist Win32 debugging; not actually necessary. */
1852 { char* nm = nameFromStaticOPtr(p);
1860 void* lookupOTabName ( Module m, char* sym )
1862 assert(isModule(m));
1863 if (module(m).object)
1864 return ocLookupSym ( module(m).object, sym );
1869 void* lookupOExtraTabName ( char* sym )
1873 for (m = MODULE_BASE_ADDR;
1874 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1875 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1876 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1877 void* ad = ocLookupSym ( oc, sym );
1885 /* Only call this if in dire straits; searches every object symtab
1886 in the system -- so is therefore slow.
1888 void* lookupOTabNameAbsolutelyEverywhere ( char* sym )
1893 for (m = MODULE_BASE_ADDR;
1894 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1895 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1896 if (module(m).object) {
1897 ad = ocLookupSym ( module(m).object, sym );
1900 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1901 ad = ocLookupSym ( oc, sym );
1910 OSectionKind lookupSection ( void* ad )
1917 for (m = MODULE_BASE_ADDR;
1918 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1919 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1920 if (module(m).object) {
1921 sect = ocLookupSection ( module(m).object, ad );
1922 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1925 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1926 sect = ocLookupSection ( oc, ad );
1927 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1932 return HUGS_SECTIONKIND_OTHER;
1936 /* Called by the evaluator's GC to tell Hugs to mark stuff in the
1939 void markHugsObjects( void )
1944 for ( nm = NAME_BASE_ADDR;
1945 nm < NAME_BASE_ADDR+tabNameSz; ++nm ) {
1946 if (tabName[nm-NAME_BASE_ADDR].inUse) {
1947 Cell cl = name(nm).closure;
1950 snd(cl) = MarkRoot ( snd(cl) );
1955 for ( tc = TYCON_BASE_ADDR;
1956 tc < TYCON_BASE_ADDR+tabTyconSz; ++tc ) {
1957 if (tabTycon[tc-TYCON_BASE_ADDR].inUse) {
1958 Cell cl = tycon(tc).closure;
1961 snd(cl) = MarkRoot ( snd(cl) );
1969 /* --------------------------------------------------------------------------
1972 * Provides a garbage collectable heap for storage of expressions etc.
1974 * Now incorporates a flat resource: A two-space collected extension of
1975 * the heap that provides storage for contiguous arrays of Cell storage,
1976 * cooperating with the garbage collection mechanisms for the main heap.
1977 * ------------------------------------------------------------------------*/
1979 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1980 Heap heapFst; /* array of fst component of pairs */
1981 Heap heapSnd; /* array of snd component of pairs */
1984 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1985 /* C stack; use with extreme care! */
1988 Int numGcs; /* number of garbage collections */
1989 Int cellsRecovered; /* number of cells recovered */
1991 static Cell freeList; /* free list of unused cells */
1992 static Cell lsave, rsave; /* save components of pair */
1996 static Int markCount, stackRoots;
1998 #define initStackRoots() stackRoots = 0
1999 #define recordStackRoot() stackRoots++
2012 #define start() markCount = 0
2013 #define end(thing,rs) \
2015 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
2018 #define recordMark() markCount++
2020 #else /* !GC_STATISTICS */
2025 #define initStackRoots()
2026 #define recordStackRoot()
2029 #define end(thing,root)
2030 #define recordMark()
2032 #endif /* !GC_STATISTICS */
2034 Cell pair(l,r) /* Allocate pair (l, r) from */
2035 Cell l, r; { /* heap, garbage collecting first */
2036 Cell c = freeList; /* if necessary ... */
2047 freeList = snd(freeList);
2055 static Int marksSize;
2057 void mark ( Cell root )
2060 Cell mstack[NUM_MSTACK];
2064 mstack[++msp] = root;
2067 if (msp > msp_max) msp_max = msp;
2069 if (!isGenPair(c)) continue;
2070 if (fst(c)==FREECELL) continue;
2072 register int place = placeInSet(c);
2073 register int mask = maskInSet(c);
2074 if (!(marks[place]&mask)) {
2075 marks[place] |= mask;
2076 if (msp >= NUM_MSTACK-5) {
2078 "hugs: fatal stack overflow during GC. "
2079 "Increase NUM_MSTACK.\n" );
2082 mstack[++msp] = fst(c);
2083 mstack[++msp] = snd(c);
2087 // fprintf(stderr, "%d ",msp_max);
2091 Void garbageCollect() { /* Run garbage collector ... */
2092 /* disable break checking */
2097 jmp_buf regs; /* save registers on stack */
2098 HugsBreakAction oldBrk
2099 = setBreakAction ( HugsIgnoreBreak );
2105 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
2108 everybody(MARK); /* Mark all components of system */
2110 gcScanning(); /* scan mark set */
2117 for (i=1; i<=heapSize; i++) {
2118 if ((marks[place] & mask) == 0) {
2125 if (++j == bitsPerWord) {
2132 gcRecovered(recovered);
2133 setBreakAction ( oldBrk );
2137 #if defined(DEBUG_STORAGE) || defined(DEBUG_STORAGE_EXTRA)
2138 /* fprintf(stderr, "\n--- GC recovered %d\n",recovered ); */
2141 /* can only return if freeList is nonempty on return. */
2142 if (recovered<minRecovery || isNull(freeList)) {
2143 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
2146 cellsRecovered = recovered;
2149 /* --------------------------------------------------------------------------
2150 * Code for saving last expression entered:
2152 * This is a little tricky because some text values (e.g. strings or variable
2153 * names) may not be defined or have the same value when the expression is
2154 * recalled. These text values are therefore saved in the top portion of
2156 * ------------------------------------------------------------------------*/
2158 static Cell lastExprSaved; /* last expression to be saved */
2160 Void setLastExpr(e) /* save expression for later recall*/
2162 lastExprSaved = NIL; /* in case attempt to save fails */
2163 savedText = TEXT_SIZE;
2164 lastExprSaved = lowLevelLastIn(e);
2167 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
2168 Cell c; { /* acyclic graph) for later recall */
2169 if (isPair(c)) { /* Duplicating any text strings */
2170 if (isTagNonPtr(fst(c))) /* in case these are lost at some */
2171 switch (fst(c)) { /* point before the expr is reused */
2177 case STRCELL : return pair(fst(c),saveText(textOf(c)));
2178 default : return pair(fst(c),snd(c));
2181 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2185 return pair(EXTCOPY,saveText(extText(c)));
2191 Cell getLastExpr() { /* recover previously saved expr */
2192 return lowLevelLastOut(lastExprSaved);
2195 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
2196 Cell c; { /* except that Cells refering to */
2197 if (isPair(c)) { /* Text values are restored to */
2198 if (isTagNonPtr(fst(c))) /* appropriate values */
2205 case STRCELL : return pair(fst(c),
2206 findText(text+intValOf(c)));
2208 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
2210 default : return pair(fst(c),snd(c));
2213 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2219 /* --------------------------------------------------------------------------
2220 * Miscellaneous operations on heap cells:
2221 * ------------------------------------------------------------------------*/
2223 Cell whatIs ( register Cell c )
2226 register Cell fstc = fst(c);
2227 return isTag(fstc) ? fstc : AP;
2229 if (isOffset(c)) return OFFSET;
2230 if (isChar(c)) return CHARCELL;
2231 if (isInt(c)) return INTCELL;
2232 if (isName(c)) return NAME;
2233 if (isTycon(c)) return TYCON;
2234 if (isTuple(c)) return TUPLE;
2235 if (isClass(c)) return CLASS;
2236 if (isInst(c)) return INSTANCE;
2237 if (isModule(c)) return MODULE;
2238 if (isText(c)) return TEXTCELL;
2239 if (isInventedVar(c)) return INVAR;
2240 if (isInventedDictVar(c)) return INDVAR;
2241 if (isSpec(c)) return c;
2242 if (isNull(c)) return c;
2243 fprintf ( stderr, "whatIs: unknown %d\n", c );
2249 Cell whatIs(c) /* identify type of cell */
2252 register Cell fstc = fst(c);
2253 return isTag(fstc) ? fstc : AP;
2255 if (c<OFFMIN) return c;
2257 if (isExt(c)) return EXT;
2259 if (c>=INTMIN) return INTCELL;
2261 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
2263 else if (c>=INSTMIN) return INSTANCE;
2265 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
2266 else return MODULE;}
2267 else if (c>=OFFMIN) return OFFSET;
2269 else return (c>=EXTMIN) ?
2277 register Cell fstc = fst(c);
2278 return isTag(fstc) ? fstc : AP;
2280 if (c>=INTMIN) return INTCELL;
2281 if (c>=CHARMIN) return CHARCELL;
2282 if (c>=CLASSMIN) return CLASS;
2283 if (c>=INSTMIN) return INSTANCE;
2284 if (c>=NAMEMIN) return NAME;
2285 if (c>=TYCMIN) return TYCON;
2286 if (c>=MODMIN) return MODULE;
2287 if (c>=OFFMIN) return OFFSET;
2289 if (c>=EXTMIN) return EXT;
2291 if (c>=TUPMIN) return TUPLE;
2297 /* A very, very simple printer.
2298 * Output is uglier than from printExp - but the printer is more
2299 * robust and can be used on any data structure irrespective of
2302 Void print ( Cell c, Int depth )
2307 else if (isNull(c)) {
2310 else if (isTagPtr(c)) {
2311 Printf("TagP(%d)", c);
2313 else if (isTagNonPtr(c)) {
2314 Printf("TagNP(%d)", c);
2316 else if (isSpec(c) && c != STAR) {
2317 Printf("TagS(%d)", c);
2319 else if (isText(c)) {
2320 Printf("text(%d)=\"%s\"",c-TEXT_BASE_ADDR,textToStr(c));
2322 else if (isInventedVar(c)) {
2323 Printf("invented(%d)", c-INVAR_BASE_ADDR);
2325 else if (isInventedDictVar(c)) {
2326 Printf("inventedDict(%d)",c-INDVAR_BASE_ADDR);
2329 Int tag = whatIs(c);
2333 print(fst(c), depth-1);
2335 print(snd(c), depth-1);
2339 Printf("free(%d)", c);
2342 Printf("int(%d)", intOf(c));
2345 Printf("bignum(%s)", bignumToString(c));
2348 Printf("char('%c')", charOf(c));
2351 Printf("strcell(\"%s\")",textToStr(snd(c)));
2354 Printf("mptr(%p)",mptrOf(c));
2357 Printf("cptr(%p)",cptrOf(c));
2360 Printf("addr(%p)",addrOf(c));
2363 Printf("class(%d)", c-CCLASS_BASE_ADDR);
2364 Printf("=\"%s\"", textToStr(cclass(c).text));
2367 Printf("instance(%d)", c - INST_BASE_ADDR);
2370 Printf("name(%d)", c-NAME_BASE_ADDR);
2371 Printf("=\"%s\"", textToStr(name(c).text));
2374 Printf("tycon(%d)", c-TYCON_BASE_ADDR);
2375 Printf("=\"%s\"", textToStr(tycon(c).text));
2378 Printf("module(%d)", c - MODULE_BASE_ADDR);
2379 Printf("=\"%s\"", textToStr(module(c).text));
2382 Printf("Offset %d", offsetOf(c));
2385 Printf("%s", textToStr(ghcTupleText(c)));
2389 print(snd(c),depth-1);
2393 print(snd(c),depth-1);
2397 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2398 Printf("%d ", intOf(fst(snd(c))));
2399 print(snd(snd(c)),depth-1);
2401 print(snd(c),depth-1);
2415 Printf("{dict %d}",textOf(c));
2421 Printf("{id %s}",textToStr(textOf(c)));
2425 Printf("{ip %s}",textToStr(textOf(c)));
2428 Printf("?%s",textToStr(textOf(c)));
2432 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2436 print(fst(snd(c)),depth-1);
2438 print(snd(snd(c)),depth-1);
2443 print(snd(c),depth-1);
2448 print(snd(c),depth-1);
2453 print(fst(snd(c)),depth-1);
2455 print(snd(snd(c)),depth-1);
2460 print(fst(snd(c)),depth-1);
2462 print(snd(snd(c)),depth-1);
2466 Printf("FromQual(");
2467 print(fst(snd(c)),depth-1);
2469 print(snd(snd(c)),depth-1);
2473 Printf("StgVar%d=",-c);
2474 print(snd(c), depth-1);
2478 print(fst(snd(c)),depth-1);
2480 print(snd(snd(c)),depth-1);
2485 print(fst(snd(c)),depth-1);
2487 print(snd(snd(c)),depth-1);
2492 print(fst(snd(c)),depth-1);
2494 print(snd(snd(c)),depth-1);
2498 Printf("PrimCase(");
2499 print(fst(snd(c)),depth-1);
2501 print(snd(snd(c)),depth-1);
2506 print(snd(c),depth-1);
2510 Printf("(UNBOXEDTUP,");
2511 print(snd(c),depth-1);
2516 print(zfst(c),depth-1);
2518 print(zsnd(c),depth-1);
2522 Printf("<ZTriple ");
2523 print(zfst3(c),depth-1);
2525 print(zsnd3(c),depth-1);
2527 print(zthd3(c),depth-1);
2532 print(snd(c),depth-1);
2536 if (isTagNonPtr(tag)) {
2537 Printf("(TagNP=%d,%d)", c, tag);
2538 } else if (isTagPtr(tag)) {
2539 Printf("(TagP=%d,",tag);
2540 print(snd(c), depth-1);
2543 } else if (c == tag) {
2544 Printf("Tag(%d)", c);
2546 Printf("Tag(%d)=%d", c, tag);
2555 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2556 Cell c; { /* also recognises DICTVAR cells */
2558 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2561 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2563 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2566 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2568 if (!isPair(c)) return FALSE;
2571 case VAROPCELL : return TRUE;
2573 case QUALIDENT : return isVar(snd(snd(c)));
2575 default : return FALSE;
2579 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2581 if (!isPair(c)) return FALSE;
2584 case CONOPCELL : return TRUE;
2586 case QUALIDENT : return isCon(snd(snd(c)));
2588 default : return FALSE;
2592 Bool isQualIdent(c) /* is cell a qualified identifier? */
2594 return isPair(c) && (fst(c)==QUALIDENT);
2597 Bool eqQualIdent ( QualId c1, QualId c2 )
2599 assert(isQualIdent(c1));
2600 if (!isQualIdent(c2)) {
2601 assert(isQualIdent(c2));
2603 return qmodOf(c1)==qmodOf(c2) &&
2604 qtextOf(c1)==qtextOf(c2);
2607 Bool isIdent(c) /* is cell an identifier? */
2609 if (!isPair(c)) return FALSE;
2614 case CONOPCELL : return TRUE;
2616 case QUALIDENT : return TRUE;
2618 default : return FALSE;
2622 Bool isInt(c) /* cell holds integer value? */
2624 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2627 Int intOf(c) /* find integer value of cell? */
2630 return isPair(c) ? (Int)(snd(c)) : (Int)(c-SMALL_INT_ZERO);
2633 Cell mkInt(n) /* make cell representing integer */
2635 return (SMALL_INT_MIN <= SMALL_INT_ZERO+n &&
2636 SMALL_INT_ZERO+n <= SMALL_INT_MAX)
2641 #if SIZEOF_VOID_P == SIZEOF_INT
2643 typedef union {Int i; Ptr p;} IntOrPtr;
2650 return pair(ADDRCELL,x.i);
2657 assert(fst(c) == ADDRCELL);
2667 return pair(MPTRCELL,x.i);
2674 assert(fst(c) == MPTRCELL);
2684 return pair(CPTRCELL,x.i);
2691 assert(fst(c) == CPTRCELL);
2696 #elif SIZEOF_VOID_P == 2*SIZEOF_INT
2698 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2705 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2712 assert(fst(c) == PTRCELL);
2713 x.i.i1 = intOf(fst(snd(c)));
2714 x.i.i2 = intOf(snd(snd(c)));
2723 return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2730 assert(fst(c) == CPTRCELL);
2731 x.i.i1 = intOf(fst(snd(c)));
2732 x.i.i2 = intOf(snd(snd(c)));
2738 #error "Can't implement mkPtr/ptrOf on this architecture."
2743 String stringNegate( s )
2751 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2756 /* --------------------------------------------------------------------------
2758 * ------------------------------------------------------------------------*/
2760 Int length(xs) /* calculate length of list xs */
2763 for (; nonNull(xs); ++n)
2768 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2769 List xs, ys; { /* ys by modifying xs ... */
2774 while (nonNull(tl(zs)))
2781 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2784 for (; nonNull(xs); xs=tl(xs))
2785 ys = cons(hd(xs),ys);
2789 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2792 return revOnto(dupOnto(xs,NIL),ys);
2795 List dupList(xs) /* Duplicate spine of list xs */
2798 for (; nonNull(xs); xs=tl(xs))
2799 ys = cons(hd(xs),ys);
2803 List revOnto(xs,ys) /* Destructively reverse elements of*/
2804 List xs, ys; { /* list xs onto list ys... */
2807 while (nonNull(xs)) {
2816 QualId qualidIsMember ( QualId q, List xs )
2818 for (; nonNull(xs); xs=tl(xs)) {
2819 if (eqQualIdent(q, hd(xs)))
2825 Cell varIsMember(t,xs) /* Test if variable is a member of */
2826 Text t; /* given list of variables */
2828 assert(isText(t) || isInventedVar(t) || isInventedDictVar(t));
2829 for (; nonNull(xs); xs=tl(xs))
2830 if (t==textOf(hd(xs)))
2835 Name nameIsMember(t,ns) /* Test if name with text t is a */
2836 Text t; /* member of list of names xs */
2838 for (; nonNull(ns); ns=tl(ns))
2839 if (t==name(hd(ns)).text)
2844 Cell intIsMember(n,xs) /* Test if integer n is member of */
2845 Int n; /* given list of integers */
2847 for (; nonNull(xs); xs=tl(xs))
2848 if (n==intOf(hd(xs)))
2853 Cell cellIsMember(x,xs) /* Test for membership of specific */
2854 Cell x; /* cell x in list xs */
2856 for (; nonNull(xs); xs=tl(xs))
2862 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2865 for (; nonNull(xs); xs=tl(xs))
2871 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2872 Cell c; /* association lists */
2874 for (; nonNull(xs); xs=tl(xs))
2880 List replicate(n,x) /* create list of n copies of x */
2889 List diffList(from,take) /* list difference: from\take */
2890 List from, take; { /* result contains all elements of */
2891 List result = NIL; /* `from' not appearing in `take' */
2893 while (nonNull(from)) {
2894 List next = tl(from);
2895 if (!cellIsMember(hd(from),take)) {
2904 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2908 for(;nonNull(xs);xs=tl(xs)) {
2911 result=cons(x,result);
2917 List take(n,xs) /* destructively truncate list to */
2918 Int n; /* specified length */
2924 while (1<n-- && nonNull(xs))
2931 List splitAt(n,xs) /* drop n things from front of list*/
2940 Cell nth(n,xs) /* extract n'th element of list */
2943 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2950 List removeCell(x,xs) /* destructively remove cell from */
2955 return tl(xs); /* element at front of list */
2959 for (; nonNull(curr); prev=curr, curr=tl(prev))
2961 tl(prev) = tl(curr);
2962 return xs; /* element in middle of list */
2966 return xs; /* here if element not found */
2969 List nubList(xs) /* nuke dups in list */
2970 List xs; { /* non destructive */
2972 for (; nonNull(xs); xs=tl(xs))
2973 if (isNull(cellIsMember(hd(xs),outs)))
2974 outs = cons(hd(xs),outs);
2980 /* --------------------------------------------------------------------------
2981 * Tagged tuples (experimental)
2982 * ------------------------------------------------------------------------*/
2984 static void z_tag_check ( Cell x, int tag, char* caller )
2988 sprintf(buf,"z_tag_check(%s): null\n", caller);
2991 if (whatIs(x) != tag) {
2993 "z_tag_check(%s): tag was %d, expected %d\n",
2994 caller, whatIs(x), tag );
2999 Cell zpair ( Cell x1, Cell x2 )
3000 { return ap(ZTUP2,ap(x1,x2)); }
3001 Cell zfst ( Cell zpair )
3002 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
3003 Cell zsnd ( Cell zpair )
3004 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
3006 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
3007 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
3008 Cell zfst3 ( Cell zpair )
3009 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
3010 Cell zsnd3 ( Cell zpair )
3011 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
3012 Cell zthd3 ( Cell zpair )
3013 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
3015 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
3016 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
3017 Cell zsel14 ( Cell zpair )
3018 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
3019 Cell zsel24 ( Cell zpair )
3020 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
3021 Cell zsel34 ( Cell zpair )
3022 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
3023 Cell zsel44 ( Cell zpair )
3024 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
3026 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
3027 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
3028 Cell zsel15 ( Cell zpair )
3029 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
3030 Cell zsel25 ( Cell zpair )
3031 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
3032 Cell zsel35 ( Cell zpair )
3033 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
3034 Cell zsel45 ( Cell zpair )
3035 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
3036 Cell zsel55 ( Cell zpair )
3037 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
3040 Cell unap ( int tag, Cell c )
3043 if (whatIs(c) != tag) {
3044 sprintf(buf, "unap: specified %d, actual %d\n",
3051 /* --------------------------------------------------------------------------
3052 * Operations on applications:
3053 * ------------------------------------------------------------------------*/
3055 Int argCount; /* number of args in application */
3057 Cell getHead(e) /* get head cell of application */
3058 Cell e; { /* set number of args in argCount */
3059 for (argCount=0; isAp(e); e=fun(e))
3064 List getArgs(e) /* get list of arguments in function*/
3065 Cell e; { /* application: */
3066 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
3068 for (as=NIL; isAp(e); e=fun(e))
3069 as = cons(arg(e),as);
3073 Cell nthArg(n,e) /* return nth arg in application */
3074 Int n; /* of function to m args (m>=n) */
3075 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
3076 for (n=numArgs(e)-n-1; n>0; n--)
3081 Int numArgs(e) /* find number of arguments to expr */
3084 for (n=0; isAp(e); e=fun(e))
3089 Cell applyToArgs(f,args) /* destructively apply list of args */
3090 Cell f; /* to function f */
3092 while (nonNull(args)) {
3093 Cell temp = tl(args);
3094 tl(args) = hd(args);
3102 /* --------------------------------------------------------------------------
3104 * ------------------------------------------------------------------------*/
3106 /* Given the address of an info table, find the constructor/tuple
3107 that it belongs to, and return the name. Only needed for debugging.
3109 char* lookupHugsItblName ( void* v )
3112 for (i = TYCON_BASE_ADDR;
3113 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3114 if (tabTycon[i-TYCON_BASE_ADDR].inUse
3115 && tycon(i).itbl == v)
3116 return textToStr(tycon(i).text);
3118 for (i = NAME_BASE_ADDR;
3119 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3120 if (tabName[i-NAME_BASE_ADDR].inUse
3121 && name(i).itbl == v)
3122 return textToStr(name(i).text);
3127 static String maybeModuleStr ( Module m )
3129 if (isModule(m)) return textToStr(module(m).text); else return "??";
3132 static String maybeNameStr ( Name n )
3134 if (isName(n)) return textToStr(name(n).text); else return "??";
3137 static String maybeTyconStr ( Tycon t )
3139 if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
3142 static String maybeClassStr ( Class c )
3144 if (isClass(c)) return textToStr(cclass(c).text); else return "??";
3147 static String maybeText ( Text t )
3149 if (isNull(t)) return "(nil)";
3150 return textToStr(t);
3153 static void print100 ( Int x )
3155 print ( x, 100); printf("\n");
3158 void dumpTycon ( Int t )
3160 if (isTycon(TYCON_BASE_ADDR+t) && !isTycon(t)) t += TYCON_BASE_ADDR;
3162 printf ( "dumpTycon %d: not a tycon\n", t);
3166 printf ( " text: %s\n", textToStr(tycon(t).text) );
3167 printf ( " line: %d\n", tycon(t).line );
3168 printf ( " mod: %s\n", maybeModuleStr(tycon(t).mod));
3169 printf ( " tuple: %d\n", tycon(t).tuple);
3170 printf ( " arity: %d\n", tycon(t).arity);
3171 printf ( " kind: "); print100(tycon(t).kind);
3172 printf ( " what: %d\n", tycon(t).what);
3173 printf ( " defn: "); print100(tycon(t).defn);
3174 printf ( " cToT: %d %s\n", tycon(t).conToTag,
3175 maybeNameStr(tycon(t).conToTag));
3176 printf ( " tToC: %d %s\n", tycon(t).tagToCon,
3177 maybeNameStr(tycon(t).tagToCon));
3178 printf ( " itbl: %p\n", tycon(t).itbl);
3179 printf ( " nextTH: %d %s\n", tycon(t).nextTyconHash,
3180 maybeTyconStr(tycon(t).nextTyconHash));
3184 void dumpName ( Int n )
3186 if (isName(NAME_BASE_ADDR+n) && !isName(n)) n += NAME_BASE_ADDR;
3188 printf ( "dumpName %d: not a name\n", n);
3192 printf ( " text: %s\n", textToStr(name(n).text) );
3193 printf ( " line: %d\n", name(n).line );
3194 printf ( " mod: %s\n", maybeModuleStr(name(n).mod));
3195 printf ( " syntax: %d\n", name(n).syntax );
3196 printf ( " parent: %d\n", name(n).parent );
3197 printf ( " arity: %d\n", name(n).arity );
3198 printf ( " number: %d\n", name(n).number );
3199 printf ( " type: "); print100(name(n).type);
3200 printf ( " defn: %d\n", name(n).defn );
3201 printf ( " cconv: %d\n", name(n).callconv );
3202 printf ( " primop: %p\n", name(n).primop );
3203 printf ( " itbl: %p\n", name(n).itbl );
3204 printf ( " closure: %d\n", name(n).closure );
3205 printf ( " nextNH: %d\n", name(n).nextNameHash );
3210 void dumpClass ( Int c )
3212 if (isClass(CCLASS_BASE_ADDR+c) && !isClass(c)) c += CCLASS_BASE_ADDR;
3214 printf ( "dumpClass %d: not a class\n", c);
3218 printf ( " text: %s\n", textToStr(cclass(c).text) );
3219 printf ( " line: %d\n", cclass(c).line );
3220 printf ( " mod: %s\n", maybeModuleStr(cclass(c).mod));
3221 printf ( " arity: %d\n", cclass(c).arity );
3222 printf ( " level: %d\n", cclass(c).level );
3223 printf ( " kinds: "); print100( cclass(c).kinds );
3224 printf ( " fds: %d\n", cclass(c).fds );
3225 printf ( " xfds: %d\n", cclass(c).xfds );
3226 printf ( " head: "); print100( cclass(c).head );
3227 printf ( " dcon: "); print100( cclass(c).dcon );
3228 printf ( " supers: "); print100( cclass(c).supers );
3229 printf ( " #supers: %d\n", cclass(c).numSupers );
3230 printf ( " dsels: "); print100( cclass(c).dsels );
3231 printf ( " members: "); print100( cclass(c).members );
3232 printf ( "#members: %d\n", cclass(c).numMembers );
3233 printf ( "defaults: "); print100( cclass(c).defaults );
3234 printf ( " insts: "); print100( cclass(c).instances );
3239 void dumpInst ( Int i )
3241 if (isInst(INST_BASE_ADDR+i) && !isInst(i)) i += INST_BASE_ADDR;
3243 printf ( "dumpInst %d: not an instance\n", i);
3247 printf ( " class: %s\n", maybeClassStr(inst(i).c) );
3248 printf ( " line: %d\n", inst(i).line );
3249 printf ( " mod: %s\n", maybeModuleStr(inst(i).mod));
3250 printf ( " kinds: "); print100( inst(i).kinds );
3251 printf ( " head: "); print100( inst(i).head );
3252 printf ( " specs: "); print100( inst(i).specifics );
3253 printf ( " #specs: %d\n", inst(i).numSpecifics );
3254 printf ( " impls: "); print100( inst(i).implements );
3255 printf ( " builder: %s\n", maybeNameStr( inst(i).builder ) );
3260 /* --------------------------------------------------------------------------
3262 * ------------------------------------------------------------------------*/
3269 case POSTPREL: break;
3271 case RESET : clearStack();
3273 /* the next 2 statements are particularly important
3274 * if you are using GLOBALfst or GLOBALsnd since the
3275 * corresponding registers may be reset to their
3276 * uninitialised initial values by a longjump.
3278 heapTopFst = heapFst + heapSize;
3279 heapTopSnd = heapSnd + heapSize;
3283 if (isNull(lastExprSaved))
3284 savedText = TEXT_SIZE;
3289 for (i = NAME_BASE_ADDR;
3290 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3291 if (tabName[i-NAME_BASE_ADDR].inUse) {
3292 mark(name(i).parent);
3295 mark(name(i).closure);
3298 end("Names", nameHw-NAMEMIN);
3301 for (i = MODULE_BASE_ADDR;
3302 i < MODULE_BASE_ADDR+tabModuleSz; ++i) {
3303 if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3304 mark(module(i).tycons);
3305 mark(module(i).names);
3306 mark(module(i).classes);
3307 mark(module(i).exports);
3308 mark(module(i).qualImports);
3309 mark(module(i).codeList);
3310 mark(module(i).tree);
3311 mark(module(i).uses);
3312 mark(module(i).objectExtraNames);
3317 mark(targetModules);
3318 end("Modules", moduleHw-MODMIN);
3321 for (i = TYCON_BASE_ADDR;
3322 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3323 if (tabTycon[i-TYCON_BASE_ADDR].inUse) {
3324 mark(tycon(i).kind);
3325 mark(tycon(i).what);
3326 mark(tycon(i).defn);
3327 mark(tycon(i).closure);
3330 end("Type constructors", tyconHw-TYCMIN);
3333 for (i = CCLASS_BASE_ADDR;
3334 i < CCLASS_BASE_ADDR+tabClassSz; ++i) {
3335 if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
3336 mark(cclass(i).kinds);
3337 mark(cclass(i).fds);
3338 mark(cclass(i).xfds);
3339 mark(cclass(i).head);
3340 mark(cclass(i).supers);
3341 mark(cclass(i).dsels);
3342 mark(cclass(i).members);
3343 mark(cclass(i).defaults);
3344 mark(cclass(i).instances);
3348 end("Classes", classHw-CLASSMIN);
3351 for (i = INST_BASE_ADDR;
3352 i < INST_BASE_ADDR+tabInstSz; ++i) {
3353 if (tabInst[i-INST_BASE_ADDR].inUse) {
3354 mark(inst(i).kinds);
3356 mark(inst(i).specifics);
3357 mark(inst(i).implements);
3360 end("Instances", instHw-INSTMIN);
3363 for (i=0; i<=sp; ++i)
3368 mark(lastExprSaved);
3371 end("Last expression", 3);
3376 end("C stack", stackRoots);
3381 case PREPREL : heapFst = heapAlloc(heapSize);
3382 heapSnd = heapAlloc(heapSize);
3384 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3385 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3390 heapTopFst = heapFst + heapSize;
3391 heapTopSnd = heapSnd + heapSize;
3392 for (i=1; i<heapSize; ++i) {
3396 snd(-heapSize) = NIL;
3403 marksSize = bitArraySize(heapSize);
3404 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3405 ERRMSG(0) "Unable to allocate gc markspace"
3412 nextNewText = INVAR_BASE_ADDR;
3413 nextNewDText = INDVAR_BASE_ADDR;
3414 lastExprSaved = NIL;
3415 savedText = TEXT_SIZE;
3417 for (i=0; i<TEXTHSZ; ++i) textHash[i][0] = NOTEXT;
3418 for (i=0; i<TYCONHSZ; ++i) tyconHash[RC_T(i)] = NIL;
3419 for (i=0; i<NAMEHSZ; ++i) nameHash[RC_N(i)] = NIL;
3425 /*-------------------------------------------------------------------------*/