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/07 11:14:57 $
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(tup)
585 assert(isTuple(tup));
587 if (tup >= 100) internal("ghcTupleText");
589 for (i = 1; i <= tup; i++) buf[i] = ',';
592 return findText(buf);
595 Tycon mkTuple ( Int n )
599 internal("mkTuple: request for tuple of unsupported size");
600 for (i = TYCMIN; i < tyconHw; i++)
601 if (tycon(i).tuple == n) return i;
602 internal("mkTuple: request for non-existent tuple");
605 Void allocTupleTycon ( Int n )
611 for (i = TYCMIN; i < tyconHw; i++)
612 if (tycon(i).tuple == n) return;
613 sprintf(buf,"Tuple%d",n);
614 //t = addPrimTycon(findText(buf),simpleKind(n),n, DATATYPE,NIL);
617 for (i = 0; i < n; i++) k = ap(STAR,k);
618 t = newTycon(findText(buf));
621 tycon(t).what = DATATYPE;
624 /* --------------------------------------------------------------------------
627 * A Name represents a top level binding of a value to an identifier.
628 * Such values may be a constructor function, a member function in a
629 * class, a user-defined or primitive value/function.
631 * Names are indexed by Text values ... a very simple hash functions speeds
632 * access to the table of Names and Name entries with the same hash value
633 * are chained together, with the most recent entry at the front of the
635 * ------------------------------------------------------------------------*/
637 #define NAMEHSZ 256 /* Size of Name hash table */
638 #define nHash(x) ((x)%NAMEHSZ) /* hash fn :: Text->Int */
639 Name nameHw; /* next unused name */
640 static Name DEFTABLE(nameHash,NAMEHSZ); /* Hash table storage */
641 struct strName DEFTABLE(tabName,NUM_NAME); /* Name table storage */
643 Name newName(t,parent) /* Add new name to name table */
647 if (nameHw-NAMEMIN >= NUM_NAME) {
648 ERRMSG(0) "Name storage space exhausted"
651 name(nameHw).text = t; /* clear new name record */
652 name(nameHw).line = 0;
653 name(nameHw).syntax = NO_SYNTAX;
654 name(nameHw).parent = parent;
655 name(nameHw).arity = 0;
656 name(nameHw).number = EXECNAME;
657 name(nameHw).defn = NIL;
658 name(nameHw).stgVar = NIL;
659 name(nameHw).callconv = NIL;
660 name(nameHw).type = NIL;
661 name(nameHw).primop = 0;
662 name(nameHw).mod = currentModule;
663 name(nameHw).itbl = NULL;
664 module(currentModule).names=cons(nameHw,module(currentModule).names);
665 name(nameHw).nextNameHash = nameHash[h];
666 nameHash[h] = nameHw;
670 Name findName(t) /* Locate name in name table */
672 Name n = nameHash[nHash(t)];
674 while (nonNull(n) && name(n).text!=t)
675 n = name(n).nextNameHash;
679 Name addName(nm) /* Insert Name in name table - if */
680 Name nm; { /* no clash is caused */
681 Name oldnm = findName(name(nm).text);
684 module(currentModule).names=cons(nm,module(currentModule).names);
690 static Void local hashName(nm) /* Insert Name into hash table */
697 name(nm).nextNameHash = nameHash[h];
701 Name findQualName(id) /* Locate (possibly qualified) name*/
702 Cell id; { /* in name table */
704 internal("findQualName");
710 return findName(textOf(id));
712 Text t = qtextOf(id);
713 Module m = findQualifier(qmodOf(id));
715 if (isNull(m)) return NIL;
716 for(es=module(m).exports; nonNull(es); es=tl(es)) {
718 if (isName(e) && name(e).text==t)
720 else if (isPair(e) && DOTDOT==snd(e)) {
721 List subentities = NIL;
724 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
725 subentities = tycon(c).defn;
727 subentities = cclass(c).members;
728 for(; nonNull(subentities); subentities=tl(subentities)) {
729 if (!isName(hd(subentities)))
730 internal("findQualName3");
731 if (name(hd(subentities)).text == t)
732 return hd(subentities);
738 default : internal("findQualName2");
740 return 0; /* NOTREACHED */
744 Name nameFromStgVar ( StgVar v )
747 for (n = NAMEMIN; n < nameHw; n++)
748 if (name(n).stgVar == v) return n;
752 void* getHugs_AsmObject_for ( char* s )
755 Text t = findText(s);
757 for (n = NAMEMIN; n < nameHw; n++)
758 if (name(n).text == t) break;
759 if (n == nameHw) internal("getHugs_AsmObject_for(1)");
761 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
762 internal("getHugs_AsmObject_for(2)");
763 return ptrOf(stgVarInfo(v));
766 /* --------------------------------------------------------------------------
767 * Primitive functions:
768 * ------------------------------------------------------------------------*/
770 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
771 Text t; /* sets rep, not type */
774 Int rep; { /* Really AsmRep */
775 Name n = newName(t,NIL);
776 name(n).arity = arity;
777 name(n).number = cfunNo(no);
779 name(n).primop = (void*)rep;
784 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
789 Name n = newName(t,NIL);
790 name(n).arity = arity;
791 name(n).number = cfunNo(no);
797 Int sfunPos(s,c) /* Find position of field with */
798 Name s; /* selector s in constructor c. */
802 for (; nonNull(cns); cns=tl(cns))
804 return intOf(snd(hd(cns)));
806 return 0;/* NOTREACHED */
809 static List local insertName(nm,ns) /* insert name nm into sorted list */
814 String s = textToStr(name(nm).text);
816 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
817 if (hd(curr)==nm) /* just in case we get duplicates! */
823 tl(prev) = cons(nm,curr);
827 return cons(nm,curr);
830 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
831 String pat; /* to list of names ns */
832 List ns; { /* Null pattern matches every name */
833 Name nm; /* (Names with NIL type, or hidden */
835 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
836 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
837 String str = textToStr(name(nm).text);
838 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
839 ns = insertName(nm,ns);
843 List mns = module(currentModule).names;
844 for(; nonNull(mns); mns=tl(mns)) {
846 if (!inventedText(name(nm).text)) {
847 String str = textToStr(name(nm).text);
848 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
849 ns = insertName(nm,ns);
856 /* --------------------------------------------------------------------------
857 * A simple string matching routine
858 * `*' matches any sequence of zero or more characters
859 * `?' matches any single character exactly
860 * `@str' matches the string str exactly (ignoring any special chars)
861 * `\c' matches the character c only (ignoring special chars)
862 * c matches the character c only
863 * ------------------------------------------------------------------------*/
865 static Void local patternError(s) /* report error in pattern */
867 ERRMSG(0) "%s in pattern", s
871 static Bool local stringMatch(pat,str) /* match string against pattern */
877 case '\0' : return (*str=='\0');
880 if (stringMatch(pat+1,str))
885 case '?' : if (*str++=='\0')
890 case '[' : { Bool found = FALSE;
891 while (*++pat!='\0' && *pat!=']')
892 if (!found && ( pat[0] == *str ||
901 patternError("missing `]'");
909 case '\\' : if (*++pat == '\0')
910 patternError("extra trailing `\\'");
912 default : if (*pat++ != *str++)
918 /* --------------------------------------------------------------------------
919 * Storage of type classes, instances etc...:
920 * ------------------------------------------------------------------------*/
922 static Class classHw; /* next unused class */
923 static List classes; /* list of classes in current scope */
924 static Inst instHw; /* next unused instance record */
926 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
927 struct strInst far *tabInst; /* (pointer to) table of instances */
929 Class newClass(t) /* add new class to class table */
931 if (classHw-CLASSMIN >= NUM_CLASSES) {
932 ERRMSG(0) "Class storage space exhausted"
935 cclass(classHw).text = t;
936 cclass(classHw).arity = 0;
937 cclass(classHw).kinds = NIL;
938 cclass(classHw).head = NIL;
939 cclass(classHw).fds = NIL;
940 cclass(classHw).xfds = NIL;
941 cclass(classHw).dcon = NIL;
942 cclass(classHw).supers = NIL;
943 cclass(classHw).dsels = NIL;
944 cclass(classHw).members = NIL;
945 cclass(classHw).defaults = NIL;
946 cclass(classHw).instances = NIL;
947 classes=cons(classHw,classes);
948 cclass(classHw).mod = currentModule;
949 module(currentModule).classes=cons(classHw,module(currentModule).classes);
953 Class classMax() { /* Return max Class in use ... */
954 return classHw; /* This is a bit ugly, but it's not*/
955 } /* worth a lot of effort right now */
957 Class findClass(t) /* look for named class in table */
961 for (cs=classes; nonNull(cs); cs=tl(cs)) {
963 if (cclass(cl).text==t)
969 Class addClass(c) /* Insert Class in class list */
970 Class c; { /* - if no clash caused */
971 Class oldc = findClass(cclass(c).text);
973 classes=cons(c,classes);
974 module(currentModule).classes=cons(c,module(currentModule).classes);
981 Class findQualClass(c) /* Look for (possibly qualified) */
982 Cell c; { /* class in class list */
983 if (!isQualIdent(c)) {
984 return findClass(textOf(c));
987 Module m = findQualifier(qmodOf(c));
991 for (es=module(m).exports; nonNull(es); es=tl(es)) {
993 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
1000 Inst newInst() { /* Add new instance to table */
1001 if (instHw-INSTMIN >= NUM_INSTS) {
1002 ERRMSG(0) "Instance storage space exhausted"
1005 inst(instHw).kinds = NIL;
1006 inst(instHw).head = NIL;
1007 inst(instHw).specifics = NIL;
1008 inst(instHw).implements = NIL;
1009 inst(instHw).builder = NIL;
1010 inst(instHw).mod = currentModule;
1016 extern Void printInst Args((Inst));
1020 Class cl = inst(in).c;
1021 Printf("%s-", textToStr(cclass(cl).text));
1022 printType(stdout,inst(in).t);
1024 #endif /* DEBUG_DICTS */
1026 Inst findFirstInst(tc) /* look for 1st instance involving */
1027 Tycon tc; { /* the type constructor tc */
1028 return findNextInst(tc,INSTMIN-1);
1031 Inst findNextInst(tc,in) /* look for next instance involving*/
1032 Tycon tc; /* the type constructor tc */
1033 Inst in; { /* starting after instance in */
1034 while (++in < instHw) {
1035 Cell pi = inst(in).head;
1036 for (; isAp(pi); pi=fun(pi))
1037 if (typeInvolves(arg(pi),tc))
1043 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1044 Type ty; /* type constructor/tuple tc. */
1047 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1048 || typeInvolves(arg(ty),tc)));
1051 /* --------------------------------------------------------------------------
1054 * Various parts of the system use a stack of cells. Most of the stack
1055 * operations are defined as macros, expanded inline.
1056 * ------------------------------------------------------------------------*/
1058 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
1059 StackPtr sp; /* stack pointer */
1061 #if GIMME_STACK_DUMPS
1063 #define UPPER_DISP 5 /* # display entries on top of stack */
1064 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
1066 Void hugsStackOverflow() { /* Report stack overflow */
1068 extern Cell evalRoots[];
1070 ERRMSG(0) "Control stack overflow" ETHEN
1073 if (rootsp>=UPPER_DISP+LOWER_DISP) {
1074 for (i=0; i<UPPER_DISP; i++) {
1075 ERRTEXT "\nwhile evaluating: " ETHEN
1076 ERREXPR(evalRoots[rootsp-i]);
1078 ERRTEXT "\n..." ETHEN
1079 for (i=LOWER_DISP-1; i>=0; i--) {
1080 ERRTEXT "\nwhile evaluating: " ETHEN
1081 ERREXPR(evalRoots[i]);
1085 for (i=rootsp; i>=0; i--) {
1086 ERRTEXT "\nwhile evaluating: " ETHEN
1087 ERREXPR(evalRoots[i]);
1095 #else /* !GIMME_STACK_DUMPS */
1097 Void hugsStackOverflow() { /* Report stack overflow */
1098 ERRMSG(0) "Control stack overflow"
1102 #endif /* !GIMME_STACK_DUMPS */
1104 /* --------------------------------------------------------------------------
1107 * A Module represents a user defined module.
1109 * Note: there are now two lookup mechanisms in the system:
1111 * 1) The exports from a module are stored in a big list.
1112 * We resolve qualified names, and import lists by linearly scanning
1113 * through this list.
1115 * 2) Unqualified imports and local definitions for the current module
1116 * are stored in hash tables (tyconHash and nameHash) or linear lists
1119 * ------------------------------------------------------------------------*/
1121 static Module moduleHw; /* next unused Module */
1122 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
1123 Module currentModule; /* Module currently being processed*/
1125 Bool isValidModule(m) /* is m a legitimate module id? */
1127 return (MODMIN <= m && m < moduleHw);
1130 Module newModule(t) /* add new module to module table */
1132 if (moduleHw-MODMIN >= NUM_MODULE) {
1133 ERRMSG(0) "Module storage space exhausted"
1136 module(moduleHw).text = t; /* clear new module record */
1137 module(moduleHw).qualImports = NIL;
1138 module(moduleHw).exports = NIL;
1139 module(moduleHw).tycons = NIL;
1140 module(moduleHw).names = NIL;
1141 module(moduleHw).classes = NIL;
1142 module(moduleHw).oImage = NULL;
1143 module(moduleHw).oTab = NULL;
1144 module(moduleHw).sizeoTab = 0;
1145 module(moduleHw).usedoTab = 0;
1146 module(moduleHw).dlTab = NULL;
1147 module(moduleHw).sizedlTab = 0;
1148 module(moduleHw).useddlTab = 0;
1152 void ppModules ( void )
1155 fflush(stderr); fflush(stdout);
1156 printf ( "begin MODULES\n" );
1157 for (i = moduleHw-1; i >= MODMIN; i--)
1158 printf ( " %2d: %16s\n",
1159 i-MODMIN, textToStr(module(i).text)
1161 printf ( "end MODULES\n" );
1162 fflush(stderr); fflush(stdout);
1166 Module findModule(t) /* locate Module in module table */
1169 for(m=MODMIN; m<moduleHw; ++m) {
1170 if (module(m).text==t)
1176 Module findModid(c) /* Find module by name or filename */
1178 switch (whatIs(c)) {
1179 case STRCELL : { Script s = scriptThisFile(snd(c));
1180 return (s==-1) ? NIL : moduleOfScript(s);
1182 case CONIDCELL : return findModule(textOf(c));
1183 default : internal("findModid");
1185 return NIL;/*NOTUSED*/
1188 static local Module findQualifier(t) /* locate Module in import list */
1191 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1192 if (textOf(fst(hd(ms)))==t)
1196 if (module(currentModule).text==t)
1197 return currentModule;
1202 Void setCurrModule(m) /* set lookup tables for current module */
1205 assert(isModule(m));
1206 if (m!=currentModule) {
1207 currentModule = m; /* This is the only assignment to currentModule */
1208 for (i=0; i<TYCONHSZ; ++i)
1210 mapProc(hashTycon,module(m).tycons);
1211 for (i=0; i<NAMEHSZ; ++i)
1213 mapProc(hashName,module(m).names);
1214 classes = module(m).classes;
1218 Name jrsFindQualName ( Text mn, Text sn )
1223 for (m=MODMIN; m<moduleHw; m++)
1224 if (module(m).text == mn) break;
1225 if (m == moduleHw) return NIL;
1227 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1228 if (name(hd(ns)).text == sn) return hd(ns);
1234 /* A bit tricky. Assumes that if tab==NULL, then
1235 currUsed and *currSize must be zero.
1238 void* genericExpand ( void* tab,
1239 int* currSize, int currUsed,
1240 int initSize, int elemSize )
1244 if (currUsed < *currSize)
1246 size2 = (*currSize == 0) ? initSize : (2 * *currSize);
1247 tab2 = malloc ( size2 * elemSize );
1249 ERRMSG(0) "Can't allocate enough memory to resize a table"
1253 memcpy ( tab2, tab, elemSize * *currSize );
1255 if (tab) free ( tab );
1259 void addOTabName ( Module m, char* nm, void* ad )
1262 = genericExpand ( module(m).oTab,
1263 &module(m).sizeoTab,
1267 module(m).oTab[ module(m).usedoTab ].nm = nm;
1268 module(m).oTab[ module(m).usedoTab ].ad = ad;
1269 module(m).usedoTab++;
1273 void addDLSect ( Module m, void* start, void* end, DLSect sect )
1276 = genericExpand ( module(m).dlTab,
1277 &module(m).sizedlTab,
1278 module(m).useddlTab,
1279 4, sizeof(DLTabEnt) );
1280 module(m).dlTab[ module(m).useddlTab ].start = start;
1281 module(m).dlTab[ module(m).useddlTab ].end = end;
1282 module(m).dlTab[ module(m).useddlTab ].sect = sect;
1283 module(m).useddlTab++;
1287 void* lookupOTabName ( Module m, char* nm )
1290 for (i = 0; i < module(m).usedoTab; i++) {
1293 "lookupOTabName: request %s, table has %s\n",
1294 nm, module(m).oTab[i].nm );
1295 if (0==strcmp(nm,module(m).oTab[i].nm))
1296 return module(m).oTab[i].ad;
1302 char* nameFromOPtr ( void* p )
1306 for (m=MODMIN; m<moduleHw; m++)
1307 for (i = 0; i < module(m).usedoTab; i++)
1308 if (p == module(m).oTab[i].ad)
1309 return module(m).oTab[i].nm;
1314 DLSect lookupDLSect ( void* ad )
1318 for (m=MODMIN; m<moduleHw; m++)
1319 for (i = 0; i < module(m).useddlTab; i++)
1320 if (module(m).dlTab[i].start <= ad &&
1321 ad <= module(m).dlTab[i].end)
1322 return module(m).dlTab[i].sect;
1323 return HUGS_DL_SECTION_OTHER;
1327 /* --------------------------------------------------------------------------
1328 * Script file storage:
1330 * script files are read into the system one after another. The state of
1331 * the stored data structures (except the garbage-collected heap) is recorded
1332 * before reading a new script. In the event of being unable to read the
1333 * script, or if otherwise requested, the system can be restored to its
1334 * original state immediately before the file was read.
1335 * ------------------------------------------------------------------------*/
1337 typedef struct { /* record of storage state prior to */
1338 Text file; /* reading script/module */
1352 #ifdef DEBUG_SHOWUSE
1353 static Void local showUse(msg,val,mx)
1356 Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1360 static Script scriptHw; /* next unused script number */
1361 static script scripts[NUM_SCRIPTS]; /* storage for script records */
1364 void ppScripts ( void )
1367 fflush(stderr); fflush(stdout);
1368 printf ( "begin SCRIPTS\n" );
1369 for (i = scriptHw-1; i >= 0; i--)
1370 printf ( " %2d: %16s tH=%d mH=%d yH=%d "
1371 "nH=%d cH=%d iH=%d nnS=%d,%d\n",
1372 i, textToStr(scripts[i].file),
1373 scripts[i].textHw, scripts[i].moduleHw,
1374 scripts[i].tyconHw, scripts[i].nameHw,
1375 scripts[i].classHw, scripts[i].instHw,
1376 scripts[i].nextNewText, scripts[i].nextNewDText
1378 printf ( "end SCRIPTS\n" );
1379 fflush(stderr); fflush(stdout);
1382 Script startNewScript(f) /* start new script, keeping record */
1383 String f; { /* of status for later restoration */
1384 if (scriptHw >= NUM_SCRIPTS) {
1385 ERRMSG(0) "Too many script files in use"
1388 #ifdef DEBUG_SHOWUSE
1389 showUse("Text", textHw, NUM_TEXT);
1390 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
1391 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
1392 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
1393 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
1394 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
1396 showUse("Ext", extHw-EXTMIN, NUM_EXT);
1399 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
1400 scripts[scriptHw].textHw = textHw;
1401 scripts[scriptHw].nextNewText = nextNewText;
1402 scripts[scriptHw].nextNewDText = nextNewDText;
1403 scripts[scriptHw].moduleHw = moduleHw;
1404 scripts[scriptHw].tyconHw = tyconHw;
1405 scripts[scriptHw].nameHw = nameHw;
1406 scripts[scriptHw].classHw = classHw;
1407 scripts[scriptHw].instHw = instHw;
1409 scripts[scriptHw].extHw = extHw;
1414 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1415 return (scriptHw==0);
1418 Bool moduleThisScript(m) /* Test if given module is defined */
1419 Module m; { /* in current script file */
1420 return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
1423 Module lastModule() { /* Return module in current script file */
1424 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1427 #define scriptThis(nm,t,tag) Script nm(x) \
1431 && x>=scripts[s].tag) \
1435 scriptThis(scriptThisName,Name,nameHw)
1436 scriptThis(scriptThisTycon,Tycon,tyconHw)
1437 scriptThis(scriptThisInst,Inst,instHw)
1438 scriptThis(scriptThisClass,Class,classHw)
1441 Module moduleOfScript(s)
1443 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1446 String fileOfModule(m)
1449 if (m == modulePrelude) {
1452 for(s=0; s<scriptHw; ++s) {
1453 if (scripts[s].moduleHw == m) {
1454 return textToStr(scripts[s].file);
1460 Script scriptThisFile(f)
1463 for (s=0; s < scriptHw; ++s) {
1464 if (scripts[s].file == f) {
1468 if (f == findText(STD_PRELUDE)) {
1474 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1475 Script sno; { /* to reading script sno */
1476 if (sno<scriptHw) { /* is there anything to restore? */
1478 textHw = scripts[sno].textHw;
1479 nextNewText = scripts[sno].nextNewText;
1480 nextNewDText = scripts[sno].nextNewDText;
1481 moduleHw = scripts[sno].moduleHw;
1482 tyconHw = scripts[sno].tyconHw;
1483 nameHw = scripts[sno].nameHw;
1484 classHw = scripts[sno].classHw;
1485 instHw = scripts[sno].instHw;
1487 dictHw = scripts[sno].dictHw;
1490 extHw = scripts[sno].extHw;
1494 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1495 if (module(i).objectFile) {
1496 printf("[bogus] closing objectFile for module %d\n",i);
1497 /*dlclose(module(i).objectFile);*/
1500 moduleHw = scripts[sno].moduleHw;
1502 for (i=0; i<TEXTHSZ; ++i) {
1504 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1505 && textHash[i][j]<textHw)
1508 textHash[i][j] = NOTEXT;
1512 for (i=0; i<TYCONHSZ; ++i) {
1515 for (i=0; i<NAMEHSZ; ++i) {
1519 for (i=CLASSMIN; i<classHw; i++) {
1520 List ins = cclass(i).instances;
1523 while (nonNull(ins)) {
1524 List temp = tl(ins);
1525 if (hd(ins)<instHw) {
1531 cclass(i).instances = rev(is);
1538 /* --------------------------------------------------------------------------
1541 * Provides a garbage collectable heap for storage of expressions etc.
1543 * Now incorporates a flat resource: A two-space collected extension of
1544 * the heap that provides storage for contiguous arrays of Cell storage,
1545 * cooperating with the garbage collection mechanisms for the main heap.
1546 * ------------------------------------------------------------------------*/
1548 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1549 Heap heapFst; /* array of fst component of pairs */
1550 Heap heapSnd; /* array of snd component of pairs */
1557 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1558 /* C stack; use with extreme care! */
1560 Int numGcs; /* number of garbage collections */
1561 Int cellsRecovered; /* number of cells recovered */
1563 static Cell freeList; /* free list of unused cells */
1564 static Cell lsave, rsave; /* save components of pair */
1568 static Int markCount, stackRoots;
1570 #define initStackRoots() stackRoots = 0
1571 #define recordStackRoot() stackRoots++
1584 #define start() markCount = 0
1585 #define end(thing,rs) \
1587 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1590 #define recordMark() markCount++
1592 #else /* !GC_STATISTICS */
1597 #define initStackRoots()
1598 #define recordStackRoot()
1601 #define end(thing,root)
1602 #define recordMark()
1604 #endif /* !GC_STATISTICS */
1606 Cell pair(l,r) /* Allocate pair (l, r) from */
1607 Cell l, r; { /* heap, garbage collecting first */
1608 Cell c = freeList; /* if necessary ... */
1620 freeList = snd(freeList);
1627 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1628 Cell dst, src; { /* both *MUST* be pairs */
1629 if (isPair(dst) && isPair(src)) {
1630 fst(dst) = fst(src);
1631 snd(dst) = snd(src);
1634 internal("overwrite");
1638 static Int marksSize;
1640 Cell markExpr(c) /* External interface to markCell */
1642 return isGenPair(c) ? markCell(c) : c;
1645 static Cell local markCell(c) /* Traverse part of graph marking */
1646 Cell c; { /* cells reachable from given root */
1647 /* markCell(c) is only called if c */
1649 { register int place = placeInSet(c);
1650 register int mask = maskInSet(c);
1651 if (marks[place]&mask)
1654 marks[place] |= mask;
1659 /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1660 if (isGenPair(fst(c))) {
1662 fst(c) = markCell(fst(c));
1665 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1673 static Void local markSnd(c) /* Variant of markCell used to */
1674 Cell c; { /* update snd component of cell */
1675 Cell t; /* using tail recursion */
1677 ma: t = c; /* Keep pointer to original pair */
1682 { register int place = placeInSet(c);
1683 register int mask = maskInSet(c);
1684 if (marks[place]&mask)
1687 marks[place] |= mask;
1692 if (isGenPair(fst(c))) {
1693 fst(c) = markCell(fst(c));
1696 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1701 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1702 Cell n; { /* it was a cell ref, but don't */
1703 /* move cell so we don't have */
1704 /* to modify the stored value of n */
1711 Void garbageCollect() { /* Run garbage collector ... */
1712 Bool breakStat = breakOn(FALSE); /* disable break checking */
1718 jmp_buf regs; /* save registers on stack */
1722 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1725 everybody(MARK); /* Mark all components of system */
1727 gcScanning(); /* scan mark set */
1734 for (i=1; i<=heapSize; i++) {
1735 if ((marks[place] & mask) == 0) {
1742 if (++j == bitsPerWord) {
1749 gcRecovered(recovered);
1750 breakOn(breakStat); /* restore break trapping if nec. */
1754 /* can only return if freeList is nonempty on return. */
1755 if (recovered<minRecovery || isNull(freeList)) {
1756 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1759 cellsRecovered = recovered;
1762 /* --------------------------------------------------------------------------
1763 * Code for saving last expression entered:
1765 * This is a little tricky because some text values (e.g. strings or variable
1766 * names) may not be defined or have the same value when the expression is
1767 * recalled. These text values are therefore saved in the top portion of
1769 * ------------------------------------------------------------------------*/
1771 static Cell lastExprSaved; /* last expression to be saved */
1773 Void setLastExpr(e) /* save expression for later recall*/
1775 lastExprSaved = NIL; /* in case attempt to save fails */
1776 savedText = NUM_TEXT;
1777 lastExprSaved = lowLevelLastIn(e);
1780 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
1781 Cell c; { /* acyclic graph) for later recall */
1782 if (isPair(c)) { /* Duplicating any text strings */
1783 if (isBoxTag(fst(c))) /* in case these are lost at some */
1784 switch (fst(c)) { /* point before the expr is reused */
1790 case STRCELL : return pair(fst(c),saveText(textOf(c)));
1791 default : return pair(fst(c),snd(c));
1794 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
1798 return pair(EXTCOPY,saveText(extText(c)));
1804 Cell getLastExpr() { /* recover previously saved expr */
1805 return lowLevelLastOut(lastExprSaved);
1808 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
1809 Cell c; { /* except that Cells refering to */
1810 if (isPair(c)) { /* Text values are restored to */
1811 if (isBoxTag(fst(c))) /* appropriate values */
1818 case STRCELL : return pair(fst(c),
1819 findText(text+intValOf(c)));
1821 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
1823 default : return pair(fst(c),snd(c));
1826 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
1832 /* --------------------------------------------------------------------------
1833 * Miscellaneous operations on heap cells:
1834 * ------------------------------------------------------------------------*/
1836 /* Profiling suggests that the number of calls to whatIs() is typically */
1837 /* rather high. The recoded version below attempts to improve the average */
1838 /* performance for whatIs() using a binary search for part of the analysis */
1840 Cell whatIs(c) /* identify type of cell */
1843 register Cell fstc = fst(c);
1844 return isTag(fstc) ? fstc : AP;
1846 if (c<OFFMIN) return c;
1848 if (isExt(c)) return EXT;
1850 if (c>=INTMIN) return INTCELL;
1852 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
1854 else if (c>=INSTMIN) return INSTANCE;
1856 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
1857 else return MODULE;}
1858 else if (c>=OFFMIN) return OFFSET;
1860 else return (c>=EXTMIN) ?
1867 register Cell fstc = fst(c);
1868 return isTag(fstc) ? fstc : AP;
1870 if (c>=INTMIN) return INTCELL;
1871 if (c>=CHARMIN) return CHARCELL;
1872 if (c>=CLASSMIN) return CLASS;
1873 if (c>=INSTMIN) return INSTANCE;
1874 if (c>=NAMEMIN) return NAME;
1875 if (c>=TYCMIN) return TYCON;
1876 if (c>=MODMIN) return MODULE;
1877 if (c>=OFFMIN) return OFFSET;
1879 if (c>=EXTMIN) return EXT;
1881 if (c>=TUPMIN) return TUPLE;
1886 /* A very, very simple printer.
1887 * Output is uglier than from printExp - but the printer is more
1888 * robust and can be used on any data structure irrespective of
1891 Void print Args((Cell, Int));
1892 Void print(c, depth)
1897 #if 0 /* Not in this version of Hugs */
1898 } else if (isPair(c) && !isGenPair(c)) {
1899 extern Void printEvalCell Args((Cell, Int));
1900 printEvalCell(c,depth);
1903 Int tag = whatIs(c);
1907 print(fst(c), depth-1);
1909 print(snd(c), depth-1);
1913 Printf("free(%d)", c);
1916 Printf("int(%d)", intOf(c));
1919 Printf("bignum(%s)", bignumToString(c));
1922 Printf("char('%c')", charOf(c));
1925 Printf("ptr(%p)",ptrOf(c));
1928 Printf("class(%d)", c-CLASSMIN);
1929 if (CLASSMIN <= c && c < classHw) {
1930 Printf("=\"%s\"", textToStr(cclass(c).text));
1934 Printf("instance(%d)", c - INSTMIN);
1937 Printf("name(%d)", c-NAMEMIN);
1938 if (NAMEMIN <= c && c < nameHw) {
1939 Printf("=\"%s\"", textToStr(name(c).text));
1943 Printf("tycon(%d)", c-TYCMIN);
1944 if (TYCMIN <= c && c < tyconHw)
1945 Printf("=\"%s\"", textToStr(tycon(c).text));
1948 Printf("module(%d)", c - MODMIN);
1951 Printf("Offset %d", offsetOf(c));
1954 Printf("Tuple %d", tupleOf(c));
1958 print(snd(c),depth-1);
1962 print(snd(c),depth-1);
1966 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
1967 Printf("%d ", intOf(fst(snd(c))));
1968 print(snd(snd(c)),depth-1);
1970 print(snd(c),depth-1);
1987 Printf("{dict %d}",textOf(c));
1993 Printf("{id %s}",textToStr(textOf(c)));
1997 Printf("{ip %s}",textToStr(textOf(c)));
2000 Printf("?%s",textToStr(textOf(c)));
2004 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2008 print(fst(snd(c)),depth-1);
2010 print(snd(snd(c)),depth-1);
2015 print(snd(c),depth-1);
2020 print(snd(c),depth-1);
2025 print(fst(snd(c)),depth-1);
2027 print(snd(snd(c)),depth-1);
2032 print(fst(snd(c)),depth-1);
2034 print(snd(snd(c)),depth-1);
2038 Printf("FromQual(");
2039 print(fst(snd(c)),depth-1);
2041 print(snd(snd(c)),depth-1);
2045 Printf("StgVar%d=",-c);
2046 print(snd(c), depth-1);
2050 print(fst(snd(c)),depth-1);
2052 print(snd(snd(c)),depth-1);
2057 print(fst(snd(c)),depth-1);
2059 print(snd(snd(c)),depth-1);
2064 print(fst(snd(c)),depth-1);
2066 print(snd(snd(c)),depth-1);
2070 Printf("PrimCase(");
2071 print(fst(snd(c)),depth-1);
2073 print(snd(snd(c)),depth-1);
2078 print(snd(c),depth-1);
2082 Printf("(UNBOXEDTUP,");
2083 print(snd(c),depth-1);
2088 print(snd(c),depth-1);
2092 if (isBoxTag(tag)) {
2093 Printf("Tag(%d)=%d", c, tag);
2094 } else if (isConTag(tag)) {
2095 Printf("%d@(%d,",c,tag);
2096 print(snd(c), depth-1);
2099 } else if (c == tag) {
2100 Printf("Tag(%d)", c);
2102 Printf("Tag(%d)=%d", c, tag);
2111 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2112 Cell c; { /* also recognises DICTVAR cells */
2114 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2117 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2119 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2122 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2124 if (!isPair(c)) return FALSE;
2127 case VAROPCELL : return TRUE;
2129 case QUALIDENT : return isVar(snd(snd(c)));
2131 default : return FALSE;
2135 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2137 if (!isPair(c)) return FALSE;
2140 case CONOPCELL : return TRUE;
2142 case QUALIDENT : return isCon(snd(snd(c)));
2144 default : return FALSE;
2148 Bool isQualIdent(c) /* is cell a qualified identifier? */
2150 return isPair(c) && (fst(c)==QUALIDENT);
2153 Bool isIdent(c) /* is cell an identifier? */
2155 if (!isPair(c)) return FALSE;
2160 case CONOPCELL : return TRUE;
2162 case QUALIDENT : return TRUE;
2164 default : return FALSE;
2168 Bool isInt(c) /* cell holds integer value? */
2170 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2173 Int intOf(c) /* find integer value of cell? */
2177 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
2180 Cell mkInt(n) /* make cell representing integer */
2182 return (MINSMALLINT <= n && n <= MAXSMALLINT)
2187 #if SIZEOF_INTP == SIZEOF_INT
2188 typedef union {Int i; Ptr p;} IntOrPtr;
2194 return pair(PTRCELL,x.i);
2201 assert(fst(c) == PTRCELL);
2210 return pair(CPTRCELL,x.i);
2217 assert(fst(c) == CPTRCELL);
2221 #elif SIZEOF_INTP == 2*SIZEOF_INT
2222 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2228 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2235 assert(fst(c) == PTRCELL);
2236 x.i.i1 = intOf(fst(snd(c)));
2237 x.i.i2 = intOf(snd(snd(c)));
2241 #warning "type Addr not supported on this architecture - don't use it"
2245 ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
2252 ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
2257 String stringNegate( s )
2265 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2270 /* --------------------------------------------------------------------------
2272 * ------------------------------------------------------------------------*/
2274 Int length(xs) /* calculate length of list xs */
2277 for (; nonNull(xs); ++n)
2282 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2283 List xs, ys; { /* ys by modifying xs ... */
2288 while (nonNull(tl(zs)))
2295 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2298 for (; nonNull(xs); xs=tl(xs))
2299 ys = cons(hd(xs),ys);
2303 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2306 return revOnto(dupOnto(xs,NIL),ys);
2309 List dupList(xs) /* Duplicate spine of list xs */
2312 for (; nonNull(xs); xs=tl(xs))
2313 ys = cons(hd(xs),ys);
2317 List revOnto(xs,ys) /* Destructively reverse elements of*/
2318 List xs, ys; { /* list xs onto list ys... */
2321 while (nonNull(xs)) {
2330 Cell varIsMember(t,xs) /* Test if variable is a member of */
2331 Text t; /* given list of variables */
2333 for (; nonNull(xs); xs=tl(xs))
2334 if (t==textOf(hd(xs)))
2339 Name nameIsMember(t,ns) /* Test if name with text t is a */
2340 Text t; /* member of list of names xs */
2342 for (; nonNull(ns); ns=tl(ns))
2343 if (t==name(hd(ns)).text)
2348 Cell intIsMember(n,xs) /* Test if integer n is member of */
2349 Int n; /* given list of integers */
2351 for (; nonNull(xs); xs=tl(xs))
2352 if (n==intOf(hd(xs)))
2357 Cell cellIsMember(x,xs) /* Test for membership of specific */
2358 Cell x; /* cell x in list xs */
2360 for (; nonNull(xs); xs=tl(xs))
2366 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2369 for (; nonNull(xs); xs=tl(xs))
2375 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2376 Cell c; /* association lists */
2378 for (; nonNull(xs); xs=tl(xs))
2384 List replicate(n,x) /* create list of n copies of x */
2393 List diffList(from,take) /* list difference: from\take */
2394 List from, take; { /* result contains all elements of */
2395 List result = NIL; /* `from' not appearing in `take' */
2397 while (nonNull(from)) {
2398 List next = tl(from);
2399 if (!cellIsMember(hd(from),take)) {
2408 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2412 for(;nonNull(xs);xs=tl(xs)) {
2415 result=cons(x,result);
2421 List take(n,xs) /* destructively truncate list to */
2422 Int n; /* specified length */
2428 while (1<n-- && nonNull(xs))
2435 List splitAt(n,xs) /* drop n things from front of list*/
2444 Cell nth(n,xs) /* extract n'th element of list */
2447 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2454 List removeCell(x,xs) /* destructively remove cell from */
2459 return tl(xs); /* element at front of list */
2463 for (; nonNull(curr); prev=curr, curr=tl(prev))
2465 tl(prev) = tl(curr);
2466 return xs; /* element in middle of list */
2470 return xs; /* here if element not found */
2473 List nubList(xs) /* nuke dups in list */
2474 List xs; { /* non destructive */
2476 for (; nonNull(xs); xs=tl(xs))
2477 if (isNull(cellIsMember(hd(xs),outs)))
2478 outs = cons(hd(xs),outs);
2483 /* --------------------------------------------------------------------------
2484 * Operations on applications:
2485 * ------------------------------------------------------------------------*/
2487 Int argCount; /* number of args in application */
2489 Cell getHead(e) /* get head cell of application */
2490 Cell e; { /* set number of args in argCount */
2491 for (argCount=0; isAp(e); e=fun(e))
2496 List getArgs(e) /* get list of arguments in function*/
2497 Cell e; { /* application: */
2498 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2500 for (as=NIL; isAp(e); e=fun(e))
2501 as = cons(arg(e),as);
2505 Cell nthArg(n,e) /* return nth arg in application */
2506 Int n; /* of function to m args (m>=n) */
2507 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2508 for (n=numArgs(e)-n-1; n>0; n--)
2513 Int numArgs(e) /* find number of arguments to expr */
2516 for (n=0; isAp(e); e=fun(e))
2521 Cell applyToArgs(f,args) /* destructively apply list of args */
2522 Cell f; /* to function f */
2524 while (nonNull(args)) {
2525 Cell temp = tl(args);
2526 tl(args) = hd(args);
2535 /* --------------------------------------------------------------------------
2537 * ------------------------------------------------------------------------*/
2539 /*---------------------------------------------------------------------------
2540 * GreenCard entry points
2542 * GreenCard generated code accesses Hugs data structures and functions
2543 * (only) via these functions (which are stored in the virtual function
2545 *-------------------------------------------------------------------------*/
2549 static Cell makeTuple Args((Int));
2550 static Cell makeInt Args((Int));
2551 static Cell makeChar Args((Char));
2552 static Char CharOf Args((Cell));
2553 static Cell makeFloat Args((FloatPro));
2554 static Void* derefMallocPtr Args((Cell));
2555 static Cell* Fst Args((Cell));
2556 static Cell* Snd Args((Cell));
2558 static Cell makeTuple(n) Int n; { return mkTuple(n); }
2559 static Cell makeInt(n) Int n; { return mkInt(n); }
2560 static Cell makeChar(n) Char n; { return mkChar(n); }
2561 static Char CharOf(n) Cell n; { return charOf(n); }
2562 static Cell makeFloat(n) FloatPro n; { return mkFloat(n); }
2563 static Void* derefMallocPtr(n) Cell n; { return derefMP(n); }
2564 static Cell* Fst(n) Cell n; { return (Cell*)&fst(n); }
2565 static Cell* Snd(n) Cell n; { return (Cell*)&snd(n); }
2567 HugsAPI1* hugsAPI1() {
2568 static HugsAPI1 api;
2569 static Bool initialised = FALSE;
2571 api.nameTrue = nameTrue;
2572 api.nameFalse = nameFalse;
2573 api.nameNil = nameNil;
2574 api.nameCons = nameCons;
2575 api.nameJust = nameJust;
2576 api.nameNothing = nameNothing;
2577 api.nameLeft = nameLeft;
2578 api.nameRight = nameRight;
2579 api.nameUnit = nameUnit;
2580 api.nameIORun = nameIORun;
2581 api.makeInt = makeInt;
2582 api.makeChar = makeChar;
2583 api.CharOf = CharOf;
2584 api.makeFloat = makeFloat;
2585 api.makeTuple = makeTuple;
2587 api.mkMallocPtr = mkMallocPtr;
2588 api.derefMallocPtr = derefMallocPtr;
2589 api.mkStablePtr = mkStablePtr;
2590 api.derefStablePtr = derefStablePtr;
2591 api.freeStablePtr = freeStablePtr;
2593 api.evalWithNoError = evalWithNoError;
2594 api.evalFails = evalFails;
2595 api.whnfArgs = &whnfArgs;
2596 api.whnfHead = &whnfHead;
2597 api.whnfInt = &whnfInt;
2598 api.whnfFloat = &whnfFloat;
2599 api.garbageCollect = garbageCollect;
2600 api.stackOverflow = hugsStackOverflow;
2601 api.internal = internal;
2602 api.registerPrims = registerPrims;
2603 api.addPrimCfun = addPrimCfun;
2604 api.inventText = inventText;
2607 api.cellStack = cellStack;
2613 #endif /* GREENCARD */
2616 /* --------------------------------------------------------------------------
2618 * ------------------------------------------------------------------------*/
2621 static void far* safeFarCalloc Args((Int,Int));
2622 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
2623 Int n, s; { /* for non-null return */
2624 void far* tab = farCalloc(n,s);
2626 ERRMSG(0) "Cannot allocate run-time tables"
2631 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
2633 #define TABALLOC(v,t,n)
2641 case RESET : clearStack();
2643 /* the next 2 statements are particularly important
2644 * if you are using GLOBALfst or GLOBALsnd since the
2645 * corresponding registers may be reset to their
2646 * uninitialised initial values by a longjump.
2648 heapTopFst = heapFst + heapSize;
2649 heapTopSnd = heapSnd + heapSize;
2653 if (isNull(lastExprSaved))
2654 savedText = NUM_TEXT;
2659 for (i=NAMEMIN; i<nameHw; ++i) {
2660 mark(name(i).parent);
2662 mark(name(i).stgVar);
2665 end("Names", nameHw-NAMEMIN);
2668 for (i=MODMIN; i<moduleHw; ++i) {
2669 mark(module(i).tycons);
2670 mark(module(i).names);
2671 mark(module(i).classes);
2672 mark(module(i).exports);
2673 mark(module(i).qualImports);
2675 end("Modules", moduleHw-MODMIN);
2678 for (i=TYCMIN; i<tyconHw; ++i) {
2679 mark(tycon(i).defn);
2680 mark(tycon(i).kind);
2681 mark(tycon(i).what);
2683 end("Type constructors", tyconHw-TYCMIN);
2686 for (i=CLASSMIN; i<classHw; ++i) {
2687 mark(cclass(i).head);
2688 mark(cclass(i).kinds);
2689 mark(cclass(i).fds);
2690 mark(cclass(i).xfds);
2691 mark(cclass(i).dsels);
2692 mark(cclass(i).supers);
2693 mark(cclass(i).members);
2694 mark(cclass(i).defaults);
2695 mark(cclass(i).instances);
2698 end("Classes", classHw-CLASSMIN);
2701 for (i=INSTMIN; i<instHw; ++i) {
2703 mark(inst(i).kinds);
2704 mark(inst(i).specifics);
2705 mark(inst(i).implements);
2707 end("Instances", instHw-INSTMIN);
2710 for (i=0; i<=sp; ++i)
2715 mark(lastExprSaved);
2718 end("Last expression", 3);
2723 end("C stack", stackRoots);
2728 case INSTALL : heapFst = heapAlloc(heapSize);
2729 heapSnd = heapAlloc(heapSize);
2731 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
2732 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
2737 heapTopFst = heapFst + heapSize;
2738 heapTopSnd = heapSnd + heapSize;
2739 for (i=1; i<heapSize; ++i) {
2743 snd(-heapSize) = NIL;
2750 marksSize = bitArraySize(heapSize);
2751 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
2752 ERRMSG(0) "Unable to allocate gc markspace"
2756 TABALLOC(text, char, NUM_TEXT)
2757 TABALLOC(tyconHash, Tycon, TYCONHSZ)
2758 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
2759 TABALLOC(nameHash, Name, NAMEHSZ)
2760 TABALLOC(tabName, struct strName, NUM_NAME)
2761 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
2762 TABALLOC(cellStack, Cell, NUM_STACK)
2763 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
2765 TABALLOC(tabExt, Text, NUM_EXT)
2770 nextNewText = NUM_TEXT;
2771 nextNewDText = (-1);
2772 lastExprSaved = NIL;
2773 savedText = NUM_TEXT;
2774 for (i=0; i<TEXTHSZ; ++i)
2775 textHash[i][0] = NOTEXT;
2781 for (i=0; i<TYCONHSZ; ++i)
2788 for (i=0; i<NAMEHSZ; ++i)
2799 tabInst = (struct strInst far *)
2800 farCalloc(NUM_INSTS,sizeof(struct strInst));
2803 ERRMSG(0) "Cannot allocate instance tables"
2813 /*-------------------------------------------------------------------------*/