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/12 09:37:19 $
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 /* see comment in compiler.c about this,
1644 and interaction with info tables */
1645 if (nukeModule_needs_major_gc) {
1646 /* fprintf ( stderr, "doing major GC in nukeModule\n"); */
1648 nukeModule_needs_major_gc = FALSE;
1651 oc = module(m).object;
1657 oc = module(m).objectExtras;
1664 for (i = NAME_BASE_ADDR; i < NAME_BASE_ADDR+tabNameSz; i++)
1665 if (tabName[i-NAME_BASE_ADDR].inUse && name(i).mod == m) {
1666 if (name(i).itbl) free(name(i).itbl);
1667 name(i).itbl = NULL;
1671 for (i = TYCON_BASE_ADDR; i < TYCON_BASE_ADDR+tabTyconSz; i++)
1672 if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).mod == m) {
1673 if (tycon(i).itbl) 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 Name jrsFindQualName ( Text mn, Text sn )
1784 for (m = MODULE_BASE_ADDR;
1785 m < MODULE_BASE_ADDR+tabModuleSz; m++)
1786 if (tabModule[m-MODULE_BASE_ADDR].inUse
1787 && module(m).text == mn) break;
1789 if (m == MODULE_BASE_ADDR+tabModuleSz) return NIL;
1791 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1792 if (name(hd(ns)).text == sn) return hd(ns);
1798 char* nameFromOPtr ( void* p )
1802 for (m = MODULE_BASE_ADDR;
1803 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1804 if (tabModule[m-MODULE_BASE_ADDR].inUse && module(m).object) {
1805 char* nm = ocLookupAddr ( module(m).object, p );
1810 /* A kludge to assist Win32 debugging; not actually necessary. */
1811 { char* nm = nameFromStaticOPtr(p);
1819 void* lookupOTabName ( Module m, char* sym )
1821 assert(isModule(m));
1822 if (module(m).object)
1823 return ocLookupSym ( module(m).object, sym );
1828 void* lookupOExtraTabName ( char* sym )
1832 for (m = MODULE_BASE_ADDR;
1833 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1834 if (tabModule[m-MODULE_BASE_ADDR].inUse)
1835 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1836 void* ad = ocLookupSym ( oc, sym );
1844 /* Only call this if in dire straits; searches every object symtab
1845 in the system -- so is therefore slow.
1847 void* lookupOTabNameAbsolutelyEverywhere ( char* sym )
1852 for (m = MODULE_BASE_ADDR;
1853 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1854 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1855 if (module(m).object) {
1856 ad = ocLookupSym ( module(m).object, sym );
1859 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1860 ad = ocLookupSym ( oc, sym );
1869 OSectionKind lookupSection ( void* ad )
1876 for (m = MODULE_BASE_ADDR;
1877 m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1878 if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1879 if (module(m).object) {
1880 sect = ocLookupSection ( module(m).object, ad );
1881 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1884 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1885 sect = ocLookupSection ( oc, ad );
1886 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1891 return HUGS_SECTIONKIND_OTHER;
1895 /* --------------------------------------------------------------------------
1898 * Provides a garbage collectable heap for storage of expressions etc.
1900 * Now incorporates a flat resource: A two-space collected extension of
1901 * the heap that provides storage for contiguous arrays of Cell storage,
1902 * cooperating with the garbage collection mechanisms for the main heap.
1903 * ------------------------------------------------------------------------*/
1905 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1906 Heap heapFst; /* array of fst component of pairs */
1907 Heap heapSnd; /* array of snd component of pairs */
1910 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1911 /* C stack; use with extreme care! */
1913 Int numGcs; /* number of garbage collections */
1914 Int cellsRecovered; /* number of cells recovered */
1916 static Cell freeList; /* free list of unused cells */
1917 static Cell lsave, rsave; /* save components of pair */
1921 static Int markCount, stackRoots;
1923 #define initStackRoots() stackRoots = 0
1924 #define recordStackRoot() stackRoots++
1937 #define start() markCount = 0
1938 #define end(thing,rs) \
1940 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1943 #define recordMark() markCount++
1945 #else /* !GC_STATISTICS */
1950 #define initStackRoots()
1951 #define recordStackRoot()
1954 #define end(thing,root)
1955 #define recordMark()
1957 #endif /* !GC_STATISTICS */
1959 Cell pair(l,r) /* Allocate pair (l, r) from */
1960 Cell l, r; { /* heap, garbage collecting first */
1961 Cell c = freeList; /* if necessary ... */
1972 freeList = snd(freeList);
1980 static Int marksSize;
1982 void mark ( Cell root )
1985 Cell mstack[NUM_MSTACK];
1989 mstack[++msp] = root;
1992 if (msp > msp_max) msp_max = msp;
1994 if (!isGenPair(c)) continue;
1995 if (fst(c)==FREECELL) continue;
1997 register int place = placeInSet(c);
1998 register int mask = maskInSet(c);
1999 if (!(marks[place]&mask)) {
2000 marks[place] |= mask;
2001 if (msp >= NUM_MSTACK-5) {
2003 "hugs: fatal stack overflow during GC. "
2004 "Increase NUM_MSTACK.\n" );
2007 mstack[++msp] = fst(c);
2008 mstack[++msp] = snd(c);
2012 // fprintf(stderr, "%d ",msp_max);
2016 Void garbageCollect() { /* Run garbage collector ... */
2017 /* disable break checking */
2022 jmp_buf regs; /* save registers on stack */
2023 HugsBreakAction oldBrk
2024 = setBreakAction ( HugsIgnoreBreak );
2030 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
2033 everybody(MARK); /* Mark all components of system */
2035 gcScanning(); /* scan mark set */
2042 for (i=1; i<=heapSize; i++) {
2043 if ((marks[place] & mask) == 0) {
2050 if (++j == bitsPerWord) {
2057 gcRecovered(recovered);
2058 setBreakAction ( oldBrk );
2062 #if defined(DEBUG_STORAGE) || defined(DEBUG_STORAGE_EXTRA)
2063 /* fprintf(stderr, "\n--- GC recovered %d\n",recovered ); */
2066 /* can only return if freeList is nonempty on return. */
2067 if (recovered<minRecovery || isNull(freeList)) {
2068 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
2071 cellsRecovered = recovered;
2074 /* --------------------------------------------------------------------------
2075 * Code for saving last expression entered:
2077 * This is a little tricky because some text values (e.g. strings or variable
2078 * names) may not be defined or have the same value when the expression is
2079 * recalled. These text values are therefore saved in the top portion of
2081 * ------------------------------------------------------------------------*/
2083 static Cell lastExprSaved; /* last expression to be saved */
2085 Void setLastExpr(e) /* save expression for later recall*/
2087 lastExprSaved = NIL; /* in case attempt to save fails */
2088 savedText = TEXT_SIZE;
2089 lastExprSaved = lowLevelLastIn(e);
2092 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
2093 Cell c; { /* acyclic graph) for later recall */
2094 if (isPair(c)) { /* Duplicating any text strings */
2095 if (isTagNonPtr(fst(c))) /* in case these are lost at some */
2096 switch (fst(c)) { /* point before the expr is reused */
2102 case STRCELL : return pair(fst(c),saveText(textOf(c)));
2103 default : return pair(fst(c),snd(c));
2106 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2110 return pair(EXTCOPY,saveText(extText(c)));
2116 Cell getLastExpr() { /* recover previously saved expr */
2117 return lowLevelLastOut(lastExprSaved);
2120 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
2121 Cell c; { /* except that Cells refering to */
2122 if (isPair(c)) { /* Text values are restored to */
2123 if (isTagNonPtr(fst(c))) /* appropriate values */
2130 case STRCELL : return pair(fst(c),
2131 findText(text+intValOf(c)));
2133 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
2135 default : return pair(fst(c),snd(c));
2138 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2144 /* --------------------------------------------------------------------------
2145 * Miscellaneous operations on heap cells:
2146 * ------------------------------------------------------------------------*/
2148 Cell whatIs ( register Cell c )
2151 register Cell fstc = fst(c);
2152 return isTag(fstc) ? fstc : AP;
2154 if (isOffset(c)) return OFFSET;
2155 if (isChar(c)) return CHARCELL;
2156 if (isInt(c)) return INTCELL;
2157 if (isName(c)) return NAME;
2158 if (isTycon(c)) return TYCON;
2159 if (isTuple(c)) return TUPLE;
2160 if (isClass(c)) return CLASS;
2161 if (isInst(c)) return INSTANCE;
2162 if (isModule(c)) return MODULE;
2163 if (isText(c)) return TEXTCELL;
2164 if (isInventedVar(c)) return INVAR;
2165 if (isInventedDictVar(c)) return INDVAR;
2166 if (isSpec(c)) return c;
2167 if (isNull(c)) return c;
2168 fprintf ( stderr, "whatIs: unknown %d\n", c );
2174 Cell whatIs(c) /* identify type of cell */
2177 register Cell fstc = fst(c);
2178 return isTag(fstc) ? fstc : AP;
2180 if (c<OFFMIN) return c;
2182 if (isExt(c)) return EXT;
2184 if (c>=INTMIN) return INTCELL;
2186 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
2188 else if (c>=INSTMIN) return INSTANCE;
2190 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
2191 else return MODULE;}
2192 else if (c>=OFFMIN) return OFFSET;
2194 else return (c>=EXTMIN) ?
2202 register Cell fstc = fst(c);
2203 return isTag(fstc) ? fstc : AP;
2205 if (c>=INTMIN) return INTCELL;
2206 if (c>=CHARMIN) return CHARCELL;
2207 if (c>=CLASSMIN) return CLASS;
2208 if (c>=INSTMIN) return INSTANCE;
2209 if (c>=NAMEMIN) return NAME;
2210 if (c>=TYCMIN) return TYCON;
2211 if (c>=MODMIN) return MODULE;
2212 if (c>=OFFMIN) return OFFSET;
2214 if (c>=EXTMIN) return EXT;
2216 if (c>=TUPMIN) return TUPLE;
2222 /* A very, very simple printer.
2223 * Output is uglier than from printExp - but the printer is more
2224 * robust and can be used on any data structure irrespective of
2227 Void print ( Cell c, Int depth )
2232 else if (isNull(c)) {
2235 else if (isTagPtr(c)) {
2236 Printf("TagP(%d)", c);
2238 else if (isTagNonPtr(c)) {
2239 Printf("TagNP(%d)", c);
2241 else if (isSpec(c) && c != STAR) {
2242 Printf("TagS(%d)", c);
2244 else if (isText(c)) {
2245 Printf("text(%d)=\"%s\"",c-TEXT_BASE_ADDR,textToStr(c));
2247 else if (isInventedVar(c)) {
2248 Printf("invented(%d)", c-INVAR_BASE_ADDR);
2250 else if (isInventedDictVar(c)) {
2251 Printf("inventedDict(%d)",c-INDVAR_BASE_ADDR);
2254 Int tag = whatIs(c);
2258 print(fst(c), depth-1);
2260 print(snd(c), depth-1);
2264 Printf("free(%d)", c);
2267 Printf("int(%d)", intOf(c));
2270 Printf("bignum(%s)", bignumToString(c));
2273 Printf("char('%c')", charOf(c));
2276 Printf("ptr(%p)",ptrOf(c));
2279 Printf("class(%d)", c-CCLASS_BASE_ADDR);
2280 Printf("=\"%s\"", textToStr(cclass(c).text));
2283 Printf("instance(%d)", c - INST_BASE_ADDR);
2286 Printf("name(%d)", c-NAME_BASE_ADDR);
2287 Printf("=\"%s\"", textToStr(name(c).text));
2290 Printf("tycon(%d)", c-TYCON_BASE_ADDR);
2291 Printf("=\"%s\"", textToStr(tycon(c).text));
2294 Printf("module(%d)", c - MODULE_BASE_ADDR);
2295 Printf("=\"%s\"", textToStr(module(c).text));
2298 Printf("Offset %d", offsetOf(c));
2301 Printf("%s", textToStr(ghcTupleText(c)));
2305 print(snd(c),depth-1);
2309 print(snd(c),depth-1);
2313 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2314 Printf("%d ", intOf(fst(snd(c))));
2315 print(snd(snd(c)),depth-1);
2317 print(snd(c),depth-1);
2331 Printf("{dict %d}",textOf(c));
2337 Printf("{id %s}",textToStr(textOf(c)));
2341 Printf("{ip %s}",textToStr(textOf(c)));
2344 Printf("?%s",textToStr(textOf(c)));
2348 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2352 print(fst(snd(c)),depth-1);
2354 print(snd(snd(c)),depth-1);
2359 print(snd(c),depth-1);
2364 print(snd(c),depth-1);
2369 print(fst(snd(c)),depth-1);
2371 print(snd(snd(c)),depth-1);
2376 print(fst(snd(c)),depth-1);
2378 print(snd(snd(c)),depth-1);
2382 Printf("FromQual(");
2383 print(fst(snd(c)),depth-1);
2385 print(snd(snd(c)),depth-1);
2389 Printf("StgVar%d=",-c);
2390 print(snd(c), depth-1);
2394 print(fst(snd(c)),depth-1);
2396 print(snd(snd(c)),depth-1);
2401 print(fst(snd(c)),depth-1);
2403 print(snd(snd(c)),depth-1);
2408 print(fst(snd(c)),depth-1);
2410 print(snd(snd(c)),depth-1);
2414 Printf("PrimCase(");
2415 print(fst(snd(c)),depth-1);
2417 print(snd(snd(c)),depth-1);
2422 print(snd(c),depth-1);
2426 Printf("(UNBOXEDTUP,");
2427 print(snd(c),depth-1);
2432 print(zfst(c),depth-1);
2434 print(zsnd(c),depth-1);
2438 Printf("<ZTriple ");
2439 print(zfst3(c),depth-1);
2441 print(zsnd3(c),depth-1);
2443 print(zthd3(c),depth-1);
2448 print(snd(c),depth-1);
2452 if (isTagNonPtr(tag)) {
2453 Printf("(TagNP=%d,%d)", c, tag);
2454 } else if (isTagPtr(tag)) {
2455 Printf("(TagP=%d,",tag);
2456 print(snd(c), depth-1);
2459 } else if (c == tag) {
2460 Printf("Tag(%d)", c);
2462 Printf("Tag(%d)=%d", c, tag);
2471 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2472 Cell c; { /* also recognises DICTVAR cells */
2474 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2477 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2479 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2482 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2484 if (!isPair(c)) return FALSE;
2487 case VAROPCELL : return TRUE;
2489 case QUALIDENT : return isVar(snd(snd(c)));
2491 default : return FALSE;
2495 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2497 if (!isPair(c)) return FALSE;
2500 case CONOPCELL : return TRUE;
2502 case QUALIDENT : return isCon(snd(snd(c)));
2504 default : return FALSE;
2508 Bool isQualIdent(c) /* is cell a qualified identifier? */
2510 return isPair(c) && (fst(c)==QUALIDENT);
2513 Bool eqQualIdent ( QualId c1, QualId c2 )
2515 assert(isQualIdent(c1));
2516 if (!isQualIdent(c2)) {
2517 assert(isQualIdent(c2));
2519 return qmodOf(c1)==qmodOf(c2) &&
2520 qtextOf(c1)==qtextOf(c2);
2523 Bool isIdent(c) /* is cell an identifier? */
2525 if (!isPair(c)) return FALSE;
2530 case CONOPCELL : return TRUE;
2532 case QUALIDENT : return TRUE;
2534 default : return FALSE;
2538 Bool isInt(c) /* cell holds integer value? */
2540 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2543 Int intOf(c) /* find integer value of cell? */
2546 return isPair(c) ? (Int)(snd(c)) : (Int)(c-SMALL_INT_ZERO);
2549 Cell mkInt(n) /* make cell representing integer */
2551 return (SMALL_INT_MIN <= SMALL_INT_ZERO+n &&
2552 SMALL_INT_ZERO+n <= SMALL_INT_MAX)
2557 #if SIZEOF_VOID_P == SIZEOF_INT
2559 typedef union {Int i; Ptr p;} IntOrPtr;
2566 return pair(PTRCELL,x.i);
2573 assert(fst(c) == PTRCELL);
2583 return pair(CPTRCELL,x.i);
2590 assert(fst(c) == CPTRCELL);
2595 #elif SIZEOF_VOID_P == 2*SIZEOF_INT
2597 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2604 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2611 assert(fst(c) == PTRCELL);
2612 x.i.i1 = intOf(fst(snd(c)));
2613 x.i.i2 = intOf(snd(snd(c)));
2622 return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2629 assert(fst(c) == CPTRCELL);
2630 x.i.i1 = intOf(fst(snd(c)));
2631 x.i.i2 = intOf(snd(snd(c)));
2637 #error "Can't implement mkPtr/ptrOf on this architecture."
2642 String stringNegate( s )
2650 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2655 /* --------------------------------------------------------------------------
2657 * ------------------------------------------------------------------------*/
2659 Int length(xs) /* calculate length of list xs */
2662 for (; nonNull(xs); ++n)
2667 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2668 List xs, ys; { /* ys by modifying xs ... */
2673 while (nonNull(tl(zs)))
2680 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2683 for (; nonNull(xs); xs=tl(xs))
2684 ys = cons(hd(xs),ys);
2688 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2691 return revOnto(dupOnto(xs,NIL),ys);
2694 List dupList(xs) /* Duplicate spine of list xs */
2697 for (; nonNull(xs); xs=tl(xs))
2698 ys = cons(hd(xs),ys);
2702 List revOnto(xs,ys) /* Destructively reverse elements of*/
2703 List xs, ys; { /* list xs onto list ys... */
2706 while (nonNull(xs)) {
2715 QualId qualidIsMember ( QualId q, List xs )
2717 for (; nonNull(xs); xs=tl(xs)) {
2718 if (eqQualIdent(q, hd(xs)))
2724 Cell varIsMember(t,xs) /* Test if variable is a member of */
2725 Text t; /* given list of variables */
2727 assert(isText(t) || isInventedVar(t) || isInventedDictVar(t));
2728 for (; nonNull(xs); xs=tl(xs))
2729 if (t==textOf(hd(xs)))
2734 Name nameIsMember(t,ns) /* Test if name with text t is a */
2735 Text t; /* member of list of names xs */
2737 for (; nonNull(ns); ns=tl(ns))
2738 if (t==name(hd(ns)).text)
2743 Cell intIsMember(n,xs) /* Test if integer n is member of */
2744 Int n; /* given list of integers */
2746 for (; nonNull(xs); xs=tl(xs))
2747 if (n==intOf(hd(xs)))
2752 Cell cellIsMember(x,xs) /* Test for membership of specific */
2753 Cell x; /* cell x in list xs */
2755 for (; nonNull(xs); xs=tl(xs))
2761 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2764 for (; nonNull(xs); xs=tl(xs))
2770 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2771 Cell c; /* association lists */
2773 for (; nonNull(xs); xs=tl(xs))
2779 List replicate(n,x) /* create list of n copies of x */
2788 List diffList(from,take) /* list difference: from\take */
2789 List from, take; { /* result contains all elements of */
2790 List result = NIL; /* `from' not appearing in `take' */
2792 while (nonNull(from)) {
2793 List next = tl(from);
2794 if (!cellIsMember(hd(from),take)) {
2803 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2807 for(;nonNull(xs);xs=tl(xs)) {
2810 result=cons(x,result);
2816 List take(n,xs) /* destructively truncate list to */
2817 Int n; /* specified length */
2823 while (1<n-- && nonNull(xs))
2830 List splitAt(n,xs) /* drop n things from front of list*/
2839 Cell nth(n,xs) /* extract n'th element of list */
2842 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2849 List removeCell(x,xs) /* destructively remove cell from */
2854 return tl(xs); /* element at front of list */
2858 for (; nonNull(curr); prev=curr, curr=tl(prev))
2860 tl(prev) = tl(curr);
2861 return xs; /* element in middle of list */
2865 return xs; /* here if element not found */
2868 List nubList(xs) /* nuke dups in list */
2869 List xs; { /* non destructive */
2871 for (; nonNull(xs); xs=tl(xs))
2872 if (isNull(cellIsMember(hd(xs),outs)))
2873 outs = cons(hd(xs),outs);
2879 /* --------------------------------------------------------------------------
2880 * Tagged tuples (experimental)
2881 * ------------------------------------------------------------------------*/
2883 static void z_tag_check ( Cell x, int tag, char* caller )
2887 sprintf(buf,"z_tag_check(%s): null\n", caller);
2890 if (whatIs(x) != tag) {
2892 "z_tag_check(%s): tag was %d, expected %d\n",
2893 caller, whatIs(x), tag );
2898 Cell zpair ( Cell x1, Cell x2 )
2899 { return ap(ZTUP2,ap(x1,x2)); }
2900 Cell zfst ( Cell zpair )
2901 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2902 Cell zsnd ( Cell zpair )
2903 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2905 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2906 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2907 Cell zfst3 ( Cell zpair )
2908 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2909 Cell zsnd3 ( Cell zpair )
2910 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2911 Cell zthd3 ( Cell zpair )
2912 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2914 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2915 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2916 Cell zsel14 ( Cell zpair )
2917 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2918 Cell zsel24 ( Cell zpair )
2919 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2920 Cell zsel34 ( Cell zpair )
2921 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2922 Cell zsel44 ( Cell zpair )
2923 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2925 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2926 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2927 Cell zsel15 ( Cell zpair )
2928 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2929 Cell zsel25 ( Cell zpair )
2930 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2931 Cell zsel35 ( Cell zpair )
2932 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2933 Cell zsel45 ( Cell zpair )
2934 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2935 Cell zsel55 ( Cell zpair )
2936 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2939 Cell unap ( int tag, Cell c )
2942 if (whatIs(c) != tag) {
2943 sprintf(buf, "unap: specified %d, actual %d\n",
2950 /* --------------------------------------------------------------------------
2951 * Operations on applications:
2952 * ------------------------------------------------------------------------*/
2954 Int argCount; /* number of args in application */
2956 Cell getHead(e) /* get head cell of application */
2957 Cell e; { /* set number of args in argCount */
2958 for (argCount=0; isAp(e); e=fun(e))
2963 List getArgs(e) /* get list of arguments in function*/
2964 Cell e; { /* application: */
2965 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2967 for (as=NIL; isAp(e); e=fun(e))
2968 as = cons(arg(e),as);
2972 Cell nthArg(n,e) /* return nth arg in application */
2973 Int n; /* of function to m args (m>=n) */
2974 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2975 for (n=numArgs(e)-n-1; n>0; n--)
2980 Int numArgs(e) /* find number of arguments to expr */
2983 for (n=0; isAp(e); e=fun(e))
2988 Cell applyToArgs(f,args) /* destructively apply list of args */
2989 Cell f; /* to function f */
2991 while (nonNull(args)) {
2992 Cell temp = tl(args);
2993 tl(args) = hd(args);
3001 /* --------------------------------------------------------------------------
3003 * ------------------------------------------------------------------------*/
3005 /* Given the address of an info table, find the constructor/tuple
3006 that it belongs to, and return the name. Only needed for debugging.
3008 char* lookupHugsItblName ( void* v )
3011 for (i = TYCON_BASE_ADDR;
3012 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3013 if (tabTycon[i-TYCON_BASE_ADDR].inUse
3014 && tycon(i).itbl == v)
3015 return textToStr(tycon(i).text);
3017 for (i = NAME_BASE_ADDR;
3018 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3019 if (tabName[i-NAME_BASE_ADDR].inUse
3020 && name(i).itbl == v)
3021 return textToStr(name(i).text);
3026 static String maybeModuleStr ( Module m )
3028 if (isModule(m)) return textToStr(module(m).text); else return "??";
3031 static String maybeNameStr ( Name n )
3033 if (isName(n)) return textToStr(name(n).text); else return "??";
3036 static String maybeTyconStr ( Tycon t )
3038 if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
3041 static String maybeClassStr ( Class c )
3043 if (isClass(c)) return textToStr(cclass(c).text); else return "??";
3046 static String maybeText ( Text t )
3048 if (isNull(t)) return "(nil)";
3049 return textToStr(t);
3052 static void print100 ( Int x )
3054 print ( x, 100); printf("\n");
3057 void dumpTycon ( Int t )
3059 if (isTycon(TYCON_BASE_ADDR+t) && !isTycon(t)) t += TYCON_BASE_ADDR;
3061 printf ( "dumpTycon %d: not a tycon\n", t);
3065 printf ( " text: %s\n", textToStr(tycon(t).text) );
3066 printf ( " line: %d\n", tycon(t).line );
3067 printf ( " mod: %s\n", maybeModuleStr(tycon(t).mod));
3068 printf ( " tuple: %d\n", tycon(t).tuple);
3069 printf ( " arity: %d\n", tycon(t).arity);
3070 printf ( " kind: "); print100(tycon(t).kind);
3071 printf ( " what: %d\n", tycon(t).what);
3072 printf ( " defn: "); print100(tycon(t).defn);
3073 printf ( " cToT: %d %s\n", tycon(t).conToTag,
3074 maybeNameStr(tycon(t).conToTag));
3075 printf ( " tToC: %d %s\n", tycon(t).tagToCon,
3076 maybeNameStr(tycon(t).tagToCon));
3077 printf ( " itbl: %p\n", tycon(t).itbl);
3078 printf ( " nextTH: %d %s\n", tycon(t).nextTyconHash,
3079 maybeTyconStr(tycon(t).nextTyconHash));
3083 void dumpName ( Int n )
3085 if (isName(NAME_BASE_ADDR+n) && !isName(n)) n += NAME_BASE_ADDR;
3087 printf ( "dumpName %d: not a name\n", n);
3091 printf ( " text: %s\n", textToStr(name(n).text) );
3092 printf ( " line: %d\n", name(n).line );
3093 printf ( " mod: %s\n", maybeModuleStr(name(n).mod));
3094 printf ( " syntax: %d\n", name(n).syntax );
3095 printf ( " parent: %d\n", name(n).parent );
3096 printf ( " arity: %d\n", name(n).arity );
3097 printf ( " number: %d\n", name(n).number );
3098 printf ( " type: "); print100(name(n).type);
3099 printf ( " defn: %d\n", name(n).defn );
3100 printf ( " stgVar: "); print100(name(n).stgVar);
3101 printf ( " cconv: %d\n", name(n).callconv );
3102 printf ( " primop: %p\n", name(n).primop );
3103 printf ( " itbl: %p\n", name(n).itbl );
3104 printf ( " nextNH: %d\n", name(n).nextNameHash );
3109 void dumpClass ( Int c )
3111 if (isClass(CCLASS_BASE_ADDR+c) && !isClass(c)) c += CCLASS_BASE_ADDR;
3113 printf ( "dumpClass %d: not a class\n", c);
3117 printf ( " text: %s\n", textToStr(cclass(c).text) );
3118 printf ( " line: %d\n", cclass(c).line );
3119 printf ( " mod: %s\n", maybeModuleStr(cclass(c).mod));
3120 printf ( " arity: %d\n", cclass(c).arity );
3121 printf ( " level: %d\n", cclass(c).level );
3122 printf ( " kinds: "); print100( cclass(c).kinds );
3123 printf ( " fds: %d\n", cclass(c).fds );
3124 printf ( " xfds: %d\n", cclass(c).xfds );
3125 printf ( " head: "); print100( cclass(c).head );
3126 printf ( " dcon: "); print100( cclass(c).dcon );
3127 printf ( " supers: "); print100( cclass(c).supers );
3128 printf ( " #supers: %d\n", cclass(c).numSupers );
3129 printf ( " dsels: "); print100( cclass(c).dsels );
3130 printf ( " members: "); print100( cclass(c).members );
3131 printf ( "#members: %d\n", cclass(c).numMembers );
3132 printf ( "defaults: "); print100( cclass(c).defaults );
3133 printf ( " insts: "); print100( cclass(c).instances );
3138 void dumpInst ( Int i )
3140 if (isInst(INST_BASE_ADDR+i) && !isInst(i)) i += INST_BASE_ADDR;
3142 printf ( "dumpInst %d: not an instance\n", i);
3146 printf ( " class: %s\n", maybeClassStr(inst(i).c) );
3147 printf ( " line: %d\n", inst(i).line );
3148 printf ( " mod: %s\n", maybeModuleStr(inst(i).mod));
3149 printf ( " kinds: "); print100( inst(i).kinds );
3150 printf ( " head: "); print100( inst(i).head );
3151 printf ( " specs: "); print100( inst(i).specifics );
3152 printf ( " #specs: %d\n", inst(i).numSpecifics );
3153 printf ( " impls: "); print100( inst(i).implements );
3154 printf ( " builder: %s\n", maybeNameStr( inst(i).builder ) );
3159 /* --------------------------------------------------------------------------
3161 * ------------------------------------------------------------------------*/
3168 case POSTPREL: break;
3170 case RESET : clearStack();
3172 /* the next 2 statements are particularly important
3173 * if you are using GLOBALfst or GLOBALsnd since the
3174 * corresponding registers may be reset to their
3175 * uninitialised initial values by a longjump.
3177 heapTopFst = heapFst + heapSize;
3178 heapTopSnd = heapSnd + heapSize;
3182 if (isNull(lastExprSaved))
3183 savedText = TEXT_SIZE;
3188 for (i = NAME_BASE_ADDR;
3189 i < NAME_BASE_ADDR+tabNameSz; ++i) {
3190 if (tabName[i-NAME_BASE_ADDR].inUse) {
3191 mark(name(i).parent);
3194 mark(name(i).stgVar);
3197 end("Names", nameHw-NAMEMIN);
3200 for (i = MODULE_BASE_ADDR;
3201 i < MODULE_BASE_ADDR+tabModuleSz; ++i) {
3202 if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3203 mark(module(i).tycons);
3204 mark(module(i).names);
3205 mark(module(i).classes);
3206 mark(module(i).exports);
3207 mark(module(i).qualImports);
3208 mark(module(i).tree);
3209 mark(module(i).uses);
3210 mark(module(i).objectExtraNames);
3215 mark(targetModules);
3216 end("Modules", moduleHw-MODMIN);
3219 for (i = TYCON_BASE_ADDR;
3220 i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3221 if (tabTycon[i-TYCON_BASE_ADDR].inUse) {
3222 mark(tycon(i).kind);
3223 mark(tycon(i).what);
3224 mark(tycon(i).defn);
3227 end("Type constructors", tyconHw-TYCMIN);
3230 for (i = CCLASS_BASE_ADDR;
3231 i < CCLASS_BASE_ADDR+tabClassSz; ++i) {
3232 if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
3233 mark(cclass(i).kinds);
3234 mark(cclass(i).fds);
3235 mark(cclass(i).xfds);
3236 mark(cclass(i).head);
3237 mark(cclass(i).supers);
3238 mark(cclass(i).dsels);
3239 mark(cclass(i).members);
3240 mark(cclass(i).defaults);
3241 mark(cclass(i).instances);
3245 end("Classes", classHw-CLASSMIN);
3248 for (i = INST_BASE_ADDR;
3249 i < INST_BASE_ADDR+tabInstSz; ++i) {
3250 if (tabInst[i-INST_BASE_ADDR].inUse) {
3251 mark(inst(i).kinds);
3253 mark(inst(i).specifics);
3254 mark(inst(i).implements);
3257 end("Instances", instHw-INSTMIN);
3260 for (i=0; i<=sp; ++i)
3265 mark(lastExprSaved);
3268 end("Last expression", 3);
3273 end("C stack", stackRoots);
3278 case PREPREL : heapFst = heapAlloc(heapSize);
3279 heapSnd = heapAlloc(heapSize);
3281 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3282 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3287 heapTopFst = heapFst + heapSize;
3288 heapTopSnd = heapSnd + heapSize;
3289 for (i=1; i<heapSize; ++i) {
3293 snd(-heapSize) = NIL;
3300 marksSize = bitArraySize(heapSize);
3301 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3302 ERRMSG(0) "Unable to allocate gc markspace"
3309 nextNewText = INVAR_BASE_ADDR;
3310 nextNewDText = INDVAR_BASE_ADDR;
3311 lastExprSaved = NIL;
3312 savedText = TEXT_SIZE;
3314 for (i=0; i<TEXTHSZ; ++i) textHash[i][0] = NOTEXT;
3315 for (i=0; i<TYCONHSZ; ++i) tyconHash[RC_T(i)] = NIL;
3316 for (i=0; i<NAMEHSZ; ++i) nameHash[RC_N(i)] = NIL;
3322 /*-------------------------------------------------------------------------*/