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/03 17:01:23 $
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).mod = currentModule;
470 module(currentModule).tycons = cons(tyconHw,module(currentModule).tycons);
471 tycon(tyconHw).nextTyconHash = tyconHash[h];
472 tyconHash[h] = tyconHw;
477 Tycon findTycon(t) /* locate Tycon in tycon table */
479 Tycon tc = tyconHash[tHash(t)];
481 while (nonNull(tc) && tycon(tc).text!=t)
482 tc = tycon(tc).nextTyconHash;
486 Tycon addTycon(tc) /* Insert Tycon in tycon table - if no clash is caused */
488 Tycon oldtc = findTycon(tycon(tc).text);
491 module(currentModule).tycons=cons(tc,module(currentModule).tycons);
497 static Void local hashTycon(tc) /* Insert Tycon into hash table */
501 Text t = tycon(tc).text;
503 tycon(tc).nextTyconHash = tyconHash[h];
508 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
510 if (!isPair(id)) internal("findQualTycon");
514 return findTycon(textOf(id));
516 Text t = qtextOf(id);
517 Module m = findQualifier(qmodOf(id));
519 if (isNull(m)) return NIL;
520 for(es=module(m).exports; nonNull(es); es=tl(es)) {
522 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t)
527 default : internal("findQualTycon2");
529 return NIL; /* NOTREACHED */
532 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr */
538 Tycon tc = newTycon(t);
540 tycon(tc).kind = kind;
541 tycon(tc).what = what;
542 tycon(tc).defn = defn;
543 tycon(tc).arity = ar;
547 static List local insertTycon(tc,ts) /* insert tycon tc into sorted list*/
552 String s = textToStr(tycon(tc).text);
554 while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
555 if (hd(curr)==tc) /* just in case we get duplicates! */
561 tl(prev) = cons(tc,curr);
565 return cons(tc,curr);
568 List addTyconsMatching(pat,ts) /* Add tycons matching pattern pat */
569 String pat; /* to list of Tycons ts */
570 List ts; { /* Null pattern matches every tycon*/
571 Tycon tc; /* (Tycons with NIL kind excluded) */
572 for (tc=TYCMIN; tc<tyconHw; ++tc)
573 if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
574 if (nonNull(tycon(tc).kind))
575 ts = insertTycon(tc,ts);
579 Text ghcTupleText(tup)
583 assert(isTuple(tup));
585 if (tup >= 100) internal("ghcTupleText");
587 for (i = 1; i <= tup; i++) buf[i] = ',';
590 return findText(buf);
593 /* --------------------------------------------------------------------------
596 * A Name represents a top level binding of a value to an identifier.
597 * Such values may be a constructor function, a member function in a
598 * class, a user-defined or primitive value/function.
600 * Names are indexed by Text values ... a very simple hash functions speeds
601 * access to the table of Names and Name entries with the same hash value
602 * are chained together, with the most recent entry at the front of the
604 * ------------------------------------------------------------------------*/
606 #define NAMEHSZ 256 /* Size of Name hash table */
607 #define nHash(x) ((x)%NAMEHSZ) /* hash fn :: Text->Int */
608 Name nameHw; /* next unused name */
609 static Name DEFTABLE(nameHash,NAMEHSZ); /* Hash table storage */
610 struct strName DEFTABLE(tabName,NUM_NAME); /* Name table storage */
612 Name newName(t,parent) /* Add new name to name table */
616 if (nameHw-NAMEMIN >= NUM_NAME) {
617 ERRMSG(0) "Name storage space exhausted"
620 name(nameHw).text = t; /* clear new name record */
621 name(nameHw).line = 0;
622 name(nameHw).syntax = NO_SYNTAX;
623 name(nameHw).parent = parent;
624 name(nameHw).arity = 0;
625 name(nameHw).number = EXECNAME;
626 name(nameHw).defn = NIL;
627 name(nameHw).stgVar = NIL;
628 name(nameHw).callconv = NIL;
629 name(nameHw).type = NIL;
630 name(nameHw).primop = 0;
631 name(nameHw).mod = currentModule;
632 module(currentModule).names=cons(nameHw,module(currentModule).names);
633 name(nameHw).nextNameHash = nameHash[h];
634 nameHash[h] = nameHw;
638 Name findName(t) /* Locate name in name table */
640 Name n = nameHash[nHash(t)];
642 while (nonNull(n) && name(n).text!=t)
643 n = name(n).nextNameHash;
647 Name addName(nm) /* Insert Name in name table - if */
648 Name nm; { /* no clash is caused */
649 Name oldnm = findName(name(nm).text);
652 module(currentModule).names=cons(nm,module(currentModule).names);
658 static Void local hashName(nm) /* Insert Name into hash table */
665 name(nm).nextNameHash = nameHash[h];
669 Name findQualName(id) /* Locate (possibly qualified) name*/
670 Cell id; { /* in name table */
672 internal("findQualName");
678 return findName(textOf(id));
680 Text t = qtextOf(id);
681 Module m = findQualifier(qmodOf(id));
683 if (isNull(m)) return NIL;
684 for(es=module(m).exports; nonNull(es); es=tl(es)) {
686 if (isName(e) && name(e).text==t)
688 else if (isPair(e) && DOTDOT==snd(e)) {
689 List subentities = NIL;
692 && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
693 subentities = tycon(c).defn;
695 subentities = cclass(c).members;
696 for(; nonNull(subentities); subentities=tl(subentities)) {
697 if (!isName(hd(subentities)))
698 internal("findQualName3");
699 if (name(hd(subentities)).text == t)
700 return hd(subentities);
706 default : internal("findQualName2");
708 return 0; /* NOTREACHED */
712 Name nameFromStgVar ( StgVar v )
715 for (n = NAMEMIN; n < nameHw; n++)
716 if (name(n).stgVar == v) return n;
720 void* getHugs_AsmObject_for ( char* s )
723 Text t = findText(s);
725 for (n = NAMEMIN; n < nameHw; n++)
726 if (name(n).text == t) break;
727 if (n == nameHw) internal("getHugs_AsmObject_for(1)");
729 if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
730 internal("getHugs_AsmObject_for(2)");
731 return ptrOf(stgVarInfo(v));
734 /* --------------------------------------------------------------------------
735 * Primitive functions:
736 * ------------------------------------------------------------------------*/
738 Name addPrimCfunREP(t,arity,no,rep) /* add primitive constructor func */
739 Text t; /* sets rep, not type */
742 Int rep; { /* Really AsmRep */
743 Name n = newName(t,NIL);
744 name(n).arity = arity;
745 name(n).number = cfunNo(no);
747 name(n).primop = (void*)rep;
752 Name addPrimCfun(t,arity,no,type) /* add primitive constructor func */
757 Name n = newName(t,NIL);
758 name(n).arity = arity;
759 name(n).number = cfunNo(no);
765 Int sfunPos(s,c) /* Find position of field with */
766 Name s; /* selector s in constructor c. */
770 for (; nonNull(cns); cns=tl(cns))
772 return intOf(snd(hd(cns)));
774 return 0;/* NOTREACHED */
777 static List local insertName(nm,ns) /* insert name nm into sorted list */
782 String s = textToStr(name(nm).text);
784 while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
785 if (hd(curr)==nm) /* just in case we get duplicates! */
791 tl(prev) = cons(nm,curr);
795 return cons(nm,curr);
798 List addNamesMatching(pat,ns) /* Add names matching pattern pat */
799 String pat; /* to list of names ns */
800 List ns; { /* Null pattern matches every name */
801 Name nm; /* (Names with NIL type, or hidden */
803 for (nm=NAMEMIN; nm<nameHw; ++nm) /* or invented names are excluded) */
804 if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
805 String str = textToStr(name(nm).text);
806 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
807 ns = insertName(nm,ns);
811 List mns = module(currentModule).names;
812 for(; nonNull(mns); mns=tl(mns)) {
814 if (!inventedText(name(nm).text)) {
815 String str = textToStr(name(nm).text);
816 if (str[0]!='_' && (!pat || stringMatch(pat,str)))
817 ns = insertName(nm,ns);
824 /* --------------------------------------------------------------------------
825 * A simple string matching routine
826 * `*' matches any sequence of zero or more characters
827 * `?' matches any single character exactly
828 * `@str' matches the string str exactly (ignoring any special chars)
829 * `\c' matches the character c only (ignoring special chars)
830 * c matches the character c only
831 * ------------------------------------------------------------------------*/
833 static Void local patternError(s) /* report error in pattern */
835 ERRMSG(0) "%s in pattern", s
839 static Bool local stringMatch(pat,str) /* match string against pattern */
845 case '\0' : return (*str=='\0');
848 if (stringMatch(pat+1,str))
853 case '?' : if (*str++=='\0')
858 case '[' : { Bool found = FALSE;
859 while (*++pat!='\0' && *pat!=']')
860 if (!found && ( pat[0] == *str ||
869 patternError("missing `]'");
877 case '\\' : if (*++pat == '\0')
878 patternError("extra trailing `\\'");
880 default : if (*pat++ != *str++)
886 /* --------------------------------------------------------------------------
887 * Storage of type classes, instances etc...:
888 * ------------------------------------------------------------------------*/
890 static Class classHw; /* next unused class */
891 static List classes; /* list of classes in current scope */
892 static Inst instHw; /* next unused instance record */
894 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records */
895 struct strInst far *tabInst; /* (pointer to) table of instances */
897 Class newClass(t) /* add new class to class table */
899 if (classHw-CLASSMIN >= NUM_CLASSES) {
900 ERRMSG(0) "Class storage space exhausted"
903 cclass(classHw).text = t;
904 cclass(classHw).arity = 0;
905 cclass(classHw).kinds = NIL;
906 cclass(classHw).head = NIL;
907 cclass(classHw).fds = NIL;
908 cclass(classHw).xfds = NIL;
909 cclass(classHw).dcon = NIL;
910 cclass(classHw).supers = NIL;
911 cclass(classHw).dsels = NIL;
912 cclass(classHw).members = NIL;
913 cclass(classHw).defaults = NIL;
914 cclass(classHw).instances = NIL;
915 classes=cons(classHw,classes);
916 cclass(classHw).mod = currentModule;
917 module(currentModule).classes=cons(classHw,module(currentModule).classes);
921 Class classMax() { /* Return max Class in use ... */
922 return classHw; /* This is a bit ugly, but it's not*/
923 } /* worth a lot of effort right now */
925 Class findClass(t) /* look for named class in table */
929 for (cs=classes; nonNull(cs); cs=tl(cs)) {
931 if (cclass(cl).text==t)
937 Class addClass(c) /* Insert Class in class list */
938 Class c; { /* - if no clash caused */
939 Class oldc = findClass(cclass(c).text);
941 classes=cons(c,classes);
942 module(currentModule).classes=cons(c,module(currentModule).classes);
949 Class findQualClass(c) /* Look for (possibly qualified) */
950 Cell c; { /* class in class list */
951 if (!isQualIdent(c)) {
952 return findClass(textOf(c));
955 Module m = findQualifier(qmodOf(c));
959 for (es=module(m).exports; nonNull(es); es=tl(es)) {
961 if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t)
968 Inst newInst() { /* Add new instance to table */
969 if (instHw-INSTMIN >= NUM_INSTS) {
970 ERRMSG(0) "Instance storage space exhausted"
973 inst(instHw).kinds = NIL;
974 inst(instHw).head = NIL;
975 inst(instHw).specifics = NIL;
976 inst(instHw).implements = NIL;
977 inst(instHw).builder = NIL;
978 inst(instHw).mod = currentModule;
984 extern Void printInst Args((Inst));
988 Class cl = inst(in).c;
989 Printf("%s-", textToStr(cclass(cl).text));
990 printType(stdout,inst(in).t);
992 #endif /* DEBUG_DICTS */
994 Inst findFirstInst(tc) /* look for 1st instance involving */
995 Tycon tc; { /* the type constructor tc */
996 return findNextInst(tc,INSTMIN-1);
999 Inst findNextInst(tc,in) /* look for next instance involving*/
1000 Tycon tc; /* the type constructor tc */
1001 Inst in; { /* starting after instance in */
1002 while (++in < instHw) {
1003 Cell pi = inst(in).head;
1004 for (; isAp(pi); pi=fun(pi))
1005 if (typeInvolves(arg(pi),tc))
1011 static Bool local typeInvolves(ty,tc) /* Test to see if type ty involves */
1012 Type ty; /* type constructor/tuple tc. */
1015 || (isAp(ty) && (typeInvolves(fun(ty),tc)
1016 || typeInvolves(arg(ty),tc)));
1019 /* --------------------------------------------------------------------------
1022 * Various parts of the system use a stack of cells. Most of the stack
1023 * operations are defined as macros, expanded inline.
1024 * ------------------------------------------------------------------------*/
1026 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack */
1027 StackPtr sp; /* stack pointer */
1029 #if GIMME_STACK_DUMPS
1031 #define UPPER_DISP 5 /* # display entries on top of stack */
1032 #define LOWER_DISP 5 /* # display entries on bottom of stack*/
1034 Void hugsStackOverflow() { /* Report stack overflow */
1036 extern Cell evalRoots[];
1038 ERRMSG(0) "Control stack overflow" ETHEN
1041 if (rootsp>=UPPER_DISP+LOWER_DISP) {
1042 for (i=0; i<UPPER_DISP; i++) {
1043 ERRTEXT "\nwhile evaluating: " ETHEN
1044 ERREXPR(evalRoots[rootsp-i]);
1046 ERRTEXT "\n..." ETHEN
1047 for (i=LOWER_DISP-1; i>=0; i--) {
1048 ERRTEXT "\nwhile evaluating: " ETHEN
1049 ERREXPR(evalRoots[i]);
1053 for (i=rootsp; i>=0; i--) {
1054 ERRTEXT "\nwhile evaluating: " ETHEN
1055 ERREXPR(evalRoots[i]);
1063 #else /* !GIMME_STACK_DUMPS */
1065 Void hugsStackOverflow() { /* Report stack overflow */
1066 ERRMSG(0) "Control stack overflow"
1070 #endif /* !GIMME_STACK_DUMPS */
1072 /* --------------------------------------------------------------------------
1075 * A Module represents a user defined module.
1077 * Note: there are now two lookup mechanisms in the system:
1079 * 1) The exports from a module are stored in a big list.
1080 * We resolve qualified names, and import lists by linearly scanning
1081 * through this list.
1083 * 2) Unqualified imports and local definitions for the current module
1084 * are stored in hash tables (tyconHash and nameHash) or linear lists
1087 * ------------------------------------------------------------------------*/
1089 static Module moduleHw; /* next unused Module */
1090 struct Module DEFTABLE(tabModule,NUM_MODULE); /* Module storage */
1091 Module currentModule; /* Module currently being processed*/
1093 Bool isValidModule(m) /* is m a legitimate module id? */
1095 return (MODMIN <= m && m < moduleHw);
1098 Module newModule(t) /* add new module to module table */
1100 if (moduleHw-MODMIN >= NUM_MODULE) {
1101 ERRMSG(0) "Module storage space exhausted"
1104 module(moduleHw).text = t; /* clear new module record */
1105 module(moduleHw).qualImports = NIL;
1106 module(moduleHw).exports = NIL;
1107 module(moduleHw).tycons = NIL;
1108 module(moduleHw).names = NIL;
1109 module(moduleHw).classes = NIL;
1110 module(moduleHw).oImage = NULL;
1111 module(moduleHw).oTab = NULL;
1112 module(moduleHw).sizeoTab = 0;
1113 module(moduleHw).usedoTab = 0;
1114 module(moduleHw).dlTab = NULL;
1115 module(moduleHw).sizedlTab = 0;
1116 module(moduleHw).useddlTab = 0;
1120 void ppModules ( void )
1123 fflush(stderr); fflush(stdout);
1124 printf ( "begin MODULES\n" );
1125 for (i = moduleHw-1; i >= MODMIN; i--)
1126 printf ( " %2d: %16s\n",
1127 i-MODMIN, textToStr(module(i).text)
1129 printf ( "end MODULES\n" );
1130 fflush(stderr); fflush(stdout);
1134 Module findModule(t) /* locate Module in module table */
1137 for(m=MODMIN; m<moduleHw; ++m) {
1138 if (module(m).text==t)
1144 Module findModid(c) /* Find module by name or filename */
1146 switch (whatIs(c)) {
1147 case STRCELL : { Script s = scriptThisFile(snd(c));
1148 return (s==-1) ? NIL : moduleOfScript(s);
1150 case CONIDCELL : return findModule(textOf(c));
1151 default : internal("findModid");
1153 return NIL;/*NOTUSED*/
1156 static local Module findQualifier(t) /* locate Module in import list */
1159 for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1160 if (textOf(fst(hd(ms)))==t)
1164 if (module(currentModule).text==t)
1165 return currentModule;
1170 Void setCurrModule(m) /* set lookup tables for current module */
1173 assert(isModule(m));
1174 if (m!=currentModule) {
1175 currentModule = m; /* This is the only assignment to currentModule */
1176 for (i=0; i<TYCONHSZ; ++i)
1178 mapProc(hashTycon,module(m).tycons);
1179 for (i=0; i<NAMEHSZ; ++i)
1181 mapProc(hashName,module(m).names);
1182 classes = module(m).classes;
1186 Name jrsFindQualName ( Text mn, Text sn )
1191 for (m=MODMIN; m<moduleHw; m++)
1192 if (module(m).text == mn) break;
1193 if (m == moduleHw) return NIL;
1195 for (ns = module(m).names; nonNull(ns); ns=tl(ns))
1196 if (name(hd(ns)).text == sn) return hd(ns);
1202 /* A bit tricky. Assumes that if tab==NULL, then
1203 currUsed and *currSize must be zero.
1206 void* genericExpand ( void* tab,
1207 int* currSize, int currUsed,
1208 int initSize, int elemSize )
1212 if (currUsed < *currSize)
1214 size2 = (*currSize == 0) ? initSize : (2 * *currSize);
1215 tab2 = malloc ( size2 * elemSize );
1217 ERRMSG(0) "Can't allocate enough memory to resize a table"
1221 memcpy ( tab2, tab, elemSize * *currSize );
1223 if (tab) free ( tab );
1227 void addOTabName ( Module m, char* nm, void* ad )
1230 = genericExpand ( module(m).oTab,
1231 &module(m).sizeoTab,
1235 module(m).oTab[ module(m).usedoTab ].nm = nm;
1236 module(m).oTab[ module(m).usedoTab ].ad = ad;
1237 module(m).usedoTab++;
1241 void addDLSect ( Module m, void* start, void* end, DLSect sect )
1244 = genericExpand ( module(m).dlTab,
1245 &module(m).sizedlTab,
1246 module(m).useddlTab,
1247 4, sizeof(DLTabEnt) );
1248 module(m).dlTab[ module(m).useddlTab ].start = start;
1249 module(m).dlTab[ module(m).useddlTab ].end = end;
1250 module(m).dlTab[ module(m).useddlTab ].sect = sect;
1251 module(m).useddlTab++;
1255 void* lookupOTabName ( Module m, char* nm )
1258 for (i = 0; i < module(m).usedoTab; i++) {
1261 "lookupOTabName: request %s, table has %s\n",
1262 nm, module(m).oTab[i].nm );
1263 if (0==strcmp(nm,module(m).oTab[i].nm))
1264 return module(m).oTab[i].ad;
1270 char* nameFromOPtr ( void* p )
1274 for (m=MODMIN; m<moduleHw; m++)
1275 for (i = 0; i < module(m).usedoTab; i++)
1276 if (p == module(m).oTab[i].ad)
1277 return module(m).oTab[i].nm;
1282 DLSect lookupDLSect ( void* ad )
1286 for (m=MODMIN; m<moduleHw; m++)
1287 for (i = 0; i < module(m).useddlTab; i++)
1288 if (module(m).dlTab[i].start <= ad &&
1289 ad <= module(m).dlTab[i].end)
1290 return module(m).dlTab[i].sect;
1291 return HUGS_DL_SECTION_OTHER;
1295 /* --------------------------------------------------------------------------
1296 * Script file storage:
1298 * script files are read into the system one after another. The state of
1299 * the stored data structures (except the garbage-collected heap) is recorded
1300 * before reading a new script. In the event of being unable to read the
1301 * script, or if otherwise requested, the system can be restored to its
1302 * original state immediately before the file was read.
1303 * ------------------------------------------------------------------------*/
1305 typedef struct { /* record of storage state prior to */
1306 Text file; /* reading script/module */
1320 #ifdef DEBUG_SHOWUSE
1321 static Void local showUse(msg,val,mx)
1324 Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1328 static Script scriptHw; /* next unused script number */
1329 static script scripts[NUM_SCRIPTS]; /* storage for script records */
1332 void ppScripts ( void )
1335 fflush(stderr); fflush(stdout);
1336 printf ( "begin SCRIPTS\n" );
1337 for (i = scriptHw-1; i >= 0; i--)
1338 printf ( " %2d: %16s tH=%d mH=%d yH=%d "
1339 "nH=%d cH=%d iH=%d nnS=%d,%d\n",
1340 i, textToStr(scripts[i].file),
1341 scripts[i].textHw, scripts[i].moduleHw,
1342 scripts[i].tyconHw, scripts[i].nameHw,
1343 scripts[i].classHw, scripts[i].instHw,
1344 scripts[i].nextNewText, scripts[i].nextNewDText
1346 printf ( "end SCRIPTS\n" );
1347 fflush(stderr); fflush(stdout);
1350 Script startNewScript(f) /* start new script, keeping record */
1351 String f; { /* of status for later restoration */
1352 if (scriptHw >= NUM_SCRIPTS) {
1353 ERRMSG(0) "Too many script files in use"
1356 #ifdef DEBUG_SHOWUSE
1357 showUse("Text", textHw, NUM_TEXT);
1358 showUse("Module", moduleHw-MODMIN, NUM_MODULE);
1359 showUse("Tycon", tyconHw-TYCMIN, NUM_TYCON);
1360 showUse("Name", nameHw-NAMEMIN, NUM_NAME);
1361 showUse("Class", classHw-CLASSMIN, NUM_CLASSES);
1362 showUse("Inst", instHw-INSTMIN, NUM_INSTS);
1364 showUse("Ext", extHw-EXTMIN, NUM_EXT);
1367 scripts[scriptHw].file = findText( f ? f : "<nofile>" );
1368 scripts[scriptHw].textHw = textHw;
1369 scripts[scriptHw].nextNewText = nextNewText;
1370 scripts[scriptHw].nextNewDText = nextNewDText;
1371 scripts[scriptHw].moduleHw = moduleHw;
1372 scripts[scriptHw].tyconHw = tyconHw;
1373 scripts[scriptHw].nameHw = nameHw;
1374 scripts[scriptHw].classHw = classHw;
1375 scripts[scriptHw].instHw = instHw;
1377 scripts[scriptHw].extHw = extHw;
1382 Bool isPreludeScript() { /* Test whether this is the Prelude*/
1383 return (scriptHw==0);
1386 Bool moduleThisScript(m) /* Test if given module is defined */
1387 Module m; { /* in current script file */
1388 return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
1391 Module lastModule() { /* Return module in current script file */
1392 return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1395 #define scriptThis(nm,t,tag) Script nm(x) \
1399 && x>=scripts[s].tag) \
1403 scriptThis(scriptThisName,Name,nameHw)
1404 scriptThis(scriptThisTycon,Tycon,tyconHw)
1405 scriptThis(scriptThisInst,Inst,instHw)
1406 scriptThis(scriptThisClass,Class,classHw)
1409 Module moduleOfScript(s)
1411 return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1414 String fileOfModule(m)
1417 if (m == modulePrelude) {
1420 for(s=0; s<scriptHw; ++s) {
1421 if (scripts[s].moduleHw == m) {
1422 return textToStr(scripts[s].file);
1428 Script scriptThisFile(f)
1431 for (s=0; s < scriptHw; ++s) {
1432 if (scripts[s].file == f) {
1436 if (f == findText(STD_PRELUDE)) {
1442 Void dropScriptsFrom(sno) /* Restore storage to state prior */
1443 Script sno; { /* to reading script sno */
1444 if (sno<scriptHw) { /* is there anything to restore? */
1446 textHw = scripts[sno].textHw;
1447 nextNewText = scripts[sno].nextNewText;
1448 nextNewDText = scripts[sno].nextNewDText;
1449 moduleHw = scripts[sno].moduleHw;
1450 tyconHw = scripts[sno].tyconHw;
1451 nameHw = scripts[sno].nameHw;
1452 classHw = scripts[sno].classHw;
1453 instHw = scripts[sno].instHw;
1455 dictHw = scripts[sno].dictHw;
1458 extHw = scripts[sno].extHw;
1462 for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1463 if (module(i).objectFile) {
1464 printf("[bogus] closing objectFile for module %d\n",i);
1465 /*dlclose(module(i).objectFile);*/
1468 moduleHw = scripts[sno].moduleHw;
1470 for (i=0; i<TEXTHSZ; ++i) {
1472 while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1473 && textHash[i][j]<textHw)
1476 textHash[i][j] = NOTEXT;
1480 for (i=0; i<TYCONHSZ; ++i) {
1483 for (i=0; i<NAMEHSZ; ++i) {
1487 for (i=CLASSMIN; i<classHw; i++) {
1488 List ins = cclass(i).instances;
1491 while (nonNull(ins)) {
1492 List temp = tl(ins);
1493 if (hd(ins)<instHw) {
1499 cclass(i).instances = rev(is);
1506 /* --------------------------------------------------------------------------
1509 * Provides a garbage collectable heap for storage of expressions etc.
1511 * Now incorporates a flat resource: A two-space collected extension of
1512 * the heap that provides storage for contiguous arrays of Cell storage,
1513 * cooperating with the garbage collection mechanisms for the main heap.
1514 * ------------------------------------------------------------------------*/
1516 Int heapSize = DEFAULTHEAP; /* number of cells in heap */
1517 Heap heapFst; /* array of fst component of pairs */
1518 Heap heapSnd; /* array of snd component of pairs */
1525 Bool consGC = TRUE; /* Set to FALSE to turn off gc from*/
1526 /* C stack; use with extreme care! */
1528 Int numGcs; /* number of garbage collections */
1529 Int cellsRecovered; /* number of cells recovered */
1531 static Cell freeList; /* free list of unused cells */
1532 static Cell lsave, rsave; /* save components of pair */
1536 static Int markCount, stackRoots;
1538 #define initStackRoots() stackRoots = 0
1539 #define recordStackRoot() stackRoots++
1552 #define start() markCount = 0
1553 #define end(thing,rs) \
1555 Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1558 #define recordMark() markCount++
1560 #else /* !GC_STATISTICS */
1565 #define initStackRoots()
1566 #define recordStackRoot()
1569 #define end(thing,root)
1570 #define recordMark()
1572 #endif /* !GC_STATISTICS */
1574 Cell pair(l,r) /* Allocate pair (l, r) from */
1575 Cell l, r; { /* heap, garbage collecting first */
1576 Cell c = freeList; /* if necessary ... */
1588 freeList = snd(freeList);
1595 Void overwrite(dst,src) /* overwrite dst cell with src cell*/
1596 Cell dst, src; { /* both *MUST* be pairs */
1597 if (isPair(dst) && isPair(src)) {
1598 fst(dst) = fst(src);
1599 snd(dst) = snd(src);
1602 internal("overwrite");
1606 static Int marksSize;
1608 Cell markExpr(c) /* External interface to markCell */
1610 return isGenPair(c) ? markCell(c) : c;
1613 static Cell local markCell(c) /* Traverse part of graph marking */
1614 Cell c; { /* cells reachable from given root */
1615 /* markCell(c) is only called if c */
1617 { register int place = placeInSet(c);
1618 register int mask = maskInSet(c);
1619 if (marks[place]&mask)
1622 marks[place] |= mask;
1627 /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1628 if (isGenPair(fst(c))) {
1630 fst(c) = markCell(fst(c));
1633 else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1641 static Void local markSnd(c) /* Variant of markCell used to */
1642 Cell c; { /* update snd component of cell */
1643 Cell t; /* using tail recursion */
1645 ma: t = c; /* Keep pointer to original pair */
1650 { register int place = placeInSet(c);
1651 register int mask = maskInSet(c);
1652 if (marks[place]&mask)
1655 marks[place] |= mask;
1660 if (isGenPair(fst(c))) {
1661 fst(c) = markCell(fst(c));
1664 else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1669 Void markWithoutMove(n) /* Garbage collect cell at n, as if*/
1670 Cell n; { /* it was a cell ref, but don't */
1671 /* move cell so we don't have */
1672 /* to modify the stored value of n */
1679 Void garbageCollect() { /* Run garbage collector ... */
1680 Bool breakStat = breakOn(FALSE); /* disable break checking */
1686 jmp_buf regs; /* save registers on stack */
1690 for (i=0; i<marksSize; ++i) /* initialise mark set to empty */
1693 everybody(MARK); /* Mark all components of system */
1695 gcScanning(); /* scan mark set */
1702 for (i=1; i<=heapSize; i++) {
1703 if ((marks[place] & mask) == 0) {
1710 if (++j == bitsPerWord) {
1717 gcRecovered(recovered);
1718 breakOn(breakStat); /* restore break trapping if nec. */
1722 /* can only return if freeList is nonempty on return. */
1723 if (recovered<minRecovery || isNull(freeList)) {
1724 ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1727 cellsRecovered = recovered;
1730 /* --------------------------------------------------------------------------
1731 * Code for saving last expression entered:
1733 * This is a little tricky because some text values (e.g. strings or variable
1734 * names) may not be defined or have the same value when the expression is
1735 * recalled. These text values are therefore saved in the top portion of
1737 * ------------------------------------------------------------------------*/
1739 static Cell lastExprSaved; /* last expression to be saved */
1741 Void setLastExpr(e) /* save expression for later recall*/
1743 lastExprSaved = NIL; /* in case attempt to save fails */
1744 savedText = NUM_TEXT;
1745 lastExprSaved = lowLevelLastIn(e);
1748 static Cell local lowLevelLastIn(c) /* Duplicate expression tree (i.e. */
1749 Cell c; { /* acyclic graph) for later recall */
1750 if (isPair(c)) { /* Duplicating any text strings */
1751 if (isBoxTag(fst(c))) /* in case these are lost at some */
1752 switch (fst(c)) { /* point before the expr is reused */
1758 case STRCELL : return pair(fst(c),saveText(textOf(c)));
1759 default : return pair(fst(c),snd(c));
1762 return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
1766 return pair(EXTCOPY,saveText(extText(c)));
1772 Cell getLastExpr() { /* recover previously saved expr */
1773 return lowLevelLastOut(lastExprSaved);
1776 static Cell local lowLevelLastOut(c) /* As with lowLevelLastIn() above */
1777 Cell c; { /* except that Cells refering to */
1778 if (isPair(c)) { /* Text values are restored to */
1779 if (isBoxTag(fst(c))) /* appropriate values */
1786 case STRCELL : return pair(fst(c),
1787 findText(text+intValOf(c)));
1789 case EXTCOPY : return mkExt(findText(text+intValOf(c)));
1791 default : return pair(fst(c),snd(c));
1794 return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
1800 /* --------------------------------------------------------------------------
1801 * Miscellaneous operations on heap cells:
1802 * ------------------------------------------------------------------------*/
1804 /* Profiling suggests that the number of calls to whatIs() is typically */
1805 /* rather high. The recoded version below attempts to improve the average */
1806 /* performance for whatIs() using a binary search for part of the analysis */
1808 Cell whatIs(c) /* identify type of cell */
1811 register Cell fstc = fst(c);
1812 return isTag(fstc) ? fstc : AP;
1814 if (c<TUPMIN) return c;
1815 if (c>=INTMIN) return INTCELL;
1817 if (c>=NAMEMIN){if (c>=CLASSMIN) {if (c>=CHARMIN) return CHARCELL;
1819 else if (c>=INSTMIN) return INSTANCE;
1821 else if (c>=MODMIN) {if (c>=TYCMIN) return TYCON;
1822 else return MODULE;}
1823 else if (c>=OFFMIN) return OFFSET;
1825 else return (c>=EXTMIN) ?
1832 register Cell fstc = fst(c);
1833 return isTag(fstc) ? fstc : AP;
1835 if (c>=INTMIN) return INTCELL;
1836 if (c>=CHARMIN) return CHARCELL;
1837 if (c>=CLASSMIN) return CLASS;
1838 if (c>=INSTMIN) return INSTANCE;
1839 if (c>=NAMEMIN) return NAME;
1840 if (c>=TYCMIN) return TYCON;
1841 if (c>=MODMIN) return MODULE;
1842 if (c>=OFFMIN) return OFFSET;
1844 if (c>=EXTMIN) return EXT;
1846 if (c>=TUPMIN) return TUPLE;
1851 /* A very, very simple printer.
1852 * Output is uglier than from printExp - but the printer is more
1853 * robust and can be used on any data structure irrespective of
1856 Void print Args((Cell, Int));
1857 Void print(c, depth)
1862 #if 0 /* Not in this version of Hugs */
1863 } else if (isPair(c) && !isGenPair(c)) {
1864 extern Void printEvalCell Args((Cell, Int));
1865 printEvalCell(c,depth);
1868 Int tag = whatIs(c);
1872 print(fst(c), depth-1);
1874 print(snd(c), depth-1);
1878 Printf("free(%d)", c);
1881 Printf("int(%d)", intOf(c));
1884 Printf("bignum(%s)", bignumToString(c));
1887 Printf("char('%c')", charOf(c));
1890 Printf("ptr(%p)",ptrOf(c));
1893 Printf("class(%d)", c-CLASSMIN);
1894 if (CLASSMIN <= c && c < classHw) {
1895 Printf("=\"%s\"", textToStr(cclass(c).text));
1899 Printf("instance(%d)", c - INSTMIN);
1902 Printf("name(%d)", c-NAMEMIN);
1903 if (NAMEMIN <= c && c < nameHw) {
1904 Printf("=\"%s\"", textToStr(name(c).text));
1908 Printf("tycon(%d)", c-TYCMIN);
1909 if (TYCMIN <= c && c < tyconHw)
1910 Printf("=\"%s\"", textToStr(tycon(c).text));
1913 Printf("module(%d)", c - MODMIN);
1916 Printf("Offset %d", offsetOf(c));
1919 Printf("Tuple %d", tupleOf(c));
1923 print(snd(c),depth-1);
1927 print(snd(c),depth-1);
1931 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
1932 Printf("%d ", intOf(fst(snd(c))));
1933 print(snd(snd(c)),depth-1);
1935 print(snd(c),depth-1);
1952 Printf("{dict %d}",textOf(c));
1958 Printf("{id %s}",textToStr(textOf(c)));
1962 Printf("{ip %s}",textToStr(textOf(c)));
1965 Printf("?%s",textToStr(textOf(c)));
1969 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
1973 print(fst(snd(c)),depth-1);
1975 print(snd(snd(c)),depth-1);
1980 print(snd(c),depth-1);
1985 print(snd(c),depth-1);
1990 print(fst(snd(c)),depth-1);
1992 print(snd(snd(c)),depth-1);
1997 print(fst(snd(c)),depth-1);
1999 print(snd(snd(c)),depth-1);
2003 Printf("FromQual(");
2004 print(fst(snd(c)),depth-1);
2006 print(snd(snd(c)),depth-1);
2010 Printf("StgVar%d=",-c);
2011 print(snd(c), depth-1);
2015 print(fst(snd(c)),depth-1);
2017 print(snd(snd(c)),depth-1);
2022 print(fst(snd(c)),depth-1);
2024 print(snd(snd(c)),depth-1);
2029 print(fst(snd(c)),depth-1);
2031 print(snd(snd(c)),depth-1);
2035 Printf("PrimCase(");
2036 print(fst(snd(c)),depth-1);
2038 print(snd(snd(c)),depth-1);
2043 print(snd(c),depth-1);
2047 Printf("(UNBOXEDTUP,");
2048 print(snd(c),depth-1);
2053 print(snd(c),depth-1);
2057 if (isBoxTag(tag)) {
2058 Printf("Tag(%d)=%d", c, tag);
2059 } else if (isConTag(tag)) {
2060 Printf("%d@(%d,",c,tag);
2061 print(snd(c), depth-1);
2064 } else if (c == tag) {
2065 Printf("Tag(%d)", c);
2067 Printf("Tag(%d)=%d", c, tag);
2076 Bool isVar(c) /* is cell a VARIDCELL/VAROPCELL ? */
2077 Cell c; { /* also recognises DICTVAR cells */
2079 (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2082 Bool isCon(c) /* is cell a CONIDCELL/CONOPCELL ? */
2084 return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2087 Bool isQVar(c) /* is cell a [un]qualified varop/id? */
2089 if (!isPair(c)) return FALSE;
2092 case VAROPCELL : return TRUE;
2094 case QUALIDENT : return isVar(snd(snd(c)));
2096 default : return FALSE;
2100 Bool isQCon(c) /*is cell a [un]qualified conop/id? */
2102 if (!isPair(c)) return FALSE;
2105 case CONOPCELL : return TRUE;
2107 case QUALIDENT : return isCon(snd(snd(c)));
2109 default : return FALSE;
2113 Bool isQualIdent(c) /* is cell a qualified identifier? */
2115 return isPair(c) && (fst(c)==QUALIDENT);
2118 Bool isIdent(c) /* is cell an identifier? */
2120 if (!isPair(c)) return FALSE;
2125 case CONOPCELL : return TRUE;
2127 case QUALIDENT : return TRUE;
2129 default : return FALSE;
2133 Bool isInt(c) /* cell holds integer value? */
2135 return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2138 Int intOf(c) /* find integer value of cell? */
2142 return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
2145 Cell mkInt(n) /* make cell representing integer */
2147 return (MINSMALLINT <= n && n <= MAXSMALLINT)
2152 #if SIZEOF_INTP == SIZEOF_INT
2153 typedef union {Int i; Ptr p;} IntOrPtr;
2159 return pair(PTRCELL,x.i);
2166 assert(fst(c) == PTRCELL);
2175 return pair(CPTRCELL,x.i);
2182 assert(fst(c) == CPTRCELL);
2186 #elif SIZEOF_INTP == 2*SIZEOF_INT
2187 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2193 return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2200 assert(fst(c) == PTRCELL);
2201 x.i.i1 = intOf(fst(snd(c)));
2202 x.i.i2 = intOf(snd(snd(c)));
2206 #warning "type Addr not supported on this architecture - don't use it"
2210 ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
2217 ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
2222 String stringNegate( s )
2230 strcpy(&t[1],s); /* ToDo: use strncpy instead */
2235 /* --------------------------------------------------------------------------
2237 * ------------------------------------------------------------------------*/
2239 Int length(xs) /* calculate length of list xs */
2242 for (; nonNull(xs); ++n)
2247 List appendOnto(xs,ys) /* Destructively prepend xs onto */
2248 List xs, ys; { /* ys by modifying xs ... */
2253 while (nonNull(tl(zs)))
2260 List dupOnto(xs,ys) /* non-destructively prepend xs backwards onto ys */
2263 for (; nonNull(xs); xs=tl(xs))
2264 ys = cons(hd(xs),ys);
2268 List dupListOnto(xs,ys) /* Duplicate spine of list xs onto ys */
2271 return revOnto(dupOnto(xs,NIL),ys);
2274 List dupList(xs) /* Duplicate spine of list xs */
2277 for (; nonNull(xs); xs=tl(xs))
2278 ys = cons(hd(xs),ys);
2282 List revOnto(xs,ys) /* Destructively reverse elements of*/
2283 List xs, ys; { /* list xs onto list ys... */
2286 while (nonNull(xs)) {
2295 Cell varIsMember(t,xs) /* Test if variable is a member of */
2296 Text t; /* given list of variables */
2298 for (; nonNull(xs); xs=tl(xs))
2299 if (t==textOf(hd(xs)))
2304 Name nameIsMember(t,ns) /* Test if name with text t is a */
2305 Text t; /* member of list of names xs */
2307 for (; nonNull(ns); ns=tl(ns))
2308 if (t==name(hd(ns)).text)
2313 Cell intIsMember(n,xs) /* Test if integer n is member of */
2314 Int n; /* given list of integers */
2316 for (; nonNull(xs); xs=tl(xs))
2317 if (n==intOf(hd(xs)))
2322 Cell cellIsMember(x,xs) /* Test for membership of specific */
2323 Cell x; /* cell x in list xs */
2325 for (; nonNull(xs); xs=tl(xs))
2331 Cell cellAssoc(c,xs) /* Lookup cell in association list */
2334 for (; nonNull(xs); xs=tl(xs))
2340 Cell cellRevAssoc(c,xs) /* Lookup cell in range of */
2341 Cell c; /* association lists */
2343 for (; nonNull(xs); xs=tl(xs))
2349 List replicate(n,x) /* create list of n copies of x */
2358 List diffList(from,take) /* list difference: from\take */
2359 List from, take; { /* result contains all elements of */
2360 List result = NIL; /* `from' not appearing in `take' */
2362 while (nonNull(from)) {
2363 List next = tl(from);
2364 if (!cellIsMember(hd(from),take)) {
2373 List deleteCell(xs, y) /* copy xs deleting pointers to y */
2377 for(;nonNull(xs);xs=tl(xs)) {
2380 result=cons(x,result);
2386 List take(n,xs) /* destructively truncate list to */
2387 Int n; /* specified length */
2393 while (1<n-- && nonNull(xs))
2400 List splitAt(n,xs) /* drop n things from front of list*/
2409 Cell nth(n,xs) /* extract n'th element of list */
2412 for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2419 List removeCell(x,xs) /* destructively remove cell from */
2424 return tl(xs); /* element at front of list */
2428 for (; nonNull(curr); prev=curr, curr=tl(prev))
2430 tl(prev) = tl(curr);
2431 return xs; /* element in middle of list */
2435 return xs; /* here if element not found */
2438 List nubList(xs) /* nuke dups in list */
2439 List xs; { /* non destructive */
2441 for (; nonNull(xs); xs=tl(xs))
2442 if (isNull(cellIsMember(hd(xs),outs)))
2443 outs = cons(hd(xs),outs);
2448 /* --------------------------------------------------------------------------
2449 * Operations on applications:
2450 * ------------------------------------------------------------------------*/
2452 Int argCount; /* number of args in application */
2454 Cell getHead(e) /* get head cell of application */
2455 Cell e; { /* set number of args in argCount */
2456 for (argCount=0; isAp(e); e=fun(e))
2461 List getArgs(e) /* get list of arguments in function*/
2462 Cell e; { /* application: */
2463 List as; /* getArgs(f e1 .. en) = [e1,..,en] */
2465 for (as=NIL; isAp(e); e=fun(e))
2466 as = cons(arg(e),as);
2470 Cell nthArg(n,e) /* return nth arg in application */
2471 Int n; /* of function to m args (m>=n) */
2472 Cell e; { /* nthArg n (f x0 x1 ... xm) = xn */
2473 for (n=numArgs(e)-n-1; n>0; n--)
2478 Int numArgs(e) /* find number of arguments to expr */
2481 for (n=0; isAp(e); e=fun(e))
2486 Cell applyToArgs(f,args) /* destructively apply list of args */
2487 Cell f; /* to function f */
2489 while (nonNull(args)) {
2490 Cell temp = tl(args);
2491 tl(args) = hd(args);
2500 /* --------------------------------------------------------------------------
2502 * ------------------------------------------------------------------------*/
2504 /*---------------------------------------------------------------------------
2505 * GreenCard entry points
2507 * GreenCard generated code accesses Hugs data structures and functions
2508 * (only) via these functions (which are stored in the virtual function
2510 *-------------------------------------------------------------------------*/
2514 static Cell makeTuple Args((Int));
2515 static Cell makeInt Args((Int));
2516 static Cell makeChar Args((Char));
2517 static Char CharOf Args((Cell));
2518 static Cell makeFloat Args((FloatPro));
2519 static Void* derefMallocPtr Args((Cell));
2520 static Cell* Fst Args((Cell));
2521 static Cell* Snd Args((Cell));
2523 static Cell makeTuple(n) Int n; { return mkTuple(n); }
2524 static Cell makeInt(n) Int n; { return mkInt(n); }
2525 static Cell makeChar(n) Char n; { return mkChar(n); }
2526 static Char CharOf(n) Cell n; { return charOf(n); }
2527 static Cell makeFloat(n) FloatPro n; { return mkFloat(n); }
2528 static Void* derefMallocPtr(n) Cell n; { return derefMP(n); }
2529 static Cell* Fst(n) Cell n; { return (Cell*)&fst(n); }
2530 static Cell* Snd(n) Cell n; { return (Cell*)&snd(n); }
2532 HugsAPI1* hugsAPI1() {
2533 static HugsAPI1 api;
2534 static Bool initialised = FALSE;
2536 api.nameTrue = nameTrue;
2537 api.nameFalse = nameFalse;
2538 api.nameNil = nameNil;
2539 api.nameCons = nameCons;
2540 api.nameJust = nameJust;
2541 api.nameNothing = nameNothing;
2542 api.nameLeft = nameLeft;
2543 api.nameRight = nameRight;
2544 api.nameUnit = nameUnit;
2545 api.nameIORun = nameIORun;
2546 api.makeInt = makeInt;
2547 api.makeChar = makeChar;
2548 api.CharOf = CharOf;
2549 api.makeFloat = makeFloat;
2550 api.makeTuple = makeTuple;
2552 api.mkMallocPtr = mkMallocPtr;
2553 api.derefMallocPtr = derefMallocPtr;
2554 api.mkStablePtr = mkStablePtr;
2555 api.derefStablePtr = derefStablePtr;
2556 api.freeStablePtr = freeStablePtr;
2558 api.evalWithNoError = evalWithNoError;
2559 api.evalFails = evalFails;
2560 api.whnfArgs = &whnfArgs;
2561 api.whnfHead = &whnfHead;
2562 api.whnfInt = &whnfInt;
2563 api.whnfFloat = &whnfFloat;
2564 api.garbageCollect = garbageCollect;
2565 api.stackOverflow = hugsStackOverflow;
2566 api.internal = internal;
2567 api.registerPrims = registerPrims;
2568 api.addPrimCfun = addPrimCfun;
2569 api.inventText = inventText;
2572 api.cellStack = cellStack;
2578 #endif /* GREENCARD */
2581 /* --------------------------------------------------------------------------
2583 * ------------------------------------------------------------------------*/
2586 static void far* safeFarCalloc Args((Int,Int));
2587 static void far* safeFarCalloc(n,s) /* allocate table storage and check*/
2588 Int n, s; { /* for non-null return */
2589 void far* tab = farCalloc(n,s);
2591 ERRMSG(0) "Cannot allocate run-time tables"
2596 #define TABALLOC(v,t,n) v=(t far*)safeFarCalloc(n,sizeof(t));
2598 #define TABALLOC(v,t,n)
2606 case RESET : clearStack();
2608 /* the next 2 statements are particularly important
2609 * if you are using GLOBALfst or GLOBALsnd since the
2610 * corresponding registers may be reset to their
2611 * uninitialised initial values by a longjump.
2613 heapTopFst = heapFst + heapSize;
2614 heapTopSnd = heapSnd + heapSize;
2618 if (isNull(lastExprSaved))
2619 savedText = NUM_TEXT;
2624 for (i=NAMEMIN; i<nameHw; ++i) {
2625 mark(name(i).parent);
2627 mark(name(i).stgVar);
2630 end("Names", nameHw-NAMEMIN);
2633 for (i=MODMIN; i<moduleHw; ++i) {
2634 mark(module(i).tycons);
2635 mark(module(i).names);
2636 mark(module(i).classes);
2637 mark(module(i).exports);
2638 mark(module(i).qualImports);
2640 end("Modules", moduleHw-MODMIN);
2643 for (i=TYCMIN; i<tyconHw; ++i) {
2644 mark(tycon(i).defn);
2645 mark(tycon(i).kind);
2646 mark(tycon(i).what);
2648 end("Type constructors", tyconHw-TYCMIN);
2651 for (i=CLASSMIN; i<classHw; ++i) {
2652 mark(cclass(i).head);
2653 mark(cclass(i).kinds);
2654 mark(cclass(i).fds);
2655 mark(cclass(i).xfds);
2656 mark(cclass(i).dsels);
2657 mark(cclass(i).supers);
2658 mark(cclass(i).members);
2659 mark(cclass(i).defaults);
2660 mark(cclass(i).instances);
2663 end("Classes", classHw-CLASSMIN);
2666 for (i=INSTMIN; i<instHw; ++i) {
2668 mark(inst(i).kinds);
2669 mark(inst(i).specifics);
2670 mark(inst(i).implements);
2672 end("Instances", instHw-INSTMIN);
2675 for (i=0; i<=sp; ++i)
2680 mark(lastExprSaved);
2683 end("Last expression", 3);
2688 end("C stack", stackRoots);
2693 case INSTALL : heapFst = heapAlloc(heapSize);
2694 heapSnd = heapAlloc(heapSize);
2696 if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
2697 ERRMSG(0) "Cannot allocate heap storage (%d cells)",
2702 heapTopFst = heapFst + heapSize;
2703 heapTopSnd = heapSnd + heapSize;
2704 for (i=1; i<heapSize; ++i) {
2708 snd(-heapSize) = NIL;
2715 marksSize = bitArraySize(heapSize);
2716 if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
2717 ERRMSG(0) "Unable to allocate gc markspace"
2721 TABALLOC(text, char, NUM_TEXT)
2722 TABALLOC(tyconHash, Tycon, TYCONHSZ)
2723 TABALLOC(tabTycon, struct strTycon, NUM_TYCON)
2724 TABALLOC(nameHash, Name, NAMEHSZ)
2725 TABALLOC(tabName, struct strName, NUM_NAME)
2726 TABALLOC(tabClass, struct strClass, NUM_CLASSES)
2727 TABALLOC(cellStack, Cell, NUM_STACK)
2728 TABALLOC(tabModule, struct Module, NUM_SCRIPTS)
2730 TABALLOC(tabExt, Text, NUM_EXT)
2735 nextNewText = NUM_TEXT;
2736 nextNewDText = (-1);
2737 lastExprSaved = NIL;
2738 savedText = NUM_TEXT;
2739 for (i=0; i<TEXTHSZ; ++i)
2740 textHash[i][0] = NOTEXT;
2746 for (i=0; i<TYCONHSZ; ++i)
2753 for (i=0; i<NAMEHSZ; ++i)
2764 tabInst = (struct strInst far *)
2765 farCalloc(NUM_INSTS,sizeof(struct strInst));
2768 ERRMSG(0) "Cannot allocate instance tables"
2778 /*-------------------------------------------------------------------------*/