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/14 15:18:06 $
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 module(currentModule).tycons = cons(tc,module(currentModule).tycons);
664 tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
665 tyconHash[RC_T(h)] = tc;
669 Tycon findTycon(t) /* locate Tycon in tycon table */
671 Tycon tc = tyconHash[RC_T(tHash(t))];
672 assert(isTycon(tc) || isTuple(tc) || isNull(tc));
673 while (nonNull(tc) && tycon(tc).text!=t)
674 tc = tycon(tc).nextTyconHash;
678 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
681 assert(isTycon(tc) || isTuple(tc));
682 oldtc = findTycon(tycon(tc).text);
685 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
691 static Void local hashTycon(tc) /* Insert Tycon into hash table */
695 assert(isTycon(tc) || isTuple(tc));
696 {int i; for (i = 0; i < TYCONHSZ; i++)
697 assert (tyconHash[i] == 0
698 || isTycon(tyconHash[i])
699 || isTuple(tyconHash[i]));
703 tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
704 tyconHash[RC_T(h)] = tc;
707 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
709 if (!isPair(id)) internal("findQualTycon");
713 return findTycon(textOf(id));
715 Text t = qtextOf(id);
716 Module m = findQualifier(qmodOf(id));
718 if (isNull(m)) return NIL;
719 for(es=module(m).exports; nonNull(es); es=tl(es)) {
721 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
726 default : internal("findQualTycon2");
728 return NIL; /* NOTREACHED */
731 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
737 Tycon tc = newTycon(t);
739 tycon(tc).kind = kind;
740 tycon(tc).what = what;
741 tycon(tc).defn = defn;
742 tycon(tc).arity = ar;
746 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
751 String s = textToStr(tycon(tc).text);
753 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
754 if (hd(curr)==tc) /* just in case we get duplicates! */
760 tl(prev) = cons(tc,curr);
764 return cons(tc,curr);
767 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
768 String pat; /* to list of Tycons ts */
769 List ts; { /* Null pattern matches every tycon*/
770 Tycon tc; /* (Tycons with NIL kind excluded) */
771 for (tc = TYCON_BASE_ADDR;
772 tc < TYCON_BASE_ADDR+tabTyconSz; ++tc)
773 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
774 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
775 if (nonNull(tycon(tc).kind))
776 ts = insertTycon(tc,ts);
780 Text ghcTupleText_n ( Int n )
785 if (n < 0 || n >= 100) internal("ghcTupleText_n");
786 if (n == 1) internal("ghcTupleText_n==1");
788 for (i = 1; i <= n-1; i++) buf[x++] = ',';
791 return findText(buf);
794 Text ghcTupleText(tup)
797 assert(isTuple(tup));
799 return ghcTupleText_n ( tupleOf(tup) );
803 Tycon mkTuple ( Int n )
807 internal("mkTuple: request for tuple of unsupported size");
808 for (i = TYCON_BASE_ADDR;
809 i < TYCON_BASE_ADDR+tabTyconSz; i++)
810 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
811 if (tycon(i).tuple == n) return i;
812 internal("mkTuple: request for non-existent tuple");
816 /* --------------------------------------------------------------------------
819 * A Name represents a top level binding of a value to an identifier.
820 * Such values may be a constructor function, a member function in a
821 * class, a user-defined or primitive value/function.
823 * Names are indexed by Text values ... a very simple hash functions speeds
824 * access to the table of Names and Name entries with the same hash value
825 * are chained together, with the most recent entry at the front of the
827 * ------------------------------------------------------------------------*/
829 #define NAMEHSZ 256 /* Size of Name hash table */
830 static Name nameHash[NAMEHSZ]; /* Hash table storage */
832 static int nHash(Text x)
834 assert(isText(x) || inventedText(x));
842 assert (x >= 0 && x < NAMEHSZ);
846 void hashSanity ( void )
849 for (i = 0; i < TYCONHSZ; i++) {
852 assert(isTycon(j) || isTuple(j));
853 j = tycon(j).nextTyconHash;
856 for (i = 0; i < NAMEHSZ; i++) {
860 j = name(j).nextNameHash;
865 Name newName ( Text t, Cell parent ) /* Add new name to name table */
868 Name nm = allocNewName();
870 [nm-NAME_BASE_ADDR].mod = currentModule;
871 name(nm).text = t; /* clear new name record */
873 name(nm).syntax = NO_SYNTAX;
874 name(nm).parent = parent;
876 name(nm).number = EXECNAME;
878 name(nm).hasStrict = FALSE;
879 name(nm).stgVar = NIL;
880 name(nm).callconv = NIL;
882 name(nm).primop = NULL;
883 name(nm).itbl = NULL;
884 module(currentModule).names = cons(nm,module(currentModule).names);
885 name(nm).nextNameHash = nameHash[RC_N(h)];
886 nameHash[RC_N(h)] = nm;
890 Name findName(t) /* Locate name in name table */
892 Name n = nameHash[RC_N(nHash(t))];
893 assert(isText(t) || isInventedVar(t) || isInventedDictVar(t));
894 assert(isName(n) || isNull(n));
895 while (nonNull(n) && name(n).text!=t)
896 n = name(n).nextNameHash;
900 Name addName(nm) /* Insert Name in name table - if */
901 Name nm; { /* no clash is caused */
904 oldnm = findName(name(nm).text);
907 module(currentModule).names=cons(nm,module(currentModule).names);
913 static Void local hashName(nm) /* Insert Name into hash table */
920 name(nm).nextNameHash = nameHash[RC_N(h)];
921 nameHash[RC_N(h)] = nm;
924 Name findQualName(id) /* Locate (possibly qualified) name*/
925 Cell id; { /* in name table */
927 internal("findQualName");
933 return findName(textOf(id));
935 Text t = qtextOf(id);
936 Module m = findQualifier(qmodOf(id));
938 if (isNull(m)) return NIL;
939 for(es=module(m).exports; nonNull(es); es=tl(es)) {
941 if (isName(e) && name(e).text==t)
943 else if (isPair(e) && DOTDOT==snd(e)) {
944 List subentities = NIL;
947 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
948 subentities = tycon(c).defn;
950 subentities = cclass(c).members;
951 for(; nonNull(subentities); subentities=tl(subentities)) {
952 if (!isName(hd(subentities)))
953 internal("findQualName3");
954 if (name(hd(subentities)).text == t)
955 return hd(subentities);
961 default : internal("findQualName2");
963 return 0; /* NOTREACHED */
967 Name nameFromStgVar ( StgVar v )
970 for (n = NAME_BASE_ADDR;
971 n < NAME_BASE_ADDR+tabNameSz; n++)
972 if (tabName[n-NAME_BASE_ADDR].inUse)
973 if (name(n).stgVar == v) return n;
977 void* getHugs_AsmObject_for ( char* s )
980 Text t = findText(s);
982 for (n = NAME_BASE_ADDR;
983 n < NAME_BASE_ADDR+tabNameSz; n++)
984 if (tabName[n-NAME_BASE_ADDR].inUse)
985 if (name(n).text == t) break;
986 if (n == NAME_BASE_ADDR+tabNameSz) {
987 fprintf ( stderr, "can't find `%s' in ...\n", s );
988 internal("getHugs_AsmObject_for(1)");
991 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
992 internal("getHugs_AsmObject_for(2)");
993 return ptrOf(stgVarInfo(v));
996 /* --------------------------------------------------------------------------
997 * Primitive functions:
998 * ------------------------------------------------------------------------*/
1000 Module findFakeModule ( Text t )
1002 Module m = findModule(t);
1004 if (!module(m).fake) internal("findFakeModule");
1007 module(m).fake = TRUE;
1013 Name addWiredInBoxingTycon
1014 ( String modNm, String typeNm, String constrNm,
1015 Int rep, Kind kind )
1019 Text modT = findText(modNm);
1020 Text typeT = findText(typeNm);
1021 Text conT = findText(constrNm);
1022 Module m = findFakeModule(modT);
1025 n = newName(conT,NIL);
1027 name(n).number = cfunNo(0);
1029 name(n).primop = (void*)rep;
1031 t = newTycon(typeT);
1032 tycon(t).what = DATATYPE;
1033 tycon(t).kind = kind;
1038 Tycon addTupleTycon ( Int n )
1046 for (i = TYCON_BASE_ADDR;
1047 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1048 if (tabTycon[i-TYCON_BASE_ADDR].inUse)
1049 if (tycon(i).tuple == n) return i;
1052 m = findFakeModule(findText(n==0 ? "PrelBase" : "PrelTup")); else
1053 m = findModule(findText("PrelPrim"));
1057 for (i = 0; i < n; i++) k = ap(STAR,k);
1058 t = newTycon(ghcTupleText_n(n));
1061 tycon(t).what = DATATYPE;
1064 /* maybe we want to do this for all n ? */
1065 nm = newName(ghcTupleText_n(n), t);
1066 name(nm).type = t; /* ummm ... for n > 0 */
1073 Tycon addWiredInEnumTycon ( String modNm, String typeNm,
1074 List /*of Text*/ constrs )
1078 Text modT = findText(modNm);
1079 Text typeT = findText(typeNm);
1080 Module m = findFakeModule(modT);
1083 t = newTycon(typeT);
1084 tycon(t).kind = STAR;
1085 tycon(t).what = DATATYPE;
1087 constrs = reverse(constrs);
1088 i = length(constrs);
1089 for (; nonNull(constrs); constrs=tl(constrs),i--) {
1090 Text conT = hd(constrs);
1091 Name con = newName(conT,t);
1092 name(con).number = cfunNo(i);
1094 name(con).parent = t;
1095 tycon(t).defn = cons(con, tycon(t).defn);
1101 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
1102 Text t; /* sets rep, not type */
1105 Int rep; { /* Really AsmRep */
1106 Name n = newName(t,NIL);
1107 name(n).arity = arity;
1108 name(n).number = cfunNo(no);
1110 name(n).primop = (void*)rep;
1115 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
1120 Name n = newName(t,NIL);
1121 name(n).arity = arity;
1122 name(n).number = cfunNo(no);
1123 name(n).type = type;
1128 Int sfunPos(s,c) /* Find position of field with */
1129 Name s; /* selector s in constructor c. */
1133 for (; nonNull(cns); cns=tl(cns))
1134 if (fst(hd(cns))==c)
1135 return intOf(snd(hd(cns)));
1136 internal("sfunPos");
1137 return 0;/* NOTREACHED */
1140 static List local insertName(nm,ns) /* insert name nm into sorted list */
1145 String s = textToStr(name(nm).text);
1147 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
1148 if (hd(curr)==nm) /* just in case we get duplicates! */
1153 if (nonNull(prev)) {
1154 tl(prev) = cons(nm,curr);
1158 return cons(nm,curr);
1161 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
1162 String pat; /* to list of names ns */
1163 List ns; { /* Null pattern matches every name */
1164 Name nm; /* (Names with NIL type, or hidden */
1165 /* or invented names are excluded) */
1167 for (nm = NAME_BASE_ADDR;
1168 nm < NAME_BASE_ADDR+tabNameSz; ++nm)
1169 if (tabName[nm-NAME_BASE_ADDR].inUse) {
1170 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
1171 String str = textToStr(name(nm).text);
1172 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1173 ns = insertName(nm,ns);
1178 List mns = module(currentModule).names;
1179 for(; nonNull(mns); mns=tl(mns)) {
1181 if (!inventedText(name(nm).text)) {
1182 String str = textToStr(name(nm).text);
1183 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
1184 ns = insertName(nm,ns);
1191 /* --------------------------------------------------------------------------
1192 * A simple string matching routine
1193 * `*' matches any sequence of zero or more characters
1194 * `?' matches any single character exactly
1195 * `@str' matches the string str exactly (ignoring any special chars)
1196 * `\c' matches the character c only (ignoring special chars)
1197 * c matches the character c only
1198 * ------------------------------------------------------------------------*/
1200 static Void local patternError(s) /* report error in pattern */
1202 ERRMSG(0) "%s in pattern", s
1206 static Bool local stringMatch(pat,str) /* match string against pattern */
1212 case '\0' : return (*str=='\0');
1215 if (stringMatch(pat+1,str))
1220 case '?' : if (*str++=='\0')
1225 case '[' : { Bool found = FALSE;
1226 while (*++pat!='\0' && *pat!=']')
1227 if (!found && ( pat[0] == *str ||
1236 patternError("missing `]'");
1244 case '\\' : if (*++pat == '\0')
1245 patternError("extra trailing `\\'");
1247 default : if (*pat++ != *str++)
1253 /* --------------------------------------------------------------------------
1254 * Storage of type classes, instances etc...:
1255 * ------------------------------------------------------------------------*/
1257 static List classes; /* list of classes in current scope */
1259 Class newClass ( Text t ) /* add new class to class table */
1261 Class cl = allocNewClass();
1263 [cl-CCLASS_BASE_ADDR].mod = currentModule;
1264 cclass(cl).text = t;
1265 cclass(cl).arity = 0;
1266 cclass(cl).kinds = NIL;
1267 cclass(cl).head = NIL;
1268 cclass(cl).fds = NIL;
1269 cclass(cl).xfds = NIL;
1270 cclass(cl).dcon = NIL;
1271 cclass(cl).supers = NIL;
1272 cclass(cl).dsels = NIL;
1273 cclass(cl).members = NIL;
1274 cclass(cl).defaults = NIL;
1275 cclass(cl).instances = NIL;
1276 classes = cons(cl,classes);
1277 module(currentModule).classes
1278 = cons(cl,module(currentModule).classes);
1282 Class findClass(t) /* look for named class in table */
1286 for (cs=classes; nonNull(cs); cs=tl(cs)) {
1288 if (cclass(cl).text==t)
1294 Class addClass(c) /* Insert Class in class list */
1295 Class c; { /* - if no clash caused */
1297 assert(whatIs(c)==CLASS);
1298 oldc = findClass(cclass(c).text);
1300 classes=cons(c,classes);
1301 module(currentModule).classes=cons(c,module(currentModule).classes);
1308 Class findQualClass(c) /* Look for (possibly qualified) */
1309 Cell c; { /* class in class list */
1310 if (!isQualIdent(c)) {
1311 return findClass(textOf(c));
1313 Text t = qtextOf(c);
1314 Module m = findQualifier(qmodOf(c));
1318 for (es=module(m).exports; nonNull(es); es=tl(es)) {
1320 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
1327 Inst newInst() { /* Add new instance to table */
1328 Inst in = allocNewInst();
1330 [in-INST_BASE_ADDR].mod = currentModule;
1331 inst(in).kinds = NIL;
1332 inst(in).head = NIL;
1333 inst(in).specifics = NIL;
1334 inst(in).implements = NIL;
1335 inst(in).builder = NIL;
1340 extern Void printInst ( Inst));
1344 Class cl = inst(in).c;
1345 Printf("%s-", textToStr(cclass(cl).text));
1346 printType(stdout,inst(in).t);
1348 #endif /* DEBUG_DICTS */
1350 Inst findFirstInst(tc) /* look for 1st instance involving */
1351 Tycon tc; { /* the type constructor tc */
1352 return findNextInst(tc,INST_BASE_ADDR-1);
1355 Inst findNextInst(tc,in) /* look for next instance involving*/
1356 Tycon tc; /* the type constructor tc */
1357 Inst in; { /* starting after instance in */
1359 while (++in < INST_BASE_ADDR+tabInstSz) {
1360 if (!tabInst[in-INST_BASE_ADDR].inUse) continue;
1361 assert(isModule(inst(in).mod));
1363 for (; isAp(pi); pi=fun(pi))
1364 if (typeInvolves(arg(pi),tc))
1370 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1371 Type ty; /* type constructor/tuple tc. */
1374 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1375 || typeInvolves(arg(ty),tc)));
1379 /* Needed by finishGHCInstance to find classes, before the
1380 export list has been built -- so we can't use
1383 Class findQualClassWithoutConsultingExportList ( QualId q )
1393 t_class = textOf(q);
1396 t_class = qtextOf(q);
1399 for (cl = CCLASS_BASE_ADDR;
1400 cl < CCLASS_BASE_ADDR+tabClassSz; cl++) {
1401 if (tabClass[cl-CCLASS_BASE_ADDR].inUse)
1402 if (cclass(cl).text == t_class) {
1403 /* Class name is ok, but is this the right module? */
1404 if (isNull(t_mod) /* no module name specified */
1406 && t_mod == module(cclass(cl).mod).text)
1414 /* Same deal, except for Tycons. */
1415 Tycon findQualTyconWithoutConsultingExportList ( QualId q )
1425 t_tycon = textOf(q);
1428 t_tycon = qtextOf(q);
1431 for (tc = TYCON_BASE_ADDR;
1432 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1433 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1434 if (tycon(tc).text == t_tycon) {
1435 /* Tycon name is ok, but is this the right module? */
1436 if (isNull(t_mod) /* no module name specified */
1438 && t_mod == module(tycon(tc).mod).text)
1446 /* Same deal, except for Names. */
1447 Name findQualNameWithoutConsultingExportList ( QualId q )
1453 assert(isQVar(q) || isQCon(q));
1455 if (isCon(q) || isVar(q)) {
1460 t_name = qtextOf(q);
1463 for (nm = NAME_BASE_ADDR;
1464 nm < NAME_BASE_ADDR+tabNameSz; nm++) {
1465 if (tabName[nm-NAME_BASE_ADDR].inUse)
1466 if (name(nm).text == t_name) {
1467 /* Name is ok, but is this the right module? */
1468 if (isNull(t_mod) /* no module name specified */
1470 && t_mod == module(name(nm).mod).text)
1479 Tycon findTyconInAnyModule ( Text t )
1482 for (tc = TYCON_BASE_ADDR;
1483 tc < TYCON_BASE_ADDR+tabTyconSz; tc++)
1484 if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
1485 if (tycon(tc).text == t) return tc;
1489 Class findClassInAnyModule ( Text t )
1492 for (cc = CCLASS_BASE_ADDR;
1493 cc < CCLASS_BASE_ADDR+tabClassSz; cc++)
1494 if (tabClass[cc-CCLASS_BASE_ADDR].inUse)
1495 if (cclass(cc).text == t) return cc;
1499 Name findNameInAnyModule ( Text t )
1502 for (nm = NAME_BASE_ADDR;
1503 nm < NAME_BASE_ADDR+tabNameSz; nm++)
1504 if (tabName[nm-NAME_BASE_ADDR].inUse)
1505 if (name(nm).text == t) return nm;
1510 /* returns List of QualId */
1511 List getAllKnownTyconsAndClasses ( void )
1516 for (tc = TYCON_BASE_ADDR;
1517 tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
1518 if (tabTycon[tc-TYCON_BASE_ADDR].inUse) {
1519 /* almost certainly undue paranoia about duplicate avoidance */
1520 QualId q = mkQCon( module(tycon(tc).mod).text, tycon(tc).text );
1521 if (!qualidIsMember(q,xs))
1522 xs = cons ( q, xs );
1525 for (nw = CCLASS_BASE_ADDR;
1526 nw < CCLASS_BASE_ADDR+tabClassSz; nw++) {
1527 if (tabClass[nw-CCLASS_BASE_ADDR].inUse) {
1528 QualId q = mkQCon( module(cclass(nw).mod).text, cclass(nw).text );
1529 if (!qualidIsMember(q,xs))
1530 xs = cons ( q, xs );
1536 Int numQualifiers ( Type t )
1538 if (isPolyType(t)) t = monotypeOf(t);
1540 return length ( fst(snd(t)) ); else
1545 /* Purely for debugging. */
1546 void locateSymbolByName ( Text t )
1549 for (i = NAME_BASE_ADDR;
1550 i < NAME_BASE_ADDR+tabNameSz; i++)
1551 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).text == t)
1552 fprintf ( stderr, "name(%d)\n", i-NAME_BASE_ADDR);
1553 for (i = TYCON_BASE_ADDR;
1554 i < TYCON_BASE_ADDR+tabTyconSz; i++)
1555 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).text == t)
1556 fprintf ( stderr, "tycon(%d)\n", i-TYCON_BASE_ADDR);
1557 for (i = CCLASS_BASE_ADDR;
1558 i < CCLASS_BASE_ADDR+tabClassSz; i++)
1559 if (tabClass[i-CCLASS_BASE_ADDR].inUse && cclass(i).text == t)
1560 fprintf ( stderr, "class(%d)\n", i-CCLASS_BASE_ADDR);
1563 /* --------------------------------------------------------------------------
1566 * Various parts of the system use a stack of cells. Most of the stack
1567 * operations are defined as macros, expanded inline.
1568 * ------------------------------------------------------------------------*/
1570 Cell cellStack[NUM_STACK]; /* Storage for cells on stack */
1571 StackPtr sp; /* stack pointer */
1573 Void hugsStackOverflow() { /* Report stack overflow */
1574 ERRMSG(0) "Control stack overflow"
1579 /* --------------------------------------------------------------------------
1582 * A Module represents a user defined module.
1584 * Note: there are now two lookup mechanisms in the system:
1586 * 1) The exports from a module are stored in a big list.
1587 * We resolve qualified names, and import lists by linearly scanning
1588 * through this list.
1590 * 2) Unqualified imports and local definitions for the current module
1591 * are stored in hash tables (tyconHash and nameHash) or linear lists
1594 * ------------------------------------------------------------------------*/
1596 Module currentModule; /* Module currently being processed*/
1598 Bool isValidModule(m) /* is m a legitimate module id? */
1603 Module newModule ( Text t ) /* add new module to module table */
1605 Module mod = allocNewModule();
1606 module(mod).text = t; /* clear new module record */
1608 module(mod).tycons = NIL;
1609 module(mod).names = NIL;
1610 module(mod).classes = NIL;
1611 module(mod).exports = NIL;
1612 module(mod).qualImports = NIL;
1613 module(mod).fake = FALSE;
1615 module(mod).tree = NIL;
1616 module(mod).completed = FALSE;
1617 module(mod).lastStamp = 0; /* ???? */
1619 module(mod).mode = NIL;
1620 module(mod).srcExt = findText("");
1621 module(mod).uses = NIL;
1623 module(mod).objName = findText("");
1624 module(mod).objSize = 0;
1626 module(mod).object = NULL;
1627 module(mod).objectExtras = NULL;
1628 module(mod).objectExtraNames = NIL;
1633 Bool nukeModule_needs_major_gc = TRUE;
1635 void nukeModule ( Module m )
1641 if (!isModule(m)) internal("nukeModule");
1643 /* fprintf ( stderr, "NUKE MODULE %s\n", textToStr(module(m).text) ); */
1645 /* see comment in compiler.c about this,
1646 and interaction with info tables */
1647 if (nukeModule_needs_major_gc) {
1648 /* fprintf ( stderr, "doing major GC in nukeModule\n"); */
1649 /* performMajorGC(); */
1650 nukeModule_needs_major_gc = FALSE;
1653 oc = module(m).object;
1659 oc = module(m).objectExtras;
1666 for (i = NAME_BASE_ADDR; i < NAME_BASE_ADDR+tabNameSz; i++)
1667 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).mod == m) {
1669 module(name(i).mod).mode == FM_SOURCE) {
1672 name(i).itbl = NULL;
1676 for (i = TYCON_BASE_ADDR; i < TYCON_BASE_ADDR+tabTyconSz; i++)
1677 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).mod == m) {
1678 if (tycon(i).itbl &&
1679 module(tycon(i).mod).mode == FM_SOURCE) {
1680 free(tycon(i).itbl);
1682 tycon(i).itbl = NULL;
1686 for (i = CCLASS_BASE_ADDR; i < CCLASS_BASE_ADDR+tabClassSz; i++)
1687 if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
1688 if (cclass(i).mod == m) {
1691 List /* Inst */ ins;
1692 List /* Inst */ ins2 = NIL;
1693 for (ins = cclass(i).instances; nonNull(ins); ins=tl(ins))
1694 if (inst(hd(ins)).mod != m)
1695 ins2 = cons(hd(ins),ins2);
1696 cclass(i).instances = ins2;
1701 for (i = INST_BASE_ADDR; i < INST_BASE_ADDR+tabInstSz; i++)
1702 if (tabInst[i-INST_BASE_ADDR].inUse && inst(i).mod == m)
1706 //for (i = 0; i < TYCONHSZ; i++) tyconHash[i] = 0;
1707 //for (i = 0; i < NAMEHSZ; i++) nameHash[i] = 0;
1712 void ppModules ( void )
1715 fflush(stderr); fflush(stdout);
1716 printf ( "begin MODULES\n" );
1717 for (i = MODULE_BASE_ADDR+tabModuleSz-1;
1718 i >= MODULE_BASE_ADDR; i--)
1719 if (tabModule[i-MODULE_BASE_ADDR].inUse)
1720 printf ( " %2d: %16s\n",
1721 i-MODULE_BASE_ADDR, textToStr(module(i).text)
1723 printf ( "end MODULES\n" );
1724 fflush(stderr); fflush(stdout);
1728 Module findModule(t) /* locate Module in module table */
1731 for(m = MODULE_BASE_ADDR;
1732 m < MODULE_BASE_ADDR+tabModuleSz; ++m) {
1733 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1734 if (module(m).text==t)
1740 Module findModid(c) /* Find module by name or filename */
1742 switch (whatIs(c)) {
1743 case STRCELL : internal("findModid-STRCELL unimp");
1744 case CONIDCELL : return findModule(textOf(c));
1745 default : internal("findModid");
1747 return NIL;/*NOTUSED*/
1750 static local Module findQualifier(t) /* locate Module in import list */
1753 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1754 if (textOf(fst(hd(ms)))==t)
1757 if (module(currentModule).text==t)
1758 return currentModule;
1762 Void setCurrModule(m) /* set lookup tables for current module */
1765 assert(isModule(m));
1766 /* fprintf(stderr, "SET CURR MODULE %s %d\n", textToStr(module(m).text),m); */
1768 for (t = module(m).names; nonNull(t); t=tl(t))
1769 assert(isName(hd(t)));
1770 for (t = module(m).tycons; nonNull(t); t=tl(t))
1771 assert(isTycon(hd(t)) || isTuple(hd(t)));
1772 for (t = module(m).classes; nonNull(t); t=tl(t))
1773 assert(isClass(hd(t)));
1776 currentModule = m; /* This is the only assignment to currentModule */
1777 for (i=0; i<TYCONHSZ; ++i)
1778 tyconHash[RC_T(i)] = NIL;
1779 mapProc(hashTycon,module(m).tycons);
1780 for (i=0; i<NAMEHSZ; ++i)
1781 nameHash[RC_N(i)] = NIL;
1782 mapProc(hashName,module(m).names);
1783 classes = module(m).classes;
1787 Name jrsFindQualName ( Text mn, Text sn )
1792 for (m = MODULE_BASE_ADDR;
1793 m < MODULE_BASE_ADDR+tabModuleSz; m++)
1794 if (tabModule[m-MODULE_BASE_ADDR].inUse
1795 && module(m).text == mn) break;
1797 if (m == MODULE_BASE_ADDR+tabModuleSz) return NIL;
1799 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1800 if (name(hd(ns)).text == sn) return hd(ns);
1806 char* nameFromOPtr ( void* p )
1810 for (m = MODULE_BASE_ADDR;
1811 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1812 if (tabModule[m-MODULE_BASE_ADDR].inUse && module(m).object) {
1813 char* nm = ocLookupAddr ( module(m).object, p );
1818 /* A kludge to assist Win32 debugging; not actually necessary. */
1819 { char* nm = nameFromStaticOPtr(p);
1827 void* lookupOTabName ( Module m, char* sym )
1829 assert(isModule(m));
1830 if (module(m).object)
1831 return ocLookupSym ( module(m).object, sym );
1836 void* lookupOExtraTabName ( char* sym )
1840 for (m = MODULE_BASE_ADDR;
1841 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1842 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1843 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1844 void* ad = ocLookupSym ( oc, sym );
1852 /* Only call this if in dire straits; searches every object symtab
1853 in the system -- so is therefore slow.
1855 void* lookupOTabNameAbsolutelyEverywhere ( char* sym )
1860 for (m = MODULE_BASE_ADDR;
1861 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1862 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1863 if (module(m).object) {
1864 ad = ocLookupSym ( module(m).object, sym );
1867 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1868 ad = ocLookupSym ( oc, sym );
1877 OSectionKind lookupSection ( void* ad )
1884 for (m = MODULE_BASE_ADDR;
1885 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1886 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1887 if (module(m).object) {
1888 sect = ocLookupSection ( module(m).object, ad );
1889 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1892 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1893 sect = ocLookupSection ( oc, ad );
1894 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1899 return HUGS_SECTIONKIND_OTHER;
1903 /* --------------------------------------------------------------------------
1906 * Provides a garbage collectable heap for storage of expressions etc.
1908 * Now incorporates a flat resource: A two-space collected extension of
1909 * the heap that provides storage for contiguous arrays of Cell storage,
1910 * cooperating with the garbage collection mechanisms for the main heap.
1911 * ------------------------------------------------------------------------*/
1913 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1914 Heap heapFst; /* array of fst component of pairs */
1915 Heap heapSnd; /* array of snd component of pairs */
1918 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1919 /* C stack; use with extreme care! */
1921 Int numGcs; /* number of garbage collections */
1922 Int cellsRecovered; /* number of cells recovered */
1924 static Cell freeList; /* free list of unused cells */
1925 static Cell lsave, rsave; /* save components of pair */
1929 static Int markCount, stackRoots;
1931 #define initStackRoots() stackRoots = 0
1932 #define recordStackRoot() stackRoots++
1945 #define start() markCount = 0
1946 #define end(thing,rs) \
1948 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1951 #define recordMark() markCount++
1953 #else /* !GC_STATISTICS */
1958 #define initStackRoots()
1959 #define recordStackRoot()
1962 #define end(thing,root)
1963 #define recordMark()
1965 #endif /* !GC_STATISTICS */
1967 Cell pair(l,r) /* Allocate pair (l, r) from */
1968 Cell l, r; { /* heap, garbage collecting first */
1969 Cell c = freeList; /* if necessary ... */
1980 freeList = snd(freeList);
1988 static Int marksSize;
1990 void mark ( Cell root )
1993 Cell mstack[NUM_MSTACK];
1997 mstack[++msp] = root;
2000 if (msp > msp_max) msp_max = msp;
2002 if (!isGenPair(c)) continue;
2003 if (fst(c)==FREECELL) continue;
2005 register int place = placeInSet(c);
2006 register int mask = maskInSet(c);
2007 if (!(marks[place]&mask)) {
2008 marks[place] |= mask;
2009 if (msp >= NUM_MSTACK-5) {
2011 "hugs: fatal stack overflow during GC. "
2012 "Increase NUM_MSTACK.\n" );
2015 mstack[++msp] = fst(c);
2016 mstack[++msp] = snd(c);
2020 // fprintf(stderr, "%d ",msp_max);
2024 Void garbageCollect() { /* Run garbage collector ... */
2025 /* disable break checking */
2030 jmp_buf regs; /* save registers on stack */
2031 HugsBreakAction oldBrk
2032 = setBreakAction ( HugsIgnoreBreak );
2038 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
2041 everybody(MARK); /* Mark all components of system */
2043 gcScanning(); /* scan mark set */
2050 for (i=1; i<=heapSize; i++) {
2051 if ((marks[place] & mask) == 0) {
2058 if (++j == bitsPerWord) {
2065 gcRecovered(recovered);
2066 setBreakAction ( oldBrk );
2070 #if defined(DEBUG_STORAGE) || defined(DEBUG_STORAGE_EXTRA)
2071 /* fprintf(stderr, "\n--- GC recovered %d\n",recovered ); */
2074 /* can only return if freeList is nonempty on return. */
2075 if (recovered<minRecovery || isNull(freeList)) {
2076 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
2079 cellsRecovered = recovered;
2082 /* --------------------------------------------------------------------------
2083 * Code for saving last expression entered:
2085 * This is a little tricky because some text values (e.g. strings or variable
2086 * names) may not be defined or have the same value when the expression is
2087 * recalled. These text values are therefore saved in the top portion of
2089 * ------------------------------------------------------------------------*/
2091 static Cell lastExprSaved; /* last expression to be saved */
2093 Void setLastExpr(e) /* save expression for later recall*/
2095 lastExprSaved = NIL; /* in case attempt to save fails */
2096 savedText = TEXT_SIZE;
2097 lastExprSaved = lowLevelLastIn(e);
2100 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
2101 Cell c; { /* acyclic graph) for later recall */
2102 if (isPair(c)) { /* Duplicating any text strings */
2103 if (isTagNonPtr(fst(c))) /* in case these are lost at some */
2104 switch (fst(c)) { /* point before the expr is reused */
2110 case STRCELL : return pair(fst(c),saveText(textOf(c)));
2111 default : return pair(fst(c),snd(c));
2114 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2118 return pair(EXTCOPY,saveText(extText(c)));
2124 Cell getLastExpr() { /* recover previously saved expr */
2125 return lowLevelLastOut(lastExprSaved);
2128 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
2129 Cell c; { /* except that Cells refering to */
2130 if (isPair(c)) { /* Text values are restored to */
2131 if (isTagNonPtr(fst(c))) /* appropriate values */
2138 case STRCELL : return pair(fst(c),
2139 findText(text+intValOf(c)));
2141 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
2143 default : return pair(fst(c),snd(c));
2146 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2152 /* --------------------------------------------------------------------------
2153 * Miscellaneous operations on heap cells:
2154 * ------------------------------------------------------------------------*/
2156 Cell whatIs ( register Cell c )
2159 register Cell fstc = fst(c);
2160 return isTag(fstc) ? fstc : AP;
2162 if (isOffset(c)) return OFFSET;
2163 if (isChar(c)) return CHARCELL;
2164 if (isInt(c)) return INTCELL;
2165 if (isName(c)) return NAME;
2166 if (isTycon(c)) return TYCON;
2167 if (isTuple(c)) return TUPLE;
2168 if (isClass(c)) return CLASS;
2169 if (isInst(c)) return INSTANCE;
2170 if (isModule(c)) return MODULE;
2171 if (isText(c)) return TEXTCELL;
2172 if (isInventedVar(c)) return INVAR;
2173 if (isInventedDictVar(c)) return INDVAR;
2174 if (isSpec(c)) return c;
2175 if (isNull(c)) return c;
2176 fprintf ( stderr, "whatIs: unknown %d\n", c );
2182 Cell whatIs(c) /* identify type of cell */
2185 register Cell fstc = fst(c);
2186 return isTag(fstc) ? fstc : AP;
2188 if (c<OFFMIN) return c;
2190 if (isExt(c)) return EXT;
2192 if (c>=INTMIN) return INTCELL;
2194 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
2196 else if (c>=INSTMIN) return INSTANCE;
2198 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
2199 else return MODULE;}
2200 else if (c>=OFFMIN) return OFFSET;
2202 else return (c>=EXTMIN) ?
2210 register Cell fstc = fst(c);
2211 return isTag(fstc) ? fstc : AP;
2213 if (c>=INTMIN) return INTCELL;
2214 if (c>=CHARMIN) return CHARCELL;
2215 if (c>=CLASSMIN) return CLASS;
2216 if (c>=INSTMIN) return INSTANCE;
2217 if (c>=NAMEMIN) return NAME;
2218 if (c>=TYCMIN) return TYCON;
2219 if (c>=MODMIN) return MODULE;
2220 if (c>=OFFMIN) return OFFSET;
2222 if (c>=EXTMIN) return EXT;
2224 if (c>=TUPMIN) return TUPLE;
2230 /* A very, very simple printer.
2231 * Output is uglier than from printExp - but the printer is more
2232 * robust and can be used on any data structure irrespective of
2235 Void print ( Cell c, Int depth )
2240 else if (isNull(c)) {
2243 else if (isTagPtr(c)) {
2244 Printf("TagP(%d)", c);
2246 else if (isTagNonPtr(c)) {
2247 Printf("TagNP(%d)", c);
2249 else if (isSpec(c) && c != STAR) {
2250 Printf("TagS(%d)", c);
2252 else if (isText(c)) {
2253 Printf("text(%d)=\"%s\"",c-TEXT_BASE_ADDR,textToStr(c));
2255 else if (isInventedVar(c)) {
2256 Printf("invented(%d)", c-INVAR_BASE_ADDR);
2258 else if (isInventedDictVar(c)) {
2259 Printf("inventedDict(%d)",c-INDVAR_BASE_ADDR);
2262 Int tag = whatIs(c);
2266 print(fst(c), depth-1);
2268 print(snd(c), depth-1);
2272 Printf("free(%d)", c);
2275 Printf("int(%d)", intOf(c));
2278 Printf("bignum(%s)", bignumToString(c));
2281 Printf("char('%c')", charOf(c));
2284 Printf("ptr(%p)",ptrOf(c));
2287 Printf("class(%d)", c-CCLASS_BASE_ADDR);
2288 Printf("=\"%s\"", textToStr(cclass(c).text));
2291 Printf("instance(%d)", c - INST_BASE_ADDR);
2294 Printf("name(%d)", c-NAME_BASE_ADDR);
2295 Printf("=\"%s\"", textToStr(name(c).text));
2298 Printf("tycon(%d)", c-TYCON_BASE_ADDR);
2299 Printf("=\"%s\"", textToStr(tycon(c).text));
2302 Printf("module(%d)", c - MODULE_BASE_ADDR);
2303 Printf("=\"%s\"", textToStr(module(c).text));
2306 Printf("Offset %d", offsetOf(c));
2309 Printf("%s", textToStr(ghcTupleText(c)));
2313 print(snd(c),depth-1);
2317 print(snd(c),depth-1);
2321 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2322 Printf("%d ", intOf(fst(snd(c))));
2323 print(snd(snd(c)),depth-1);
2325 print(snd(c),depth-1);
2339 Printf("{dict %d}",textOf(c));
2345 Printf("{id %s}",textToStr(textOf(c)));
2349 Printf("{ip %s}",textToStr(textOf(c)));
2352 Printf("?%s",textToStr(textOf(c)));
2356 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2360 print(fst(snd(c)),depth-1);
2362 print(snd(snd(c)),depth-1);
2367 print(snd(c),depth-1);
2372 print(snd(c),depth-1);
2377 print(fst(snd(c)),depth-1);
2379 print(snd(snd(c)),depth-1);
2384 print(fst(snd(c)),depth-1);
2386 print(snd(snd(c)),depth-1);
2390 Printf("FromQual(");
2391 print(fst(snd(c)),depth-1);
2393 print(snd(snd(c)),depth-1);
2397 Printf("StgVar%d=",-c);
2398 print(snd(c), depth-1);
2402 print(fst(snd(c)),depth-1);
2404 print(snd(snd(c)),depth-1);
2409 print(fst(snd(c)),depth-1);
2411 print(snd(snd(c)),depth-1);
2416 print(fst(snd(c)),depth-1);
2418 print(snd(snd(c)),depth-1);
2422 Printf("PrimCase(");
2423 print(fst(snd(c)),depth-1);
2425 print(snd(snd(c)),depth-1);
2430 print(snd(c),depth-1);
2434 Printf("(UNBOXEDTUP,");
2435 print(snd(c),depth-1);
2440 print(zfst(c),depth-1);
2442 print(zsnd(c),depth-1);
2446 Printf("<ZTriple ");
2447 print(zfst3(c),depth-1);
2449 print(zsnd3(c),depth-1);
2451 print(zthd3(c),depth-1);
2456 print(snd(c),depth-1);
2460 if (isTagNonPtr(tag)) {
2461 Printf("(TagNP=%d,%d)", c, tag);
2462 } else if (isTagPtr(tag)) {
2463 Printf("(TagP=%d,",tag);
2464 print(snd(c), depth-1);
2467 } else if (c == tag) {
2468 Printf("Tag(%d)", c);
2470 Printf("Tag(%d)=%d", c, tag);
2479 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2480 Cell c; { /* also recognises DICTVAR cells */
2482 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2485 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2487 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2490 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2492 if (!isPair(c)) return FALSE;
2495 case VAROPCELL : return TRUE;
2497 case QUALIDENT : return isVar(snd(snd(c)));
2499 default : return FALSE;
2503 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2505 if (!isPair(c)) return FALSE;
2508 case CONOPCELL : return TRUE;
2510 case QUALIDENT : return isCon(snd(snd(c)));
2512 default : return FALSE;
2516 Bool isQualIdent(c) /* is cell a qualified identifier? */
2518 return isPair(c) && (fst(c)==QUALIDENT);
2521 Bool eqQualIdent ( QualId c1, QualId c2 )
2523 assert(isQualIdent(c1));
2524 if (!isQualIdent(c2)) {
2525 assert(isQualIdent(c2));
2527 return qmodOf(c1)==qmodOf(c2) &&
2528 qtextOf(c1)==qtextOf(c2);
2531 Bool isIdent(c) /* is cell an identifier? */
2533 if (!isPair(c)) return FALSE;
2538 case CONOPCELL : return TRUE;
2540 case QUALIDENT : return TRUE;
2542 default : return FALSE;
2546 Bool isInt(c) /* cell holds integer value? */
2548 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2551 Int intOf(c) /* find integer value of cell? */
2554 return isPair(c) ? (Int)(snd(c)) : (Int)(c-SMALL_INT_ZERO);
2557 Cell mkInt(n) /* make cell representing integer */
2559 return (SMALL_INT_MIN <= SMALL_INT_ZERO+n &&
2560 SMALL_INT_ZERO+n <= SMALL_INT_MAX)
2565 #if SIZEOF_VOID_P == SIZEOF_INT
2567 typedef union {Int i; Ptr p;} IntOrPtr;
2574 return pair(PTRCELL,x.i);
2581 assert(fst(c) == PTRCELL);
2591 return pair(CPTRCELL,x.i);
2598 assert(fst(c) == CPTRCELL);
2603 #elif SIZEOF_VOID_P == 2*SIZEOF_INT
2605 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2612 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2619 assert(fst(c) == PTRCELL);
2620 x.i.i1 = intOf(fst(snd(c)));
2621 x.i.i2 = intOf(snd(snd(c)));
2630 return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2637 assert(fst(c) == CPTRCELL);
2638 x.i.i1 = intOf(fst(snd(c)));
2639 x.i.i2 = intOf(snd(snd(c)));
2645 #error "Can't implement mkPtr/ptrOf on this architecture."
2650 String stringNegate( s )
2658 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2663 /* --------------------------------------------------------------------------
2665 * ------------------------------------------------------------------------*/
2667 Int length(xs) /* calculate length of list xs */
2670 for (; nonNull(xs); ++n)
2675 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2676 List xs, ys; { /* ys by modifying xs ... */
2681 while (nonNull(tl(zs)))
2688 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2691 for (; nonNull(xs); xs=tl(xs))
2692 ys = cons(hd(xs),ys);
2696 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2699 return revOnto(dupOnto(xs,NIL),ys);
2702 List dupList(xs) /* Duplicate spine of list xs */
2705 for (; nonNull(xs); xs=tl(xs))
2706 ys = cons(hd(xs),ys);
2710 List revOnto(xs,ys) /* Destructively reverse elements of*/
2711 List xs, ys; { /* list xs onto list ys... */
2714 while (nonNull(xs)) {
2723 QualId qualidIsMember ( QualId q, List xs )
2725 for (; nonNull(xs); xs=tl(xs)) {
2726 if (eqQualIdent(q, hd(xs)))
2732 Cell varIsMember(t,xs) /* Test if variable is a member of */
2733 Text t; /* given list of variables */
2735 assert(isText(t) || isInventedVar(t) || isInventedDictVar(t));
2736 for (; nonNull(xs); xs=tl(xs))
2737 if (t==textOf(hd(xs)))
2742 Name nameIsMember(t,ns) /* Test if name with text t is a */
2743 Text t; /* member of list of names xs */
2745 for (; nonNull(ns); ns=tl(ns))
2746 if (t==name(hd(ns)).text)
2751 Cell intIsMember(n,xs) /* Test if integer n is member of */
2752 Int n; /* given list of integers */
2754 for (; nonNull(xs); xs=tl(xs))
2755 if (n==intOf(hd(xs)))
2760 Cell cellIsMember(x,xs) /* Test for membership of specific */
2761 Cell x; /* cell x in list xs */
2763 for (; nonNull(xs); xs=tl(xs))
2769 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2772 for (; nonNull(xs); xs=tl(xs))
2778 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2779 Cell c; /* association lists */
2781 for (; nonNull(xs); xs=tl(xs))
2787 List replicate(n,x) /* create list of n copies of x */
2796 List diffList(from,take) /* list difference: from\take */
2797 List from, take; { /* result contains all elements of */
2798 List result = NIL; /* `from' not appearing in `take' */
2800 while (nonNull(from)) {
2801 List next = tl(from);
2802 if (!cellIsMember(hd(from),take)) {
2811 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2815 for(;nonNull(xs);xs=tl(xs)) {
2818 result=cons(x,result);
2824 List take(n,xs) /* destructively truncate list to */
2825 Int n; /* specified length */
2831 while (1<n-- && nonNull(xs))
2838 List splitAt(n,xs) /* drop n things from front of list*/
2847 Cell nth(n,xs) /* extract n'th element of list */
2850 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2857 List removeCell(x,xs) /* destructively remove cell from */
2862 return tl(xs); /* element at front of list */
2866 for (; nonNull(curr); prev=curr, curr=tl(prev))
2868 tl(prev) = tl(curr);
2869 return xs; /* element in middle of list */
2873 return xs; /* here if element not found */
2876 List nubList(xs) /* nuke dups in list */
2877 List xs; { /* non destructive */
2879 for (; nonNull(xs); xs=tl(xs))
2880 if (isNull(cellIsMember(hd(xs),outs)))
2881 outs = cons(hd(xs),outs);
2887 /* --------------------------------------------------------------------------
2888 * Tagged tuples (experimental)
2889 * ------------------------------------------------------------------------*/
2891 static void z_tag_check ( Cell x, int tag, char* caller )
2895 sprintf(buf,"z_tag_check(%s): null\n", caller);
2898 if (whatIs(x) != tag) {
2900 "z_tag_check(%s): tag was %d, expected %d\n",
2901 caller, whatIs(x), tag );
2906 Cell zpair ( Cell x1, Cell x2 )
2907 { return ap(ZTUP2,ap(x1,x2)); }
2908 Cell zfst ( Cell zpair )
2909 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2910 Cell zsnd ( Cell zpair )
2911 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2913 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2914 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2915 Cell zfst3 ( Cell zpair )
2916 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2917 Cell zsnd3 ( Cell zpair )
2918 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2919 Cell zthd3 ( Cell zpair )
2920 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2922 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2923 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2924 Cell zsel14 ( Cell zpair )
2925 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2926 Cell zsel24 ( Cell zpair )
2927 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2928 Cell zsel34 ( Cell zpair )
2929 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2930 Cell zsel44 ( Cell zpair )
2931 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2933 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2934 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2935 Cell zsel15 ( Cell zpair )
2936 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2937 Cell zsel25 ( Cell zpair )
2938 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2939 Cell zsel35 ( Cell zpair )
2940 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2941 Cell zsel45 ( Cell zpair )
2942 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2943 Cell zsel55 ( Cell zpair )
2944 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2947 Cell unap ( int tag, Cell c )
2950 if (whatIs(c) != tag) {
2951 sprintf(buf, "unap: specified %d, actual %d\n",
2958 /* --------------------------------------------------------------------------
2959 * Operations on applications:
2960 * ------------------------------------------------------------------------*/
2962 Int argCount; /* number of args in application */
2964 Cell getHead(e) /* get head cell of application */
2965 Cell e; { /* set number of args in argCount */
2966 for (argCount=0; isAp(e); e=fun(e))
2971 List getArgs(e) /* get list of arguments in function*/
2972 Cell e; { /* application: */
2973 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2975 for (as=NIL; isAp(e); e=fun(e))
2976 as = cons(arg(e),as);
2980 Cell nthArg(n,e) /* return nth arg in application */
2981 Int n; /* of function to m args (m>=n) */
2982 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2983 for (n=numArgs(e)-n-1; n>0; n--)
2988 Int numArgs(e) /* find number of arguments to expr */
2991 for (n=0; isAp(e); e=fun(e))
2996 Cell applyToArgs(f,args) /* destructively apply list of args */
2997 Cell f; /* to function f */
2999 while (nonNull(args)) {
3000 Cell temp = tl(args);
3001 tl(args) = hd(args);
3009 /* --------------------------------------------------------------------------
3011 * ------------------------------------------------------------------------*/
3013 /* Given the address of an info table, find the constructor/tuple
3014 that it belongs to, and return the name. Only needed for debugging.
3016 char* lookupHugsItblName ( void* v )
3019 for (i = TYCON_BASE_ADDR;
3020 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3021 if (tabTycon[i-TYCON_BASE_ADDR].inUse
3022 && tycon(i).itbl == v)
3023 return textToStr(tycon(i).text);
3025 for (i = NAME_BASE_ADDR;
3026 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3027 if (tabName[i-NAME_BASE_ADDR].inUse
3028 && name(i).itbl == v)
3029 return textToStr(name(i).text);
3034 static String maybeModuleStr ( Module m )
3036 if (isModule(m)) return textToStr(module(m).text); else return "??";
3039 static String maybeNameStr ( Name n )
3041 if (isName(n)) return textToStr(name(n).text); else return "??";
3044 static String maybeTyconStr ( Tycon t )
3046 if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
3049 static String maybeClassStr ( Class c )
3051 if (isClass(c)) return textToStr(cclass(c).text); else return "??";
3054 static String maybeText ( Text t )
3056 if (isNull(t)) return "(nil)";
3057 return textToStr(t);
3060 static void print100 ( Int x )
3062 print ( x, 100); printf("\n");
3065 void dumpTycon ( Int t )
3067 if (isTycon(TYCON_BASE_ADDR+t) && !isTycon(t)) t += TYCON_BASE_ADDR;
3069 printf ( "dumpTycon %d: not a tycon\n", t);
3073 printf ( " text: %s\n", textToStr(tycon(t).text) );
3074 printf ( " line: %d\n", tycon(t).line );
3075 printf ( " mod: %s\n", maybeModuleStr(tycon(t).mod));
3076 printf ( " tuple: %d\n", tycon(t).tuple);
3077 printf ( " arity: %d\n", tycon(t).arity);
3078 printf ( " kind: "); print100(tycon(t).kind);
3079 printf ( " what: %d\n", tycon(t).what);
3080 printf ( " defn: "); print100(tycon(t).defn);
3081 printf ( " cToT: %d %s\n", tycon(t).conToTag,
3082 maybeNameStr(tycon(t).conToTag));
3083 printf ( " tToC: %d %s\n", tycon(t).tagToCon,
3084 maybeNameStr(tycon(t).tagToCon));
3085 printf ( " itbl: %p\n", tycon(t).itbl);
3086 printf ( " nextTH: %d %s\n", tycon(t).nextTyconHash,
3087 maybeTyconStr(tycon(t).nextTyconHash));
3091 void dumpName ( Int n )
3093 if (isName(NAME_BASE_ADDR+n) && !isName(n)) n += NAME_BASE_ADDR;
3095 printf ( "dumpName %d: not a name\n", n);
3099 printf ( " text: %s\n", textToStr(name(n).text) );
3100 printf ( " line: %d\n", name(n).line );
3101 printf ( " mod: %s\n", maybeModuleStr(name(n).mod));
3102 printf ( " syntax: %d\n", name(n).syntax );
3103 printf ( " parent: %d\n", name(n).parent );
3104 printf ( " arity: %d\n", name(n).arity );
3105 printf ( " number: %d\n", name(n).number );
3106 printf ( " type: "); print100(name(n).type);
3107 printf ( " defn: %d\n", name(n).defn );
3108 printf ( " stgVar: "); print100(name(n).stgVar);
3109 printf ( " cconv: %d\n", name(n).callconv );
3110 printf ( " primop: %p\n", name(n).primop );
3111 printf ( " itbl: %p\n", name(n).itbl );
3112 printf ( " nextNH: %d\n", name(n).nextNameHash );
3117 void dumpClass ( Int c )
3119 if (isClass(CCLASS_BASE_ADDR+c) && !isClass(c)) c += CCLASS_BASE_ADDR;
3121 printf ( "dumpClass %d: not a class\n", c);
3125 printf ( " text: %s\n", textToStr(cclass(c).text) );
3126 printf ( " line: %d\n", cclass(c).line );
3127 printf ( " mod: %s\n", maybeModuleStr(cclass(c).mod));
3128 printf ( " arity: %d\n", cclass(c).arity );
3129 printf ( " level: %d\n", cclass(c).level );
3130 printf ( " kinds: "); print100( cclass(c).kinds );
3131 printf ( " fds: %d\n", cclass(c).fds );
3132 printf ( " xfds: %d\n", cclass(c).xfds );
3133 printf ( " head: "); print100( cclass(c).head );
3134 printf ( " dcon: "); print100( cclass(c).dcon );
3135 printf ( " supers: "); print100( cclass(c).supers );
3136 printf ( " #supers: %d\n", cclass(c).numSupers );
3137 printf ( " dsels: "); print100( cclass(c).dsels );
3138 printf ( " members: "); print100( cclass(c).members );
3139 printf ( "#members: %d\n", cclass(c).numMembers );
3140 printf ( "defaults: "); print100( cclass(c).defaults );
3141 printf ( " insts: "); print100( cclass(c).instances );
3146 void dumpInst ( Int i )
3148 if (isInst(INST_BASE_ADDR+i) && !isInst(i)) i += INST_BASE_ADDR;
3150 printf ( "dumpInst %d: not an instance\n", i);
3154 printf ( " class: %s\n", maybeClassStr(inst(i).c) );
3155 printf ( " line: %d\n", inst(i).line );
3156 printf ( " mod: %s\n", maybeModuleStr(inst(i).mod));
3157 printf ( " kinds: "); print100( inst(i).kinds );
3158 printf ( " head: "); print100( inst(i).head );
3159 printf ( " specs: "); print100( inst(i).specifics );
3160 printf ( " #specs: %d\n", inst(i).numSpecifics );
3161 printf ( " impls: "); print100( inst(i).implements );
3162 printf ( " builder: %s\n", maybeNameStr( inst(i).builder ) );
3167 /* --------------------------------------------------------------------------
3169 * ------------------------------------------------------------------------*/
3176 case POSTPREL: break;
3178 case RESET : clearStack();
3180 /* the next 2 statements are particularly important
3181 * if you are using GLOBALfst or GLOBALsnd since the
3182 * corresponding registers may be reset to their
3183 * uninitialised initial values by a longjump.
3185 heapTopFst = heapFst + heapSize;
3186 heapTopSnd = heapSnd + heapSize;
3190 if (isNull(lastExprSaved))
3191 savedText = TEXT_SIZE;
3196 for (i = NAME_BASE_ADDR;
3197 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3198 if (tabName[i-NAME_BASE_ADDR].inUse) {
3199 mark(name(i).parent);
3202 mark(name(i).stgVar);
3205 end("Names", nameHw-NAMEMIN);
3208 for (i = MODULE_BASE_ADDR;
3209 i < MODULE_BASE_ADDR+tabModuleSz; ++i) {
3210 if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3211 mark(module(i).tycons);
3212 mark(module(i).names);
3213 mark(module(i).classes);
3214 mark(module(i).exports);
3215 mark(module(i).qualImports);
3216 mark(module(i).tree);
3217 mark(module(i).uses);
3218 mark(module(i).objectExtraNames);
3223 mark(targetModules);
3224 end("Modules", moduleHw-MODMIN);
3227 for (i = TYCON_BASE_ADDR;
3228 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3229 if (tabTycon[i-TYCON_BASE_ADDR].inUse) {
3230 mark(tycon(i).kind);
3231 mark(tycon(i).what);
3232 mark(tycon(i).defn);
3235 end("Type constructors", tyconHw-TYCMIN);
3238 for (i = CCLASS_BASE_ADDR;
3239 i < CCLASS_BASE_ADDR+tabClassSz; ++i) {
3240 if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
3241 mark(cclass(i).kinds);
3242 mark(cclass(i).fds);
3243 mark(cclass(i).xfds);
3244 mark(cclass(i).head);
3245 mark(cclass(i).supers);
3246 mark(cclass(i).dsels);
3247 mark(cclass(i).members);
3248 mark(cclass(i).defaults);
3249 mark(cclass(i).instances);
3253 end("Classes", classHw-CLASSMIN);
3256 for (i = INST_BASE_ADDR;
3257 i < INST_BASE_ADDR+tabInstSz; ++i) {
3258 if (tabInst[i-INST_BASE_ADDR].inUse) {
3259 mark(inst(i).kinds);
3261 mark(inst(i).specifics);
3262 mark(inst(i).implements);
3265 end("Instances", instHw-INSTMIN);
3268 for (i=0; i<=sp; ++i)
3273 mark(lastExprSaved);
3276 end("Last expression", 3);
3281 end("C stack", stackRoots);
3286 case PREPREL : heapFst = heapAlloc(heapSize);
3287 heapSnd = heapAlloc(heapSize);
3289 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3290 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3295 heapTopFst = heapFst + heapSize;
3296 heapTopSnd = heapSnd + heapSize;
3297 for (i=1; i<heapSize; ++i) {
3301 snd(-heapSize) = NIL;
3308 marksSize = bitArraySize(heapSize);
3309 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3310 ERRMSG(0) "Unable to allocate gc markspace"
3317 nextNewText = INVAR_BASE_ADDR;
3318 nextNewDText = INDVAR_BASE_ADDR;
3319 lastExprSaved = NIL;
3320 savedText = TEXT_SIZE;
3322 for (i=0; i<TEXTHSZ; ++i) textHash[i][0] = NOTEXT;
3323 for (i=0; i<TYCONHSZ; ++i) tyconHash[RC_T(i)] = NIL;
3324 for (i=0; i<NAMEHSZ; ++i) nameHash[RC_N(i)] = NIL;
3330 /*-------------------------------------------------------------------------*/