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/03/10 20:03:36 $
14 * ------------------------------------------------------------------------*/
23 /*#define DEBUG_SHOWUSE*/
25 /* --------------------------------------------------------------------------
26 * local function prototypes:
27 * ------------------------------------------------------------------------*/
29 static Int local hash Args((String));
30 static Int local saveText Args((Text));
31 static Module local findQualifier Args((Text));
32 static Void local hashTycon Args((Tycon));
33 static List local insertTycon Args((Tycon,List));
34 static Void local hashName Args((Name));
35 static List local insertName Args((Name,List));
36 static Void local patternError Args((String));
37 static Bool local stringMatch Args((String,String));
38 static Bool local typeInvolves Args((Type,Type));
39 static Cell local markCell Args((Cell));
40 static Void local markSnd Args((Cell));
41 static Cell local lowLevelLastIn Args((Cell));
42 static Cell local lowLevelLastOut Args((Cell));
43 Module local moduleOfScript Args((Script));
44 Script local scriptThisFile Args((Text));
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 = NUM_TEXT; /* 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 DEFTABLE(text,NUM_TEXT);/* 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 (0<=t && t<NUM_TEXT) /* standard char string */
88 sprintf(newVar,"d%d",-t); /* dictionary variable */
90 sprintf(newVar,"v%d",t-NUM_TEXT); /* normal variable */
94 String identToStr(v) /*find string corresp to given ident or qualified name*/
97 internal("identToStr");
103 case CONOPCELL : return text+textOf(v);
105 case QUALIDENT : { Text pos = textHw;
107 while (pos+1 < savedText && text[t]!=0) {
108 text[pos++] = text[t++];
110 if (pos+1 < savedText) {
114 while (pos+1 < savedText && text[t]!=0) {
115 text[pos++] = text[t++];
121 internal("identToStr2");
122 return 0; /* NOTREACHED */
125 Text inventText() { /* return new unused variable name */
126 return nextNewText++;
129 Text inventDictText() { /* return new unused dictvar name */
130 return nextNewDText--;
133 Bool inventedText(t) /* Signal TRUE if text has been */
134 Text t; { /* generated internally */
135 return (t<0 || t>=NUM_TEXT);
138 #define MAX_FIXLIT 100
139 Text fixLitText(t) /* fix literal text that might include \ */
141 String s = textToStr(t);
144 for(i = 0;i < MAX_FIXLIT-2 && *s;s++) {
150 if (i < MAX_FIXLIT-2) {
153 ERRMSG(0) "storage space exhausted for internal literal string"
156 return (findText(p));
160 static Int local hash(s) /* Simple hash function on strings */
164 for (v=((int)(*s))*8; *s; s++)
165 v += ((int)(*s))*(j++);
171 Text findText(s) /* Locate string in Text array */
175 Text textPos = textHash[h][hashno];
177 #define TryMatch { Text originalTextPos = textPos; \
179 for (t=s; *t==text[textPos]; textPos++,t++) \
181 return originalTextPos; \
183 #define Skip while (text[textPos++]) ;
185 while (textPos!=NOTEXT) {
187 if (++hashno<NUM_TEXTH) /* look in next hashtable entry */
188 textPos = textHash[h][hashno];
191 while (textPos < textHw) {
202 textPos = textHw; /* if not found, save in array */
203 if (textHw + (Int)strlen(s) + 1 > savedText) {
204 ERRMSG(0) "Character string storage space exhausted"
207 while ((text[textHw++] = *s++) != 0) {
209 if (hashno<NUM_TEXTH) { /* updating hash table as necessary */
210 textHash[h][hashno] = textPos;
211 if (hashno<NUM_TEXTH-1)
212 textHash[h][hashno+1] = NOTEXT;
218 static Int local saveText(t) /* Save text value in buffer */
219 Text t; { /* at top of text table */
220 String s = textToStr(t);
223 if (textHw + l + 1 > savedText) {
224 ERRMSG(0) "Character string storage space exhausted"
228 strcpy(text+savedText,s);
233 static int fromHexDigit ( char c )
236 case '0': case '1': case '2': case '3': case '4':
237 case '5': case '6': case '7': case '8': case '9':
239 case 'a': case 'A': return 10;
240 case 'b': case 'B': return 11;
241 case 'c': case 'C': return 12;
242 case 'd': case 'D': return 13;
243 case 'e': case 'E': return 14;
244 case 'f': case 'F': return 15;
250 /* returns findText (unZencode s) */
251 Text unZcodeThenFindText ( String s )
258 nn = 100 + 10 * strlen(s);
260 if (!p) internal ("unZcodeThenFindText: malloc failed");
265 if (n > nn-90) internal ("unZcodeThenFindText: result is too big");
266 if (*s != 'z' && *s != 'Z') {
271 if (!(*s)) goto parse_error;
273 case 'Z': p[n++] = 'Z'; break;
274 case 'C': p[n++] = ':'; break;
275 case 'L': p[n++] = '('; break;
276 case 'R': p[n++] = ')'; break;
277 case 'M': p[n++] = '['; break;
278 case 'N': p[n++] = ']'; break;
279 case 'z': p[n++] = 'z'; break;
280 case 'a': p[n++] = '&'; break;
281 case 'b': p[n++] = '|'; break;
282 case 'd': p[n++] = '$'; break;
283 case 'e': p[n++] = '='; break;
284 case 'g': p[n++] = '>'; break;
285 case 'h': p[n++] = '#'; break;
286 case 'i': p[n++] = '.'; break;
287 case 'l': p[n++] = '<'; break;
288 case 'm': p[n++] = '-'; break;
289 case 'n': p[n++] = '!'; break;
290 case 'p': p[n++] = '+'; break;
291 case 'q': p[n++] = '\\'; break;
292 case 'r': p[n++] = '\''; break;
293 case 's': p[n++] = '/'; break;
294 case 't': p[n++] = '*'; break;
295 case 'u': p[n++] = '^'; break;
296 case 'v': p[n++] = '%'; break;
298 if (!s[0] || !s[1]) goto parse_error;
299 if (fromHexDigit(s[0]) < 0 || fromHexDigit(s[1]) < 0) goto parse_error;
300 p[n++] = 16 * fromHexDigit(s[0]) + fromHexDigit(s[1]);
303 case '0': case '1': case '2': case '3': case '4':
304 case '5': case '6': case '7': case '8': case '9':
307 while (*s && isdigit((int)(*s))) {
308 i = 10 * i + (*s - '0');
311 if (*s != 'T') goto parse_error;
314 while (i > 0) { p[n++] = ','; i--; };
328 fprintf ( stderr, "\nstring = `%s'\n", s );
329 internal ( "unZcodeThenFindText: parse error on above string");
330 return NIL; /*notreached*/
334 Text enZcodeThenFindText ( String s )
339 char toHex[16] = "0123456789ABCDEF";
342 nn = 100 + 10 * strlen(s);
344 if (!p) internal ("enZcodeThenFindText: malloc failed");
348 if (n > nn-90) internal ("enZcodeThenFindText: result is too big");
351 && (isalnum((int)(*s)) || *s == '_')) {
359 while (*s && *s==',') { s++; tup++; };
360 if (*s != ')') internal("enZcodeThenFindText: invalid tuple type");
363 sprintf(num,"%d",tup);
364 p[n] = 0; strcat ( &(p[n]), num ); n += strlen(num);
369 case '(': p[n++] = 'Z'; p[n++] = 'L'; break;
370 case ')': p[n++] = 'Z'; p[n++] = 'R'; break;
371 case '[': p[n++] = 'Z'; p[n++] = 'M'; break;
372 case ']': p[n++] = 'Z'; p[n++] = 'N'; break;
373 case ':': p[n++] = 'Z'; p[n++] = 'C'; break;
374 case 'Z': p[n++] = 'Z'; p[n++] = 'Z'; break;
375 case 'z': p[n++] = 'z'; p[n++] = 'z'; break;
376 case '&': p[n++] = 'z'; p[n++] = 'a'; break;
377 case '|': p[n++] = 'z'; p[n++] = 'b'; break;
378 case '$': p[n++] = 'z'; p[n++] = 'd'; break;
379 case '=': p[n++] = 'z'; p[n++] = 'e'; break;
380 case '>': p[n++] = 'z'; p[n++] = 'g'; break;
381 case '#': p[n++] = 'z'; p[n++] = 'h'; break;
382 case '.': p[n++] = 'z'; p[n++] = 'i'; break;
383 case '<': p[n++] = 'z'; p[n++] = 'l'; break;
384 case '-': p[n++] = 'z'; p[n++] = 'm'; break;
385 case '!': p[n++] = 'z'; p[n++] = 'n'; break;
386 case '+': p[n++] = 'z'; p[n++] = 'p'; break;
387 case '\'': p[n++] = 'z'; p[n++] = 'q'; break;
388 case '\\': p[n++] = 'z'; p[n++] = 'r'; break;
389 case '/': p[n++] = 'z'; p[n++] = 's'; break;
390 case '*': p[n++] = 'z'; p[n++] = 't'; break;
391 case '^': p[n++] = 'z'; p[n++] = 'u'; break;
392 case '%': p[n++] = 'z'; p[n++] = 'v'; break;
393 default: s--; p[n++] = 'z'; p[n++] = 'x';
394 p[n++] = toHex[(int)(*s)/16];
395 p[n++] = toHex[(int)(*s)%16];
406 Text textOf ( Cell c )
409 (whatIs(c)==VARIDCELL
410 || whatIs(c)==CONIDCELL
411 || whatIs(c)==VAROPCELL
412 || whatIs(c)==CONOPCELL
413 || whatIs(c)==STRCELL
414 || whatIs(c)==DICTVAR
419 fprintf(stderr, "\ntextOf: bad tag %d\n",whatIs(c) );
420 internal("textOf: bad tag");
425 /* --------------------------------------------------------------------------
428 * Currently, the only attributes that we store for each Ext value is the
429 * corresponding Text label. At some later stage, we may decide to cache
430 * types, predicates, etc. here as a space saving gesture. Given that Text
431 * comparison is cheap, and that this is an experimental implementation, we
432 * will use a straightforward linear search to locate Ext values from their
433 * corresponding Text labels; a hashing scheme can be introduced later if
434 * this turns out to be a problem.
435 * ------------------------------------------------------------------------*/
438 Text DEFTABLE(tabExt,NUM_EXT); /* Storage for Ext names */
441 Ext mkExt(t) /* Allocate or find an Ext value */
447 if (extHw-EXTMIN >= NUM_EXT) {
448 ERRMSG(0) "Ext storage space exhausted"
456 /* --------------------------------------------------------------------------
459 * A Tycon represents a user defined type constructor. Tycons are indexed
460 * by Text values ... a very simple hash function is used to improve lookup
461 * times. Tycon entries with the same hash code are chained together, with
462 * the most recent entry at the front of the list.
463 * ------------------------------------------------------------------------*/
465 #define TYCONHSZ 256 /* Size of Tycon hash table*/
466 #define tHash(x) ((x)%TYCONHSZ) /* Tycon hash function */
467 static Tycon tyconHw; /* next unused Tycon */
468 static Tycon DEFTABLE(tyconHash,TYCONHSZ); /* Hash table storage */
469 struct strTycon DEFTABLE(tabTycon,NUM_TYCON); /* Tycon storage */
471 Tycon newTycon(t) /* add new tycon to tycon table */
474 if (tyconHw-TYCMIN >= NUM_TYCON) {
475 ERRMSG(0) "Type constructor storage space exhausted"
478 tycon(tyconHw).text = t; /* clear new tycon record */
479 tycon(tyconHw).kind = NIL;
480 tycon(tyconHw).defn = NIL;
481 tycon(tyconHw).what = NIL;
482 tycon(tyconHw).conToTag = NIL;
483 tycon(tyconHw).tagToCon = NIL;
484 tycon(tyconHw).tuple = -1;
485 tycon(tyconHw).mod = currentModule;
486 tycon(tyconHw).itbl = NULL;
487 module(currentModule).tycons = cons(tyconHw,module(currentModule).tycons);
488 tycon(tyconHw).nextTyconHash = tyconHash[h];
489 tyconHash[h] = tyconHw;
494 Tycon findTycon(t) /* locate Tycon in tycon table */
496 Tycon tc = tyconHash[tHash(t)];
498 while (nonNull(tc) && tycon(tc).text!=t)
499 tc = tycon(tc).nextTyconHash;
503 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
506 assert(whatIs(tc)==TYCON || whatIs(tc)==TUPLE);
507 oldtc = findTycon(tycon(tc).text);
510 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
516 static Void local hashTycon(tc) /* Insert Tycon into hash table */
518 if (!(isTycon(tc) || isTuple(tc))) {
519 printf("\nbad stuff: " ); print(tc,10); printf("\n");
520 assert(isTycon(tc) || isTuple(tc));
523 Text t = tycon(tc).text;
525 tycon(tc).nextTyconHash = tyconHash[h];
530 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
532 if (!isPair(id)) internal("findQualTycon");
536 return findTycon(textOf(id));
538 Text t = qtextOf(id);
539 Module m = findQualifier(qmodOf(id));
541 if (isNull(m)) return NIL;
542 for(es=module(m).exports; nonNull(es); es=tl(es)) {
544 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
549 default : internal("findQualTycon2");
551 return NIL; /* NOTREACHED */
554 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
560 Tycon tc = newTycon(t);
562 tycon(tc).kind = kind;
563 tycon(tc).what = what;
564 tycon(tc).defn = defn;
565 tycon(tc).arity = ar;
569 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
574 String s = textToStr(tycon(tc).text);
576 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
577 if (hd(curr)==tc) /* just in case we get duplicates! */
583 tl(prev) = cons(tc,curr);
587 return cons(tc,curr);
590 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
591 String pat; /* to list of Tycons ts */
592 List ts; { /* Null pattern matches every tycon*/
593 Tycon tc; /* (Tycons with NIL kind excluded) */
594 for (tc=TYCMIN; tc<tyconHw; ++tc)
595 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
596 if (nonNull(tycon(tc).kind))
597 ts = insertTycon(tc,ts);
601 Text ghcTupleText_n ( Int n )
606 if (n < 0 || n >= 100) internal("ghcTupleText_n");
607 if (n == 1) internal("ghcTupleText_n==1");
609 for (i = 1; i <= n-1; i++) buf[x++] = ',';
612 return findText(buf);
615 Text ghcTupleText(tup)
618 assert(isTuple(tup));
620 return ghcTupleText_n ( tupleOf(tup) );
624 Tycon mkTuple ( Int n )
628 internal("mkTuple: request for tuple of unsupported size");
629 for (i = TYCMIN; i < tyconHw; i++)
630 if (tycon(i).tuple == n) return i;
631 internal("mkTuple: request for non-existent tuple");
635 /* --------------------------------------------------------------------------
638 * A Name represents a top level binding of a value to an identifier.
639 * Such values may be a constructor function, a member function in a
640 * class, a user-defined or primitive value/function.
642 * Names are indexed by Text values ... a very simple hash functions speeds
643 * access to the table of Names and Name entries with the same hash value
644 * are chained together, with the most recent entry at the front of the
646 * ------------------------------------------------------------------------*/
648 #define NAMEHSZ 256 /* Size of Name hash table */
649 #define nHash(x) ((x)%NAMEHSZ) /* hash fn :: Text->Int */
650 Name nameHw; /* next unused name */
651 static Name DEFTABLE(nameHash,NAMEHSZ); /* Hash table storage */
652 struct strName DEFTABLE(tabName,NUM_NAME); /* Name table storage */
654 Name newName(t,parent) /* Add new name to name table */
658 if (nameHw-NAMEMIN >= NUM_NAME) {
659 ERRMSG(0) "Name storage space exhausted"
662 name(nameHw).text = t; /* clear new name record */
663 name(nameHw).line = 0;
664 name(nameHw).syntax = NO_SYNTAX;
665 name(nameHw).parent = parent;
666 name(nameHw).arity = 0;
667 name(nameHw).number = EXECNAME;
668 name(nameHw).defn = NIL;
669 name(nameHw).stgVar = NIL;
670 name(nameHw).callconv = NIL;
671 name(nameHw).type = NIL;
672 name(nameHw).primop = 0;
673 name(nameHw).mod = currentModule;
674 name(nameHw).itbl = NULL;
675 module(currentModule).names=cons(nameHw,module(currentModule).names);
676 name(nameHw).nextNameHash = nameHash[h];
677 nameHash[h] = nameHw;
681 Name findName(t) /* Locate name in name table */
683 Name n = nameHash[nHash(t)];
685 while (nonNull(n) && name(n).text!=t)
686 n = name(n).nextNameHash;
690 Name addName(nm) /* Insert Name in name table - if */
691 Name nm; { /* no clash is caused */
693 assert(whatIs(nm)==NAME);
694 oldnm = findName(name(nm).text);
697 module(currentModule).names=cons(nm,module(currentModule).names);
703 static Void local hashName(nm) /* Insert Name into hash table */
710 name(nm).nextNameHash = nameHash[h];
714 Name findQualName(id) /* Locate (possibly qualified) name*/
715 Cell id; { /* in name table */
717 internal("findQualName");
723 return findName(textOf(id));
725 Text t = qtextOf(id);
726 Module m = findQualifier(qmodOf(id));
728 if (isNull(m)) return NIL;
729 for(es=module(m).exports; nonNull(es); es=tl(es)) {
731 if (isName(e) && name(e).text==t)
733 else if (isPair(e) && DOTDOT==snd(e)) {
734 List subentities = NIL;
737 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
738 subentities = tycon(c).defn;
740 subentities = cclass(c).members;
741 for(; nonNull(subentities); subentities=tl(subentities)) {
742 if (!isName(hd(subentities)))
743 internal("findQualName3");
744 if (name(hd(subentities)).text == t)
745 return hd(subentities);
751 default : internal("findQualName2");
753 return 0; /* NOTREACHED */
757 Name nameFromStgVar ( StgVar v )
760 for (n = NAMEMIN; n < nameHw; n++)
761 if (name(n).stgVar == v) return n;
765 void* getHugs_AsmObject_for ( char* s )
768 Text t = findText(s);
770 for (n = NAMEMIN; n < nameHw; n++)
771 if (name(n).text == t) break;
773 fprintf ( stderr, "can't find `%s' in ...\n", s );
774 internal("getHugs_AsmObject_for(1)");
777 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
778 internal("getHugs_AsmObject_for(2)");
779 return ptrOf(stgVarInfo(v));
782 /* --------------------------------------------------------------------------
783 * Primitive functions:
784 * ------------------------------------------------------------------------*/
786 Module findFakeModule ( Text t )
788 Module m = findModule(t);
790 if (!module(m).fake) internal("findFakeModule");
793 module(m).fake = TRUE;
799 Name addWiredInBoxingTycon
800 ( String modNm, String typeNm, String constrNm,
805 Text modT = findText(modNm);
806 Text typeT = findText(typeNm);
807 Text conT = findText(constrNm);
808 Module m = findFakeModule(modT);
811 n = newName(conT,NIL);
813 name(n).number = cfunNo(0);
815 name(n).primop = (void*)rep;
818 tycon(t).what = DATATYPE;
819 tycon(t).kind = kind;
824 Tycon addTupleTycon ( Int n )
832 for (i = TYCMIN; i < tyconHw; i++)
833 if (tycon(i).tuple == n) return i;
836 m = findFakeModule(findText(n==0 ? "PrelBase" : "PrelTup")); else
837 m = findModule(findText("Prelude"));
841 for (i = 0; i < n; i++) k = ap(STAR,k);
842 t = newTycon(ghcTupleText_n(n));
845 tycon(t).what = DATATYPE;
848 /* maybe we want to do this for all n ? */
849 nm = newName(ghcTupleText_n(n), t);
850 name(nm).type = t; /* ummm ... for n > 0 */
857 Tycon addWiredInEnumTycon ( String modNm, String typeNm,
858 List /*of Text*/ constrs )
862 Text modT = findText(modNm);
863 Text typeT = findText(typeNm);
864 Module m = findFakeModule(modT);
868 tycon(t).kind = STAR;
869 tycon(t).what = DATATYPE;
871 constrs = reverse(constrs);
873 for (; nonNull(constrs); constrs=tl(constrs),i--) {
874 Text conT = hd(constrs);
875 Name con = newName(conT,t);
876 name(con).number = cfunNo(i);
878 name(con).parent = t;
879 tycon(t).defn = cons(con, tycon(t).defn);
885 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
886 Text t; /* sets rep, not type */
889 Int rep; { /* Really AsmRep */
890 Name n = newName(t,NIL);
891 name(n).arity = arity;
892 name(n).number = cfunNo(no);
894 name(n).primop = (void*)rep;
899 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
904 Name n = newName(t,NIL);
905 name(n).arity = arity;
906 name(n).number = cfunNo(no);
912 Int sfunPos(s,c) /* Find position of field with */
913 Name s; /* selector s in constructor c. */
917 for (; nonNull(cns); cns=tl(cns))
919 return intOf(snd(hd(cns)));
921 return 0;/* NOTREACHED */
924 static List local insertName(nm,ns) /* insert name nm into sorted list */
929 String s = textToStr(name(nm).text);
931 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
932 if (hd(curr)==nm) /* just in case we get duplicates! */
938 tl(prev) = cons(nm,curr);
942 return cons(nm,curr);
945 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
946 String pat; /* to list of names ns */
947 List ns; { /* Null pattern matches every name */
948 Name nm; /* (Names with NIL type, or hidden */
950 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
951 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
952 String str = textToStr(name(nm).text);
953 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
954 ns = insertName(nm,ns);
958 List mns = module(currentModule).names;
959 for(; nonNull(mns); mns=tl(mns)) {
961 if (!inventedText(name(nm).text)) {
962 String str = textToStr(name(nm).text);
963 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
964 ns = insertName(nm,ns);
971 /* --------------------------------------------------------------------------
972 * A simple string matching routine
973 * `*' matches any sequence of zero or more characters
974 * `?' matches any single character exactly
975 * `@str' matches the string str exactly (ignoring any special chars)
976 * `\c' matches the character c only (ignoring special chars)
977 * c matches the character c only
978 * ------------------------------------------------------------------------*/
980 static Void local patternError(s) /* report error in pattern */
982 ERRMSG(0) "%s in pattern", s
986 static Bool local stringMatch(pat,str) /* match string against pattern */
992 case '\0' : return (*str=='\0');
995 if (stringMatch(pat+1,str))
1000 case '?' : if (*str++=='\0')
1005 case '[' : { Bool found = FALSE;
1006 while (*++pat!='\0' && *pat!=']')
1007 if (!found && ( pat[0] == *str ||
1016 patternError("missing `]'");
1024 case '\\' : if (*++pat == '\0')
1025 patternError("extra trailing `\\'");
1027 default : if (*pat++ != *str++)
1033 /* --------------------------------------------------------------------------
1034 * Storage of type classes, instances etc...:
1035 * ------------------------------------------------------------------------*/
1037 static Class classHw; /* next unused class */
1038 static List classes; /* list of classes in current scope */
1039 static Inst instHw; /* next unused instance record */
1041 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
1042 struct strInst far *tabInst; /* (pointer to) table of instances */
1044 Class newClass(t) /* add new class to class table */
1046 if (classHw-CLASSMIN >= NUM_CLASSES) {
1047 ERRMSG(0) "Class storage space exhausted"
1050 cclass(classHw).text = t;
1051 cclass(classHw).arity = 0;
1052 cclass(classHw).kinds = NIL;
1053 cclass(classHw).head = NIL;
1054 cclass(classHw).fds = NIL;
1055 cclass(classHw).xfds = NIL;
1056 cclass(classHw).dcon = NIL;
1057 cclass(classHw).supers = NIL;
1058 cclass(classHw).dsels = NIL;
1059 cclass(classHw).members = NIL;
1060 cclass(classHw).defaults = NIL;
1061 cclass(classHw).instances = NIL;
1062 classes=cons(classHw,classes);
1063 cclass(classHw).mod = currentModule;
1064 module(currentModule).classes=cons(classHw,module(currentModule).classes);
1068 Class classMax() { /* Return max Class in use ... */
1069 return classHw; /* This is a bit ugly, but it's not*/
1070 } /* worth a lot of effort right now */
1072 Class findClass(t) /* look for named class in table */
1076 for (cs=classes; nonNull(cs); cs=tl(cs)) {
1078 if (cclass(cl).text==t)
1084 Class addClass(c) /* Insert Class in class list */
1085 Class c; { /* - if no clash caused */
1087 assert(whatIs(c)==CLASS);
1088 oldc = findClass(cclass(c).text);
1090 classes=cons(c,classes);
1091 module(currentModule).classes=cons(c,module(currentModule).classes);
1098 Class findQualClass(c) /* Look for (possibly qualified) */
1099 Cell c; { /* class in class list */
1100 if (!isQualIdent(c)) {
1101 return findClass(textOf(c));
1103 Text t = qtextOf(c);
1104 Module m = findQualifier(qmodOf(c));
1108 for (es=module(m).exports; nonNull(es); es=tl(es)) {
1110 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
1117 Inst newInst() { /* Add new instance to table */
1118 if (instHw-INSTMIN >= NUM_INSTS) {
1119 ERRMSG(0) "Instance storage space exhausted"
1122 inst(instHw).kinds = NIL;
1123 inst(instHw).head = NIL;
1124 inst(instHw).specifics = NIL;
1125 inst(instHw).implements = NIL;
1126 inst(instHw).builder = NIL;
1127 inst(instHw).mod = currentModule;
1133 extern Void printInst Args((Inst));
1137 Class cl = inst(in).c;
1138 Printf("%s-", textToStr(cclass(cl).text));
1139 printType(stdout,inst(in).t);
1141 #endif /* DEBUG_DICTS */
1143 Inst findFirstInst(tc) /* look for 1st instance involving */
1144 Tycon tc; { /* the type constructor tc */
1145 return findNextInst(tc,INSTMIN-1);
1148 Inst findNextInst(tc,in) /* look for next instance involving*/
1149 Tycon tc; /* the type constructor tc */
1150 Inst in; { /* starting after instance in */
1151 while (++in < instHw) {
1152 Cell pi = inst(in).head;
1153 for (; isAp(pi); pi=fun(pi))
1154 if (typeInvolves(arg(pi),tc))
1160 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1161 Type ty; /* type constructor/tuple tc. */
1164 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1165 || typeInvolves(arg(ty),tc)));
1169 /* Needed by finishGHCInstance to find classes, before the
1170 export list has been built -- so we can't use
1173 Class findQualClassWithoutConsultingExportList ( QualId q )
1183 t_class = textOf(q);
1186 t_class = qtextOf(q);
1189 for (cl = CLASSMIN; cl < classHw; cl++) {
1190 if (cclass(cl).text == t_class) {
1191 /* Class name is ok, but is this the right module? */
1192 if (isNull(t_mod) /* no module name specified */
1194 && t_mod == module(cclass(cl).mod).text)
1203 /* Same deal, except for Tycons. */
1204 Tycon findQualTyconWithoutConsultingExportList ( QualId q )
1214 t_tycon = textOf(q);
1217 t_tycon = qtextOf(q);
1220 for (tc = TYCMIN; tc < tyconHw; tc++) {
1221 if (tycon(tc).text == t_tycon) {
1222 /* Tycon name is ok, but is this the right module? */
1223 if (isNull(t_mod) /* no module name specified */
1225 && t_mod == module(tycon(tc).mod).text)
1233 Tycon findTyconInAnyModule ( Text t )
1236 for (tc = TYCMIN; tc < tyconHw; tc++)
1237 if (tycon(tc).text == t) return tc;
1241 Class findClassInAnyModule ( Text t )
1244 for (cc = CLASSMIN; cc < classHw; cc++)
1245 if (cclass(cc).text == t) return cc;
1249 Name findNameInAnyModule ( Text t )
1252 for (nm = NAMEMIN; nm < nameHw; nm++)
1253 if (name(nm).text == t) return nm;
1257 /* Same deal, except for Names. */
1258 Name findQualNameWithoutConsultingExportList ( QualId q )
1264 assert(isQVar(q) || isQCon(q));
1266 if (isCon(q) || isVar(q)) {
1271 t_name = qtextOf(q);
1274 for (nm = NAMEMIN; nm < nameHw; nm++) {
1275 if (name(nm).text == t_name) {
1276 /* Name is ok, but is this the right module? */
1277 if (isNull(t_mod) /* no module name specified */
1279 && t_mod == module(name(nm).mod).text)
1288 /* returns List of QualId */
1289 List getAllKnownTyconsAndClasses ( void )
1294 for (tc = TYCMIN; tc < tyconHw; tc++) {
1295 /* almost certainly undue paranoia about duplicate avoidance, but .. */
1296 QualId q = mkQCon( module(tycon(tc).mod).text, tycon(tc).text );
1297 if (!qualidIsMember(q,xs))
1298 xs = cons ( q, xs );
1300 for (nw = CLASSMIN; nw < classHw; nw++) {
1301 QualId q = mkQCon( module(cclass(nw).mod).text, cclass(nw).text );
1302 if (!qualidIsMember(q,xs))
1303 xs = cons ( q, xs );
1308 /* Purely for debugging. */
1309 void locateSymbolByName ( Text t )
1312 for (i = NAMEMIN; i < nameHw; i++)
1313 if (name(i).text == t)
1314 fprintf ( stderr, "name(%d)\n", i-NAMEMIN);
1315 for (i = TYCMIN; i < tyconHw; i++)
1316 if (tycon(i).text == t)
1317 fprintf ( stderr, "tycon(%d)\n", i-TYCMIN);
1318 for (i = CLASSMIN; i < classHw; i++)
1319 if (cclass(i).text == t)
1320 fprintf ( stderr, "class(%d)\n", i-CLASSMIN);
1323 /* --------------------------------------------------------------------------
1326 * Various parts of the system use a stack of cells. Most of the stack
1327 * operations are defined as macros, expanded inline.
1328 * ------------------------------------------------------------------------*/
1330 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
1331 StackPtr sp; /* stack pointer */
1333 #if GIMME_STACK_DUMPS
1335 #define UPPER_DISP 5 /* # display entries on top of stack */
1336 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
1338 Void hugsStackOverflow() { /* Report stack overflow */
1340 extern Cell evalRoots[];
1342 ERRMSG(0) "Control stack overflow" ETHEN
1345 if (rootsp>=UPPER_DISP+LOWER_DISP) {
1346 for (i=0; i<UPPER_DISP; i++) {
1347 ERRTEXT "\nwhile evaluating: " ETHEN
1348 ERREXPR(evalRoots[rootsp-i]);
1350 ERRTEXT "\n..." ETHEN
1351 for (i=LOWER_DISP-1; i>=0; i--) {
1352 ERRTEXT "\nwhile evaluating: " ETHEN
1353 ERREXPR(evalRoots[i]);
1357 for (i=rootsp; i>=0; i--) {
1358 ERRTEXT "\nwhile evaluating: " ETHEN
1359 ERREXPR(evalRoots[i]);
1367 #else /* !GIMME_STACK_DUMPS */
1369 Void hugsStackOverflow() { /* Report stack overflow */
1370 ERRMSG(0) "Control stack overflow"
1374 #endif /* !GIMME_STACK_DUMPS */
1376 /* --------------------------------------------------------------------------
1379 * A Module represents a user defined module.
1381 * Note: there are now two lookup mechanisms in the system:
1383 * 1) The exports from a module are stored in a big list.
1384 * We resolve qualified names, and import lists by linearly scanning
1385 * through this list.
1387 * 2) Unqualified imports and local definitions for the current module
1388 * are stored in hash tables (tyconHash and nameHash) or linear lists
1391 * ------------------------------------------------------------------------*/
1393 static Module moduleHw; /* next unused Module */
1394 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
1395 Module currentModule; /* Module currently being processed*/
1397 Bool isValidModule(m) /* is m a legitimate module id? */
1399 return (MODMIN <= m && m < moduleHw);
1402 Module newModule(t) /* add new module to module table */
1404 if (moduleHw-MODMIN >= NUM_MODULE) {
1405 ERRMSG(0) "Module storage space exhausted"
1408 module(moduleHw).text = t; /* clear new module record */
1409 module(moduleHw).qualImports = NIL;
1410 module(moduleHw).fake = FALSE;
1411 module(moduleHw).exports = NIL;
1412 module(moduleHw).tycons = NIL;
1413 module(moduleHw).names = NIL;
1414 module(moduleHw).classes = NIL;
1415 module(moduleHw).object = NULL;
1416 module(moduleHw).objectExtras = NULL;
1417 module(moduleHw).objectExtraNames = NIL;
1421 void ppModules ( void )
1424 fflush(stderr); fflush(stdout);
1425 printf ( "begin MODULES\n" );
1426 for (i = moduleHw-1; i >= MODMIN; i--)
1427 printf ( " %2d: %16s\n",
1428 i-MODMIN, textToStr(module(i).text)
1430 printf ( "end MODULES\n" );
1431 fflush(stderr); fflush(stdout);
1435 Module findModule(t) /* locate Module in module table */
1438 for(m=MODMIN; m<moduleHw; ++m) {
1439 if (module(m).text==t)
1445 Module findModid(c) /* Find module by name or filename */
1447 switch (whatIs(c)) {
1448 case STRCELL : { Script s = scriptThisFile(snd(c));
1449 return (s==-1) ? NIL : moduleOfScript(s);
1451 case CONIDCELL : return findModule(textOf(c));
1452 default : internal("findModid");
1454 return NIL;/*NOTUSED*/
1457 static local Module findQualifier(t) /* locate Module in import list */
1460 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1461 if (textOf(fst(hd(ms)))==t)
1465 if (module(currentModule).text==t)
1466 return currentModule;
1471 Void setCurrModule(m) /* set lookup tables for current module */
1474 assert(isModule(m));
1475 if (m!=currentModule) {
1476 currentModule = m; /* This is the only assignment to currentModule */
1477 for (i=0; i<TYCONHSZ; ++i)
1479 mapProc(hashTycon,module(m).tycons);
1480 for (i=0; i<NAMEHSZ; ++i)
1482 mapProc(hashName,module(m).names);
1483 classes = module(m).classes;
1487 Name jrsFindQualName ( Text mn, Text sn )
1492 for (m=MODMIN; m<moduleHw; m++)
1493 if (module(m).text == mn) break;
1494 if (m == moduleHw) return NIL;
1496 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1497 if (name(hd(ns)).text == sn) return hd(ns);
1503 char* nameFromOPtr ( void* p )
1507 for (m=MODMIN; m<moduleHw; m++) {
1508 if (module(m).object) {
1509 char* nm = ocLookupAddr ( module(m).object, p );
1514 /* A kludge to assist Win32 debugging; not actually necessary. */
1515 { char* nm = nameFromStaticOPtr(p);
1523 void* lookupOTabName ( Module m, char* sym )
1525 if (module(m).object)
1526 return ocLookupSym ( module(m).object, sym );
1531 void* lookupOExtraTabName ( char* sym )
1535 for (m = MODMIN; m < moduleHw; m++) {
1536 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1537 void* ad = ocLookupSym ( oc, sym );
1545 OSectionKind lookupSection ( void* ad )
1552 for (m=MODMIN; m<moduleHw; m++) {
1553 if (module(m).object) {
1554 sect = ocLookupSection ( module(m).object, ad );
1555 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1558 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1559 sect = ocLookupSection ( oc, ad );
1560 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1564 return HUGS_SECTIONKIND_OTHER;
1568 /* --------------------------------------------------------------------------
1569 * Script file storage:
1571 * script files are read into the system one after another. The state of
1572 * the stored data structures (except the garbage-collected heap) is recorded
1573 * before reading a new script. In the event of being unable to read the
1574 * script, or if otherwise requested, the system can be restored to its
1575 * original state immediately before the file was read.
1576 * ------------------------------------------------------------------------*/
1578 typedef struct { /* record of storage state prior to */
1579 Text file; /* reading script/module */
1593 #ifdef DEBUG_SHOWUSE
1594 static Void local showUse(msg,val,mx)
1597 Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1601 static Script scriptHw; /* next unused script number */
1602 static script scripts[NUM_SCRIPTS]; /* storage for script records */
1605 void ppScripts ( void )
1608 fflush(stderr); fflush(stdout);
1609 printf ( "begin SCRIPTS\n" );
1610 for (i = scriptHw-1; i >= 0; i--)
1611 printf ( " %2d: %16s tH=%d mH=%d yH=%d "
1612 "nH=%d cH=%d iH=%d nnS=%d,%d\n",
1613 i, textToStr(scripts[i].file),
1614 scripts[i].textHw, scripts[i].moduleHw,
1615 scripts[i].tyconHw, scripts[i].nameHw,
1616 scripts[i].classHw, scripts[i].instHw,
1617 scripts[i].nextNewText, scripts[i].nextNewDText
1619 printf ( "end SCRIPTS\n" );
1620 fflush(stderr); fflush(stdout);
1623 Script startNewScript(f) /* start new script, keeping record */
1624 String f; { /* of status for later restoration */
1625 if (scriptHw >= NUM_SCRIPTS) {
1626 ERRMSG(0) "Too many script files in use"
1629 #ifdef DEBUG_SHOWUSE
1630 showUse("Text", textHw, NUM_TEXT);
1631 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
1632 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
1633 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
1634 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
1635 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
1637 showUse("Ext", extHw-EXTMIN, NUM_EXT);
1640 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
1641 scripts[scriptHw].textHw = textHw;
1642 scripts[scriptHw].nextNewText = nextNewText;
1643 scripts[scriptHw].nextNewDText = nextNewDText;
1644 scripts[scriptHw].moduleHw = moduleHw;
1645 scripts[scriptHw].tyconHw = tyconHw;
1646 scripts[scriptHw].nameHw = nameHw;
1647 scripts[scriptHw].classHw = classHw;
1648 scripts[scriptHw].instHw = instHw;
1650 scripts[scriptHw].extHw = extHw;
1655 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1656 return (scriptHw < N_PRELUDE_SCRIPTS /*==0*/ );
1659 Bool moduleThisScript(m) /* Test if given module is defined */
1660 Module m; { /* in current script file */
1662 || m>=scripts[scriptHw-1].moduleHw;
1665 Module lastModule() { /* Return module in current script file */
1666 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1669 #define scriptThis(nm,t,tag) Script nm(x) \
1673 && x>=scripts[s].tag) \
1677 scriptThis(scriptThisName,Name,nameHw)
1678 scriptThis(scriptThisTycon,Tycon,tyconHw)
1679 scriptThis(scriptThisInst,Inst,instHw)
1680 scriptThis(scriptThisClass,Class,classHw)
1683 Module moduleOfScript(s)
1685 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1688 String fileOfModule(m)
1691 if (m == modulePrelude) {
1694 for(s=0; s<scriptHw; ++s) {
1695 if (scripts[s].moduleHw == m) {
1696 return textToStr(scripts[s].file);
1702 Script scriptThisFile(f)
1705 for (s=0; s < scriptHw; ++s) {
1706 if (scripts[s].file == f) {
1710 if (f == findText(STD_PRELUDE)) {
1716 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1717 Script sno; { /* to reading script sno */
1718 if (sno<scriptHw) { /* is there anything to restore? */
1720 textHw = scripts[sno].textHw;
1721 nextNewText = scripts[sno].nextNewText;
1722 nextNewDText = scripts[sno].nextNewDText;
1723 moduleHw = scripts[sno].moduleHw;
1724 tyconHw = scripts[sno].tyconHw;
1725 nameHw = scripts[sno].nameHw;
1726 classHw = scripts[sno].classHw;
1727 instHw = scripts[sno].instHw;
1729 dictHw = scripts[sno].dictHw;
1732 extHw = scripts[sno].extHw;
1736 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1737 if (module(i).objectFile) {
1738 printf("[bogus] closing objectFile for module %d\n",i);
1739 /*dlclose(module(i).objectFile);*/
1742 moduleHw = scripts[sno].moduleHw;
1744 for (i=0; i<TEXTHSZ; ++i) {
1746 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1747 && textHash[i][j]<textHw)
1750 textHash[i][j] = NOTEXT;
1754 for (i=0; i<TYCONHSZ; ++i) {
1757 for (i=0; i<NAMEHSZ; ++i) {
1761 for (i=CLASSMIN; i<classHw; i++) {
1762 List ins = cclass(i).instances;
1765 while (nonNull(ins)) {
1766 List temp = tl(ins);
1767 if (hd(ins)<instHw) {
1773 cclass(i).instances = rev(is);
1780 /* --------------------------------------------------------------------------
1783 * Provides a garbage collectable heap for storage of expressions etc.
1785 * Now incorporates a flat resource: A two-space collected extension of
1786 * the heap that provides storage for contiguous arrays of Cell storage,
1787 * cooperating with the garbage collection mechanisms for the main heap.
1788 * ------------------------------------------------------------------------*/
1790 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1791 Heap heapFst; /* array of fst component of pairs */
1792 Heap heapSnd; /* array of snd component of pairs */
1799 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1800 /* C stack; use with extreme care! */
1802 Int numGcs; /* number of garbage collections */
1803 Int cellsRecovered; /* number of cells recovered */
1805 static Cell freeList; /* free list of unused cells */
1806 static Cell lsave, rsave; /* save components of pair */
1810 static Int markCount, stackRoots;
1812 #define initStackRoots() stackRoots = 0
1813 #define recordStackRoot() stackRoots++
1826 #define start() markCount = 0
1827 #define end(thing,rs) \
1829 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1832 #define recordMark() markCount++
1834 #else /* !GC_STATISTICS */
1839 #define initStackRoots()
1840 #define recordStackRoot()
1843 #define end(thing,root)
1844 #define recordMark()
1846 #endif /* !GC_STATISTICS */
1848 Cell pair(l,r) /* Allocate pair (l, r) from */
1849 Cell l, r; { /* heap, garbage collecting first */
1850 Cell c = freeList; /* if necessary ... */
1862 freeList = snd(freeList);
1869 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1870 Cell dst, src; { /* both *MUST* be pairs */
1871 if (isPair(dst) && isPair(src)) {
1872 fst(dst) = fst(src);
1873 snd(dst) = snd(src);
1876 internal("overwrite");
1880 static Int marksSize;
1882 Cell markExpr(c) /* External interface to markCell */
1884 return isGenPair(c) ? markCell(c) : c;
1887 static Cell local markCell(c) /* Traverse part of graph marking */
1888 Cell c; { /* cells reachable from given root */
1889 /* markCell(c) is only called if c */
1891 { register int place = placeInSet(c);
1892 register int mask = maskInSet(c);
1893 if (marks[place]&mask)
1896 marks[place] |= mask;
1901 /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1902 if (isGenPair(fst(c))) {
1904 fst(c) = markCell(fst(c));
1907 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1915 static Void local markSnd(c) /* Variant of markCell used to */
1916 Cell c; { /* update snd component of cell */
1917 Cell t; /* using tail recursion */
1919 ma: t = c; /* Keep pointer to original pair */
1924 { register int place = placeInSet(c);
1925 register int mask = maskInSet(c);
1926 if (marks[place]&mask)
1929 marks[place] |= mask;
1934 if (isGenPair(fst(c))) {
1935 fst(c) = markCell(fst(c));
1938 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1943 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1944 Cell n; { /* it was a cell ref, but don't */
1945 /* move cell so we don't have */
1946 /* to modify the stored value of n */
1953 Void garbageCollect() { /* Run garbage collector ... */
1954 Bool breakStat = breakOn(FALSE); /* disable break checking */
1960 jmp_buf regs; /* save registers on stack */
1964 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1967 everybody(MARK); /* Mark all components of system */
1969 gcScanning(); /* scan mark set */
1976 for (i=1; i<=heapSize; i++) {
1977 if ((marks[place] & mask) == 0) {
1984 if (++j == bitsPerWord) {
1991 gcRecovered(recovered);
1992 breakOn(breakStat); /* restore break trapping if nec. */
1996 /* can only return if freeList is nonempty on return. */
1997 if (recovered<minRecovery || isNull(freeList)) {
1998 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
2001 cellsRecovered = recovered;
2004 /* --------------------------------------------------------------------------
2005 * Code for saving last expression entered:
2007 * This is a little tricky because some text values (e.g. strings or variable
2008 * names) may not be defined or have the same value when the expression is
2009 * recalled. These text values are therefore saved in the top portion of
2011 * ------------------------------------------------------------------------*/
2013 static Cell lastExprSaved; /* last expression to be saved */
2015 Void setLastExpr(e) /* save expression for later recall*/
2017 lastExprSaved = NIL; /* in case attempt to save fails */
2018 savedText = NUM_TEXT;
2019 lastExprSaved = lowLevelLastIn(e);
2022 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
2023 Cell c; { /* acyclic graph) for later recall */
2024 if (isPair(c)) { /* Duplicating any text strings */
2025 if (isBoxTag(fst(c))) /* in case these are lost at some */
2026 switch (fst(c)) { /* point before the expr is reused */
2032 case STRCELL : return pair(fst(c),saveText(textOf(c)));
2033 default : return pair(fst(c),snd(c));
2036 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2040 return pair(EXTCOPY,saveText(extText(c)));
2046 Cell getLastExpr() { /* recover previously saved expr */
2047 return lowLevelLastOut(lastExprSaved);
2050 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
2051 Cell c; { /* except that Cells refering to */
2052 if (isPair(c)) { /* Text values are restored to */
2053 if (isBoxTag(fst(c))) /* appropriate values */
2060 case STRCELL : return pair(fst(c),
2061 findText(text+intValOf(c)));
2063 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
2065 default : return pair(fst(c),snd(c));
2068 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2074 /* --------------------------------------------------------------------------
2075 * Miscellaneous operations on heap cells:
2076 * ------------------------------------------------------------------------*/
2078 /* Profiling suggests that the number of calls to whatIs() is typically */
2079 /* rather high. The recoded version below attempts to improve the average */
2080 /* performance for whatIs() using a binary search for part of the analysis */
2082 Cell whatIs(c) /* identify type of cell */
2085 register Cell fstc = fst(c);
2086 return isTag(fstc) ? fstc : AP;
2088 if (c<OFFMIN) return c;
2090 if (isExt(c)) return EXT;
2092 if (c>=INTMIN) return INTCELL;
2094 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
2096 else if (c>=INSTMIN) return INSTANCE;
2098 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
2099 else return MODULE;}
2100 else if (c>=OFFMIN) return OFFSET;
2102 else return (c>=EXTMIN) ?
2109 register Cell fstc = fst(c);
2110 return isTag(fstc) ? fstc : AP;
2112 if (c>=INTMIN) return INTCELL;
2113 if (c>=CHARMIN) return CHARCELL;
2114 if (c>=CLASSMIN) return CLASS;
2115 if (c>=INSTMIN) return INSTANCE;
2116 if (c>=NAMEMIN) return NAME;
2117 if (c>=TYCMIN) return TYCON;
2118 if (c>=MODMIN) return MODULE;
2119 if (c>=OFFMIN) return OFFSET;
2121 if (c>=EXTMIN) return EXT;
2123 if (c>=TUPMIN) return TUPLE;
2127 /* A very, very simple printer.
2128 * Output is uglier than from printExp - but the printer is more
2129 * robust and can be used on any data structure irrespective of
2132 Void print Args((Cell, Int));
2133 Void print(c, depth)
2139 Int tag = whatIs(c);
2143 print(fst(c), depth-1);
2145 print(snd(c), depth-1);
2149 Printf("free(%d)", c);
2152 Printf("int(%d)", intOf(c));
2155 Printf("bignum(%s)", bignumToString(c));
2158 Printf("char('%c')", charOf(c));
2161 Printf("ptr(%p)",ptrOf(c));
2164 Printf("class(%d)", c-CLASSMIN);
2165 if (CLASSMIN <= c && c < classHw) {
2166 Printf("=\"%s\"", textToStr(cclass(c).text));
2170 Printf("instance(%d)", c - INSTMIN);
2173 Printf("name(%d)", c-NAMEMIN);
2174 if (NAMEMIN <= c && c < nameHw) {
2175 Printf("=\"%s\"", textToStr(name(c).text));
2179 Printf("tycon(%d)", c-TYCMIN);
2180 if (TYCMIN <= c && c < tyconHw)
2181 Printf("=\"%s\"", textToStr(tycon(c).text));
2184 Printf("module(%d)", c - MODMIN);
2187 Printf("Offset %d", offsetOf(c));
2190 Printf("%s", textToStr(ghcTupleText(c)));
2194 print(snd(c),depth-1);
2198 print(snd(c),depth-1);
2202 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2203 Printf("%d ", intOf(fst(snd(c))));
2204 print(snd(snd(c)),depth-1);
2206 print(snd(c),depth-1);
2223 Printf("{dict %d}",textOf(c));
2229 Printf("{id %s}",textToStr(textOf(c)));
2233 Printf("{ip %s}",textToStr(textOf(c)));
2236 Printf("?%s",textToStr(textOf(c)));
2240 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2244 print(fst(snd(c)),depth-1);
2246 print(snd(snd(c)),depth-1);
2251 print(snd(c),depth-1);
2256 print(snd(c),depth-1);
2261 print(fst(snd(c)),depth-1);
2263 print(snd(snd(c)),depth-1);
2268 print(fst(snd(c)),depth-1);
2270 print(snd(snd(c)),depth-1);
2274 Printf("FromQual(");
2275 print(fst(snd(c)),depth-1);
2277 print(snd(snd(c)),depth-1);
2281 Printf("StgVar%d=",-c);
2282 print(snd(c), depth-1);
2286 print(fst(snd(c)),depth-1);
2288 print(snd(snd(c)),depth-1);
2293 print(fst(snd(c)),depth-1);
2295 print(snd(snd(c)),depth-1);
2300 print(fst(snd(c)),depth-1);
2302 print(snd(snd(c)),depth-1);
2306 Printf("PrimCase(");
2307 print(fst(snd(c)),depth-1);
2309 print(snd(snd(c)),depth-1);
2314 print(snd(c),depth-1);
2318 Printf("(UNBOXEDTUP,");
2319 print(snd(c),depth-1);
2324 print(zfst(c),depth-1);
2326 print(zsnd(c),depth-1);
2330 Printf("<ZTriple ");
2331 print(zfst3(c),depth-1);
2333 print(zsnd3(c),depth-1);
2335 print(zthd3(c),depth-1);
2340 print(snd(c),depth-1);
2344 if (isBoxTag(tag)) {
2345 Printf("Tag(%d)=%d", c, tag);
2346 } else if (isConTag(tag)) {
2347 Printf("%d@(%d,",c,tag);
2348 print(snd(c), depth-1);
2351 } else if (c == tag) {
2352 Printf("Tag(%d)", c);
2354 Printf("Tag(%d)=%d", c, tag);
2363 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2364 Cell c; { /* also recognises DICTVAR cells */
2366 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2369 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2371 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2374 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2376 if (!isPair(c)) return FALSE;
2379 case VAROPCELL : return TRUE;
2381 case QUALIDENT : return isVar(snd(snd(c)));
2383 default : return FALSE;
2387 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2389 if (!isPair(c)) return FALSE;
2392 case CONOPCELL : return TRUE;
2394 case QUALIDENT : return isCon(snd(snd(c)));
2396 default : return FALSE;
2400 Bool isQualIdent(c) /* is cell a qualified identifier? */
2402 return isPair(c) && (fst(c)==QUALIDENT);
2405 Bool eqQualIdent ( QualId c1, QualId c2 )
2407 assert(isQualIdent(c1));
2408 if (!isQualIdent(c2)) {
2409 assert(isQualIdent(c2));
2411 return qmodOf(c1)==qmodOf(c2) &&
2412 qtextOf(c1)==qtextOf(c2);
2415 Bool isIdent(c) /* is cell an identifier? */
2417 if (!isPair(c)) return FALSE;
2422 case CONOPCELL : return TRUE;
2424 case QUALIDENT : return TRUE;
2426 default : return FALSE;
2430 Bool isInt(c) /* cell holds integer value? */
2432 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2435 Int intOf(c) /* find integer value of cell? */
2438 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
2441 Cell mkInt(n) /* make cell representing integer */
2443 return (MINSMALLINT <= n && n <= MAXSMALLINT)
2448 #if SIZEOF_VOID_P == SIZEOF_INT
2450 typedef union {Int i; Ptr p;} IntOrPtr;
2457 return pair(PTRCELL,x.i);
2464 assert(fst(c) == PTRCELL);
2474 return pair(CPTRCELL,x.i);
2481 assert(fst(c) == CPTRCELL);
2486 #elif SIZEOF_VOID_P == 2*SIZEOF_INT
2488 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2495 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2502 assert(fst(c) == PTRCELL);
2503 x.i.i1 = intOf(fst(snd(c)));
2504 x.i.i2 = intOf(snd(snd(c)));
2513 return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2520 assert(fst(c) == CPTRCELL);
2521 x.i.i1 = intOf(fst(snd(c)));
2522 x.i.i2 = intOf(snd(snd(c)));
2528 #error "Can't implement mkPtr/ptrOf on this architecture."
2533 String stringNegate( s )
2541 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2546 /* --------------------------------------------------------------------------
2548 * ------------------------------------------------------------------------*/
2550 Int length(xs) /* calculate length of list xs */
2553 for (; nonNull(xs); ++n)
2558 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2559 List xs, ys; { /* ys by modifying xs ... */
2564 while (nonNull(tl(zs)))
2571 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2574 for (; nonNull(xs); xs=tl(xs))
2575 ys = cons(hd(xs),ys);
2579 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2582 return revOnto(dupOnto(xs,NIL),ys);
2585 List dupList(xs) /* Duplicate spine of list xs */
2588 for (; nonNull(xs); xs=tl(xs))
2589 ys = cons(hd(xs),ys);
2593 List revOnto(xs,ys) /* Destructively reverse elements of*/
2594 List xs, ys; { /* list xs onto list ys... */
2597 while (nonNull(xs)) {
2606 QualId qualidIsMember ( QualId q, List xs )
2608 for (; nonNull(xs); xs=tl(xs)) {
2609 if (eqQualIdent(q, hd(xs)))
2615 Cell varIsMember(t,xs) /* Test if variable is a member of */
2616 Text t; /* given list of variables */
2618 for (; nonNull(xs); xs=tl(xs))
2619 if (t==textOf(hd(xs)))
2624 Name nameIsMember(t,ns) /* Test if name with text t is a */
2625 Text t; /* member of list of names xs */
2627 for (; nonNull(ns); ns=tl(ns))
2628 if (t==name(hd(ns)).text)
2633 Cell intIsMember(n,xs) /* Test if integer n is member of */
2634 Int n; /* given list of integers */
2636 for (; nonNull(xs); xs=tl(xs))
2637 if (n==intOf(hd(xs)))
2642 Cell cellIsMember(x,xs) /* Test for membership of specific */
2643 Cell x; /* cell x in list xs */
2645 for (; nonNull(xs); xs=tl(xs))
2651 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2654 for (; nonNull(xs); xs=tl(xs))
2660 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2661 Cell c; /* association lists */
2663 for (; nonNull(xs); xs=tl(xs))
2669 List replicate(n,x) /* create list of n copies of x */
2678 List diffList(from,take) /* list difference: from\take */
2679 List from, take; { /* result contains all elements of */
2680 List result = NIL; /* `from' not appearing in `take' */
2682 while (nonNull(from)) {
2683 List next = tl(from);
2684 if (!cellIsMember(hd(from),take)) {
2693 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2697 for(;nonNull(xs);xs=tl(xs)) {
2700 result=cons(x,result);
2706 List take(n,xs) /* destructively truncate list to */
2707 Int n; /* specified length */
2713 while (1<n-- && nonNull(xs))
2720 List splitAt(n,xs) /* drop n things from front of list*/
2729 Cell nth(n,xs) /* extract n'th element of list */
2732 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2739 List removeCell(x,xs) /* destructively remove cell from */
2744 return tl(xs); /* element at front of list */
2748 for (; nonNull(curr); prev=curr, curr=tl(prev))
2750 tl(prev) = tl(curr);
2751 return xs; /* element in middle of list */
2755 return xs; /* here if element not found */
2758 List nubList(xs) /* nuke dups in list */
2759 List xs; { /* non destructive */
2761 for (; nonNull(xs); xs=tl(xs))
2762 if (isNull(cellIsMember(hd(xs),outs)))
2763 outs = cons(hd(xs),outs);
2769 /* --------------------------------------------------------------------------
2770 * Strongly-typed lists (z-lists) and tuples (experimental)
2771 * ------------------------------------------------------------------------*/
2773 static void z_tag_check ( Cell x, int tag, char* caller )
2777 sprintf(buf,"z_tag_check(%s): null\n", caller);
2780 if (whatIs(x) != tag) {
2782 "z_tag_check(%s): tag was %d, expected %d\n",
2783 caller, whatIs(x), tag );
2789 Cell zcons ( Cell x, Cell xs )
2791 if (!(isNull(xs) || whatIs(xs)==ZCONS))
2792 internal("zcons: ill typed tail");
2793 return ap(ZCONS,ap(x,xs));
2796 Cell zhd ( Cell xs )
2798 if (isNull(xs)) internal("zhd: empty list");
2799 z_tag_check(xs,ZCONS,"zhd");
2800 return fst( snd(xs) );
2803 Cell ztl ( Cell xs )
2805 if (isNull(xs)) internal("ztl: empty list");
2806 z_tag_check(xs,ZCONS,"zhd");
2807 return snd( snd(xs) );
2810 Int zlength ( ZList xs )
2813 while (nonNull(xs)) {
2814 z_tag_check(xs,ZCONS,"zlength");
2816 xs = snd( snd(xs) );
2821 ZList zreverse ( ZList xs )
2824 while (nonNull(xs)) {
2825 z_tag_check(xs,ZCONS,"zreverse");
2826 rev = zcons(zhd(xs),rev);
2832 Cell zsingleton ( Cell x )
2834 return zcons (x,NIL);
2837 Cell zdoubleton ( Cell x, Cell y )
2839 return zcons(x,zcons(y,NIL));
2843 Cell zpair ( Cell x1, Cell x2 )
2844 { return ap(ZTUP2,ap(x1,x2)); }
2845 Cell zfst ( Cell zpair )
2846 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2847 Cell zsnd ( Cell zpair )
2848 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2850 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2851 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2852 Cell zfst3 ( Cell zpair )
2853 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2854 Cell zsnd3 ( Cell zpair )
2855 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2856 Cell zthd3 ( Cell zpair )
2857 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2859 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2860 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2861 Cell zsel14 ( Cell zpair )
2862 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2863 Cell zsel24 ( Cell zpair )
2864 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2865 Cell zsel34 ( Cell zpair )
2866 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2867 Cell zsel44 ( Cell zpair )
2868 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2870 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2871 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2872 Cell zsel15 ( Cell zpair )
2873 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2874 Cell zsel25 ( Cell zpair )
2875 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2876 Cell zsel35 ( Cell zpair )
2877 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2878 Cell zsel45 ( Cell zpair )
2879 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2880 Cell zsel55 ( Cell zpair )
2881 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2884 Cell unap ( int tag, Cell c )
2887 if (whatIs(c) != tag) {
2888 sprintf(buf, "unap: specified %d, actual %d\n",
2895 /* --------------------------------------------------------------------------
2896 * Operations on applications:
2897 * ------------------------------------------------------------------------*/
2899 Int argCount; /* number of args in application */
2901 Cell getHead(e) /* get head cell of application */
2902 Cell e; { /* set number of args in argCount */
2903 for (argCount=0; isAp(e); e=fun(e))
2908 List getArgs(e) /* get list of arguments in function*/
2909 Cell e; { /* application: */
2910 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2912 for (as=NIL; isAp(e); e=fun(e))
2913 as = cons(arg(e),as);
2917 Cell nthArg(n,e) /* return nth arg in application */
2918 Int n; /* of function to m args (m>=n) */
2919 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2920 for (n=numArgs(e)-n-1; n>0; n--)
2925 Int numArgs(e) /* find number of arguments to expr */
2928 for (n=0; isAp(e); e=fun(e))
2933 Cell applyToArgs(f,args) /* destructively apply list of args */
2934 Cell f; /* to function f */
2936 while (nonNull(args)) {
2937 Cell temp = tl(args);
2938 tl(args) = hd(args);
2946 /* --------------------------------------------------------------------------
2948 * ------------------------------------------------------------------------*/
2950 static String maybeModuleStr ( Module m )
2952 if (isModule(m)) return textToStr(module(m).text); else return "??";
2955 static String maybeNameStr ( Name n )
2957 if (isName(n)) return textToStr(name(n).text); else return "??";
2960 static String maybeTyconStr ( Tycon t )
2962 if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
2965 static String maybeClassStr ( Class c )
2967 if (isClass(c)) return textToStr(cclass(c).text); else return "??";
2970 static String maybeText ( Text t )
2972 if (isNull(t)) return "(nil)";
2973 return textToStr(t);
2976 static void print100 ( Int x )
2978 print ( x, 100); printf("\n");
2981 void dumpTycon ( Int t )
2983 if (isTycon(TYCMIN+t) && !isTycon(t)) t += TYCMIN;
2985 printf ( "dumpTycon %d: not a tycon\n", t);
2989 printf ( " text: %s\n", textToStr(tycon(t).text) );
2990 printf ( " line: %d\n", tycon(t).line );
2991 printf ( " mod: %s\n", maybeModuleStr(tycon(t).mod));
2992 printf ( " tuple: %d\n", tycon(t).tuple);
2993 printf ( " arity: %d\n", tycon(t).arity);
2994 printf ( " kind: "); print100(tycon(t).kind);
2995 printf ( " what: %d\n", tycon(t).what);
2996 printf ( " defn: "); print100(tycon(t).defn);
2997 printf ( " cToT: %d %s\n", tycon(t).conToTag,
2998 maybeNameStr(tycon(t).conToTag));
2999 printf ( " tToC: %d %s\n", tycon(t).tagToCon,
3000 maybeNameStr(tycon(t).tagToCon));
3001 printf ( " itbl: %p\n", tycon(t).itbl);
3002 printf ( " nextTH: %d %s\n", tycon(t).nextTyconHash,
3003 maybeTyconStr(tycon(t).nextTyconHash));
3007 void dumpName ( Int n )
3009 if (isName(NAMEMIN+n) && !isName(n)) n += NAMEMIN;
3011 printf ( "dumpName %d: not a name\n", n);
3015 printf ( " text: %s\n", textToStr(name(n).text) );
3016 printf ( " line: %d\n", name(n).line );
3017 printf ( " mod: %s\n", maybeModuleStr(name(n).mod));
3018 printf ( " syntax: %d\n", name(n).syntax );
3019 printf ( " parent: %d\n", name(n).parent );
3020 printf ( " arity: %d\n", name(n).arity );
3021 printf ( " number: %d\n", name(n).number );
3022 printf ( " type: "); print100(name(n).type);
3023 printf ( " defn: %d\n", name(n).defn );
3024 printf ( " stgVar: "); print100(name(n).stgVar);
3025 printf ( " cconv: %d\n", name(n).callconv );
3026 printf ( " primop: %p\n", name(n).primop );
3027 printf ( " itbl: %p\n", name(n).itbl );
3028 printf ( " nextNH: %d\n", name(n).nextNameHash );
3033 void dumpClass ( Int c )
3035 if (isClass(CLASSMIN+c) && !isClass(c)) c += CLASSMIN;
3037 printf ( "dumpClass %d: not a class\n", c);
3041 printf ( " text: %s\n", textToStr(cclass(c).text) );
3042 printf ( " line: %d\n", cclass(c).line );
3043 printf ( " mod: %s\n", maybeModuleStr(cclass(c).mod));
3044 printf ( " arity: %d\n", cclass(c).arity );
3045 printf ( " level: %d\n", cclass(c).level );
3046 printf ( " kinds: "); print100( cclass(c).kinds );
3047 printf ( " fds: %d\n", cclass(c).fds );
3048 printf ( " xfds: %d\n", cclass(c).xfds );
3049 printf ( " head: "); print100( cclass(c).head );
3050 printf ( " dcon: "); print100( cclass(c).dcon );
3051 printf ( " supers: "); print100( cclass(c).supers );
3052 printf ( " #supers: %d\n", cclass(c).numSupers );
3053 printf ( " dsels: "); print100( cclass(c).dsels );
3054 printf ( " members: "); print100( cclass(c).members );
3055 printf ( "#members: %d\n", cclass(c).numMembers );
3056 printf ( "defaults: "); print100( cclass(c).defaults );
3057 printf ( " insts: "); print100( cclass(c).instances );
3062 void dumpInst ( Int i )
3064 if (isInst(INSTMIN+i) && !isInst(i)) i += INSTMIN;
3066 printf ( "dumpInst %d: not an instance\n", i);
3070 printf ( " class: %s\n", maybeClassStr(inst(i).c) );
3071 printf ( " line: %d\n", inst(i).line );
3072 printf ( " mod: %s\n", maybeModuleStr(inst(i).mod));
3073 printf ( " kinds: "); print100( inst(i).kinds );
3074 printf ( " head: "); print100( inst(i).head );
3075 printf ( " specs: "); print100( inst(i).specifics );
3076 printf ( " #specs: %d\n", inst(i).numSpecifics );
3077 printf ( " impls: "); print100( inst(i).implements );
3078 printf ( " builder: %s\n", maybeNameStr( inst(i).builder ) );
3083 /* --------------------------------------------------------------------------
3085 * ------------------------------------------------------------------------*/
3088 static void far* safeFarCalloc Args((Int,Int));
3089 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
3090 Int n, s; { /* for non-null return */
3091 void far* tab = farCalloc(n,s);
3093 ERRMSG(0) "Cannot allocate run-time tables"
3098 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
3100 #define TABALLOC(v,t,n)
3108 case POSTPREL: break;
3110 case RESET : clearStack();
3112 /* the next 2 statements are particularly important
3113 * if you are using GLOBALfst or GLOBALsnd since the
3114 * corresponding registers may be reset to their
3115 * uninitialised initial values by a longjump.
3117 heapTopFst = heapFst + heapSize;
3118 heapTopSnd = heapSnd + heapSize;
3122 if (isNull(lastExprSaved))
3123 savedText = NUM_TEXT;
3128 for (i=NAMEMIN; i<nameHw; ++i) {
3129 mark(name(i).parent);
3131 mark(name(i).stgVar);
3134 end("Names", nameHw-NAMEMIN);
3137 for (i=MODMIN; i<moduleHw; ++i) {
3138 mark(module(i).tycons);
3139 mark(module(i).names);
3140 mark(module(i).classes);
3141 mark(module(i).exports);
3142 mark(module(i).qualImports);
3143 mark(module(i).objectExtraNames);
3145 end("Modules", moduleHw-MODMIN);
3148 for (i=TYCMIN; i<tyconHw; ++i) {
3149 mark(tycon(i).defn);
3150 mark(tycon(i).kind);
3151 mark(tycon(i).what);
3153 end("Type constructors", tyconHw-TYCMIN);
3156 for (i=CLASSMIN; i<classHw; ++i) {
3157 mark(cclass(i).head);
3158 mark(cclass(i).kinds);
3159 mark(cclass(i).fds);
3160 mark(cclass(i).xfds);
3161 mark(cclass(i).dsels);
3162 mark(cclass(i).supers);
3163 mark(cclass(i).members);
3164 mark(cclass(i).defaults);
3165 mark(cclass(i).instances);
3168 end("Classes", classHw-CLASSMIN);
3171 for (i=INSTMIN; i<instHw; ++i) {
3173 mark(inst(i).kinds);
3174 mark(inst(i).specifics);
3175 mark(inst(i).implements);
3177 end("Instances", instHw-INSTMIN);
3180 for (i=0; i<=sp; ++i)
3185 mark(lastExprSaved);
3188 end("Last expression", 3);
3193 end("C stack", stackRoots);
3198 case PREPREL : heapFst = heapAlloc(heapSize);
3199 heapSnd = heapAlloc(heapSize);
3201 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3202 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3207 heapTopFst = heapFst + heapSize;
3208 heapTopSnd = heapSnd + heapSize;
3209 for (i=1; i<heapSize; ++i) {
3213 snd(-heapSize) = NIL;
3220 marksSize = bitArraySize(heapSize);
3221 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3222 ERRMSG(0) "Unable to allocate gc markspace"
3226 TABALLOC(text, char, NUM_TEXT)
3227 TABALLOC(tyconHash, Tycon, TYCONHSZ)
3228 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
3229 TABALLOC(nameHash, Name, NAMEHSZ)
3230 TABALLOC(tabName, struct strName, NUM_NAME)
3231 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
3232 TABALLOC(cellStack, Cell, NUM_STACK)
3233 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
3235 TABALLOC(tabExt, Text, NUM_EXT)
3240 nextNewText = NUM_TEXT;
3241 nextNewDText = (-1);
3242 lastExprSaved = NIL;
3243 savedText = NUM_TEXT;
3244 for (i=0; i<TEXTHSZ; ++i)
3245 textHash[i][0] = NOTEXT;
3251 for (i=0; i<TYCONHSZ; ++i)
3258 for (i=0; i<NAMEHSZ; ++i)
3269 tabInst = (struct strInst far *)
3270 farCalloc(NUM_INSTS,sizeof(struct strInst));
3273 ERRMSG(0) "Cannot allocate instance tables"
3283 /*-------------------------------------------------------------------------*/