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: 1999/12/10 15:59:53 $
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 == '_')) {
356 case '(': p[n++] = 'Z'; p[n++] = 'L'; break;
357 case ')': p[n++] = 'Z'; p[n++] = 'R'; break;
358 case '[': p[n++] = 'Z'; p[n++] = 'M'; break;
359 case ']': p[n++] = 'Z'; p[n++] = 'N'; break;
360 case ':': p[n++] = 'Z'; p[n++] = 'C'; break;
361 case 'Z': p[n++] = 'Z'; p[n++] = 'Z'; break;
362 case 'z': p[n++] = 'z'; p[n++] = 'z'; break;
363 case '&': p[n++] = 'z'; p[n++] = 'a'; break;
364 case '|': p[n++] = 'z'; p[n++] = 'b'; break;
365 case '$': p[n++] = 'z'; p[n++] = 'd'; break;
366 case '=': p[n++] = 'z'; p[n++] = 'e'; break;
367 case '>': p[n++] = 'z'; p[n++] = 'g'; break;
368 case '#': p[n++] = 'z'; p[n++] = 'h'; break;
369 case '.': p[n++] = 'z'; p[n++] = 'i'; break;
370 case '<': p[n++] = 'z'; p[n++] = 'l'; 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++] = 'p'; break;
374 case '\'': p[n++] = 'z'; p[n++] = 'q'; break;
375 case '\\': p[n++] = 'z'; p[n++] = 'r'; break;
376 case '/': p[n++] = 'z'; p[n++] = 's'; break;
377 case '*': p[n++] = 'z'; p[n++] = 't'; break;
378 case '^': p[n++] = 'z'; p[n++] = 'u'; break;
379 case '%': p[n++] = 'z'; p[n++] = 'v'; break;
380 default: s--; p[n++] = 'z'; p[n++] = 'x';
381 p[n++] = toHex[(int)(*s)/16];
382 p[n++] = toHex[(int)(*s)%16];
393 Text textOf ( Cell c )
396 (whatIs(c)==VARIDCELL
397 || whatIs(c)==CONIDCELL
398 || whatIs(c)==VAROPCELL
399 || whatIs(c)==CONOPCELL
400 || whatIs(c)==STRCELL
401 || whatIs(c)==DICTVAR
404 fprintf(stderr, "\ntextOf: bad tag %d\n",whatIs(c) );
405 internal("textOf: bad tag");
410 /* --------------------------------------------------------------------------
413 * Currently, the only attributes that we store for each Ext value is the
414 * corresponding Text label. At some later stage, we may decide to cache
415 * types, predicates, etc. here as a space saving gesture. Given that Text
416 * comparison is cheap, and that this is an experimental implementation, we
417 * will use a straightforward linear search to locate Ext values from their
418 * corresponding Text labels; a hashing scheme can be introduced later if
419 * this turns out to be a problem.
420 * ------------------------------------------------------------------------*/
423 Text DEFTABLE(tabExt,NUM_EXT); /* Storage for Ext names */
426 Ext mkExt(t) /* Allocate or find an Ext value */
432 if (extHw-EXTMIN >= NUM_EXT) {
433 ERRMSG(0) "Ext storage space exhausted"
441 /* --------------------------------------------------------------------------
444 * A Tycon represents a user defined type constructor. Tycons are indexed
445 * by Text values ... a very simple hash function is used to improve lookup
446 * times. Tycon entries with the same hash code are chained together, with
447 * the most recent entry at the front of the list.
448 * ------------------------------------------------------------------------*/
450 #define TYCONHSZ 256 /* Size of Tycon hash table*/
451 #define tHash(x) ((x)%TYCONHSZ) /* Tycon hash function */
452 static Tycon tyconHw; /* next unused Tycon */
453 static Tycon DEFTABLE(tyconHash,TYCONHSZ); /* Hash table storage */
454 struct strTycon DEFTABLE(tabTycon,NUM_TYCON); /* Tycon storage */
456 Tycon newTycon(t) /* add new tycon to tycon table */
459 if (tyconHw-TYCMIN >= NUM_TYCON) {
460 ERRMSG(0) "Type constructor storage space exhausted"
463 tycon(tyconHw).text = t; /* clear new tycon record */
464 tycon(tyconHw).kind = NIL;
465 tycon(tyconHw).defn = NIL;
466 tycon(tyconHw).what = NIL;
467 tycon(tyconHw).conToTag = NIL;
468 tycon(tyconHw).tagToCon = NIL;
469 tycon(tyconHw).tuple = -1;
470 tycon(tyconHw).mod = currentModule;
471 tycon(tyconHw).itbl = NULL;
472 module(currentModule).tycons = cons(tyconHw,module(currentModule).tycons);
473 tycon(tyconHw).nextTyconHash = tyconHash[h];
474 tyconHash[h] = tyconHw;
479 Tycon findTycon(t) /* locate Tycon in tycon table */
481 Tycon tc = tyconHash[tHash(t)];
483 while (nonNull(tc) && tycon(tc).text!=t)
484 tc = tycon(tc).nextTyconHash;
488 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
490 Tycon oldtc = findTycon(tycon(tc).text);
493 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
499 static Void local hashTycon(tc) /* Insert Tycon into hash table */
501 assert(isTycon(tc) || isTuple(tc));
503 Text t = tycon(tc).text;
505 tycon(tc).nextTyconHash = tyconHash[h];
510 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
512 if (!isPair(id)) internal("findQualTycon");
516 return findTycon(textOf(id));
518 Text t = qtextOf(id);
519 Module m = findQualifier(qmodOf(id));
521 if (isNull(m)) return NIL;
522 for(es=module(m).exports; nonNull(es); es=tl(es)) {
524 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
529 default : internal("findQualTycon2");
531 return NIL; /* NOTREACHED */
534 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
540 Tycon tc = newTycon(t);
542 tycon(tc).kind = kind;
543 tycon(tc).what = what;
544 tycon(tc).defn = defn;
545 tycon(tc).arity = ar;
549 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
554 String s = textToStr(tycon(tc).text);
556 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
557 if (hd(curr)==tc) /* just in case we get duplicates! */
563 tl(prev) = cons(tc,curr);
567 return cons(tc,curr);
570 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
571 String pat; /* to list of Tycons ts */
572 List ts; { /* Null pattern matches every tycon*/
573 Tycon tc; /* (Tycons with NIL kind excluded) */
574 for (tc=TYCMIN; tc<tyconHw; ++tc)
575 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
576 if (nonNull(tycon(tc).kind))
577 ts = insertTycon(tc,ts);
581 Text ghcTupleText_n ( Int n )
585 if (n < 0 || n >= 100) internal("ghcTupleText_n");
587 for (i = 1; i <= n; i++) buf[i] = ',';
590 return findText(buf);
593 Text ghcTupleText(tup)
595 assert(isTuple(tup));
596 return ghcTupleText_n ( tupleOf(tup) );
600 Tycon mkTuple ( Int n )
604 internal("mkTuple: request for tuple of unsupported size");
605 for (i = TYCMIN; i < tyconHw; i++)
606 if (tycon(i).tuple == n) return i;
607 internal("mkTuple: request for non-existent tuple");
610 Void allocTupleTycon ( Int n )
615 for (i = TYCMIN; i < tyconHw; i++)
616 if (tycon(i).tuple == n) return;
618 //t = addPrimTycon(findText(buf),simpleKind(n),n, DATATYPE,NIL);
621 for (i = 0; i < n; i++) k = ap(STAR,k);
622 t = newTycon(ghcTupleText_n(n));
625 tycon(t).what = DATATYPE;
628 /* --------------------------------------------------------------------------
631 * A Name represents a top level binding of a value to an identifier.
632 * Such values may be a constructor function, a member function in a
633 * class, a user-defined or primitive value/function.
635 * Names are indexed by Text values ... a very simple hash functions speeds
636 * access to the table of Names and Name entries with the same hash value
637 * are chained together, with the most recent entry at the front of the
639 * ------------------------------------------------------------------------*/
641 #define NAMEHSZ 256 /* Size of Name hash table */
642 #define nHash(x) ((x)%NAMEHSZ) /* hash fn :: Text->Int */
643 Name nameHw; /* next unused name */
644 static Name DEFTABLE(nameHash,NAMEHSZ); /* Hash table storage */
645 struct strName DEFTABLE(tabName,NUM_NAME); /* Name table storage */
647 Name newName(t,parent) /* Add new name to name table */
651 if (nameHw-NAMEMIN >= NUM_NAME) {
652 ERRMSG(0) "Name storage space exhausted"
655 name(nameHw).text = t; /* clear new name record */
656 name(nameHw).line = 0;
657 name(nameHw).syntax = NO_SYNTAX;
658 name(nameHw).parent = parent;
659 name(nameHw).arity = 0;
660 name(nameHw).number = EXECNAME;
661 name(nameHw).defn = NIL;
662 name(nameHw).stgVar = NIL;
663 name(nameHw).callconv = NIL;
664 name(nameHw).type = NIL;
665 name(nameHw).primop = 0;
666 name(nameHw).mod = currentModule;
667 name(nameHw).itbl = NULL;
668 module(currentModule).names=cons(nameHw,module(currentModule).names);
669 name(nameHw).nextNameHash = nameHash[h];
670 nameHash[h] = nameHw;
674 Name findName(t) /* Locate name in name table */
676 Name n = nameHash[nHash(t)];
678 while (nonNull(n) && name(n).text!=t)
679 n = name(n).nextNameHash;
683 Name addName(nm) /* Insert Name in name table - if */
684 Name nm; { /* no clash is caused */
685 Name oldnm = findName(name(nm).text);
688 module(currentModule).names=cons(nm,module(currentModule).names);
694 static Void local hashName(nm) /* Insert Name into hash table */
701 name(nm).nextNameHash = nameHash[h];
705 Name findQualName(id) /* Locate (possibly qualified) name*/
706 Cell id; { /* in name table */
708 internal("findQualName");
714 return findName(textOf(id));
716 Text t = qtextOf(id);
717 Module m = findQualifier(qmodOf(id));
719 if (isNull(m)) return NIL;
720 for(es=module(m).exports; nonNull(es); es=tl(es)) {
722 if (isName(e) && name(e).text==t)
724 else if (isPair(e) && DOTDOT==snd(e)) {
725 List subentities = NIL;
728 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
729 subentities = tycon(c).defn;
731 subentities = cclass(c).members;
732 for(; nonNull(subentities); subentities=tl(subentities)) {
733 if (!isName(hd(subentities)))
734 internal("findQualName3");
735 if (name(hd(subentities)).text == t)
736 return hd(subentities);
742 default : internal("findQualName2");
744 return 0; /* NOTREACHED */
748 Name nameFromStgVar ( StgVar v )
751 for (n = NAMEMIN; n < nameHw; n++)
752 if (name(n).stgVar == v) return n;
756 void* getHugs_AsmObject_for ( char* s )
759 Text t = findText(s);
761 for (n = NAMEMIN; n < nameHw; n++)
762 if (name(n).text == t) break;
763 if (n == nameHw) internal("getHugs_AsmObject_for(1)");
765 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
766 internal("getHugs_AsmObject_for(2)");
767 return ptrOf(stgVarInfo(v));
770 /* --------------------------------------------------------------------------
771 * Primitive functions:
772 * ------------------------------------------------------------------------*/
774 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
775 Text t; /* sets rep, not type */
778 Int rep; { /* Really AsmRep */
779 Name n = newName(t,NIL);
780 name(n).arity = arity;
781 name(n).number = cfunNo(no);
783 name(n).primop = (void*)rep;
788 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
793 Name n = newName(t,NIL);
794 name(n).arity = arity;
795 name(n).number = cfunNo(no);
801 Int sfunPos(s,c) /* Find position of field with */
802 Name s; /* selector s in constructor c. */
806 for (; nonNull(cns); cns=tl(cns))
808 return intOf(snd(hd(cns)));
810 return 0;/* NOTREACHED */
813 static List local insertName(nm,ns) /* insert name nm into sorted list */
818 String s = textToStr(name(nm).text);
820 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
821 if (hd(curr)==nm) /* just in case we get duplicates! */
827 tl(prev) = cons(nm,curr);
831 return cons(nm,curr);
834 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
835 String pat; /* to list of names ns */
836 List ns; { /* Null pattern matches every name */
837 Name nm; /* (Names with NIL type, or hidden */
839 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
840 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
841 String str = textToStr(name(nm).text);
842 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
843 ns = insertName(nm,ns);
847 List mns = module(currentModule).names;
848 for(; nonNull(mns); mns=tl(mns)) {
850 if (!inventedText(name(nm).text)) {
851 String str = textToStr(name(nm).text);
852 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
853 ns = insertName(nm,ns);
860 /* --------------------------------------------------------------------------
861 * A simple string matching routine
862 * `*' matches any sequence of zero or more characters
863 * `?' matches any single character exactly
864 * `@str' matches the string str exactly (ignoring any special chars)
865 * `\c' matches the character c only (ignoring special chars)
866 * c matches the character c only
867 * ------------------------------------------------------------------------*/
869 static Void local patternError(s) /* report error in pattern */
871 ERRMSG(0) "%s in pattern", s
875 static Bool local stringMatch(pat,str) /* match string against pattern */
881 case '\0' : return (*str=='\0');
884 if (stringMatch(pat+1,str))
889 case '?' : if (*str++=='\0')
894 case '[' : { Bool found = FALSE;
895 while (*++pat!='\0' && *pat!=']')
896 if (!found && ( pat[0] == *str ||
905 patternError("missing `]'");
913 case '\\' : if (*++pat == '\0')
914 patternError("extra trailing `\\'");
916 default : if (*pat++ != *str++)
922 /* --------------------------------------------------------------------------
923 * Storage of type classes, instances etc...:
924 * ------------------------------------------------------------------------*/
926 static Class classHw; /* next unused class */
927 static List classes; /* list of classes in current scope */
928 static Inst instHw; /* next unused instance record */
930 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
931 struct strInst far *tabInst; /* (pointer to) table of instances */
933 Class newClass(t) /* add new class to class table */
935 if (classHw-CLASSMIN >= NUM_CLASSES) {
936 ERRMSG(0) "Class storage space exhausted"
939 cclass(classHw).text = t;
940 cclass(classHw).arity = 0;
941 cclass(classHw).kinds = NIL;
942 cclass(classHw).head = NIL;
943 cclass(classHw).fds = NIL;
944 cclass(classHw).xfds = NIL;
945 cclass(classHw).dcon = NIL;
946 cclass(classHw).supers = NIL;
947 cclass(classHw).dsels = NIL;
948 cclass(classHw).members = NIL;
949 cclass(classHw).defaults = NIL;
950 cclass(classHw).instances = NIL;
951 classes=cons(classHw,classes);
952 cclass(classHw).mod = currentModule;
953 module(currentModule).classes=cons(classHw,module(currentModule).classes);
957 Class classMax() { /* Return max Class in use ... */
958 return classHw; /* This is a bit ugly, but it's not*/
959 } /* worth a lot of effort right now */
961 Class findClass(t) /* look for named class in table */
965 for (cs=classes; nonNull(cs); cs=tl(cs)) {
967 if (cclass(cl).text==t)
973 Class addClass(c) /* Insert Class in class list */
974 Class c; { /* - if no clash caused */
975 Class oldc = findClass(cclass(c).text);
977 classes=cons(c,classes);
978 module(currentModule).classes=cons(c,module(currentModule).classes);
985 Class findQualClass(c) /* Look for (possibly qualified) */
986 Cell c; { /* class in class list */
987 if (!isQualIdent(c)) {
988 return findClass(textOf(c));
991 Module m = findQualifier(qmodOf(c));
995 for (es=module(m).exports; nonNull(es); es=tl(es)) {
997 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
1004 Inst newInst() { /* Add new instance to table */
1005 if (instHw-INSTMIN >= NUM_INSTS) {
1006 ERRMSG(0) "Instance storage space exhausted"
1009 inst(instHw).kinds = NIL;
1010 inst(instHw).head = NIL;
1011 inst(instHw).specifics = NIL;
1012 inst(instHw).implements = NIL;
1013 inst(instHw).builder = NIL;
1014 inst(instHw).mod = currentModule;
1020 extern Void printInst Args((Inst));
1024 Class cl = inst(in).c;
1025 Printf("%s-", textToStr(cclass(cl).text));
1026 printType(stdout,inst(in).t);
1028 #endif /* DEBUG_DICTS */
1030 Inst findFirstInst(tc) /* look for 1st instance involving */
1031 Tycon tc; { /* the type constructor tc */
1032 return findNextInst(tc,INSTMIN-1);
1035 Inst findNextInst(tc,in) /* look for next instance involving*/
1036 Tycon tc; /* the type constructor tc */
1037 Inst in; { /* starting after instance in */
1038 while (++in < instHw) {
1039 Cell pi = inst(in).head;
1040 for (; isAp(pi); pi=fun(pi))
1041 if (typeInvolves(arg(pi),tc))
1047 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1048 Type ty; /* type constructor/tuple tc. */
1051 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1052 || typeInvolves(arg(ty),tc)));
1055 Inst findSimpleInstance ( ConId klass, ConId dataty )
1058 for (in = INSTMIN; in < instHw; in++) {
1059 Cell head = inst(in).head;
1060 if (isClass(fun(head))
1061 && cclass(fun(head)).text==textOf(klass)
1062 && typeInvolves(arg(head), findTycon(textOf(dataty)) )
1069 /* --------------------------------------------------------------------------
1072 * Various parts of the system use a stack of cells. Most of the stack
1073 * operations are defined as macros, expanded inline.
1074 * ------------------------------------------------------------------------*/
1076 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
1077 StackPtr sp; /* stack pointer */
1079 #if GIMME_STACK_DUMPS
1081 #define UPPER_DISP 5 /* # display entries on top of stack */
1082 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
1084 Void hugsStackOverflow() { /* Report stack overflow */
1086 extern Cell evalRoots[];
1088 ERRMSG(0) "Control stack overflow" ETHEN
1091 if (rootsp>=UPPER_DISP+LOWER_DISP) {
1092 for (i=0; i<UPPER_DISP; i++) {
1093 ERRTEXT "\nwhile evaluating: " ETHEN
1094 ERREXPR(evalRoots[rootsp-i]);
1096 ERRTEXT "\n..." ETHEN
1097 for (i=LOWER_DISP-1; i>=0; i--) {
1098 ERRTEXT "\nwhile evaluating: " ETHEN
1099 ERREXPR(evalRoots[i]);
1103 for (i=rootsp; i>=0; i--) {
1104 ERRTEXT "\nwhile evaluating: " ETHEN
1105 ERREXPR(evalRoots[i]);
1113 #else /* !GIMME_STACK_DUMPS */
1115 Void hugsStackOverflow() { /* Report stack overflow */
1116 ERRMSG(0) "Control stack overflow"
1120 #endif /* !GIMME_STACK_DUMPS */
1122 /* --------------------------------------------------------------------------
1125 * A Module represents a user defined module.
1127 * Note: there are now two lookup mechanisms in the system:
1129 * 1) The exports from a module are stored in a big list.
1130 * We resolve qualified names, and import lists by linearly scanning
1131 * through this list.
1133 * 2) Unqualified imports and local definitions for the current module
1134 * are stored in hash tables (tyconHash and nameHash) or linear lists
1137 * ------------------------------------------------------------------------*/
1139 static Module moduleHw; /* next unused Module */
1140 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
1141 Module currentModule; /* Module currently being processed*/
1143 Bool isValidModule(m) /* is m a legitimate module id? */
1145 return (MODMIN <= m && m < moduleHw);
1148 Module newModule(t) /* add new module to module table */
1150 if (moduleHw-MODMIN >= NUM_MODULE) {
1151 ERRMSG(0) "Module storage space exhausted"
1154 module(moduleHw).text = t; /* clear new module record */
1155 module(moduleHw).qualImports = NIL;
1156 module(moduleHw).exports = NIL;
1157 module(moduleHw).tycons = NIL;
1158 module(moduleHw).names = NIL;
1159 module(moduleHw).classes = NIL;
1160 module(moduleHw).oImage = NULL;
1161 module(moduleHw).oTab = NULL;
1162 module(moduleHw).sizeoTab = 0;
1163 module(moduleHw).usedoTab = 0;
1164 module(moduleHw).dlTab = NULL;
1165 module(moduleHw).sizedlTab = 0;
1166 module(moduleHw).useddlTab = 0;
1170 void ppModules ( void )
1173 fflush(stderr); fflush(stdout);
1174 printf ( "begin MODULES\n" );
1175 for (i = moduleHw-1; i >= MODMIN; i--)
1176 printf ( " %2d: %16s\n",
1177 i-MODMIN, textToStr(module(i).text)
1179 printf ( "end MODULES\n" );
1180 fflush(stderr); fflush(stdout);
1184 Module findModule(t) /* locate Module in module table */
1187 for(m=MODMIN; m<moduleHw; ++m) {
1188 if (module(m).text==t)
1194 Module findModid(c) /* Find module by name or filename */
1196 switch (whatIs(c)) {
1197 case STRCELL : { Script s = scriptThisFile(snd(c));
1198 return (s==-1) ? NIL : moduleOfScript(s);
1200 case CONIDCELL : return findModule(textOf(c));
1201 default : internal("findModid");
1203 return NIL;/*NOTUSED*/
1206 static local Module findQualifier(t) /* locate Module in import list */
1209 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1210 if (textOf(fst(hd(ms)))==t)
1214 if (module(currentModule).text==t)
1215 return currentModule;
1220 Void setCurrModule(m) /* set lookup tables for current module */
1223 assert(isModule(m));
1224 if (m!=currentModule) {
1225 currentModule = m; /* This is the only assignment to currentModule */
1226 for (i=0; i<TYCONHSZ; ++i)
1228 mapProc(hashTycon,module(m).tycons);
1229 for (i=0; i<NAMEHSZ; ++i)
1231 mapProc(hashName,module(m).names);
1232 classes = module(m).classes;
1236 Name jrsFindQualName ( Text mn, Text sn )
1241 for (m=MODMIN; m<moduleHw; m++)
1242 if (module(m).text == mn) break;
1243 if (m == moduleHw) return NIL;
1245 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1246 if (name(hd(ns)).text == sn) return hd(ns);
1252 /* A bit tricky. Assumes that if tab==NULL, then
1253 currUsed and *currSize must be zero.
1256 void* genericExpand ( void* tab,
1257 int* currSize, int currUsed,
1258 int initSize, int elemSize )
1262 if (currUsed < *currSize)
1264 size2 = (*currSize == 0) ? initSize : (2 * *currSize);
1265 tab2 = malloc ( size2 * elemSize );
1267 ERRMSG(0) "Can't allocate enough memory to resize a table"
1271 memcpy ( tab2, tab, elemSize * *currSize );
1273 if (tab) free ( tab );
1277 void addOTabName ( Module m, char* nm, void* ad )
1280 = genericExpand ( module(m).oTab,
1281 &module(m).sizeoTab,
1285 module(m).oTab[ module(m).usedoTab ].nm = nm;
1286 module(m).oTab[ module(m).usedoTab ].ad = ad;
1287 module(m).usedoTab++;
1291 void addDLSect ( Module m, void* start, void* end, DLSect sect )
1294 = genericExpand ( module(m).dlTab,
1295 &module(m).sizedlTab,
1296 module(m).useddlTab,
1297 4, sizeof(DLTabEnt) );
1298 module(m).dlTab[ module(m).useddlTab ].start = start;
1299 module(m).dlTab[ module(m).useddlTab ].end = end;
1300 module(m).dlTab[ module(m).useddlTab ].sect = sect;
1301 module(m).useddlTab++;
1305 void* lookupOTabName ( Module m, char* nm )
1308 for (i = 0; i < module(m).usedoTab; i++) {
1311 "lookupOTabName: request %s, table has %s\n",
1312 nm, module(m).oTab[i].nm );
1313 if (0==strcmp(nm,module(m).oTab[i].nm))
1314 return module(m).oTab[i].ad;
1320 char* nameFromOPtr ( void* p )
1324 for (m=MODMIN; m<moduleHw; m++)
1325 for (i = 0; i < module(m).usedoTab; i++)
1326 if (p == module(m).oTab[i].ad)
1327 return module(m).oTab[i].nm;
1332 DLSect lookupDLSect ( void* ad )
1336 for (m=MODMIN; m<moduleHw; m++)
1337 for (i = 0; i < module(m).useddlTab; i++)
1338 if (module(m).dlTab[i].start <= ad &&
1339 ad <= module(m).dlTab[i].end)
1340 return module(m).dlTab[i].sect;
1341 return HUGS_DL_SECTION_OTHER;
1345 /* --------------------------------------------------------------------------
1346 * Script file storage:
1348 * script files are read into the system one after another. The state of
1349 * the stored data structures (except the garbage-collected heap) is recorded
1350 * before reading a new script. In the event of being unable to read the
1351 * script, or if otherwise requested, the system can be restored to its
1352 * original state immediately before the file was read.
1353 * ------------------------------------------------------------------------*/
1355 typedef struct { /* record of storage state prior to */
1356 Text file; /* reading script/module */
1370 #ifdef DEBUG_SHOWUSE
1371 static Void local showUse(msg,val,mx)
1374 Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1378 static Script scriptHw; /* next unused script number */
1379 static script scripts[NUM_SCRIPTS]; /* storage for script records */
1382 void ppScripts ( void )
1385 fflush(stderr); fflush(stdout);
1386 printf ( "begin SCRIPTS\n" );
1387 for (i = scriptHw-1; i >= 0; i--)
1388 printf ( " %2d: %16s tH=%d mH=%d yH=%d "
1389 "nH=%d cH=%d iH=%d nnS=%d,%d\n",
1390 i, textToStr(scripts[i].file),
1391 scripts[i].textHw, scripts[i].moduleHw,
1392 scripts[i].tyconHw, scripts[i].nameHw,
1393 scripts[i].classHw, scripts[i].instHw,
1394 scripts[i].nextNewText, scripts[i].nextNewDText
1396 printf ( "end SCRIPTS\n" );
1397 fflush(stderr); fflush(stdout);
1400 Script startNewScript(f) /* start new script, keeping record */
1401 String f; { /* of status for later restoration */
1402 if (scriptHw >= NUM_SCRIPTS) {
1403 ERRMSG(0) "Too many script files in use"
1406 #ifdef DEBUG_SHOWUSE
1407 showUse("Text", textHw, NUM_TEXT);
1408 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
1409 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
1410 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
1411 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
1412 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
1414 showUse("Ext", extHw-EXTMIN, NUM_EXT);
1417 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
1418 scripts[scriptHw].textHw = textHw;
1419 scripts[scriptHw].nextNewText = nextNewText;
1420 scripts[scriptHw].nextNewDText = nextNewDText;
1421 scripts[scriptHw].moduleHw = moduleHw;
1422 scripts[scriptHw].tyconHw = tyconHw;
1423 scripts[scriptHw].nameHw = nameHw;
1424 scripts[scriptHw].classHw = classHw;
1425 scripts[scriptHw].instHw = instHw;
1427 scripts[scriptHw].extHw = extHw;
1432 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1433 return (scriptHw==0);
1436 Bool moduleThisScript(m) /* Test if given module is defined */
1437 Module m; { /* in current script file */
1438 return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
1441 Module lastModule() { /* Return module in current script file */
1442 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1445 #define scriptThis(nm,t,tag) Script nm(x) \
1449 && x>=scripts[s].tag) \
1453 scriptThis(scriptThisName,Name,nameHw)
1454 scriptThis(scriptThisTycon,Tycon,tyconHw)
1455 scriptThis(scriptThisInst,Inst,instHw)
1456 scriptThis(scriptThisClass,Class,classHw)
1459 Module moduleOfScript(s)
1461 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1464 String fileOfModule(m)
1467 if (m == modulePrelude) {
1470 for(s=0; s<scriptHw; ++s) {
1471 if (scripts[s].moduleHw == m) {
1472 return textToStr(scripts[s].file);
1478 Script scriptThisFile(f)
1481 for (s=0; s < scriptHw; ++s) {
1482 if (scripts[s].file == f) {
1486 if (f == findText(STD_PRELUDE)) {
1492 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1493 Script sno; { /* to reading script sno */
1494 if (sno<scriptHw) { /* is there anything to restore? */
1496 textHw = scripts[sno].textHw;
1497 nextNewText = scripts[sno].nextNewText;
1498 nextNewDText = scripts[sno].nextNewDText;
1499 moduleHw = scripts[sno].moduleHw;
1500 tyconHw = scripts[sno].tyconHw;
1501 nameHw = scripts[sno].nameHw;
1502 classHw = scripts[sno].classHw;
1503 instHw = scripts[sno].instHw;
1505 dictHw = scripts[sno].dictHw;
1508 extHw = scripts[sno].extHw;
1512 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1513 if (module(i).objectFile) {
1514 printf("[bogus] closing objectFile for module %d\n",i);
1515 /*dlclose(module(i).objectFile);*/
1518 moduleHw = scripts[sno].moduleHw;
1520 for (i=0; i<TEXTHSZ; ++i) {
1522 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1523 && textHash[i][j]<textHw)
1526 textHash[i][j] = NOTEXT;
1530 for (i=0; i<TYCONHSZ; ++i) {
1533 for (i=0; i<NAMEHSZ; ++i) {
1537 for (i=CLASSMIN; i<classHw; i++) {
1538 List ins = cclass(i).instances;
1541 while (nonNull(ins)) {
1542 List temp = tl(ins);
1543 if (hd(ins)<instHw) {
1549 cclass(i).instances = rev(is);
1556 /* --------------------------------------------------------------------------
1559 * Provides a garbage collectable heap for storage of expressions etc.
1561 * Now incorporates a flat resource: A two-space collected extension of
1562 * the heap that provides storage for contiguous arrays of Cell storage,
1563 * cooperating with the garbage collection mechanisms for the main heap.
1564 * ------------------------------------------------------------------------*/
1566 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1567 Heap heapFst; /* array of fst component of pairs */
1568 Heap heapSnd; /* array of snd component of pairs */
1575 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1576 /* C stack; use with extreme care! */
1578 Int numGcs; /* number of garbage collections */
1579 Int cellsRecovered; /* number of cells recovered */
1581 static Cell freeList; /* free list of unused cells */
1582 static Cell lsave, rsave; /* save components of pair */
1586 static Int markCount, stackRoots;
1588 #define initStackRoots() stackRoots = 0
1589 #define recordStackRoot() stackRoots++
1602 #define start() markCount = 0
1603 #define end(thing,rs) \
1605 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1608 #define recordMark() markCount++
1610 #else /* !GC_STATISTICS */
1615 #define initStackRoots()
1616 #define recordStackRoot()
1619 #define end(thing,root)
1620 #define recordMark()
1622 #endif /* !GC_STATISTICS */
1624 Cell pair(l,r) /* Allocate pair (l, r) from */
1625 Cell l, r; { /* heap, garbage collecting first */
1626 Cell c = freeList; /* if necessary ... */
1638 freeList = snd(freeList);
1645 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1646 Cell dst, src; { /* both *MUST* be pairs */
1647 if (isPair(dst) && isPair(src)) {
1648 fst(dst) = fst(src);
1649 snd(dst) = snd(src);
1652 internal("overwrite");
1656 static Int marksSize;
1658 Cell markExpr(c) /* External interface to markCell */
1660 return isGenPair(c) ? markCell(c) : c;
1663 static Cell local markCell(c) /* Traverse part of graph marking */
1664 Cell c; { /* cells reachable from given root */
1665 /* markCell(c) is only called if c */
1667 { register int place = placeInSet(c);
1668 register int mask = maskInSet(c);
1669 if (marks[place]&mask)
1672 marks[place] |= mask;
1677 /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1678 if (isGenPair(fst(c))) {
1680 fst(c) = markCell(fst(c));
1683 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1691 static Void local markSnd(c) /* Variant of markCell used to */
1692 Cell c; { /* update snd component of cell */
1693 Cell t; /* using tail recursion */
1695 ma: t = c; /* Keep pointer to original pair */
1700 { register int place = placeInSet(c);
1701 register int mask = maskInSet(c);
1702 if (marks[place]&mask)
1705 marks[place] |= mask;
1710 if (isGenPair(fst(c))) {
1711 fst(c) = markCell(fst(c));
1714 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1719 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1720 Cell n; { /* it was a cell ref, but don't */
1721 /* move cell so we don't have */
1722 /* to modify the stored value of n */
1729 Void garbageCollect() { /* Run garbage collector ... */
1730 Bool breakStat = breakOn(FALSE); /* disable break checking */
1736 jmp_buf regs; /* save registers on stack */
1740 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1743 everybody(MARK); /* Mark all components of system */
1745 gcScanning(); /* scan mark set */
1752 for (i=1; i<=heapSize; i++) {
1753 if ((marks[place] & mask) == 0) {
1760 if (++j == bitsPerWord) {
1767 gcRecovered(recovered);
1768 breakOn(breakStat); /* restore break trapping if nec. */
1772 /* can only return if freeList is nonempty on return. */
1773 if (recovered<minRecovery || isNull(freeList)) {
1774 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1777 cellsRecovered = recovered;
1780 /* --------------------------------------------------------------------------
1781 * Code for saving last expression entered:
1783 * This is a little tricky because some text values (e.g. strings or variable
1784 * names) may not be defined or have the same value when the expression is
1785 * recalled. These text values are therefore saved in the top portion of
1787 * ------------------------------------------------------------------------*/
1789 static Cell lastExprSaved; /* last expression to be saved */
1791 Void setLastExpr(e) /* save expression for later recall*/
1793 lastExprSaved = NIL; /* in case attempt to save fails */
1794 savedText = NUM_TEXT;
1795 lastExprSaved = lowLevelLastIn(e);
1798 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
1799 Cell c; { /* acyclic graph) for later recall */
1800 if (isPair(c)) { /* Duplicating any text strings */
1801 if (isBoxTag(fst(c))) /* in case these are lost at some */
1802 switch (fst(c)) { /* point before the expr is reused */
1808 case STRCELL : return pair(fst(c),saveText(textOf(c)));
1809 default : return pair(fst(c),snd(c));
1812 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
1816 return pair(EXTCOPY,saveText(extText(c)));
1822 Cell getLastExpr() { /* recover previously saved expr */
1823 return lowLevelLastOut(lastExprSaved);
1826 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
1827 Cell c; { /* except that Cells refering to */
1828 if (isPair(c)) { /* Text values are restored to */
1829 if (isBoxTag(fst(c))) /* appropriate values */
1836 case STRCELL : return pair(fst(c),
1837 findText(text+intValOf(c)));
1839 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
1841 default : return pair(fst(c),snd(c));
1844 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
1850 /* --------------------------------------------------------------------------
1851 * Miscellaneous operations on heap cells:
1852 * ------------------------------------------------------------------------*/
1854 /* Profiling suggests that the number of calls to whatIs() is typically */
1855 /* rather high. The recoded version below attempts to improve the average */
1856 /* performance for whatIs() using a binary search for part of the analysis */
1858 Cell whatIs(c) /* identify type of cell */
1861 register Cell fstc = fst(c);
1862 return isTag(fstc) ? fstc : AP;
1864 if (c<OFFMIN) return c;
1866 if (isExt(c)) return EXT;
1868 if (c>=INTMIN) return INTCELL;
1870 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
1872 else if (c>=INSTMIN) return INSTANCE;
1874 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
1875 else return MODULE;}
1876 else if (c>=OFFMIN) return OFFSET;
1878 else return (c>=EXTMIN) ?
1885 register Cell fstc = fst(c);
1886 return isTag(fstc) ? fstc : AP;
1888 if (c>=INTMIN) return INTCELL;
1889 if (c>=CHARMIN) return CHARCELL;
1890 if (c>=CLASSMIN) return CLASS;
1891 if (c>=INSTMIN) return INSTANCE;
1892 if (c>=NAMEMIN) return NAME;
1893 if (c>=TYCMIN) return TYCON;
1894 if (c>=MODMIN) return MODULE;
1895 if (c>=OFFMIN) return OFFSET;
1897 if (c>=EXTMIN) return EXT;
1899 if (c>=TUPMIN) return TUPLE;
1904 /* A very, very simple printer.
1905 * Output is uglier than from printExp - but the printer is more
1906 * robust and can be used on any data structure irrespective of
1909 Void print Args((Cell, Int));
1910 Void print(c, depth)
1915 #if 0 /* Not in this version of Hugs */
1916 } else if (isPair(c) && !isGenPair(c)) {
1917 extern Void printEvalCell Args((Cell, Int));
1918 printEvalCell(c,depth);
1921 Int tag = whatIs(c);
1925 print(fst(c), depth-1);
1927 print(snd(c), depth-1);
1931 Printf("free(%d)", c);
1934 Printf("int(%d)", intOf(c));
1937 Printf("bignum(%s)", bignumToString(c));
1940 Printf("char('%c')", charOf(c));
1943 Printf("ptr(%p)",ptrOf(c));
1946 Printf("class(%d)", c-CLASSMIN);
1947 if (CLASSMIN <= c && c < classHw) {
1948 Printf("=\"%s\"", textToStr(cclass(c).text));
1952 Printf("instance(%d)", c - INSTMIN);
1955 Printf("name(%d)", c-NAMEMIN);
1956 if (NAMEMIN <= c && c < nameHw) {
1957 Printf("=\"%s\"", textToStr(name(c).text));
1961 Printf("tycon(%d)", c-TYCMIN);
1962 if (TYCMIN <= c && c < tyconHw)
1963 Printf("=\"%s\"", textToStr(tycon(c).text));
1966 Printf("module(%d)", c - MODMIN);
1969 Printf("Offset %d", offsetOf(c));
1972 Printf("%s", textToStr(ghcTupleText(tupleOf(c))));
1976 print(snd(c),depth-1);
1980 print(snd(c),depth-1);
1984 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
1985 Printf("%d ", intOf(fst(snd(c))));
1986 print(snd(snd(c)),depth-1);
1988 print(snd(c),depth-1);
2005 Printf("{dict %d}",textOf(c));
2011 Printf("{id %s}",textToStr(textOf(c)));
2015 Printf("{ip %s}",textToStr(textOf(c)));
2018 Printf("?%s",textToStr(textOf(c)));
2022 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2026 print(fst(snd(c)),depth-1);
2028 print(snd(snd(c)),depth-1);
2033 print(snd(c),depth-1);
2038 print(snd(c),depth-1);
2043 print(fst(snd(c)),depth-1);
2045 print(snd(snd(c)),depth-1);
2050 print(fst(snd(c)),depth-1);
2052 print(snd(snd(c)),depth-1);
2056 Printf("FromQual(");
2057 print(fst(snd(c)),depth-1);
2059 print(snd(snd(c)),depth-1);
2063 Printf("StgVar%d=",-c);
2064 print(snd(c), depth-1);
2068 print(fst(snd(c)),depth-1);
2070 print(snd(snd(c)),depth-1);
2075 print(fst(snd(c)),depth-1);
2077 print(snd(snd(c)),depth-1);
2082 print(fst(snd(c)),depth-1);
2084 print(snd(snd(c)),depth-1);
2088 Printf("PrimCase(");
2089 print(fst(snd(c)),depth-1);
2091 print(snd(snd(c)),depth-1);
2096 print(snd(c),depth-1);
2100 Printf("(UNBOXEDTUP,");
2101 print(snd(c),depth-1);
2106 print(snd(c),depth-1);
2110 print(snd(c),depth-1);
2114 if (isBoxTag(tag)) {
2115 Printf("Tag(%d)=%d", c, tag);
2116 } else if (isConTag(tag)) {
2117 Printf("%d@(%d,",c,tag);
2118 print(snd(c), depth-1);
2121 } else if (c == tag) {
2122 Printf("Tag(%d)", c);
2124 Printf("Tag(%d)=%d", c, tag);
2133 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2134 Cell c; { /* also recognises DICTVAR cells */
2136 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2139 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2141 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2144 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2146 if (!isPair(c)) return FALSE;
2149 case VAROPCELL : return TRUE;
2151 case QUALIDENT : return isVar(snd(snd(c)));
2153 default : return FALSE;
2157 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2159 if (!isPair(c)) return FALSE;
2162 case CONOPCELL : return TRUE;
2164 case QUALIDENT : return isCon(snd(snd(c)));
2166 default : return FALSE;
2170 Bool isQualIdent(c) /* is cell a qualified identifier? */
2172 return isPair(c) && (fst(c)==QUALIDENT);
2175 Bool isIdent(c) /* is cell an identifier? */
2177 if (!isPair(c)) return FALSE;
2182 case CONOPCELL : return TRUE;
2184 case QUALIDENT : return TRUE;
2186 default : return FALSE;
2190 Bool isInt(c) /* cell holds integer value? */
2192 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2195 Int intOf(c) /* find integer value of cell? */
2199 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
2202 Cell mkInt(n) /* make cell representing integer */
2204 return (MINSMALLINT <= n && n <= MAXSMALLINT)
2209 #if SIZEOF_INTP == SIZEOF_INT
2210 typedef union {Int i; Ptr p;} IntOrPtr;
2216 return pair(PTRCELL,x.i);
2223 assert(fst(c) == PTRCELL);
2232 return pair(CPTRCELL,x.i);
2239 assert(fst(c) == CPTRCELL);
2243 #elif SIZEOF_INTP == 2*SIZEOF_INT
2244 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2250 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2257 assert(fst(c) == PTRCELL);
2258 x.i.i1 = intOf(fst(snd(c)));
2259 x.i.i2 = intOf(snd(snd(c)));
2263 #warning "type Addr not supported on this architecture - don't use it"
2267 ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
2274 ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
2279 String stringNegate( s )
2287 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2292 /* --------------------------------------------------------------------------
2294 * ------------------------------------------------------------------------*/
2296 Int length(xs) /* calculate length of list xs */
2299 for (; nonNull(xs); ++n)
2304 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2305 List xs, ys; { /* ys by modifying xs ... */
2310 while (nonNull(tl(zs)))
2317 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2320 for (; nonNull(xs); xs=tl(xs))
2321 ys = cons(hd(xs),ys);
2325 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2328 return revOnto(dupOnto(xs,NIL),ys);
2331 List dupList(xs) /* Duplicate spine of list xs */
2334 for (; nonNull(xs); xs=tl(xs))
2335 ys = cons(hd(xs),ys);
2339 List revOnto(xs,ys) /* Destructively reverse elements of*/
2340 List xs, ys; { /* list xs onto list ys... */
2343 while (nonNull(xs)) {
2352 Cell varIsMember(t,xs) /* Test if variable is a member of */
2353 Text t; /* given list of variables */
2355 for (; nonNull(xs); xs=tl(xs))
2356 if (t==textOf(hd(xs)))
2361 Name nameIsMember(t,ns) /* Test if name with text t is a */
2362 Text t; /* member of list of names xs */
2364 for (; nonNull(ns); ns=tl(ns))
2365 if (t==name(hd(ns)).text)
2370 Cell intIsMember(n,xs) /* Test if integer n is member of */
2371 Int n; /* given list of integers */
2373 for (; nonNull(xs); xs=tl(xs))
2374 if (n==intOf(hd(xs)))
2379 Cell cellIsMember(x,xs) /* Test for membership of specific */
2380 Cell x; /* cell x in list xs */
2382 for (; nonNull(xs); xs=tl(xs))
2388 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2391 for (; nonNull(xs); xs=tl(xs))
2397 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2398 Cell c; /* association lists */
2400 for (; nonNull(xs); xs=tl(xs))
2406 List replicate(n,x) /* create list of n copies of x */
2415 List diffList(from,take) /* list difference: from\take */
2416 List from, take; { /* result contains all elements of */
2417 List result = NIL; /* `from' not appearing in `take' */
2419 while (nonNull(from)) {
2420 List next = tl(from);
2421 if (!cellIsMember(hd(from),take)) {
2430 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2434 for(;nonNull(xs);xs=tl(xs)) {
2437 result=cons(x,result);
2443 List take(n,xs) /* destructively truncate list to */
2444 Int n; /* specified length */
2450 while (1<n-- && nonNull(xs))
2457 List splitAt(n,xs) /* drop n things from front of list*/
2466 Cell nth(n,xs) /* extract n'th element of list */
2469 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2476 List removeCell(x,xs) /* destructively remove cell from */
2481 return tl(xs); /* element at front of list */
2485 for (; nonNull(curr); prev=curr, curr=tl(prev))
2487 tl(prev) = tl(curr);
2488 return xs; /* element in middle of list */
2492 return xs; /* here if element not found */
2495 List nubList(xs) /* nuke dups in list */
2496 List xs; { /* non destructive */
2498 for (; nonNull(xs); xs=tl(xs))
2499 if (isNull(cellIsMember(hd(xs),outs)))
2500 outs = cons(hd(xs),outs);
2506 /* --------------------------------------------------------------------------
2507 * Strongly-typed lists (z-lists) and tuples (experimental)
2508 * ------------------------------------------------------------------------*/
2510 static void z_tag_check ( Cell x, int tag, char* caller )
2514 sprintf(buf,"z_tag_check(%s): null\n", caller);
2517 if (whatIs(x) != tag) {
2519 "z_tag_check(%s): tag was %d, expected %d\n",
2520 caller, whatIs(x), tag );
2526 Cell zcons ( Cell x, Cell xs )
2528 if (!(isNull(xs) || whatIs(xs)==ZCONS))
2529 internal("zcons: ill typed tail");
2530 return ap(ZCONS,ap(x,xs));
2533 Cell zhd ( Cell xs )
2535 if (isNull(xs)) internal("zhd: empty list");
2536 z_tag_check(xs,ZCONS,"zhd");
2537 return fst( snd(xs) );
2540 Cell ztl ( Cell xs )
2542 if (isNull(xs)) internal("ztl: empty list");
2543 z_tag_check(xs,ZCONS,"zhd");
2544 return snd( snd(xs) );
2547 Int zlength ( ZList xs )
2550 while (nonNull(xs)) {
2551 z_tag_check(xs,ZCONS,"zlength");
2553 xs = snd( snd(xs) );
2558 ZList zreverse ( ZList xs )
2561 while (nonNull(xs)) {
2562 z_tag_check(xs,ZCONS,"zreverse");
2563 rev = zcons(zhd(xs),rev);
2569 Cell zsingleton ( Cell x )
2571 return zcons (x,NIL);
2574 Cell zdoubleton ( Cell x, Cell y )
2576 return zcons(x,zcons(y,NIL));
2580 Cell zpair ( Cell x1, Cell x2 )
2581 { return ap(ZTUP2,ap(x1,x2)); }
2582 Cell zfst ( Cell zpair )
2583 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2584 Cell zsnd ( Cell zpair )
2585 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2587 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2588 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2589 Cell zfst3 ( Cell zpair )
2590 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2591 Cell zsnd3 ( Cell zpair )
2592 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2593 Cell zthd3 ( Cell zpair )
2594 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2596 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2597 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2598 Cell zsel14 ( Cell zpair )
2599 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2600 Cell zsel24 ( Cell zpair )
2601 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2602 Cell zsel34 ( Cell zpair )
2603 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2604 Cell zsel44 ( Cell zpair )
2605 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2607 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2608 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2609 Cell zsel15 ( Cell zpair )
2610 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2611 Cell zsel25 ( Cell zpair )
2612 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2613 Cell zsel35 ( Cell zpair )
2614 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2615 Cell zsel45 ( Cell zpair )
2616 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2617 Cell zsel55 ( Cell zpair )
2618 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2621 Cell unap ( int tag, Cell c )
2624 if (whatIs(c) != tag) {
2625 sprintf(buf, "unap: specified %d, actual %d\n",
2632 /* --------------------------------------------------------------------------
2633 * Operations on applications:
2634 * ------------------------------------------------------------------------*/
2636 Int argCount; /* number of args in application */
2638 Cell getHead(e) /* get head cell of application */
2639 Cell e; { /* set number of args in argCount */
2640 for (argCount=0; isAp(e); e=fun(e))
2645 List getArgs(e) /* get list of arguments in function*/
2646 Cell e; { /* application: */
2647 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2649 for (as=NIL; isAp(e); e=fun(e))
2650 as = cons(arg(e),as);
2654 Cell nthArg(n,e) /* return nth arg in application */
2655 Int n; /* of function to m args (m>=n) */
2656 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2657 for (n=numArgs(e)-n-1; n>0; n--)
2662 Int numArgs(e) /* find number of arguments to expr */
2665 for (n=0; isAp(e); e=fun(e))
2670 Cell applyToArgs(f,args) /* destructively apply list of args */
2671 Cell f; /* to function f */
2673 while (nonNull(args)) {
2674 Cell temp = tl(args);
2675 tl(args) = hd(args);
2684 /* --------------------------------------------------------------------------
2686 * ------------------------------------------------------------------------*/
2688 /*---------------------------------------------------------------------------
2689 * GreenCard entry points
2691 * GreenCard generated code accesses Hugs data structures and functions
2692 * (only) via these functions (which are stored in the virtual function
2694 *-------------------------------------------------------------------------*/
2698 static Cell makeTuple Args((Int));
2699 static Cell makeInt Args((Int));
2700 static Cell makeChar Args((Char));
2701 static Char CharOf Args((Cell));
2702 static Cell makeFloat Args((FloatPro));
2703 static Void* derefMallocPtr Args((Cell));
2704 static Cell* Fst Args((Cell));
2705 static Cell* Snd Args((Cell));
2707 static Cell makeTuple(n) Int n; { return mkTuple(n); }
2708 static Cell makeInt(n) Int n; { return mkInt(n); }
2709 static Cell makeChar(n) Char n; { return mkChar(n); }
2710 static Char CharOf(n) Cell n; { return charOf(n); }
2711 static Cell makeFloat(n) FloatPro n; { return mkFloat(n); }
2712 static Void* derefMallocPtr(n) Cell n; { return derefMP(n); }
2713 static Cell* Fst(n) Cell n; { return (Cell*)&fst(n); }
2714 static Cell* Snd(n) Cell n; { return (Cell*)&snd(n); }
2716 HugsAPI1* hugsAPI1() {
2717 static HugsAPI1 api;
2718 static Bool initialised = FALSE;
2720 api.nameTrue = nameTrue;
2721 api.nameFalse = nameFalse;
2722 api.nameNil = nameNil;
2723 api.nameCons = nameCons;
2724 api.nameJust = nameJust;
2725 api.nameNothing = nameNothing;
2726 api.nameLeft = nameLeft;
2727 api.nameRight = nameRight;
2728 api.nameUnit = nameUnit;
2729 api.nameIORun = nameIORun;
2730 api.makeInt = makeInt;
2731 api.makeChar = makeChar;
2732 api.CharOf = CharOf;
2733 api.makeFloat = makeFloat;
2734 api.makeTuple = makeTuple;
2736 api.mkMallocPtr = mkMallocPtr;
2737 api.derefMallocPtr = derefMallocPtr;
2738 api.mkStablePtr = mkStablePtr;
2739 api.derefStablePtr = derefStablePtr;
2740 api.freeStablePtr = freeStablePtr;
2742 api.evalWithNoError = evalWithNoError;
2743 api.evalFails = evalFails;
2744 api.whnfArgs = &whnfArgs;
2745 api.whnfHead = &whnfHead;
2746 api.whnfInt = &whnfInt;
2747 api.whnfFloat = &whnfFloat;
2748 api.garbageCollect = garbageCollect;
2749 api.stackOverflow = hugsStackOverflow;
2750 api.internal = internal;
2751 api.registerPrims = registerPrims;
2752 api.addPrimCfun = addPrimCfun;
2753 api.inventText = inventText;
2756 api.cellStack = cellStack;
2762 #endif /* GREENCARD */
2765 /* --------------------------------------------------------------------------
2767 * ------------------------------------------------------------------------*/
2770 static void far* safeFarCalloc Args((Int,Int));
2771 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
2772 Int n, s; { /* for non-null return */
2773 void far* tab = farCalloc(n,s);
2775 ERRMSG(0) "Cannot allocate run-time tables"
2780 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
2782 #define TABALLOC(v,t,n)
2790 case POSTPREL: break;
2792 case RESET : clearStack();
2794 /* the next 2 statements are particularly important
2795 * if you are using GLOBALfst or GLOBALsnd since the
2796 * corresponding registers may be reset to their
2797 * uninitialised initial values by a longjump.
2799 heapTopFst = heapFst + heapSize;
2800 heapTopSnd = heapSnd + heapSize;
2804 if (isNull(lastExprSaved))
2805 savedText = NUM_TEXT;
2810 for (i=NAMEMIN; i<nameHw; ++i) {
2811 mark(name(i).parent);
2813 mark(name(i).stgVar);
2816 end("Names", nameHw-NAMEMIN);
2819 for (i=MODMIN; i<moduleHw; ++i) {
2820 mark(module(i).tycons);
2821 mark(module(i).names);
2822 mark(module(i).classes);
2823 mark(module(i).exports);
2824 mark(module(i).qualImports);
2826 end("Modules", moduleHw-MODMIN);
2829 for (i=TYCMIN; i<tyconHw; ++i) {
2830 mark(tycon(i).defn);
2831 mark(tycon(i).kind);
2832 mark(tycon(i).what);
2834 end("Type constructors", tyconHw-TYCMIN);
2837 for (i=CLASSMIN; i<classHw; ++i) {
2838 mark(cclass(i).head);
2839 mark(cclass(i).kinds);
2840 mark(cclass(i).fds);
2841 mark(cclass(i).xfds);
2842 mark(cclass(i).dsels);
2843 mark(cclass(i).supers);
2844 mark(cclass(i).members);
2845 mark(cclass(i).defaults);
2846 mark(cclass(i).instances);
2849 end("Classes", classHw-CLASSMIN);
2852 for (i=INSTMIN; i<instHw; ++i) {
2854 mark(inst(i).kinds);
2855 mark(inst(i).specifics);
2856 mark(inst(i).implements);
2858 end("Instances", instHw-INSTMIN);
2861 for (i=0; i<=sp; ++i)
2866 mark(lastExprSaved);
2869 end("Last expression", 3);
2874 end("C stack", stackRoots);
2879 case PREPREL : heapFst = heapAlloc(heapSize);
2880 heapSnd = heapAlloc(heapSize);
2882 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
2883 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
2888 heapTopFst = heapFst + heapSize;
2889 heapTopSnd = heapSnd + heapSize;
2890 for (i=1; i<heapSize; ++i) {
2894 snd(-heapSize) = NIL;
2901 marksSize = bitArraySize(heapSize);
2902 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
2903 ERRMSG(0) "Unable to allocate gc markspace"
2907 TABALLOC(text, char, NUM_TEXT)
2908 TABALLOC(tyconHash, Tycon, TYCONHSZ)
2909 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
2910 TABALLOC(nameHash, Name, NAMEHSZ)
2911 TABALLOC(tabName, struct strName, NUM_NAME)
2912 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
2913 TABALLOC(cellStack, Cell, NUM_STACK)
2914 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
2916 TABALLOC(tabExt, Text, NUM_EXT)
2921 nextNewText = NUM_TEXT;
2922 nextNewDText = (-1);
2923 lastExprSaved = NIL;
2924 savedText = NUM_TEXT;
2925 for (i=0; i<TEXTHSZ; ++i)
2926 textHash[i][0] = NOTEXT;
2932 for (i=0; i<TYCONHSZ; ++i)
2939 for (i=0; i<NAMEHSZ; ++i)
2950 tabInst = (struct strInst far *)
2951 farCalloc(NUM_INSTS,sizeof(struct strInst));
2954 ERRMSG(0) "Cannot allocate instance tables"
2964 /*-------------------------------------------------------------------------*/