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/02/08 17:50:46 $
14 * ------------------------------------------------------------------------*/
24 /*#define DEBUG_SHOWUSE*/
26 /* --------------------------------------------------------------------------
27 * local function prototypes:
28 * ------------------------------------------------------------------------*/
30 static Int local hash Args((String));
31 static Int local saveText Args((Text));
32 static Module local findQualifier Args((Text));
33 static Void local hashTycon Args((Tycon));
34 static List local insertTycon Args((Tycon,List));
35 static Void local hashName Args((Name));
36 static List local insertName Args((Name,List));
37 static Void local patternError Args((String));
38 static Bool local stringMatch Args((String,String));
39 static Bool local typeInvolves Args((Type,Type));
40 static Cell local markCell Args((Cell));
41 static Void local markSnd Args((Cell));
42 static Cell local lowLevelLastIn Args((Cell));
43 static Cell local lowLevelLastOut Args((Cell));
44 Module local moduleOfScript Args((Script));
45 Script local scriptThisFile Args((Text));
47 /* --------------------------------------------------------------------------
50 * provides storage for the characters making up identifier and symbol
51 * names, string literals, character constants etc...
53 * All character strings are stored in a large character array, with textHw
54 * pointing to the next free position. Lookup in the array is improved using
55 * a hash table. Internally, text strings are represented by integer offsets
56 * from the beginning of the array to the string in question.
58 * Where memory permits, the use of multiple hashtables gives a significant
59 * increase in performance, particularly when large source files are used.
61 * Each string in the array is terminated by a zero byte. No string is
62 * stored more than once, so that it is safe to test equality of strings by
63 * comparing the corresponding offsets.
65 * Special text values (beyond the range of the text array table) are used
66 * to generate unique `new variable names' as required.
68 * The same text storage is also used to hold text values stored in a saved
69 * expression. This grows downwards from the top of the text table (and is
70 * not included in the hash table).
71 * ------------------------------------------------------------------------*/
73 #define TEXTHSZ 512 /* Size of Text hash table */
74 #define NOTEXT ((Text)(~0)) /* Empty bucket in Text hash table */
75 static Text textHw; /* Next unused position */
76 static Text savedText = NUM_TEXT; /* Start of saved portion of text */
77 static Text nextNewText; /* Next new text value */
78 static Text nextNewDText; /* Next new dict text value */
79 static char DEFTABLE(text,NUM_TEXT);/* Storage of character strings */
80 static Text textHash[TEXTHSZ][NUM_TEXTH]; /* Hash table storage */
82 String textToStr(t) /* find string corresp to given Text*/
84 static char newVar[16];
86 if (0<=t && t<NUM_TEXT) /* standard char string */
89 sprintf(newVar,"d%d",-t); /* dictionary variable */
91 sprintf(newVar,"v%d",t-NUM_TEXT); /* normal variable */
95 String identToStr(v) /*find string corresp to given ident or qualified name*/
98 internal("identToStr");
104 case CONOPCELL : return text+textOf(v);
106 case QUALIDENT : { Text pos = textHw;
108 while (pos+1 < savedText && text[t]!=0) {
109 text[pos++] = text[t++];
111 if (pos+1 < savedText) {
115 while (pos+1 < savedText && text[t]!=0) {
116 text[pos++] = text[t++];
122 internal("identToStr2");
123 return 0; /* NOTREACHED */
126 Text inventText() { /* return new unused variable name */
127 return nextNewText++;
130 Text inventDictText() { /* return new unused dictvar name */
131 return nextNewDText--;
134 Bool inventedText(t) /* Signal TRUE if text has been */
135 Text t; { /* generated internally */
136 return (t<0 || t>=NUM_TEXT);
139 #define MAX_FIXLIT 100
140 Text fixLitText(t) /* fix literal text that might include \ */
142 String s = textToStr(t);
145 for(i = 0;i < MAX_FIXLIT-2 && *s;s++) {
151 if (i < MAX_FIXLIT-2) {
154 ERRMSG(0) "storage space exhausted for internal literal string"
157 return (findText(p));
161 static Int local hash(s) /* Simple hash function on strings */
165 for (v=((int)(*s))*8; *s; s++)
166 v += ((int)(*s))*(j++);
172 Text findText(s) /* Locate string in Text array */
176 Text textPos = textHash[h][hashno];
178 #define TryMatch { Text originalTextPos = textPos; \
180 for (t=s; *t==text[textPos]; textPos++,t++) \
182 return originalTextPos; \
184 #define Skip while (text[textPos++]) ;
186 while (textPos!=NOTEXT) {
188 if (++hashno<NUM_TEXTH) /* look in next hashtable entry */
189 textPos = textHash[h][hashno];
192 while (textPos < textHw) {
203 textPos = textHw; /* if not found, save in array */
204 if (textHw + (Int)strlen(s) + 1 > savedText) {
205 ERRMSG(0) "Character string storage space exhausted"
208 while ((text[textHw++] = *s++) != 0) {
210 if (hashno<NUM_TEXTH) { /* updating hash table as necessary */
211 textHash[h][hashno] = textPos;
212 if (hashno<NUM_TEXTH-1)
213 textHash[h][hashno+1] = NOTEXT;
219 static Int local saveText(t) /* Save text value in buffer */
220 Text t; { /* at top of text table */
221 String s = textToStr(t);
224 if (textHw + l + 1 > savedText) {
225 ERRMSG(0) "Character string storage space exhausted"
229 strcpy(text+savedText,s);
234 static int fromHexDigit ( char c )
237 case '0': case '1': case '2': case '3': case '4':
238 case '5': case '6': case '7': case '8': case '9':
240 case 'a': case 'A': return 10;
241 case 'b': case 'B': return 11;
242 case 'c': case 'C': return 12;
243 case 'd': case 'D': return 13;
244 case 'e': case 'E': return 14;
245 case 'f': case 'F': return 15;
251 /* returns findText (unZencode s) */
252 Text unZcodeThenFindText ( String s )
259 nn = 100 + 10 * strlen(s);
261 if (!p) internal ("unZcodeThenFindText: malloc failed");
266 if (n > nn-90) internal ("unZcodeThenFindText: result is too big");
267 if (*s != 'z' && *s != 'Z') {
272 if (!(*s)) goto parse_error;
274 case 'Z': p[n++] = 'Z'; break;
275 case 'C': p[n++] = ':'; break;
276 case 'L': p[n++] = '('; break;
277 case 'R': p[n++] = ')'; break;
278 case 'M': p[n++] = '['; break;
279 case 'N': p[n++] = ']'; break;
280 case 'z': p[n++] = 'z'; break;
281 case 'a': p[n++] = '&'; break;
282 case 'b': p[n++] = '|'; break;
283 case 'd': p[n++] = '$'; break;
284 case 'e': p[n++] = '='; break;
285 case 'g': p[n++] = '>'; break;
286 case 'h': p[n++] = '#'; break;
287 case 'i': p[n++] = '.'; break;
288 case 'l': p[n++] = '<'; break;
289 case 'm': p[n++] = '-'; break;
290 case 'n': p[n++] = '!'; break;
291 case 'p': p[n++] = '+'; break;
292 case 'q': p[n++] = '\\'; break;
293 case 'r': p[n++] = '\''; break;
294 case 's': p[n++] = '/'; break;
295 case 't': p[n++] = '*'; break;
296 case 'u': p[n++] = '^'; break;
297 case 'v': p[n++] = '%'; break;
299 if (!s[0] || !s[1]) goto parse_error;
300 if (fromHexDigit(s[0]) < 0 || fromHexDigit(s[1]) < 0) goto parse_error;
301 p[n++] = 16 * fromHexDigit(s[0]) + fromHexDigit(s[1]);
304 case '0': case '1': case '2': case '3': case '4':
305 case '5': case '6': case '7': case '8': case '9':
308 while (*s && isdigit((int)(*s))) {
309 i = 10 * i + (*s - '0');
312 if (*s != 'T') goto parse_error;
315 while (i > 0) { p[n++] = ','; i--; };
329 fprintf ( stderr, "\nstring = `%s'\n", s );
330 internal ( "unZcodeThenFindText: parse error on above string");
331 return NIL; /*notreached*/
335 Text enZcodeThenFindText ( String s )
340 char toHex[16] = "0123456789ABCDEF";
343 nn = 100 + 10 * strlen(s);
345 if (!p) internal ("enZcodeThenFindText: malloc failed");
349 if (n > nn-90) internal ("enZcodeThenFindText: result is too big");
352 && (isalnum((int)(*s)) || *s == '_')) {
360 while (*s && *s==',') { s++; tup++; };
361 if (*s != ')') internal("enZcodeThenFindText: invalid tuple type");
364 sprintf(num,"%d",tup);
365 p[n] = 0; strcat ( &(p[n]), num ); n += strlen(num);
370 case '(': p[n++] = 'Z'; p[n++] = 'L'; break;
371 case ')': p[n++] = 'Z'; p[n++] = 'R'; break;
372 case '[': p[n++] = 'Z'; p[n++] = 'M'; break;
373 case ']': p[n++] = 'Z'; p[n++] = 'N'; break;
374 case ':': p[n++] = 'Z'; p[n++] = 'C'; break;
375 case 'Z': p[n++] = 'Z'; p[n++] = 'Z'; break;
376 case 'z': p[n++] = 'z'; p[n++] = 'z'; break;
377 case '&': p[n++] = 'z'; p[n++] = 'a'; break;
378 case '|': p[n++] = 'z'; p[n++] = 'b'; break;
379 case '$': p[n++] = 'z'; p[n++] = 'd'; break;
380 case '=': p[n++] = 'z'; p[n++] = 'e'; break;
381 case '>': p[n++] = 'z'; p[n++] = 'g'; break;
382 case '#': p[n++] = 'z'; p[n++] = 'h'; break;
383 case '.': p[n++] = 'z'; p[n++] = 'i'; break;
384 case '<': p[n++] = 'z'; p[n++] = 'l'; break;
385 case '-': p[n++] = 'z'; p[n++] = 'm'; break;
386 case '!': p[n++] = 'z'; p[n++] = 'n'; break;
387 case '+': p[n++] = 'z'; p[n++] = 'p'; break;
388 case '\'': p[n++] = 'z'; p[n++] = 'q'; break;
389 case '\\': p[n++] = 'z'; p[n++] = 'r'; break;
390 case '/': p[n++] = 'z'; p[n++] = 's'; break;
391 case '*': p[n++] = 'z'; p[n++] = 't'; break;
392 case '^': p[n++] = 'z'; p[n++] = 'u'; break;
393 case '%': p[n++] = 'z'; p[n++] = 'v'; break;
394 default: s--; p[n++] = 'z'; p[n++] = 'x';
395 p[n++] = toHex[(int)(*s)/16];
396 p[n++] = toHex[(int)(*s)%16];
407 Text textOf ( Cell c )
410 (whatIs(c)==VARIDCELL
411 || whatIs(c)==CONIDCELL
412 || whatIs(c)==VAROPCELL
413 || whatIs(c)==CONOPCELL
414 || whatIs(c)==STRCELL
415 || whatIs(c)==DICTVAR
418 fprintf(stderr, "\ntextOf: bad tag %d\n",whatIs(c) );
419 internal("textOf: bad tag");
424 /* --------------------------------------------------------------------------
427 * Currently, the only attributes that we store for each Ext value is the
428 * corresponding Text label. At some later stage, we may decide to cache
429 * types, predicates, etc. here as a space saving gesture. Given that Text
430 * comparison is cheap, and that this is an experimental implementation, we
431 * will use a straightforward linear search to locate Ext values from their
432 * corresponding Text labels; a hashing scheme can be introduced later if
433 * this turns out to be a problem.
434 * ------------------------------------------------------------------------*/
437 Text DEFTABLE(tabExt,NUM_EXT); /* Storage for Ext names */
440 Ext mkExt(t) /* Allocate or find an Ext value */
446 if (extHw-EXTMIN >= NUM_EXT) {
447 ERRMSG(0) "Ext storage space exhausted"
455 /* --------------------------------------------------------------------------
458 * A Tycon represents a user defined type constructor. Tycons are indexed
459 * by Text values ... a very simple hash function is used to improve lookup
460 * times. Tycon entries with the same hash code are chained together, with
461 * the most recent entry at the front of the list.
462 * ------------------------------------------------------------------------*/
464 #define TYCONHSZ 256 /* Size of Tycon hash table*/
465 #define tHash(x) ((x)%TYCONHSZ) /* Tycon hash function */
466 static Tycon tyconHw; /* next unused Tycon */
467 static Tycon DEFTABLE(tyconHash,TYCONHSZ); /* Hash table storage */
468 struct strTycon DEFTABLE(tabTycon,NUM_TYCON); /* Tycon storage */
470 Tycon newTycon(t) /* add new tycon to tycon table */
473 if (tyconHw-TYCMIN >= NUM_TYCON) {
474 ERRMSG(0) "Type constructor storage space exhausted"
477 tycon(tyconHw).text = t; /* clear new tycon record */
478 tycon(tyconHw).kind = NIL;
479 tycon(tyconHw).defn = NIL;
480 tycon(tyconHw).what = NIL;
481 tycon(tyconHw).conToTag = NIL;
482 tycon(tyconHw).tagToCon = NIL;
483 tycon(tyconHw).tuple = -1;
484 tycon(tyconHw).mod = currentModule;
485 tycon(tyconHw).itbl = NULL;
486 module(currentModule).tycons = cons(tyconHw,module(currentModule).tycons);
487 tycon(tyconHw).nextTyconHash = tyconHash[h];
488 tyconHash[h] = tyconHw;
493 Tycon findTycon(t) /* locate Tycon in tycon table */
495 Tycon tc = tyconHash[tHash(t)];
497 while (nonNull(tc) && tycon(tc).text!=t)
498 tc = tycon(tc).nextTyconHash;
502 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
505 assert(whatIs(tc)==TYCON || whatIs(tc)==TUPLE);
506 oldtc = findTycon(tycon(tc).text);
509 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
515 static Void local hashTycon(tc) /* Insert Tycon into hash table */
517 if (!(isTycon(tc) || isTuple(tc))) {
518 printf("\nbad stuff: " ); print(tc,10); printf("\n");
519 assert(isTycon(tc) || isTuple(tc));
522 Text t = tycon(tc).text;
524 tycon(tc).nextTyconHash = tyconHash[h];
529 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
531 if (!isPair(id)) internal("findQualTycon");
535 return findTycon(textOf(id));
537 Text t = qtextOf(id);
538 Module m = findQualifier(qmodOf(id));
540 if (isNull(m)) return NIL;
541 for(es=module(m).exports; nonNull(es); es=tl(es)) {
543 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
548 default : internal("findQualTycon2");
550 return NIL; /* NOTREACHED */
553 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
559 Tycon tc = newTycon(t);
561 tycon(tc).kind = kind;
562 tycon(tc).what = what;
563 tycon(tc).defn = defn;
564 tycon(tc).arity = ar;
568 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
573 String s = textToStr(tycon(tc).text);
575 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
576 if (hd(curr)==tc) /* just in case we get duplicates! */
582 tl(prev) = cons(tc,curr);
586 return cons(tc,curr);
589 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
590 String pat; /* to list of Tycons ts */
591 List ts; { /* Null pattern matches every tycon*/
592 Tycon tc; /* (Tycons with NIL kind excluded) */
593 for (tc=TYCMIN; tc<tyconHw; ++tc)
594 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
595 if (nonNull(tycon(tc).kind))
596 ts = insertTycon(tc,ts);
600 Text ghcTupleText_n ( Int n )
605 if (n < 0 || n >= 100) internal("ghcTupleText_n");
606 if (n == 1) internal("ghcTupleText_n==1");
608 for (i = 1; i <= n-1; i++) buf[x++] = ',';
611 return findText(buf);
614 Text ghcTupleText(tup)
617 assert(isTuple(tup));
619 return ghcTupleText_n ( tupleOf(tup) );
623 Tycon mkTuple ( Int n )
627 internal("mkTuple: request for tuple of unsupported size");
628 for (i = TYCMIN; i < tyconHw; i++)
629 if (tycon(i).tuple == n) return i;
630 internal("mkTuple: request for non-existent tuple");
634 /* --------------------------------------------------------------------------
637 * A Name represents a top level binding of a value to an identifier.
638 * Such values may be a constructor function, a member function in a
639 * class, a user-defined or primitive value/function.
641 * Names are indexed by Text values ... a very simple hash functions speeds
642 * access to the table of Names and Name entries with the same hash value
643 * are chained together, with the most recent entry at the front of the
645 * ------------------------------------------------------------------------*/
647 #define NAMEHSZ 256 /* Size of Name hash table */
648 #define nHash(x) ((x)%NAMEHSZ) /* hash fn :: Text->Int */
649 Name nameHw; /* next unused name */
650 static Name DEFTABLE(nameHash,NAMEHSZ); /* Hash table storage */
651 struct strName DEFTABLE(tabName,NUM_NAME); /* Name table storage */
653 Name newName(t,parent) /* Add new name to name table */
657 if (nameHw-NAMEMIN >= NUM_NAME) {
658 ERRMSG(0) "Name storage space exhausted"
661 name(nameHw).text = t; /* clear new name record */
662 name(nameHw).line = 0;
663 name(nameHw).syntax = NO_SYNTAX;
664 name(nameHw).parent = parent;
665 name(nameHw).arity = 0;
666 name(nameHw).number = EXECNAME;
667 name(nameHw).defn = NIL;
668 name(nameHw).stgVar = NIL;
669 name(nameHw).callconv = NIL;
670 name(nameHw).type = NIL;
671 name(nameHw).primop = 0;
672 name(nameHw).mod = currentModule;
673 name(nameHw).itbl = NULL;
674 module(currentModule).names=cons(nameHw,module(currentModule).names);
675 name(nameHw).nextNameHash = nameHash[h];
676 nameHash[h] = nameHw;
680 Name findName(t) /* Locate name in name table */
682 Name n = nameHash[nHash(t)];
684 while (nonNull(n) && name(n).text!=t)
685 n = name(n).nextNameHash;
689 Name addName(nm) /* Insert Name in name table - if */
690 Name nm; { /* no clash is caused */
692 assert(whatIs(nm)==NAME);
693 oldnm = findName(name(nm).text);
696 module(currentModule).names=cons(nm,module(currentModule).names);
702 static Void local hashName(nm) /* Insert Name into hash table */
709 name(nm).nextNameHash = nameHash[h];
713 Name findQualName(id) /* Locate (possibly qualified) name*/
714 Cell id; { /* in name table */
716 internal("findQualName");
722 return findName(textOf(id));
724 Text t = qtextOf(id);
725 Module m = findQualifier(qmodOf(id));
727 if (isNull(m)) return NIL;
728 for(es=module(m).exports; nonNull(es); es=tl(es)) {
730 if (isName(e) && name(e).text==t)
732 else if (isPair(e) && DOTDOT==snd(e)) {
733 List subentities = NIL;
736 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
737 subentities = tycon(c).defn;
739 subentities = cclass(c).members;
740 for(; nonNull(subentities); subentities=tl(subentities)) {
741 if (!isName(hd(subentities)))
742 internal("findQualName3");
743 if (name(hd(subentities)).text == t)
744 return hd(subentities);
750 default : internal("findQualName2");
752 return 0; /* NOTREACHED */
756 Name nameFromStgVar ( StgVar v )
759 for (n = NAMEMIN; n < nameHw; n++)
760 if (name(n).stgVar == v) return n;
764 void* getHugs_AsmObject_for ( char* s )
767 Text t = findText(s);
769 for (n = NAMEMIN; n < nameHw; n++)
770 if (name(n).text == t) break;
771 if (n == nameHw) internal("getHugs_AsmObject_for(1)");
773 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
774 internal("getHugs_AsmObject_for(2)");
775 return ptrOf(stgVarInfo(v));
778 /* --------------------------------------------------------------------------
779 * Primitive functions:
780 * ------------------------------------------------------------------------*/
782 Module findFakeModule ( Text t )
784 Module m = findModule(t);
786 if (!module(m).fake) internal("findFakeModule");
789 module(m).fake = TRUE;
795 Name addWiredInBoxingTycon
796 ( String modNm, String typeNm, String constrNm,
801 Text modT = findText(modNm);
802 Text typeT = findText(typeNm);
803 Text conT = findText(constrNm);
804 Module m = findFakeModule(modT);
807 n = newName(conT,NIL);
809 name(n).number = cfunNo(0);
811 name(n).primop = (void*)rep;
814 tycon(t).what = DATATYPE;
815 tycon(t).kind = kind;
820 Tycon addTupleTycon ( Int n )
828 for (i = TYCMIN; i < tyconHw; i++)
829 if (tycon(i).tuple == n) return i;
832 m = findFakeModule(findText(n==0 ? "PrelBase" : "PrelTup")); else
833 m = findModule(findText("Prelude"));
837 for (i = 0; i < n; i++) k = ap(STAR,k);
838 t = newTycon(ghcTupleText_n(n));
841 tycon(t).what = DATATYPE;
844 /* maybe we want to do this for all n ? */
845 nm = newName(ghcTupleText_n(n), t);
846 name(nm).type = t; /* ummm ... for n > 0 */
853 Tycon addWiredInEnumTycon ( String modNm, String typeNm,
854 List /*of Text*/ constrs )
858 Text modT = findText(modNm);
859 Text typeT = findText(typeNm);
860 Module m = findFakeModule(modT);
864 tycon(t).kind = STAR;
865 tycon(t).what = DATATYPE;
867 constrs = reverse(constrs);
869 for (; nonNull(constrs); constrs=tl(constrs),i--) {
870 Text conT = hd(constrs);
871 Name con = newName(conT,t);
872 name(con).number = cfunNo(i);
874 name(con).parent = t;
875 tycon(t).defn = cons(con, tycon(t).defn);
881 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
882 Text t; /* sets rep, not type */
885 Int rep; { /* Really AsmRep */
886 Name n = newName(t,NIL);
887 name(n).arity = arity;
888 name(n).number = cfunNo(no);
890 name(n).primop = (void*)rep;
895 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
900 Name n = newName(t,NIL);
901 name(n).arity = arity;
902 name(n).number = cfunNo(no);
908 Int sfunPos(s,c) /* Find position of field with */
909 Name s; /* selector s in constructor c. */
913 for (; nonNull(cns); cns=tl(cns))
915 return intOf(snd(hd(cns)));
917 return 0;/* NOTREACHED */
920 static List local insertName(nm,ns) /* insert name nm into sorted list */
925 String s = textToStr(name(nm).text);
927 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
928 if (hd(curr)==nm) /* just in case we get duplicates! */
934 tl(prev) = cons(nm,curr);
938 return cons(nm,curr);
941 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
942 String pat; /* to list of names ns */
943 List ns; { /* Null pattern matches every name */
944 Name nm; /* (Names with NIL type, or hidden */
946 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
947 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
948 String str = textToStr(name(nm).text);
949 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
950 ns = insertName(nm,ns);
954 List mns = module(currentModule).names;
955 for(; nonNull(mns); mns=tl(mns)) {
957 if (!inventedText(name(nm).text)) {
958 String str = textToStr(name(nm).text);
959 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
960 ns = insertName(nm,ns);
967 /* --------------------------------------------------------------------------
968 * A simple string matching routine
969 * `*' matches any sequence of zero or more characters
970 * `?' matches any single character exactly
971 * `@str' matches the string str exactly (ignoring any special chars)
972 * `\c' matches the character c only (ignoring special chars)
973 * c matches the character c only
974 * ------------------------------------------------------------------------*/
976 static Void local patternError(s) /* report error in pattern */
978 ERRMSG(0) "%s in pattern", s
982 static Bool local stringMatch(pat,str) /* match string against pattern */
988 case '\0' : return (*str=='\0');
991 if (stringMatch(pat+1,str))
996 case '?' : if (*str++=='\0')
1001 case '[' : { Bool found = FALSE;
1002 while (*++pat!='\0' && *pat!=']')
1003 if (!found && ( pat[0] == *str ||
1012 patternError("missing `]'");
1020 case '\\' : if (*++pat == '\0')
1021 patternError("extra trailing `\\'");
1023 default : if (*pat++ != *str++)
1029 /* --------------------------------------------------------------------------
1030 * Storage of type classes, instances etc...:
1031 * ------------------------------------------------------------------------*/
1033 static Class classHw; /* next unused class */
1034 static List classes; /* list of classes in current scope */
1035 static Inst instHw; /* next unused instance record */
1037 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
1038 struct strInst far *tabInst; /* (pointer to) table of instances */
1040 Class newClass(t) /* add new class to class table */
1042 if (classHw-CLASSMIN >= NUM_CLASSES) {
1043 ERRMSG(0) "Class storage space exhausted"
1046 cclass(classHw).text = t;
1047 cclass(classHw).arity = 0;
1048 cclass(classHw).kinds = NIL;
1049 cclass(classHw).head = NIL;
1050 cclass(classHw).fds = NIL;
1051 cclass(classHw).xfds = NIL;
1052 cclass(classHw).dcon = NIL;
1053 cclass(classHw).supers = NIL;
1054 cclass(classHw).dsels = NIL;
1055 cclass(classHw).members = NIL;
1056 cclass(classHw).defaults = NIL;
1057 cclass(classHw).instances = NIL;
1058 classes=cons(classHw,classes);
1059 cclass(classHw).mod = currentModule;
1060 module(currentModule).classes=cons(classHw,module(currentModule).classes);
1064 Class classMax() { /* Return max Class in use ... */
1065 return classHw; /* This is a bit ugly, but it's not*/
1066 } /* worth a lot of effort right now */
1068 Class findClass(t) /* look for named class in table */
1072 for (cs=classes; nonNull(cs); cs=tl(cs)) {
1074 if (cclass(cl).text==t)
1080 Class addClass(c) /* Insert Class in class list */
1081 Class c; { /* - if no clash caused */
1083 assert(whatIs(c)==CLASS);
1084 oldc = findClass(cclass(c).text);
1086 classes=cons(c,classes);
1087 module(currentModule).classes=cons(c,module(currentModule).classes);
1094 Class findQualClass(c) /* Look for (possibly qualified) */
1095 Cell c; { /* class in class list */
1096 if (!isQualIdent(c)) {
1097 return findClass(textOf(c));
1099 Text t = qtextOf(c);
1100 Module m = findQualifier(qmodOf(c));
1104 for (es=module(m).exports; nonNull(es); es=tl(es)) {
1106 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
1113 Inst newInst() { /* Add new instance to table */
1114 if (instHw-INSTMIN >= NUM_INSTS) {
1115 ERRMSG(0) "Instance storage space exhausted"
1118 inst(instHw).kinds = NIL;
1119 inst(instHw).head = NIL;
1120 inst(instHw).specifics = NIL;
1121 inst(instHw).implements = NIL;
1122 inst(instHw).builder = NIL;
1123 inst(instHw).mod = currentModule;
1129 extern Void printInst Args((Inst));
1133 Class cl = inst(in).c;
1134 Printf("%s-", textToStr(cclass(cl).text));
1135 printType(stdout,inst(in).t);
1137 #endif /* DEBUG_DICTS */
1139 Inst findFirstInst(tc) /* look for 1st instance involving */
1140 Tycon tc; { /* the type constructor tc */
1141 return findNextInst(tc,INSTMIN-1);
1144 Inst findNextInst(tc,in) /* look for next instance involving*/
1145 Tycon tc; /* the type constructor tc */
1146 Inst in; { /* starting after instance in */
1147 while (++in < instHw) {
1148 Cell pi = inst(in).head;
1149 for (; isAp(pi); pi=fun(pi))
1150 if (typeInvolves(arg(pi),tc))
1156 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1157 Type ty; /* type constructor/tuple tc. */
1160 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1161 || typeInvolves(arg(ty),tc)));
1165 /* Needed by finishGHCInstance to find classes, before the
1166 export list has been built -- so we can't use
1169 Class findQualClassWithoutConsultingExportList ( QualId q )
1179 t_class = textOf(q);
1182 t_class = qtextOf(q);
1185 for (cl = CLASSMIN; cl < classHw; cl++) {
1186 if (cclass(cl).text == t_class) {
1187 /* Class name is ok, but is this the right module? */
1188 if (isNull(t_mod) /* no module name specified */
1190 && t_mod == module(cclass(cl).mod).text)
1199 /* Same deal, except for Tycons. */
1200 Tycon findQualTyconWithoutConsultingExportList ( QualId q )
1210 t_tycon = textOf(q);
1213 t_tycon = qtextOf(q);
1216 for (tc = TYCMIN; tc < tyconHw; tc++) {
1217 if (tycon(tc).text == t_tycon) {
1218 /* Tycon name is ok, but is this the right module? */
1219 if (isNull(t_mod) /* no module name specified */
1221 && t_mod == module(tycon(tc).mod).text)
1229 Tycon findTyconInAnyModule ( Text t )
1232 for (tc = TYCMIN; tc < tyconHw; tc++)
1233 if (tycon(tc).text == t) return tc;
1237 Class findClassInAnyModule ( Text t )
1240 for (cc = CLASSMIN; cc < classHw; cc++)
1241 if (cclass(cc).text == t) return cc;
1245 Name findNameInAnyModule ( Text t )
1248 for (nm = NAMEMIN; nm < nameHw; nm++)
1249 if (name(nm).text == t) return nm;
1253 /* Same deal, except for Names. */
1254 Name findQualNameWithoutConsultingExportList ( QualId q )
1260 assert(isQVar(q) || isQCon(q));
1262 if (isCon(q) || isVar(q)) {
1267 t_name = qtextOf(q);
1270 for (nm = NAMEMIN; nm < nameHw; nm++) {
1271 if (name(nm).text == t_name) {
1272 /* Name is ok, but is this the right module? */
1273 if (isNull(t_mod) /* no module name specified */
1275 && t_mod == module(name(nm).mod).text)
1284 /* returns List of QualId */
1285 List getAllKnownTyconsAndClasses ( void )
1290 for (tc = TYCMIN; tc < tyconHw; tc++) {
1291 /* almost certainly undue paranoia about duplicate avoidance, but .. */
1292 QualId q = mkQCon( module(tycon(tc).mod).text, tycon(tc).text );
1293 if (!qualidIsMember(q,xs))
1294 xs = cons ( q, xs );
1296 for (nw = CLASSMIN; nw < classHw; nw++) {
1297 QualId q = mkQCon( module(cclass(nw).mod).text, cclass(nw).text );
1298 if (!qualidIsMember(q,xs))
1299 xs = cons ( q, xs );
1304 /* Purely for debugging. */
1305 void locateSymbolByName ( Text t )
1308 for (i = NAMEMIN; i < nameHw; i++)
1309 if (name(i).text == t)
1310 fprintf ( stderr, "name(%d)\n", i-NAMEMIN);
1311 for (i = TYCMIN; i < tyconHw; i++)
1312 if (tycon(i).text == t)
1313 fprintf ( stderr, "tycon(%d)\n", i-TYCMIN);
1314 for (i = CLASSMIN; i < classHw; i++)
1315 if (cclass(i).text == t)
1316 fprintf ( stderr, "class(%d)\n", i-CLASSMIN);
1319 /* --------------------------------------------------------------------------
1322 * Various parts of the system use a stack of cells. Most of the stack
1323 * operations are defined as macros, expanded inline.
1324 * ------------------------------------------------------------------------*/
1326 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
1327 StackPtr sp; /* stack pointer */
1329 #if GIMME_STACK_DUMPS
1331 #define UPPER_DISP 5 /* # display entries on top of stack */
1332 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
1334 Void hugsStackOverflow() { /* Report stack overflow */
1336 extern Cell evalRoots[];
1338 ERRMSG(0) "Control stack overflow" ETHEN
1341 if (rootsp>=UPPER_DISP+LOWER_DISP) {
1342 for (i=0; i<UPPER_DISP; i++) {
1343 ERRTEXT "\nwhile evaluating: " ETHEN
1344 ERREXPR(evalRoots[rootsp-i]);
1346 ERRTEXT "\n..." ETHEN
1347 for (i=LOWER_DISP-1; i>=0; i--) {
1348 ERRTEXT "\nwhile evaluating: " ETHEN
1349 ERREXPR(evalRoots[i]);
1353 for (i=rootsp; i>=0; i--) {
1354 ERRTEXT "\nwhile evaluating: " ETHEN
1355 ERREXPR(evalRoots[i]);
1363 #else /* !GIMME_STACK_DUMPS */
1365 Void hugsStackOverflow() { /* Report stack overflow */
1366 ERRMSG(0) "Control stack overflow"
1370 #endif /* !GIMME_STACK_DUMPS */
1372 /* --------------------------------------------------------------------------
1375 * A Module represents a user defined module.
1377 * Note: there are now two lookup mechanisms in the system:
1379 * 1) The exports from a module are stored in a big list.
1380 * We resolve qualified names, and import lists by linearly scanning
1381 * through this list.
1383 * 2) Unqualified imports and local definitions for the current module
1384 * are stored in hash tables (tyconHash and nameHash) or linear lists
1387 * ------------------------------------------------------------------------*/
1389 static Module moduleHw; /* next unused Module */
1390 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
1391 Module currentModule; /* Module currently being processed*/
1393 Bool isValidModule(m) /* is m a legitimate module id? */
1395 return (MODMIN <= m && m < moduleHw);
1398 Module newModule(t) /* add new module to module table */
1400 if (moduleHw-MODMIN >= NUM_MODULE) {
1401 ERRMSG(0) "Module storage space exhausted"
1404 module(moduleHw).text = t; /* clear new module record */
1405 module(moduleHw).qualImports = NIL;
1406 module(moduleHw).fake = FALSE;
1407 module(moduleHw).exports = NIL;
1408 module(moduleHw).tycons = NIL;
1409 module(moduleHw).names = NIL;
1410 module(moduleHw).classes = NIL;
1411 module(moduleHw).object = NULL;
1412 module(moduleHw).objectExtras = NULL;
1413 module(moduleHw).objectExtraNames = NIL;
1417 void ppModules ( void )
1420 fflush(stderr); fflush(stdout);
1421 printf ( "begin MODULES\n" );
1422 for (i = moduleHw-1; i >= MODMIN; i--)
1423 printf ( " %2d: %16s\n",
1424 i-MODMIN, textToStr(module(i).text)
1426 printf ( "end MODULES\n" );
1427 fflush(stderr); fflush(stdout);
1431 Module findModule(t) /* locate Module in module table */
1434 for(m=MODMIN; m<moduleHw; ++m) {
1435 if (module(m).text==t)
1441 Module findModid(c) /* Find module by name or filename */
1443 switch (whatIs(c)) {
1444 case STRCELL : { Script s = scriptThisFile(snd(c));
1445 return (s==-1) ? NIL : moduleOfScript(s);
1447 case CONIDCELL : return findModule(textOf(c));
1448 default : internal("findModid");
1450 return NIL;/*NOTUSED*/
1453 static local Module findQualifier(t) /* locate Module in import list */
1456 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1457 if (textOf(fst(hd(ms)))==t)
1461 if (module(currentModule).text==t)
1462 return currentModule;
1467 Void setCurrModule(m) /* set lookup tables for current module */
1470 assert(isModule(m));
1471 if (m!=currentModule) {
1472 currentModule = m; /* This is the only assignment to currentModule */
1473 for (i=0; i<TYCONHSZ; ++i)
1475 mapProc(hashTycon,module(m).tycons);
1476 for (i=0; i<NAMEHSZ; ++i)
1478 mapProc(hashName,module(m).names);
1479 classes = module(m).classes;
1483 Name jrsFindQualName ( Text mn, Text sn )
1488 for (m=MODMIN; m<moduleHw; m++)
1489 if (module(m).text == mn) break;
1490 if (m == moduleHw) return NIL;
1492 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1493 if (name(hd(ns)).text == sn) return hd(ns);
1499 char* nameFromOPtr ( void* p )
1503 for (m=MODMIN; m<moduleHw; m++) {
1504 if (module(m).object) {
1505 char* nm = ocLookupAddr ( module(m).object, p );
1513 void* lookupOTabName ( Module m, char* sym )
1515 if (module(m).object)
1516 return ocLookupSym ( module(m).object, sym );
1521 void* lookupOExtraTabName ( char* sym )
1525 for (m = MODMIN; m < moduleHw; m++) {
1526 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1527 void* ad = ocLookupSym ( oc, sym );
1535 OSectionKind lookupSection ( void* ad )
1542 for (m=MODMIN; m<moduleHw; m++) {
1543 if (module(m).object) {
1544 sect = ocLookupSection ( module(m).object, ad );
1545 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1548 for (oc = module(m).objectExtras; oc; oc=oc->next) {
1549 sect = ocLookupSection ( oc, ad );
1550 if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1554 return HUGS_SECTIONKIND_OTHER;
1558 /* --------------------------------------------------------------------------
1559 * Script file storage:
1561 * script files are read into the system one after another. The state of
1562 * the stored data structures (except the garbage-collected heap) is recorded
1563 * before reading a new script. In the event of being unable to read the
1564 * script, or if otherwise requested, the system can be restored to its
1565 * original state immediately before the file was read.
1566 * ------------------------------------------------------------------------*/
1568 typedef struct { /* record of storage state prior to */
1569 Text file; /* reading script/module */
1583 #ifdef DEBUG_SHOWUSE
1584 static Void local showUse(msg,val,mx)
1587 Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1591 static Script scriptHw; /* next unused script number */
1592 static script scripts[NUM_SCRIPTS]; /* storage for script records */
1595 void ppScripts ( void )
1598 fflush(stderr); fflush(stdout);
1599 printf ( "begin SCRIPTS\n" );
1600 for (i = scriptHw-1; i >= 0; i--)
1601 printf ( " %2d: %16s tH=%d mH=%d yH=%d "
1602 "nH=%d cH=%d iH=%d nnS=%d,%d\n",
1603 i, textToStr(scripts[i].file),
1604 scripts[i].textHw, scripts[i].moduleHw,
1605 scripts[i].tyconHw, scripts[i].nameHw,
1606 scripts[i].classHw, scripts[i].instHw,
1607 scripts[i].nextNewText, scripts[i].nextNewDText
1609 printf ( "end SCRIPTS\n" );
1610 fflush(stderr); fflush(stdout);
1613 Script startNewScript(f) /* start new script, keeping record */
1614 String f; { /* of status for later restoration */
1615 if (scriptHw >= NUM_SCRIPTS) {
1616 ERRMSG(0) "Too many script files in use"
1619 #ifdef DEBUG_SHOWUSE
1620 showUse("Text", textHw, NUM_TEXT);
1621 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
1622 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
1623 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
1624 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
1625 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
1627 showUse("Ext", extHw-EXTMIN, NUM_EXT);
1630 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
1631 scripts[scriptHw].textHw = textHw;
1632 scripts[scriptHw].nextNewText = nextNewText;
1633 scripts[scriptHw].nextNewDText = nextNewDText;
1634 scripts[scriptHw].moduleHw = moduleHw;
1635 scripts[scriptHw].tyconHw = tyconHw;
1636 scripts[scriptHw].nameHw = nameHw;
1637 scripts[scriptHw].classHw = classHw;
1638 scripts[scriptHw].instHw = instHw;
1640 scripts[scriptHw].extHw = extHw;
1645 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1646 return (scriptHw==0);
1649 Bool moduleThisScript(m) /* Test if given module is defined */
1650 Module m; { /* in current script file */
1651 return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
1654 Module lastModule() { /* Return module in current script file */
1655 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1658 #define scriptThis(nm,t,tag) Script nm(x) \
1662 && x>=scripts[s].tag) \
1666 scriptThis(scriptThisName,Name,nameHw)
1667 scriptThis(scriptThisTycon,Tycon,tyconHw)
1668 scriptThis(scriptThisInst,Inst,instHw)
1669 scriptThis(scriptThisClass,Class,classHw)
1672 Module moduleOfScript(s)
1674 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1677 String fileOfModule(m)
1680 if (m == modulePrelude) {
1683 for(s=0; s<scriptHw; ++s) {
1684 if (scripts[s].moduleHw == m) {
1685 return textToStr(scripts[s].file);
1691 Script scriptThisFile(f)
1694 for (s=0; s < scriptHw; ++s) {
1695 if (scripts[s].file == f) {
1699 if (f == findText(STD_PRELUDE)) {
1705 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1706 Script sno; { /* to reading script sno */
1707 if (sno<scriptHw) { /* is there anything to restore? */
1709 textHw = scripts[sno].textHw;
1710 nextNewText = scripts[sno].nextNewText;
1711 nextNewDText = scripts[sno].nextNewDText;
1712 moduleHw = scripts[sno].moduleHw;
1713 tyconHw = scripts[sno].tyconHw;
1714 nameHw = scripts[sno].nameHw;
1715 classHw = scripts[sno].classHw;
1716 instHw = scripts[sno].instHw;
1718 dictHw = scripts[sno].dictHw;
1721 extHw = scripts[sno].extHw;
1725 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1726 if (module(i).objectFile) {
1727 printf("[bogus] closing objectFile for module %d\n",i);
1728 /*dlclose(module(i).objectFile);*/
1731 moduleHw = scripts[sno].moduleHw;
1733 for (i=0; i<TEXTHSZ; ++i) {
1735 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1736 && textHash[i][j]<textHw)
1739 textHash[i][j] = NOTEXT;
1743 for (i=0; i<TYCONHSZ; ++i) {
1746 for (i=0; i<NAMEHSZ; ++i) {
1750 for (i=CLASSMIN; i<classHw; i++) {
1751 List ins = cclass(i).instances;
1754 while (nonNull(ins)) {
1755 List temp = tl(ins);
1756 if (hd(ins)<instHw) {
1762 cclass(i).instances = rev(is);
1769 /* --------------------------------------------------------------------------
1772 * Provides a garbage collectable heap for storage of expressions etc.
1774 * Now incorporates a flat resource: A two-space collected extension of
1775 * the heap that provides storage for contiguous arrays of Cell storage,
1776 * cooperating with the garbage collection mechanisms for the main heap.
1777 * ------------------------------------------------------------------------*/
1779 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1780 Heap heapFst; /* array of fst component of pairs */
1781 Heap heapSnd; /* array of snd component of pairs */
1788 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1789 /* C stack; use with extreme care! */
1791 Int numGcs; /* number of garbage collections */
1792 Int cellsRecovered; /* number of cells recovered */
1794 static Cell freeList; /* free list of unused cells */
1795 static Cell lsave, rsave; /* save components of pair */
1799 static Int markCount, stackRoots;
1801 #define initStackRoots() stackRoots = 0
1802 #define recordStackRoot() stackRoots++
1815 #define start() markCount = 0
1816 #define end(thing,rs) \
1818 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1821 #define recordMark() markCount++
1823 #else /* !GC_STATISTICS */
1828 #define initStackRoots()
1829 #define recordStackRoot()
1832 #define end(thing,root)
1833 #define recordMark()
1835 #endif /* !GC_STATISTICS */
1837 Cell pair(l,r) /* Allocate pair (l, r) from */
1838 Cell l, r; { /* heap, garbage collecting first */
1839 Cell c = freeList; /* if necessary ... */
1851 freeList = snd(freeList);
1858 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1859 Cell dst, src; { /* both *MUST* be pairs */
1860 if (isPair(dst) && isPair(src)) {
1861 fst(dst) = fst(src);
1862 snd(dst) = snd(src);
1865 internal("overwrite");
1869 static Int marksSize;
1871 Cell markExpr(c) /* External interface to markCell */
1873 return isGenPair(c) ? markCell(c) : c;
1876 static Cell local markCell(c) /* Traverse part of graph marking */
1877 Cell c; { /* cells reachable from given root */
1878 /* markCell(c) is only called if c */
1880 { register int place = placeInSet(c);
1881 register int mask = maskInSet(c);
1882 if (marks[place]&mask)
1885 marks[place] |= mask;
1890 /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1891 if (isGenPair(fst(c))) {
1893 fst(c) = markCell(fst(c));
1896 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1904 static Void local markSnd(c) /* Variant of markCell used to */
1905 Cell c; { /* update snd component of cell */
1906 Cell t; /* using tail recursion */
1908 ma: t = c; /* Keep pointer to original pair */
1913 { register int place = placeInSet(c);
1914 register int mask = maskInSet(c);
1915 if (marks[place]&mask)
1918 marks[place] |= mask;
1923 if (isGenPair(fst(c))) {
1924 fst(c) = markCell(fst(c));
1927 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1932 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1933 Cell n; { /* it was a cell ref, but don't */
1934 /* move cell so we don't have */
1935 /* to modify the stored value of n */
1942 Void garbageCollect() { /* Run garbage collector ... */
1943 Bool breakStat = breakOn(FALSE); /* disable break checking */
1949 jmp_buf regs; /* save registers on stack */
1953 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1956 everybody(MARK); /* Mark all components of system */
1958 gcScanning(); /* scan mark set */
1965 for (i=1; i<=heapSize; i++) {
1966 if ((marks[place] & mask) == 0) {
1973 if (++j == bitsPerWord) {
1980 gcRecovered(recovered);
1981 breakOn(breakStat); /* restore break trapping if nec. */
1985 /* can only return if freeList is nonempty on return. */
1986 if (recovered<minRecovery || isNull(freeList)) {
1987 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1990 cellsRecovered = recovered;
1993 /* --------------------------------------------------------------------------
1994 * Code for saving last expression entered:
1996 * This is a little tricky because some text values (e.g. strings or variable
1997 * names) may not be defined or have the same value when the expression is
1998 * recalled. These text values are therefore saved in the top portion of
2000 * ------------------------------------------------------------------------*/
2002 static Cell lastExprSaved; /* last expression to be saved */
2004 Void setLastExpr(e) /* save expression for later recall*/
2006 lastExprSaved = NIL; /* in case attempt to save fails */
2007 savedText = NUM_TEXT;
2008 lastExprSaved = lowLevelLastIn(e);
2011 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
2012 Cell c; { /* acyclic graph) for later recall */
2013 if (isPair(c)) { /* Duplicating any text strings */
2014 if (isBoxTag(fst(c))) /* in case these are lost at some */
2015 switch (fst(c)) { /* point before the expr is reused */
2021 case STRCELL : return pair(fst(c),saveText(textOf(c)));
2022 default : return pair(fst(c),snd(c));
2025 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2029 return pair(EXTCOPY,saveText(extText(c)));
2035 Cell getLastExpr() { /* recover previously saved expr */
2036 return lowLevelLastOut(lastExprSaved);
2039 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
2040 Cell c; { /* except that Cells refering to */
2041 if (isPair(c)) { /* Text values are restored to */
2042 if (isBoxTag(fst(c))) /* appropriate values */
2049 case STRCELL : return pair(fst(c),
2050 findText(text+intValOf(c)));
2052 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
2054 default : return pair(fst(c),snd(c));
2057 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2063 /* --------------------------------------------------------------------------
2064 * Miscellaneous operations on heap cells:
2065 * ------------------------------------------------------------------------*/
2067 /* Profiling suggests that the number of calls to whatIs() is typically */
2068 /* rather high. The recoded version below attempts to improve the average */
2069 /* performance for whatIs() using a binary search for part of the analysis */
2071 Cell whatIs(c) /* identify type of cell */
2074 register Cell fstc = fst(c);
2075 return isTag(fstc) ? fstc : AP;
2077 if (c<OFFMIN) return c;
2079 if (isExt(c)) return EXT;
2081 if (c>=INTMIN) return INTCELL;
2083 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
2085 else if (c>=INSTMIN) return INSTANCE;
2087 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
2088 else return MODULE;}
2089 else if (c>=OFFMIN) return OFFSET;
2091 else return (c>=EXTMIN) ?
2098 register Cell fstc = fst(c);
2099 return isTag(fstc) ? fstc : AP;
2101 if (c>=INTMIN) return INTCELL;
2102 if (c>=CHARMIN) return CHARCELL;
2103 if (c>=CLASSMIN) return CLASS;
2104 if (c>=INSTMIN) return INSTANCE;
2105 if (c>=NAMEMIN) return NAME;
2106 if (c>=TYCMIN) return TYCON;
2107 if (c>=MODMIN) return MODULE;
2108 if (c>=OFFMIN) return OFFSET;
2110 if (c>=EXTMIN) return EXT;
2112 if (c>=TUPMIN) return TUPLE;
2117 /* A very, very simple printer.
2118 * Output is uglier than from printExp - but the printer is more
2119 * robust and can be used on any data structure irrespective of
2122 Void print Args((Cell, Int));
2123 Void print(c, depth)
2128 #if 0 /* Not in this version of Hugs */
2129 } else if (isPair(c) && !isGenPair(c)) {
2130 extern Void printEvalCell Args((Cell, Int));
2131 printEvalCell(c,depth);
2134 Int tag = whatIs(c);
2138 print(fst(c), depth-1);
2140 print(snd(c), depth-1);
2144 Printf("free(%d)", c);
2147 Printf("int(%d)", intOf(c));
2150 Printf("bignum(%s)", bignumToString(c));
2153 Printf("char('%c')", charOf(c));
2156 Printf("ptr(%p)",ptrOf(c));
2159 Printf("class(%d)", c-CLASSMIN);
2160 if (CLASSMIN <= c && c < classHw) {
2161 Printf("=\"%s\"", textToStr(cclass(c).text));
2165 Printf("instance(%d)", c - INSTMIN);
2168 Printf("name(%d)", c-NAMEMIN);
2169 if (NAMEMIN <= c && c < nameHw) {
2170 Printf("=\"%s\"", textToStr(name(c).text));
2174 Printf("tycon(%d)", c-TYCMIN);
2175 if (TYCMIN <= c && c < tyconHw)
2176 Printf("=\"%s\"", textToStr(tycon(c).text));
2179 Printf("module(%d)", c - MODMIN);
2182 Printf("Offset %d", offsetOf(c));
2185 Printf("%s", textToStr(ghcTupleText(c)));
2189 print(snd(c),depth-1);
2193 print(snd(c),depth-1);
2197 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2198 Printf("%d ", intOf(fst(snd(c))));
2199 print(snd(snd(c)),depth-1);
2201 print(snd(c),depth-1);
2218 Printf("{dict %d}",textOf(c));
2224 Printf("{id %s}",textToStr(textOf(c)));
2228 Printf("{ip %s}",textToStr(textOf(c)));
2231 Printf("?%s",textToStr(textOf(c)));
2235 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2239 print(fst(snd(c)),depth-1);
2241 print(snd(snd(c)),depth-1);
2246 print(snd(c),depth-1);
2251 print(snd(c),depth-1);
2256 print(fst(snd(c)),depth-1);
2258 print(snd(snd(c)),depth-1);
2263 print(fst(snd(c)),depth-1);
2265 print(snd(snd(c)),depth-1);
2269 Printf("FromQual(");
2270 print(fst(snd(c)),depth-1);
2272 print(snd(snd(c)),depth-1);
2276 Printf("StgVar%d=",-c);
2277 print(snd(c), depth-1);
2281 print(fst(snd(c)),depth-1);
2283 print(snd(snd(c)),depth-1);
2288 print(fst(snd(c)),depth-1);
2290 print(snd(snd(c)),depth-1);
2295 print(fst(snd(c)),depth-1);
2297 print(snd(snd(c)),depth-1);
2301 Printf("PrimCase(");
2302 print(fst(snd(c)),depth-1);
2304 print(snd(snd(c)),depth-1);
2309 print(snd(c),depth-1);
2313 Printf("(UNBOXEDTUP,");
2314 print(snd(c),depth-1);
2319 print(zfst(c),depth-1);
2321 print(zsnd(c),depth-1);
2325 Printf("<ZTriple ");
2326 print(zfst3(c),depth-1);
2328 print(zsnd3(c),depth-1);
2330 print(zthd3(c),depth-1);
2335 print(snd(c),depth-1);
2339 if (isBoxTag(tag)) {
2340 Printf("Tag(%d)=%d", c, tag);
2341 } else if (isConTag(tag)) {
2342 Printf("%d@(%d,",c,tag);
2343 print(snd(c), depth-1);
2346 } else if (c == tag) {
2347 Printf("Tag(%d)", c);
2349 Printf("Tag(%d)=%d", c, tag);
2358 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2359 Cell c; { /* also recognises DICTVAR cells */
2361 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2364 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2366 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2369 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2371 if (!isPair(c)) return FALSE;
2374 case VAROPCELL : return TRUE;
2376 case QUALIDENT : return isVar(snd(snd(c)));
2378 default : return FALSE;
2382 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2384 if (!isPair(c)) return FALSE;
2387 case CONOPCELL : return TRUE;
2389 case QUALIDENT : return isCon(snd(snd(c)));
2391 default : return FALSE;
2395 Bool isQualIdent(c) /* is cell a qualified identifier? */
2397 return isPair(c) && (fst(c)==QUALIDENT);
2400 Bool eqQualIdent ( QualId c1, QualId c2 )
2402 assert(isQualIdent(c1));
2403 if (!isQualIdent(c2)) {
2404 assert(isQualIdent(c2));
2406 return qmodOf(c1)==qmodOf(c2) &&
2407 qtextOf(c1)==qtextOf(c2);
2410 Bool isIdent(c) /* is cell an identifier? */
2412 if (!isPair(c)) return FALSE;
2417 case CONOPCELL : return TRUE;
2419 case QUALIDENT : return TRUE;
2421 default : return FALSE;
2425 Bool isInt(c) /* cell holds integer value? */
2427 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2430 Int intOf(c) /* find integer value of cell? */
2433 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
2436 Cell mkInt(n) /* make cell representing integer */
2438 return (MINSMALLINT <= n && n <= MAXSMALLINT)
2443 #if SIZEOF_INTP == SIZEOF_INT
2444 typedef union {Int i; Ptr p;} IntOrPtr;
2450 return pair(PTRCELL,x.i);
2457 assert(fst(c) == PTRCELL);
2466 return pair(CPTRCELL,x.i);
2473 assert(fst(c) == CPTRCELL);
2477 #elif SIZEOF_INTP == 2*SIZEOF_INT
2478 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2484 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2491 assert(fst(c) == PTRCELL);
2492 x.i.i1 = intOf(fst(snd(c)));
2493 x.i.i2 = intOf(snd(snd(c)));
2497 #warning "type Addr not supported on this architecture - don't use it"
2501 ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
2508 ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
2513 String stringNegate( s )
2521 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2526 /* --------------------------------------------------------------------------
2528 * ------------------------------------------------------------------------*/
2530 Int length(xs) /* calculate length of list xs */
2533 for (; nonNull(xs); ++n)
2538 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2539 List xs, ys; { /* ys by modifying xs ... */
2544 while (nonNull(tl(zs)))
2551 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2554 for (; nonNull(xs); xs=tl(xs))
2555 ys = cons(hd(xs),ys);
2559 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2562 return revOnto(dupOnto(xs,NIL),ys);
2565 List dupList(xs) /* Duplicate spine of list xs */
2568 for (; nonNull(xs); xs=tl(xs))
2569 ys = cons(hd(xs),ys);
2573 List revOnto(xs,ys) /* Destructively reverse elements of*/
2574 List xs, ys; { /* list xs onto list ys... */
2577 while (nonNull(xs)) {
2586 QualId qualidIsMember ( QualId q, List xs )
2588 for (; nonNull(xs); xs=tl(xs)) {
2589 if (eqQualIdent(q, hd(xs)))
2595 Cell varIsMember(t,xs) /* Test if variable is a member of */
2596 Text t; /* given list of variables */
2598 for (; nonNull(xs); xs=tl(xs))
2599 if (t==textOf(hd(xs)))
2604 Name nameIsMember(t,ns) /* Test if name with text t is a */
2605 Text t; /* member of list of names xs */
2607 for (; nonNull(ns); ns=tl(ns))
2608 if (t==name(hd(ns)).text)
2613 Cell intIsMember(n,xs) /* Test if integer n is member of */
2614 Int n; /* given list of integers */
2616 for (; nonNull(xs); xs=tl(xs))
2617 if (n==intOf(hd(xs)))
2622 Cell cellIsMember(x,xs) /* Test for membership of specific */
2623 Cell x; /* cell x in list xs */
2625 for (; nonNull(xs); xs=tl(xs))
2631 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2634 for (; nonNull(xs); xs=tl(xs))
2640 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2641 Cell c; /* association lists */
2643 for (; nonNull(xs); xs=tl(xs))
2649 List replicate(n,x) /* create list of n copies of x */
2658 List diffList(from,take) /* list difference: from\take */
2659 List from, take; { /* result contains all elements of */
2660 List result = NIL; /* `from' not appearing in `take' */
2662 while (nonNull(from)) {
2663 List next = tl(from);
2664 if (!cellIsMember(hd(from),take)) {
2673 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2677 for(;nonNull(xs);xs=tl(xs)) {
2680 result=cons(x,result);
2686 List take(n,xs) /* destructively truncate list to */
2687 Int n; /* specified length */
2693 while (1<n-- && nonNull(xs))
2700 List splitAt(n,xs) /* drop n things from front of list*/
2709 Cell nth(n,xs) /* extract n'th element of list */
2712 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2719 List removeCell(x,xs) /* destructively remove cell from */
2724 return tl(xs); /* element at front of list */
2728 for (; nonNull(curr); prev=curr, curr=tl(prev))
2730 tl(prev) = tl(curr);
2731 return xs; /* element in middle of list */
2735 return xs; /* here if element not found */
2738 List nubList(xs) /* nuke dups in list */
2739 List xs; { /* non destructive */
2741 for (; nonNull(xs); xs=tl(xs))
2742 if (isNull(cellIsMember(hd(xs),outs)))
2743 outs = cons(hd(xs),outs);
2749 /* --------------------------------------------------------------------------
2750 * Strongly-typed lists (z-lists) and tuples (experimental)
2751 * ------------------------------------------------------------------------*/
2753 static void z_tag_check ( Cell x, int tag, char* caller )
2757 sprintf(buf,"z_tag_check(%s): null\n", caller);
2760 if (whatIs(x) != tag) {
2762 "z_tag_check(%s): tag was %d, expected %d\n",
2763 caller, whatIs(x), tag );
2769 Cell zcons ( Cell x, Cell xs )
2771 if (!(isNull(xs) || whatIs(xs)==ZCONS))
2772 internal("zcons: ill typed tail");
2773 return ap(ZCONS,ap(x,xs));
2776 Cell zhd ( Cell xs )
2778 if (isNull(xs)) internal("zhd: empty list");
2779 z_tag_check(xs,ZCONS,"zhd");
2780 return fst( snd(xs) );
2783 Cell ztl ( Cell xs )
2785 if (isNull(xs)) internal("ztl: empty list");
2786 z_tag_check(xs,ZCONS,"zhd");
2787 return snd( snd(xs) );
2790 Int zlength ( ZList xs )
2793 while (nonNull(xs)) {
2794 z_tag_check(xs,ZCONS,"zlength");
2796 xs = snd( snd(xs) );
2801 ZList zreverse ( ZList xs )
2804 while (nonNull(xs)) {
2805 z_tag_check(xs,ZCONS,"zreverse");
2806 rev = zcons(zhd(xs),rev);
2812 Cell zsingleton ( Cell x )
2814 return zcons (x,NIL);
2817 Cell zdoubleton ( Cell x, Cell y )
2819 return zcons(x,zcons(y,NIL));
2823 Cell zpair ( Cell x1, Cell x2 )
2824 { return ap(ZTUP2,ap(x1,x2)); }
2825 Cell zfst ( Cell zpair )
2826 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2827 Cell zsnd ( Cell zpair )
2828 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2830 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2831 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2832 Cell zfst3 ( Cell zpair )
2833 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2834 Cell zsnd3 ( Cell zpair )
2835 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2836 Cell zthd3 ( Cell zpair )
2837 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2839 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2840 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2841 Cell zsel14 ( Cell zpair )
2842 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2843 Cell zsel24 ( Cell zpair )
2844 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2845 Cell zsel34 ( Cell zpair )
2846 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2847 Cell zsel44 ( Cell zpair )
2848 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2850 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2851 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2852 Cell zsel15 ( Cell zpair )
2853 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2854 Cell zsel25 ( Cell zpair )
2855 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2856 Cell zsel35 ( Cell zpair )
2857 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2858 Cell zsel45 ( Cell zpair )
2859 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2860 Cell zsel55 ( Cell zpair )
2861 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2864 Cell unap ( int tag, Cell c )
2867 if (whatIs(c) != tag) {
2868 sprintf(buf, "unap: specified %d, actual %d\n",
2875 /* --------------------------------------------------------------------------
2876 * Operations on applications:
2877 * ------------------------------------------------------------------------*/
2879 Int argCount; /* number of args in application */
2881 Cell getHead(e) /* get head cell of application */
2882 Cell e; { /* set number of args in argCount */
2883 for (argCount=0; isAp(e); e=fun(e))
2888 List getArgs(e) /* get list of arguments in function*/
2889 Cell e; { /* application: */
2890 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2892 for (as=NIL; isAp(e); e=fun(e))
2893 as = cons(arg(e),as);
2897 Cell nthArg(n,e) /* return nth arg in application */
2898 Int n; /* of function to m args (m>=n) */
2899 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2900 for (n=numArgs(e)-n-1; n>0; n--)
2905 Int numArgs(e) /* find number of arguments to expr */
2908 for (n=0; isAp(e); e=fun(e))
2913 Cell applyToArgs(f,args) /* destructively apply list of args */
2914 Cell f; /* to function f */
2916 while (nonNull(args)) {
2917 Cell temp = tl(args);
2918 tl(args) = hd(args);
2926 /* --------------------------------------------------------------------------
2928 * ------------------------------------------------------------------------*/
2930 static String maybeModuleStr ( Module m )
2932 if (isModule(m)) return textToStr(module(m).text); else return "??";
2935 static String maybeNameStr ( Name n )
2937 if (isName(n)) return textToStr(name(n).text); else return "??";
2940 static String maybeTyconStr ( Tycon t )
2942 if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
2945 static String maybeClassStr ( Class c )
2947 if (isClass(c)) return textToStr(cclass(c).text); else return "??";
2950 static String maybeText ( Text t )
2952 if (isNull(t)) return "(nil)";
2953 return textToStr(t);
2956 static void print100 ( Int x )
2958 print ( x, 100); printf("\n");
2961 void dumpTycon ( Int t )
2963 if (isTycon(TYCMIN+t) && !isTycon(t)) t += TYCMIN;
2965 printf ( "dumpTycon %d: not a tycon\n", t);
2969 printf ( " text: %s\n", textToStr(tycon(t).text) );
2970 printf ( " line: %d\n", tycon(t).line );
2971 printf ( " mod: %s\n", maybeModuleStr(tycon(t).mod));
2972 printf ( " tuple: %d\n", tycon(t).tuple);
2973 printf ( " arity: %d\n", tycon(t).arity);
2974 printf ( " kind: "); print100(tycon(t).kind);
2975 printf ( " what: %d\n", tycon(t).what);
2976 printf ( " defn: "); print100(tycon(t).defn);
2977 printf ( " cToT: %d %s\n", tycon(t).conToTag,
2978 maybeNameStr(tycon(t).conToTag));
2979 printf ( " tToC: %d %s\n", tycon(t).tagToCon,
2980 maybeNameStr(tycon(t).tagToCon));
2981 printf ( " itbl: %p\n", tycon(t).itbl);
2982 printf ( " nextTH: %d %s\n", tycon(t).nextTyconHash,
2983 maybeTyconStr(tycon(t).nextTyconHash));
2987 void dumpName ( Int n )
2989 if (isName(NAMEMIN+n) && !isName(n)) n += NAMEMIN;
2991 printf ( "dumpName %d: not a name\n", n);
2995 printf ( " text: %s\n", textToStr(name(n).text) );
2996 printf ( " line: %d\n", name(n).line );
2997 printf ( " mod: %s\n", maybeModuleStr(name(n).mod));
2998 printf ( " syntax: %d\n", name(n).syntax );
2999 printf ( " parent: %d\n", name(n).parent );
3000 printf ( " arity: %d\n", name(n).arity );
3001 printf ( " number: %d\n", name(n).number );
3002 printf ( " type: "); print100(name(n).type);
3003 printf ( " defn: %d\n", name(n).defn );
3004 printf ( " stgVar: "); print100(name(n).stgVar);
3005 printf ( " cconv: %d\n", name(n).callconv );
3006 printf ( " primop: %p\n", name(n).primop );
3007 printf ( " itbl: %p\n", name(n).itbl );
3008 printf ( " nextNH: %d\n", name(n).nextNameHash );
3013 void dumpClass ( Int c )
3015 if (isClass(CLASSMIN+c) && !isClass(c)) c += CLASSMIN;
3017 printf ( "dumpClass %d: not a class\n", c);
3021 printf ( " text: %s\n", textToStr(cclass(c).text) );
3022 printf ( " line: %d\n", cclass(c).line );
3023 printf ( " mod: %s\n", maybeModuleStr(cclass(c).mod));
3024 printf ( " arity: %d\n", cclass(c).arity );
3025 printf ( " level: %d\n", cclass(c).level );
3026 printf ( " kinds: "); print100( cclass(c).kinds );
3027 printf ( " fds: %d\n", cclass(c).fds );
3028 printf ( " xfds: %d\n", cclass(c).xfds );
3029 printf ( " head: "); print100( cclass(c).head );
3030 printf ( " dcon: "); print100( cclass(c).dcon );
3031 printf ( " supers: "); print100( cclass(c).supers );
3032 printf ( " #supers: %d\n", cclass(c).numSupers );
3033 printf ( " dsels: "); print100( cclass(c).dsels );
3034 printf ( " members: "); print100( cclass(c).members );
3035 printf ( "#members: %d\n", cclass(c).numMembers );
3036 printf ( "defaults: "); print100( cclass(c).defaults );
3037 printf ( " insts: "); print100( cclass(c).instances );
3042 void dumpInst ( Int i )
3044 if (isInst(INSTMIN+i) && !isInst(i)) i += INSTMIN;
3046 printf ( "dumpInst %d: not an instance\n", i);
3050 printf ( " class: %s\n", maybeClassStr(inst(i).c) );
3051 printf ( " line: %d\n", inst(i).line );
3052 printf ( " mod: %s\n", maybeModuleStr(inst(i).mod));
3053 printf ( " kinds: "); print100( inst(i).kinds );
3054 printf ( " head: "); print100( inst(i).head );
3055 printf ( " specs: "); print100( inst(i).specifics );
3056 printf ( " #specs: %d\n", inst(i).numSpecifics );
3057 printf ( " impls: "); print100( inst(i).implements );
3058 printf ( " builder: %s\n", maybeNameStr( inst(i).builder ) );
3063 /* --------------------------------------------------------------------------
3065 * ------------------------------------------------------------------------*/
3067 /*---------------------------------------------------------------------------
3068 * GreenCard entry points
3070 * GreenCard generated code accesses Hugs data structures and functions
3071 * (only) via these functions (which are stored in the virtual function
3073 *-------------------------------------------------------------------------*/
3077 static Cell makeTuple Args((Int));
3078 static Cell makeInt Args((Int));
3079 static Cell makeChar Args((Char));
3080 static Char CharOf Args((Cell));
3081 static Cell makeFloat Args((FloatPro));
3082 static Void* derefMallocPtr Args((Cell));
3083 static Cell* Fst Args((Cell));
3084 static Cell* Snd Args((Cell));
3086 static Cell makeTuple(n) Int n; { return mkTuple(n); }
3087 static Cell makeInt(n) Int n; { return mkInt(n); }
3088 static Cell makeChar(n) Char n; { return mkChar(n); }
3089 static Char CharOf(n) Cell n; { return charOf(n); }
3090 static Cell makeFloat(n) FloatPro n; { return mkFloat(n); }
3091 static Void* derefMallocPtr(n) Cell n; { return derefMP(n); }
3092 static Cell* Fst(n) Cell n; { return (Cell*)&fst(n); }
3093 static Cell* Snd(n) Cell n; { return (Cell*)&snd(n); }
3095 HugsAPI1* hugsAPI1() {
3096 static HugsAPI1 api;
3097 static Bool initialised = FALSE;
3099 api.nameTrue = nameTrue;
3100 api.nameFalse = nameFalse;
3101 api.nameNil = nameNil;
3102 api.nameCons = nameCons;
3103 api.nameJust = nameJust;
3104 api.nameNothing = nameNothing;
3105 api.nameLeft = nameLeft;
3106 api.nameRight = nameRight;
3107 api.nameUnit = nameUnit;
3108 api.nameIORun = nameIORun;
3109 api.makeInt = makeInt;
3110 api.makeChar = makeChar;
3111 api.CharOf = CharOf;
3112 api.makeFloat = makeFloat;
3113 api.makeTuple = makeTuple;
3115 api.mkMallocPtr = mkMallocPtr;
3116 api.derefMallocPtr = derefMallocPtr;
3117 api.mkStablePtr = mkStablePtr;
3118 api.derefStablePtr = derefStablePtr;
3119 api.freeStablePtr = freeStablePtr;
3121 api.evalWithNoError = evalWithNoError;
3122 api.evalFails = evalFails;
3123 api.whnfArgs = &whnfArgs;
3124 api.whnfHead = &whnfHead;
3125 api.whnfInt = &whnfInt;
3126 api.whnfFloat = &whnfFloat;
3127 api.garbageCollect = garbageCollect;
3128 api.stackOverflow = hugsStackOverflow;
3129 api.internal = internal;
3130 api.registerPrims = registerPrims;
3131 api.addPrimCfun = addPrimCfun;
3132 api.inventText = inventText;
3135 api.cellStack = cellStack;
3141 #endif /* GREENCARD */
3144 /* --------------------------------------------------------------------------
3146 * ------------------------------------------------------------------------*/
3149 static void far* safeFarCalloc Args((Int,Int));
3150 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
3151 Int n, s; { /* for non-null return */
3152 void far* tab = farCalloc(n,s);
3154 ERRMSG(0) "Cannot allocate run-time tables"
3159 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
3161 #define TABALLOC(v,t,n)
3169 case POSTPREL: break;
3171 case RESET : clearStack();
3173 /* the next 2 statements are particularly important
3174 * if you are using GLOBALfst or GLOBALsnd since the
3175 * corresponding registers may be reset to their
3176 * uninitialised initial values by a longjump.
3178 heapTopFst = heapFst + heapSize;
3179 heapTopSnd = heapSnd + heapSize;
3183 if (isNull(lastExprSaved))
3184 savedText = NUM_TEXT;
3189 for (i=NAMEMIN; i<nameHw; ++i) {
3190 mark(name(i).parent);
3192 mark(name(i).stgVar);
3195 end("Names", nameHw-NAMEMIN);
3198 for (i=MODMIN; i<moduleHw; ++i) {
3199 mark(module(i).tycons);
3200 mark(module(i).names);
3201 mark(module(i).classes);
3202 mark(module(i).exports);
3203 mark(module(i).qualImports);
3204 mark(module(i).objectExtraNames);
3206 end("Modules", moduleHw-MODMIN);
3209 for (i=TYCMIN; i<tyconHw; ++i) {
3210 mark(tycon(i).defn);
3211 mark(tycon(i).kind);
3212 mark(tycon(i).what);
3214 end("Type constructors", tyconHw-TYCMIN);
3217 for (i=CLASSMIN; i<classHw; ++i) {
3218 mark(cclass(i).head);
3219 mark(cclass(i).kinds);
3220 mark(cclass(i).fds);
3221 mark(cclass(i).xfds);
3222 mark(cclass(i).dsels);
3223 mark(cclass(i).supers);
3224 mark(cclass(i).members);
3225 mark(cclass(i).defaults);
3226 mark(cclass(i).instances);
3229 end("Classes", classHw-CLASSMIN);
3232 for (i=INSTMIN; i<instHw; ++i) {
3234 mark(inst(i).kinds);
3235 mark(inst(i).specifics);
3236 mark(inst(i).implements);
3238 end("Instances", instHw-INSTMIN);
3241 for (i=0; i<=sp; ++i)
3246 mark(lastExprSaved);
3249 end("Last expression", 3);
3254 end("C stack", stackRoots);
3259 case PREPREL : heapFst = heapAlloc(heapSize);
3260 heapSnd = heapAlloc(heapSize);
3262 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3263 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3268 heapTopFst = heapFst + heapSize;
3269 heapTopSnd = heapSnd + heapSize;
3270 for (i=1; i<heapSize; ++i) {
3274 snd(-heapSize) = NIL;
3281 marksSize = bitArraySize(heapSize);
3282 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3283 ERRMSG(0) "Unable to allocate gc markspace"
3287 TABALLOC(text, char, NUM_TEXT)
3288 TABALLOC(tyconHash, Tycon, TYCONHSZ)
3289 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
3290 TABALLOC(nameHash, Name, NAMEHSZ)
3291 TABALLOC(tabName, struct strName, NUM_NAME)
3292 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
3293 TABALLOC(cellStack, Cell, NUM_STACK)
3294 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
3296 TABALLOC(tabExt, Text, NUM_EXT)
3301 nextNewText = NUM_TEXT;
3302 nextNewDText = (-1);
3303 lastExprSaved = NIL;
3304 savedText = NUM_TEXT;
3305 for (i=0; i<TEXTHSZ; ++i)
3306 textHash[i][0] = NOTEXT;
3312 for (i=0; i<TYCONHSZ; ++i)
3319 for (i=0; i<NAMEHSZ; ++i)
3330 tabInst = (struct strInst far *)
3331 farCalloc(NUM_INSTS,sizeof(struct strInst));
3334 ERRMSG(0) "Cannot allocate instance tables"
3344 /*-------------------------------------------------------------------------*/