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/06 16:47:07 $
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 module(currentModule).tycons = cons(tyconHw,module(currentModule).tycons);
472 tycon(tyconHw).nextTyconHash = tyconHash[h];
473 tyconHash[h] = tyconHw;
478 Tycon findTycon(t) /* locate Tycon in tycon table */
480 Tycon tc = tyconHash[tHash(t)];
482 while (nonNull(tc) && tycon(tc).text!=t)
483 tc = tycon(tc).nextTyconHash;
487 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
489 Tycon oldtc = findTycon(tycon(tc).text);
492 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
498 static Void local hashTycon(tc) /* Insert Tycon into hash table */
500 assert(isTycon(tc) || isTuple(tc));
502 Text t = tycon(tc).text;
504 tycon(tc).nextTyconHash = tyconHash[h];
509 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
511 if (!isPair(id)) internal("findQualTycon");
515 return findTycon(textOf(id));
517 Text t = qtextOf(id);
518 Module m = findQualifier(qmodOf(id));
520 if (isNull(m)) return NIL;
521 for(es=module(m).exports; nonNull(es); es=tl(es)) {
523 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
528 default : internal("findQualTycon2");
530 return NIL; /* NOTREACHED */
533 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
539 Tycon tc = newTycon(t);
541 tycon(tc).kind = kind;
542 tycon(tc).what = what;
543 tycon(tc).defn = defn;
544 tycon(tc).arity = ar;
548 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
553 String s = textToStr(tycon(tc).text);
555 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
556 if (hd(curr)==tc) /* just in case we get duplicates! */
562 tl(prev) = cons(tc,curr);
566 return cons(tc,curr);
569 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
570 String pat; /* to list of Tycons ts */
571 List ts; { /* Null pattern matches every tycon*/
572 Tycon tc; /* (Tycons with NIL kind excluded) */
573 for (tc=TYCMIN; tc<tyconHw; ++tc)
574 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
575 if (nonNull(tycon(tc).kind))
576 ts = insertTycon(tc,ts);
580 Text ghcTupleText(tup)
584 assert(isTuple(tup));
586 if (tup >= 100) internal("ghcTupleText");
588 for (i = 1; i <= tup; i++) buf[i] = ',';
591 return findText(buf);
594 Tycon mkTuple ( Int n )
598 internal("mkTuple: request for tuple of unsupported size");
599 for (i = TYCMIN; i < tyconHw; i++)
600 if (tycon(i).tuple == n) return i;
601 internal("mkTuple: request for non-existent tuple");
604 Void allocTupleTycon ( Int n )
610 for (i = TYCMIN; i < tyconHw; i++)
611 if (tycon(i).tuple == n) return;
612 sprintf(buf,"Tuple%d",n);
613 //t = addPrimTycon(findText(buf),simpleKind(n),n, DATATYPE,NIL);
616 for (i = 0; i < n; i++) k = ap(STAR,k);
617 t = newTycon(findText(buf));
620 tycon(t).what = DATATYPE;
623 /* --------------------------------------------------------------------------
626 * A Name represents a top level binding of a value to an identifier.
627 * Such values may be a constructor function, a member function in a
628 * class, a user-defined or primitive value/function.
630 * Names are indexed by Text values ... a very simple hash functions speeds
631 * access to the table of Names and Name entries with the same hash value
632 * are chained together, with the most recent entry at the front of the
634 * ------------------------------------------------------------------------*/
636 #define NAMEHSZ 256 /* Size of Name hash table */
637 #define nHash(x) ((x)%NAMEHSZ) /* hash fn :: Text->Int */
638 Name nameHw; /* next unused name */
639 static Name DEFTABLE(nameHash,NAMEHSZ); /* Hash table storage */
640 struct strName DEFTABLE(tabName,NUM_NAME); /* Name table storage */
642 Name newName(t,parent) /* Add new name to name table */
646 if (nameHw-NAMEMIN >= NUM_NAME) {
647 ERRMSG(0) "Name storage space exhausted"
650 name(nameHw).text = t; /* clear new name record */
651 name(nameHw).line = 0;
652 name(nameHw).syntax = NO_SYNTAX;
653 name(nameHw).parent = parent;
654 name(nameHw).arity = 0;
655 name(nameHw).number = EXECNAME;
656 name(nameHw).defn = NIL;
657 name(nameHw).stgVar = NIL;
658 name(nameHw).callconv = NIL;
659 name(nameHw).type = NIL;
660 name(nameHw).primop = 0;
661 name(nameHw).mod = currentModule;
662 module(currentModule).names=cons(nameHw,module(currentModule).names);
663 name(nameHw).nextNameHash = nameHash[h];
664 nameHash[h] = nameHw;
668 Name findName(t) /* Locate name in name table */
670 Name n = nameHash[nHash(t)];
672 while (nonNull(n) && name(n).text!=t)
673 n = name(n).nextNameHash;
677 Name addName(nm) /* Insert Name in name table - if */
678 Name nm; { /* no clash is caused */
679 Name oldnm = findName(name(nm).text);
682 module(currentModule).names=cons(nm,module(currentModule).names);
688 static Void local hashName(nm) /* Insert Name into hash table */
695 name(nm).nextNameHash = nameHash[h];
699 Name findQualName(id) /* Locate (possibly qualified) name*/
700 Cell id; { /* in name table */
702 internal("findQualName");
708 return findName(textOf(id));
710 Text t = qtextOf(id);
711 Module m = findQualifier(qmodOf(id));
713 if (isNull(m)) return NIL;
714 for(es=module(m).exports; nonNull(es); es=tl(es)) {
716 if (isName(e) && name(e).text==t)
718 else if (isPair(e) && DOTDOT==snd(e)) {
719 List subentities = NIL;
722 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
723 subentities = tycon(c).defn;
725 subentities = cclass(c).members;
726 for(; nonNull(subentities); subentities=tl(subentities)) {
727 if (!isName(hd(subentities)))
728 internal("findQualName3");
729 if (name(hd(subentities)).text == t)
730 return hd(subentities);
736 default : internal("findQualName2");
738 return 0; /* NOTREACHED */
742 Name nameFromStgVar ( StgVar v )
745 for (n = NAMEMIN; n < nameHw; n++)
746 if (name(n).stgVar == v) return n;
750 void* getHugs_AsmObject_for ( char* s )
753 Text t = findText(s);
755 for (n = NAMEMIN; n < nameHw; n++)
756 if (name(n).text == t) break;
757 if (n == nameHw) internal("getHugs_AsmObject_for(1)");
759 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
760 internal("getHugs_AsmObject_for(2)");
761 return ptrOf(stgVarInfo(v));
764 /* --------------------------------------------------------------------------
765 * Primitive functions:
766 * ------------------------------------------------------------------------*/
768 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
769 Text t; /* sets rep, not type */
772 Int rep; { /* Really AsmRep */
773 Name n = newName(t,NIL);
774 name(n).arity = arity;
775 name(n).number = cfunNo(no);
777 name(n).primop = (void*)rep;
782 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
787 Name n = newName(t,NIL);
788 name(n).arity = arity;
789 name(n).number = cfunNo(no);
795 Int sfunPos(s,c) /* Find position of field with */
796 Name s; /* selector s in constructor c. */
800 for (; nonNull(cns); cns=tl(cns))
802 return intOf(snd(hd(cns)));
804 return 0;/* NOTREACHED */
807 static List local insertName(nm,ns) /* insert name nm into sorted list */
812 String s = textToStr(name(nm).text);
814 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
815 if (hd(curr)==nm) /* just in case we get duplicates! */
821 tl(prev) = cons(nm,curr);
825 return cons(nm,curr);
828 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
829 String pat; /* to list of names ns */
830 List ns; { /* Null pattern matches every name */
831 Name nm; /* (Names with NIL type, or hidden */
833 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
834 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
835 String str = textToStr(name(nm).text);
836 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
837 ns = insertName(nm,ns);
841 List mns = module(currentModule).names;
842 for(; nonNull(mns); mns=tl(mns)) {
844 if (!inventedText(name(nm).text)) {
845 String str = textToStr(name(nm).text);
846 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
847 ns = insertName(nm,ns);
854 /* --------------------------------------------------------------------------
855 * A simple string matching routine
856 * `*' matches any sequence of zero or more characters
857 * `?' matches any single character exactly
858 * `@str' matches the string str exactly (ignoring any special chars)
859 * `\c' matches the character c only (ignoring special chars)
860 * c matches the character c only
861 * ------------------------------------------------------------------------*/
863 static Void local patternError(s) /* report error in pattern */
865 ERRMSG(0) "%s in pattern", s
869 static Bool local stringMatch(pat,str) /* match string against pattern */
875 case '\0' : return (*str=='\0');
878 if (stringMatch(pat+1,str))
883 case '?' : if (*str++=='\0')
888 case '[' : { Bool found = FALSE;
889 while (*++pat!='\0' && *pat!=']')
890 if (!found && ( pat[0] == *str ||
899 patternError("missing `]'");
907 case '\\' : if (*++pat == '\0')
908 patternError("extra trailing `\\'");
910 default : if (*pat++ != *str++)
916 /* --------------------------------------------------------------------------
917 * Storage of type classes, instances etc...:
918 * ------------------------------------------------------------------------*/
920 static Class classHw; /* next unused class */
921 static List classes; /* list of classes in current scope */
922 static Inst instHw; /* next unused instance record */
924 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
925 struct strInst far *tabInst; /* (pointer to) table of instances */
927 Class newClass(t) /* add new class to class table */
929 if (classHw-CLASSMIN >= NUM_CLASSES) {
930 ERRMSG(0) "Class storage space exhausted"
933 cclass(classHw).text = t;
934 cclass(classHw).arity = 0;
935 cclass(classHw).kinds = NIL;
936 cclass(classHw).head = NIL;
937 cclass(classHw).fds = NIL;
938 cclass(classHw).xfds = NIL;
939 cclass(classHw).dcon = NIL;
940 cclass(classHw).supers = NIL;
941 cclass(classHw).dsels = NIL;
942 cclass(classHw).members = NIL;
943 cclass(classHw).defaults = NIL;
944 cclass(classHw).instances = NIL;
945 classes=cons(classHw,classes);
946 cclass(classHw).mod = currentModule;
947 module(currentModule).classes=cons(classHw,module(currentModule).classes);
951 Class classMax() { /* Return max Class in use ... */
952 return classHw; /* This is a bit ugly, but it's not*/
953 } /* worth a lot of effort right now */
955 Class findClass(t) /* look for named class in table */
959 for (cs=classes; nonNull(cs); cs=tl(cs)) {
961 if (cclass(cl).text==t)
967 Class addClass(c) /* Insert Class in class list */
968 Class c; { /* - if no clash caused */
969 Class oldc = findClass(cclass(c).text);
971 classes=cons(c,classes);
972 module(currentModule).classes=cons(c,module(currentModule).classes);
979 Class findQualClass(c) /* Look for (possibly qualified) */
980 Cell c; { /* class in class list */
981 if (!isQualIdent(c)) {
982 return findClass(textOf(c));
985 Module m = findQualifier(qmodOf(c));
989 for (es=module(m).exports; nonNull(es); es=tl(es)) {
991 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
998 Inst newInst() { /* Add new instance to table */
999 if (instHw-INSTMIN >= NUM_INSTS) {
1000 ERRMSG(0) "Instance storage space exhausted"
1003 inst(instHw).kinds = NIL;
1004 inst(instHw).head = NIL;
1005 inst(instHw).specifics = NIL;
1006 inst(instHw).implements = NIL;
1007 inst(instHw).builder = NIL;
1008 inst(instHw).mod = currentModule;
1014 extern Void printInst Args((Inst));
1018 Class cl = inst(in).c;
1019 Printf("%s-", textToStr(cclass(cl).text));
1020 printType(stdout,inst(in).t);
1022 #endif /* DEBUG_DICTS */
1024 Inst findFirstInst(tc) /* look for 1st instance involving */
1025 Tycon tc; { /* the type constructor tc */
1026 return findNextInst(tc,INSTMIN-1);
1029 Inst findNextInst(tc,in) /* look for next instance involving*/
1030 Tycon tc; /* the type constructor tc */
1031 Inst in; { /* starting after instance in */
1032 while (++in < instHw) {
1033 Cell pi = inst(in).head;
1034 for (; isAp(pi); pi=fun(pi))
1035 if (typeInvolves(arg(pi),tc))
1041 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1042 Type ty; /* type constructor/tuple tc. */
1045 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1046 || typeInvolves(arg(ty),tc)));
1049 /* --------------------------------------------------------------------------
1052 * Various parts of the system use a stack of cells. Most of the stack
1053 * operations are defined as macros, expanded inline.
1054 * ------------------------------------------------------------------------*/
1056 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
1057 StackPtr sp; /* stack pointer */
1059 #if GIMME_STACK_DUMPS
1061 #define UPPER_DISP 5 /* # display entries on top of stack */
1062 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
1064 Void hugsStackOverflow() { /* Report stack overflow */
1066 extern Cell evalRoots[];
1068 ERRMSG(0) "Control stack overflow" ETHEN
1071 if (rootsp>=UPPER_DISP+LOWER_DISP) {
1072 for (i=0; i<UPPER_DISP; i++) {
1073 ERRTEXT "\nwhile evaluating: " ETHEN
1074 ERREXPR(evalRoots[rootsp-i]);
1076 ERRTEXT "\n..." ETHEN
1077 for (i=LOWER_DISP-1; i>=0; i--) {
1078 ERRTEXT "\nwhile evaluating: " ETHEN
1079 ERREXPR(evalRoots[i]);
1083 for (i=rootsp; i>=0; i--) {
1084 ERRTEXT "\nwhile evaluating: " ETHEN
1085 ERREXPR(evalRoots[i]);
1093 #else /* !GIMME_STACK_DUMPS */
1095 Void hugsStackOverflow() { /* Report stack overflow */
1096 ERRMSG(0) "Control stack overflow"
1100 #endif /* !GIMME_STACK_DUMPS */
1102 /* --------------------------------------------------------------------------
1105 * A Module represents a user defined module.
1107 * Note: there are now two lookup mechanisms in the system:
1109 * 1) The exports from a module are stored in a big list.
1110 * We resolve qualified names, and import lists by linearly scanning
1111 * through this list.
1113 * 2) Unqualified imports and local definitions for the current module
1114 * are stored in hash tables (tyconHash and nameHash) or linear lists
1117 * ------------------------------------------------------------------------*/
1119 static Module moduleHw; /* next unused Module */
1120 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
1121 Module currentModule; /* Module currently being processed*/
1123 Bool isValidModule(m) /* is m a legitimate module id? */
1125 return (MODMIN <= m && m < moduleHw);
1128 Module newModule(t) /* add new module to module table */
1130 if (moduleHw-MODMIN >= NUM_MODULE) {
1131 ERRMSG(0) "Module storage space exhausted"
1134 module(moduleHw).text = t; /* clear new module record */
1135 module(moduleHw).qualImports = NIL;
1136 module(moduleHw).exports = NIL;
1137 module(moduleHw).tycons = NIL;
1138 module(moduleHw).names = NIL;
1139 module(moduleHw).classes = NIL;
1140 module(moduleHw).oImage = NULL;
1141 module(moduleHw).oTab = NULL;
1142 module(moduleHw).sizeoTab = 0;
1143 module(moduleHw).usedoTab = 0;
1144 module(moduleHw).dlTab = NULL;
1145 module(moduleHw).sizedlTab = 0;
1146 module(moduleHw).useddlTab = 0;
1150 void ppModules ( void )
1153 fflush(stderr); fflush(stdout);
1154 printf ( "begin MODULES\n" );
1155 for (i = moduleHw-1; i >= MODMIN; i--)
1156 printf ( " %2d: %16s\n",
1157 i-MODMIN, textToStr(module(i).text)
1159 printf ( "end MODULES\n" );
1160 fflush(stderr); fflush(stdout);
1164 Module findModule(t) /* locate Module in module table */
1167 for(m=MODMIN; m<moduleHw; ++m) {
1168 if (module(m).text==t)
1174 Module findModid(c) /* Find module by name or filename */
1176 switch (whatIs(c)) {
1177 case STRCELL : { Script s = scriptThisFile(snd(c));
1178 return (s==-1) ? NIL : moduleOfScript(s);
1180 case CONIDCELL : return findModule(textOf(c));
1181 default : internal("findModid");
1183 return NIL;/*NOTUSED*/
1186 static local Module findQualifier(t) /* locate Module in import list */
1189 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1190 if (textOf(fst(hd(ms)))==t)
1194 if (module(currentModule).text==t)
1195 return currentModule;
1200 Void setCurrModule(m) /* set lookup tables for current module */
1203 assert(isModule(m));
1204 if (m!=currentModule) {
1205 currentModule = m; /* This is the only assignment to currentModule */
1206 for (i=0; i<TYCONHSZ; ++i)
1208 mapProc(hashTycon,module(m).tycons);
1209 for (i=0; i<NAMEHSZ; ++i)
1211 mapProc(hashName,module(m).names);
1212 classes = module(m).classes;
1216 Name jrsFindQualName ( Text mn, Text sn )
1221 for (m=MODMIN; m<moduleHw; m++)
1222 if (module(m).text == mn) break;
1223 if (m == moduleHw) return NIL;
1225 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1226 if (name(hd(ns)).text == sn) return hd(ns);
1232 /* A bit tricky. Assumes that if tab==NULL, then
1233 currUsed and *currSize must be zero.
1236 void* genericExpand ( void* tab,
1237 int* currSize, int currUsed,
1238 int initSize, int elemSize )
1242 if (currUsed < *currSize)
1244 size2 = (*currSize == 0) ? initSize : (2 * *currSize);
1245 tab2 = malloc ( size2 * elemSize );
1247 ERRMSG(0) "Can't allocate enough memory to resize a table"
1251 memcpy ( tab2, tab, elemSize * *currSize );
1253 if (tab) free ( tab );
1257 void addOTabName ( Module m, char* nm, void* ad )
1260 = genericExpand ( module(m).oTab,
1261 &module(m).sizeoTab,
1265 module(m).oTab[ module(m).usedoTab ].nm = nm;
1266 module(m).oTab[ module(m).usedoTab ].ad = ad;
1267 module(m).usedoTab++;
1271 void addDLSect ( Module m, void* start, void* end, DLSect sect )
1274 = genericExpand ( module(m).dlTab,
1275 &module(m).sizedlTab,
1276 module(m).useddlTab,
1277 4, sizeof(DLTabEnt) );
1278 module(m).dlTab[ module(m).useddlTab ].start = start;
1279 module(m).dlTab[ module(m).useddlTab ].end = end;
1280 module(m).dlTab[ module(m).useddlTab ].sect = sect;
1281 module(m).useddlTab++;
1285 void* lookupOTabName ( Module m, char* nm )
1288 for (i = 0; i < module(m).usedoTab; i++) {
1291 "lookupOTabName: request %s, table has %s\n",
1292 nm, module(m).oTab[i].nm );
1293 if (0==strcmp(nm,module(m).oTab[i].nm))
1294 return module(m).oTab[i].ad;
1300 char* nameFromOPtr ( void* p )
1304 for (m=MODMIN; m<moduleHw; m++)
1305 for (i = 0; i < module(m).usedoTab; i++)
1306 if (p == module(m).oTab[i].ad)
1307 return module(m).oTab[i].nm;
1312 DLSect lookupDLSect ( void* ad )
1316 for (m=MODMIN; m<moduleHw; m++)
1317 for (i = 0; i < module(m).useddlTab; i++)
1318 if (module(m).dlTab[i].start <= ad &&
1319 ad <= module(m).dlTab[i].end)
1320 return module(m).dlTab[i].sect;
1321 return HUGS_DL_SECTION_OTHER;
1325 /* --------------------------------------------------------------------------
1326 * Script file storage:
1328 * script files are read into the system one after another. The state of
1329 * the stored data structures (except the garbage-collected heap) is recorded
1330 * before reading a new script. In the event of being unable to read the
1331 * script, or if otherwise requested, the system can be restored to its
1332 * original state immediately before the file was read.
1333 * ------------------------------------------------------------------------*/
1335 typedef struct { /* record of storage state prior to */
1336 Text file; /* reading script/module */
1350 #ifdef DEBUG_SHOWUSE
1351 static Void local showUse(msg,val,mx)
1354 Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1358 static Script scriptHw; /* next unused script number */
1359 static script scripts[NUM_SCRIPTS]; /* storage for script records */
1362 void ppScripts ( void )
1365 fflush(stderr); fflush(stdout);
1366 printf ( "begin SCRIPTS\n" );
1367 for (i = scriptHw-1; i >= 0; i--)
1368 printf ( " %2d: %16s tH=%d mH=%d yH=%d "
1369 "nH=%d cH=%d iH=%d nnS=%d,%d\n",
1370 i, textToStr(scripts[i].file),
1371 scripts[i].textHw, scripts[i].moduleHw,
1372 scripts[i].tyconHw, scripts[i].nameHw,
1373 scripts[i].classHw, scripts[i].instHw,
1374 scripts[i].nextNewText, scripts[i].nextNewDText
1376 printf ( "end SCRIPTS\n" );
1377 fflush(stderr); fflush(stdout);
1380 Script startNewScript(f) /* start new script, keeping record */
1381 String f; { /* of status for later restoration */
1382 if (scriptHw >= NUM_SCRIPTS) {
1383 ERRMSG(0) "Too many script files in use"
1386 #ifdef DEBUG_SHOWUSE
1387 showUse("Text", textHw, NUM_TEXT);
1388 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
1389 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
1390 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
1391 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
1392 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
1394 showUse("Ext", extHw-EXTMIN, NUM_EXT);
1397 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
1398 scripts[scriptHw].textHw = textHw;
1399 scripts[scriptHw].nextNewText = nextNewText;
1400 scripts[scriptHw].nextNewDText = nextNewDText;
1401 scripts[scriptHw].moduleHw = moduleHw;
1402 scripts[scriptHw].tyconHw = tyconHw;
1403 scripts[scriptHw].nameHw = nameHw;
1404 scripts[scriptHw].classHw = classHw;
1405 scripts[scriptHw].instHw = instHw;
1407 scripts[scriptHw].extHw = extHw;
1412 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1413 return (scriptHw==0);
1416 Bool moduleThisScript(m) /* Test if given module is defined */
1417 Module m; { /* in current script file */
1418 return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
1421 Module lastModule() { /* Return module in current script file */
1422 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1425 #define scriptThis(nm,t,tag) Script nm(x) \
1429 && x>=scripts[s].tag) \
1433 scriptThis(scriptThisName,Name,nameHw)
1434 scriptThis(scriptThisTycon,Tycon,tyconHw)
1435 scriptThis(scriptThisInst,Inst,instHw)
1436 scriptThis(scriptThisClass,Class,classHw)
1439 Module moduleOfScript(s)
1441 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1444 String fileOfModule(m)
1447 if (m == modulePrelude) {
1450 for(s=0; s<scriptHw; ++s) {
1451 if (scripts[s].moduleHw == m) {
1452 return textToStr(scripts[s].file);
1458 Script scriptThisFile(f)
1461 for (s=0; s < scriptHw; ++s) {
1462 if (scripts[s].file == f) {
1466 if (f == findText(STD_PRELUDE)) {
1472 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1473 Script sno; { /* to reading script sno */
1474 if (sno<scriptHw) { /* is there anything to restore? */
1476 textHw = scripts[sno].textHw;
1477 nextNewText = scripts[sno].nextNewText;
1478 nextNewDText = scripts[sno].nextNewDText;
1479 moduleHw = scripts[sno].moduleHw;
1480 tyconHw = scripts[sno].tyconHw;
1481 nameHw = scripts[sno].nameHw;
1482 classHw = scripts[sno].classHw;
1483 instHw = scripts[sno].instHw;
1485 dictHw = scripts[sno].dictHw;
1488 extHw = scripts[sno].extHw;
1492 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1493 if (module(i).objectFile) {
1494 printf("[bogus] closing objectFile for module %d\n",i);
1495 /*dlclose(module(i).objectFile);*/
1498 moduleHw = scripts[sno].moduleHw;
1500 for (i=0; i<TEXTHSZ; ++i) {
1502 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1503 && textHash[i][j]<textHw)
1506 textHash[i][j] = NOTEXT;
1510 for (i=0; i<TYCONHSZ; ++i) {
1513 for (i=0; i<NAMEHSZ; ++i) {
1517 for (i=CLASSMIN; i<classHw; i++) {
1518 List ins = cclass(i).instances;
1521 while (nonNull(ins)) {
1522 List temp = tl(ins);
1523 if (hd(ins)<instHw) {
1529 cclass(i).instances = rev(is);
1536 /* --------------------------------------------------------------------------
1539 * Provides a garbage collectable heap for storage of expressions etc.
1541 * Now incorporates a flat resource: A two-space collected extension of
1542 * the heap that provides storage for contiguous arrays of Cell storage,
1543 * cooperating with the garbage collection mechanisms for the main heap.
1544 * ------------------------------------------------------------------------*/
1546 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1547 Heap heapFst; /* array of fst component of pairs */
1548 Heap heapSnd; /* array of snd component of pairs */
1555 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1556 /* C stack; use with extreme care! */
1558 Int numGcs; /* number of garbage collections */
1559 Int cellsRecovered; /* number of cells recovered */
1561 static Cell freeList; /* free list of unused cells */
1562 static Cell lsave, rsave; /* save components of pair */
1566 static Int markCount, stackRoots;
1568 #define initStackRoots() stackRoots = 0
1569 #define recordStackRoot() stackRoots++
1582 #define start() markCount = 0
1583 #define end(thing,rs) \
1585 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1588 #define recordMark() markCount++
1590 #else /* !GC_STATISTICS */
1595 #define initStackRoots()
1596 #define recordStackRoot()
1599 #define end(thing,root)
1600 #define recordMark()
1602 #endif /* !GC_STATISTICS */
1604 Cell pair(l,r) /* Allocate pair (l, r) from */
1605 Cell l, r; { /* heap, garbage collecting first */
1606 Cell c = freeList; /* if necessary ... */
1618 freeList = snd(freeList);
1625 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1626 Cell dst, src; { /* both *MUST* be pairs */
1627 if (isPair(dst) && isPair(src)) {
1628 fst(dst) = fst(src);
1629 snd(dst) = snd(src);
1632 internal("overwrite");
1636 static Int marksSize;
1638 Cell markExpr(c) /* External interface to markCell */
1640 return isGenPair(c) ? markCell(c) : c;
1643 static Cell local markCell(c) /* Traverse part of graph marking */
1644 Cell c; { /* cells reachable from given root */
1645 /* markCell(c) is only called if c */
1647 { register int place = placeInSet(c);
1648 register int mask = maskInSet(c);
1649 if (marks[place]&mask)
1652 marks[place] |= mask;
1657 /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1658 if (isGenPair(fst(c))) {
1660 fst(c) = markCell(fst(c));
1663 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1671 static Void local markSnd(c) /* Variant of markCell used to */
1672 Cell c; { /* update snd component of cell */
1673 Cell t; /* using tail recursion */
1675 ma: t = c; /* Keep pointer to original pair */
1680 { register int place = placeInSet(c);
1681 register int mask = maskInSet(c);
1682 if (marks[place]&mask)
1685 marks[place] |= mask;
1690 if (isGenPair(fst(c))) {
1691 fst(c) = markCell(fst(c));
1694 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1699 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1700 Cell n; { /* it was a cell ref, but don't */
1701 /* move cell so we don't have */
1702 /* to modify the stored value of n */
1709 Void garbageCollect() { /* Run garbage collector ... */
1710 Bool breakStat = breakOn(FALSE); /* disable break checking */
1716 jmp_buf regs; /* save registers on stack */
1720 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1723 everybody(MARK); /* Mark all components of system */
1725 gcScanning(); /* scan mark set */
1732 for (i=1; i<=heapSize; i++) {
1733 if ((marks[place] & mask) == 0) {
1740 if (++j == bitsPerWord) {
1747 gcRecovered(recovered);
1748 breakOn(breakStat); /* restore break trapping if nec. */
1752 /* can only return if freeList is nonempty on return. */
1753 if (recovered<minRecovery || isNull(freeList)) {
1754 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1757 cellsRecovered = recovered;
1760 /* --------------------------------------------------------------------------
1761 * Code for saving last expression entered:
1763 * This is a little tricky because some text values (e.g. strings or variable
1764 * names) may not be defined or have the same value when the expression is
1765 * recalled. These text values are therefore saved in the top portion of
1767 * ------------------------------------------------------------------------*/
1769 static Cell lastExprSaved; /* last expression to be saved */
1771 Void setLastExpr(e) /* save expression for later recall*/
1773 lastExprSaved = NIL; /* in case attempt to save fails */
1774 savedText = NUM_TEXT;
1775 lastExprSaved = lowLevelLastIn(e);
1778 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
1779 Cell c; { /* acyclic graph) for later recall */
1780 if (isPair(c)) { /* Duplicating any text strings */
1781 if (isBoxTag(fst(c))) /* in case these are lost at some */
1782 switch (fst(c)) { /* point before the expr is reused */
1788 case STRCELL : return pair(fst(c),saveText(textOf(c)));
1789 default : return pair(fst(c),snd(c));
1792 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
1796 return pair(EXTCOPY,saveText(extText(c)));
1802 Cell getLastExpr() { /* recover previously saved expr */
1803 return lowLevelLastOut(lastExprSaved);
1806 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
1807 Cell c; { /* except that Cells refering to */
1808 if (isPair(c)) { /* Text values are restored to */
1809 if (isBoxTag(fst(c))) /* appropriate values */
1816 case STRCELL : return pair(fst(c),
1817 findText(text+intValOf(c)));
1819 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
1821 default : return pair(fst(c),snd(c));
1824 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
1830 /* --------------------------------------------------------------------------
1831 * Miscellaneous operations on heap cells:
1832 * ------------------------------------------------------------------------*/
1834 /* Profiling suggests that the number of calls to whatIs() is typically */
1835 /* rather high. The recoded version below attempts to improve the average */
1836 /* performance for whatIs() using a binary search for part of the analysis */
1838 Cell whatIs(c) /* identify type of cell */
1841 register Cell fstc = fst(c);
1842 return isTag(fstc) ? fstc : AP;
1844 if (c<OFFMIN) return c;
1846 if (isExt(c)) return EXT;
1848 if (c>=INTMIN) return INTCELL;
1850 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
1852 else if (c>=INSTMIN) return INSTANCE;
1854 else if (c>=MODMIN) {if (c>=TYCMIN) return isTuple(c) ? TUPLE : TYCON;
1855 else return MODULE;}
1856 else if (c>=OFFMIN) return OFFSET;
1858 else return (c>=EXTMIN) ?
1865 register Cell fstc = fst(c);
1866 return isTag(fstc) ? fstc : AP;
1868 if (c>=INTMIN) return INTCELL;
1869 if (c>=CHARMIN) return CHARCELL;
1870 if (c>=CLASSMIN) return CLASS;
1871 if (c>=INSTMIN) return INSTANCE;
1872 if (c>=NAMEMIN) return NAME;
1873 if (c>=TYCMIN) return TYCON;
1874 if (c>=MODMIN) return MODULE;
1875 if (c>=OFFMIN) return OFFSET;
1877 if (c>=EXTMIN) return EXT;
1879 if (c>=TUPMIN) return TUPLE;
1884 /* A very, very simple printer.
1885 * Output is uglier than from printExp - but the printer is more
1886 * robust and can be used on any data structure irrespective of
1889 Void print Args((Cell, Int));
1890 Void print(c, depth)
1895 #if 0 /* Not in this version of Hugs */
1896 } else if (isPair(c) && !isGenPair(c)) {
1897 extern Void printEvalCell Args((Cell, Int));
1898 printEvalCell(c,depth);
1901 Int tag = whatIs(c);
1905 print(fst(c), depth-1);
1907 print(snd(c), depth-1);
1911 Printf("free(%d)", c);
1914 Printf("int(%d)", intOf(c));
1917 Printf("bignum(%s)", bignumToString(c));
1920 Printf("char('%c')", charOf(c));
1923 Printf("ptr(%p)",ptrOf(c));
1926 Printf("class(%d)", c-CLASSMIN);
1927 if (CLASSMIN <= c && c < classHw) {
1928 Printf("=\"%s\"", textToStr(cclass(c).text));
1932 Printf("instance(%d)", c - INSTMIN);
1935 Printf("name(%d)", c-NAMEMIN);
1936 if (NAMEMIN <= c && c < nameHw) {
1937 Printf("=\"%s\"", textToStr(name(c).text));
1941 Printf("tycon(%d)", c-TYCMIN);
1942 if (TYCMIN <= c && c < tyconHw)
1943 Printf("=\"%s\"", textToStr(tycon(c).text));
1946 Printf("module(%d)", c - MODMIN);
1949 Printf("Offset %d", offsetOf(c));
1952 Printf("Tuple %d", tupleOf(c));
1956 print(snd(c),depth-1);
1960 print(snd(c),depth-1);
1964 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
1965 Printf("%d ", intOf(fst(snd(c))));
1966 print(snd(snd(c)),depth-1);
1968 print(snd(c),depth-1);
1985 Printf("{dict %d}",textOf(c));
1991 Printf("{id %s}",textToStr(textOf(c)));
1995 Printf("{ip %s}",textToStr(textOf(c)));
1998 Printf("?%s",textToStr(textOf(c)));
2002 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2006 print(fst(snd(c)),depth-1);
2008 print(snd(snd(c)),depth-1);
2013 print(snd(c),depth-1);
2018 print(snd(c),depth-1);
2023 print(fst(snd(c)),depth-1);
2025 print(snd(snd(c)),depth-1);
2030 print(fst(snd(c)),depth-1);
2032 print(snd(snd(c)),depth-1);
2036 Printf("FromQual(");
2037 print(fst(snd(c)),depth-1);
2039 print(snd(snd(c)),depth-1);
2043 Printf("StgVar%d=",-c);
2044 print(snd(c), depth-1);
2048 print(fst(snd(c)),depth-1);
2050 print(snd(snd(c)),depth-1);
2055 print(fst(snd(c)),depth-1);
2057 print(snd(snd(c)),depth-1);
2062 print(fst(snd(c)),depth-1);
2064 print(snd(snd(c)),depth-1);
2068 Printf("PrimCase(");
2069 print(fst(snd(c)),depth-1);
2071 print(snd(snd(c)),depth-1);
2076 print(snd(c),depth-1);
2080 Printf("(UNBOXEDTUP,");
2081 print(snd(c),depth-1);
2086 print(snd(c),depth-1);
2090 if (isBoxTag(tag)) {
2091 Printf("Tag(%d)=%d", c, tag);
2092 } else if (isConTag(tag)) {
2093 Printf("%d@(%d,",c,tag);
2094 print(snd(c), depth-1);
2097 } else if (c == tag) {
2098 Printf("Tag(%d)", c);
2100 Printf("Tag(%d)=%d", c, tag);
2109 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2110 Cell c; { /* also recognises DICTVAR cells */
2112 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2115 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2117 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2120 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2122 if (!isPair(c)) return FALSE;
2125 case VAROPCELL : return TRUE;
2127 case QUALIDENT : return isVar(snd(snd(c)));
2129 default : return FALSE;
2133 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2135 if (!isPair(c)) return FALSE;
2138 case CONOPCELL : return TRUE;
2140 case QUALIDENT : return isCon(snd(snd(c)));
2142 default : return FALSE;
2146 Bool isQualIdent(c) /* is cell a qualified identifier? */
2148 return isPair(c) && (fst(c)==QUALIDENT);
2151 Bool isIdent(c) /* is cell an identifier? */
2153 if (!isPair(c)) return FALSE;
2158 case CONOPCELL : return TRUE;
2160 case QUALIDENT : return TRUE;
2162 default : return FALSE;
2166 Bool isInt(c) /* cell holds integer value? */
2168 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2171 Int intOf(c) /* find integer value of cell? */
2175 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
2178 Cell mkInt(n) /* make cell representing integer */
2180 return (MINSMALLINT <= n && n <= MAXSMALLINT)
2185 #if SIZEOF_INTP == SIZEOF_INT
2186 typedef union {Int i; Ptr p;} IntOrPtr;
2192 return pair(PTRCELL,x.i);
2199 assert(fst(c) == PTRCELL);
2208 return pair(CPTRCELL,x.i);
2215 assert(fst(c) == CPTRCELL);
2219 #elif SIZEOF_INTP == 2*SIZEOF_INT
2220 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2226 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2233 assert(fst(c) == PTRCELL);
2234 x.i.i1 = intOf(fst(snd(c)));
2235 x.i.i2 = intOf(snd(snd(c)));
2239 #warning "type Addr not supported on this architecture - don't use it"
2243 ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
2250 ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
2255 String stringNegate( s )
2263 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2268 /* --------------------------------------------------------------------------
2270 * ------------------------------------------------------------------------*/
2272 Int length(xs) /* calculate length of list xs */
2275 for (; nonNull(xs); ++n)
2280 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2281 List xs, ys; { /* ys by modifying xs ... */
2286 while (nonNull(tl(zs)))
2293 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2296 for (; nonNull(xs); xs=tl(xs))
2297 ys = cons(hd(xs),ys);
2301 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2304 return revOnto(dupOnto(xs,NIL),ys);
2307 List dupList(xs) /* Duplicate spine of list xs */
2310 for (; nonNull(xs); xs=tl(xs))
2311 ys = cons(hd(xs),ys);
2315 List revOnto(xs,ys) /* Destructively reverse elements of*/
2316 List xs, ys; { /* list xs onto list ys... */
2319 while (nonNull(xs)) {
2328 Cell varIsMember(t,xs) /* Test if variable is a member of */
2329 Text t; /* given list of variables */
2331 for (; nonNull(xs); xs=tl(xs))
2332 if (t==textOf(hd(xs)))
2337 Name nameIsMember(t,ns) /* Test if name with text t is a */
2338 Text t; /* member of list of names xs */
2340 for (; nonNull(ns); ns=tl(ns))
2341 if (t==name(hd(ns)).text)
2346 Cell intIsMember(n,xs) /* Test if integer n is member of */
2347 Int n; /* given list of integers */
2349 for (; nonNull(xs); xs=tl(xs))
2350 if (n==intOf(hd(xs)))
2355 Cell cellIsMember(x,xs) /* Test for membership of specific */
2356 Cell x; /* cell x in list xs */
2358 for (; nonNull(xs); xs=tl(xs))
2364 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2367 for (; nonNull(xs); xs=tl(xs))
2373 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2374 Cell c; /* association lists */
2376 for (; nonNull(xs); xs=tl(xs))
2382 List replicate(n,x) /* create list of n copies of x */
2391 List diffList(from,take) /* list difference: from\take */
2392 List from, take; { /* result contains all elements of */
2393 List result = NIL; /* `from' not appearing in `take' */
2395 while (nonNull(from)) {
2396 List next = tl(from);
2397 if (!cellIsMember(hd(from),take)) {
2406 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2410 for(;nonNull(xs);xs=tl(xs)) {
2413 result=cons(x,result);
2419 List take(n,xs) /* destructively truncate list to */
2420 Int n; /* specified length */
2426 while (1<n-- && nonNull(xs))
2433 List splitAt(n,xs) /* drop n things from front of list*/
2442 Cell nth(n,xs) /* extract n'th element of list */
2445 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2452 List removeCell(x,xs) /* destructively remove cell from */
2457 return tl(xs); /* element at front of list */
2461 for (; nonNull(curr); prev=curr, curr=tl(prev))
2463 tl(prev) = tl(curr);
2464 return xs; /* element in middle of list */
2468 return xs; /* here if element not found */
2471 List nubList(xs) /* nuke dups in list */
2472 List xs; { /* non destructive */
2474 for (; nonNull(xs); xs=tl(xs))
2475 if (isNull(cellIsMember(hd(xs),outs)))
2476 outs = cons(hd(xs),outs);
2481 /* --------------------------------------------------------------------------
2482 * Operations on applications:
2483 * ------------------------------------------------------------------------*/
2485 Int argCount; /* number of args in application */
2487 Cell getHead(e) /* get head cell of application */
2488 Cell e; { /* set number of args in argCount */
2489 for (argCount=0; isAp(e); e=fun(e))
2494 List getArgs(e) /* get list of arguments in function*/
2495 Cell e; { /* application: */
2496 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2498 for (as=NIL; isAp(e); e=fun(e))
2499 as = cons(arg(e),as);
2503 Cell nthArg(n,e) /* return nth arg in application */
2504 Int n; /* of function to m args (m>=n) */
2505 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2506 for (n=numArgs(e)-n-1; n>0; n--)
2511 Int numArgs(e) /* find number of arguments to expr */
2514 for (n=0; isAp(e); e=fun(e))
2519 Cell applyToArgs(f,args) /* destructively apply list of args */
2520 Cell f; /* to function f */
2522 while (nonNull(args)) {
2523 Cell temp = tl(args);
2524 tl(args) = hd(args);
2533 /* --------------------------------------------------------------------------
2535 * ------------------------------------------------------------------------*/
2537 /*---------------------------------------------------------------------------
2538 * GreenCard entry points
2540 * GreenCard generated code accesses Hugs data structures and functions
2541 * (only) via these functions (which are stored in the virtual function
2543 *-------------------------------------------------------------------------*/
2547 static Cell makeTuple Args((Int));
2548 static Cell makeInt Args((Int));
2549 static Cell makeChar Args((Char));
2550 static Char CharOf Args((Cell));
2551 static Cell makeFloat Args((FloatPro));
2552 static Void* derefMallocPtr Args((Cell));
2553 static Cell* Fst Args((Cell));
2554 static Cell* Snd Args((Cell));
2556 static Cell makeTuple(n) Int n; { return mkTuple(n); }
2557 static Cell makeInt(n) Int n; { return mkInt(n); }
2558 static Cell makeChar(n) Char n; { return mkChar(n); }
2559 static Char CharOf(n) Cell n; { return charOf(n); }
2560 static Cell makeFloat(n) FloatPro n; { return mkFloat(n); }
2561 static Void* derefMallocPtr(n) Cell n; { return derefMP(n); }
2562 static Cell* Fst(n) Cell n; { return (Cell*)&fst(n); }
2563 static Cell* Snd(n) Cell n; { return (Cell*)&snd(n); }
2565 HugsAPI1* hugsAPI1() {
2566 static HugsAPI1 api;
2567 static Bool initialised = FALSE;
2569 api.nameTrue = nameTrue;
2570 api.nameFalse = nameFalse;
2571 api.nameNil = nameNil;
2572 api.nameCons = nameCons;
2573 api.nameJust = nameJust;
2574 api.nameNothing = nameNothing;
2575 api.nameLeft = nameLeft;
2576 api.nameRight = nameRight;
2577 api.nameUnit = nameUnit;
2578 api.nameIORun = nameIORun;
2579 api.makeInt = makeInt;
2580 api.makeChar = makeChar;
2581 api.CharOf = CharOf;
2582 api.makeFloat = makeFloat;
2583 api.makeTuple = makeTuple;
2585 api.mkMallocPtr = mkMallocPtr;
2586 api.derefMallocPtr = derefMallocPtr;
2587 api.mkStablePtr = mkStablePtr;
2588 api.derefStablePtr = derefStablePtr;
2589 api.freeStablePtr = freeStablePtr;
2591 api.evalWithNoError = evalWithNoError;
2592 api.evalFails = evalFails;
2593 api.whnfArgs = &whnfArgs;
2594 api.whnfHead = &whnfHead;
2595 api.whnfInt = &whnfInt;
2596 api.whnfFloat = &whnfFloat;
2597 api.garbageCollect = garbageCollect;
2598 api.stackOverflow = hugsStackOverflow;
2599 api.internal = internal;
2600 api.registerPrims = registerPrims;
2601 api.addPrimCfun = addPrimCfun;
2602 api.inventText = inventText;
2605 api.cellStack = cellStack;
2611 #endif /* GREENCARD */
2614 /* --------------------------------------------------------------------------
2616 * ------------------------------------------------------------------------*/
2619 static void far* safeFarCalloc Args((Int,Int));
2620 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
2621 Int n, s; { /* for non-null return */
2622 void far* tab = farCalloc(n,s);
2624 ERRMSG(0) "Cannot allocate run-time tables"
2629 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
2631 #define TABALLOC(v,t,n)
2639 case RESET : clearStack();
2641 /* the next 2 statements are particularly important
2642 * if you are using GLOBALfst or GLOBALsnd since the
2643 * corresponding registers may be reset to their
2644 * uninitialised initial values by a longjump.
2646 heapTopFst = heapFst + heapSize;
2647 heapTopSnd = heapSnd + heapSize;
2651 if (isNull(lastExprSaved))
2652 savedText = NUM_TEXT;
2657 for (i=NAMEMIN; i<nameHw; ++i) {
2658 mark(name(i).parent);
2660 mark(name(i).stgVar);
2663 end("Names", nameHw-NAMEMIN);
2666 for (i=MODMIN; i<moduleHw; ++i) {
2667 mark(module(i).tycons);
2668 mark(module(i).names);
2669 mark(module(i).classes);
2670 mark(module(i).exports);
2671 mark(module(i).qualImports);
2673 end("Modules", moduleHw-MODMIN);
2676 for (i=TYCMIN; i<tyconHw; ++i) {
2677 mark(tycon(i).defn);
2678 mark(tycon(i).kind);
2679 mark(tycon(i).what);
2681 end("Type constructors", tyconHw-TYCMIN);
2684 for (i=CLASSMIN; i<classHw; ++i) {
2685 mark(cclass(i).head);
2686 mark(cclass(i).kinds);
2687 mark(cclass(i).fds);
2688 mark(cclass(i).xfds);
2689 mark(cclass(i).dsels);
2690 mark(cclass(i).supers);
2691 mark(cclass(i).members);
2692 mark(cclass(i).defaults);
2693 mark(cclass(i).instances);
2696 end("Classes", classHw-CLASSMIN);
2699 for (i=INSTMIN; i<instHw; ++i) {
2701 mark(inst(i).kinds);
2702 mark(inst(i).specifics);
2703 mark(inst(i).implements);
2705 end("Instances", instHw-INSTMIN);
2708 for (i=0; i<=sp; ++i)
2713 mark(lastExprSaved);
2716 end("Last expression", 3);
2721 end("C stack", stackRoots);
2726 case INSTALL : heapFst = heapAlloc(heapSize);
2727 heapSnd = heapAlloc(heapSize);
2729 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
2730 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
2735 heapTopFst = heapFst + heapSize;
2736 heapTopSnd = heapSnd + heapSize;
2737 for (i=1; i<heapSize; ++i) {
2741 snd(-heapSize) = NIL;
2748 marksSize = bitArraySize(heapSize);
2749 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
2750 ERRMSG(0) "Unable to allocate gc markspace"
2754 TABALLOC(text, char, NUM_TEXT)
2755 TABALLOC(tyconHash, Tycon, TYCONHSZ)
2756 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
2757 TABALLOC(nameHash, Name, NAMEHSZ)
2758 TABALLOC(tabName, struct strName, NUM_NAME)
2759 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
2760 TABALLOC(cellStack, Cell, NUM_STACK)
2761 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
2763 TABALLOC(tabExt, Text, NUM_EXT)
2768 nextNewText = NUM_TEXT;
2769 nextNewDText = (-1);
2770 lastExprSaved = NIL;
2771 savedText = NUM_TEXT;
2772 for (i=0; i<TEXTHSZ; ++i)
2773 textHash[i][0] = NOTEXT;
2779 for (i=0; i<TYCONHSZ; ++i)
2786 for (i=0; i<NAMEHSZ; ++i)
2797 tabInst = (struct strInst far *)
2798 farCalloc(NUM_INSTS,sizeof(struct strInst));
2801 ERRMSG(0) "Cannot allocate instance tables"
2811 /*-------------------------------------------------------------------------*/