[project @ 1999-12-03 17:01:20 by sewardj]
[ghc-hetmet.git] / ghc / interpreter / storage.c
1
2 /* --------------------------------------------------------------------------
3  * Primitives for manipulating global data structures
4  *
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.
10  *
11  * $RCSfile: storage.c,v $
12  * $Revision: 1.21 $
13  * $Date: 1999/12/03 17:01:23 $
14  * ------------------------------------------------------------------------*/
15
16 #include "prelude.h"
17 #include "storage.h"
18 #include "backend.h"
19 #include "connect.h"
20 #include "errors.h"
21 #include <setjmp.h>
22
23 /*#define DEBUG_SHOWUSE*/
24
25 /* --------------------------------------------------------------------------
26  * local function prototypes:
27  * ------------------------------------------------------------------------*/
28
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));
45
46 /* --------------------------------------------------------------------------
47  * Text storage:
48  *
49  * provides storage for the characters making up identifier and symbol
50  * names, string literals, character constants etc...
51  *
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.
56  *
57  * Where memory permits, the use of multiple hashtables gives a significant
58  * increase in performance, particularly when large source files are used.
59  *
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.
63  *
64  * Special text values (beyond the range of the text array table) are used
65  * to generate unique `new variable names' as required.
66  *
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  * ------------------------------------------------------------------------*/
71
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        */
80
81 String textToStr(t)                    /* find string corresp to given Text*/
82 Text t; {
83     static char newVar[16];
84
85     if (0<=t && t<NUM_TEXT)                     /* standard char string    */
86         return text + t;
87     if (t<0)
88         sprintf(newVar,"d%d",-t);               /* dictionary variable     */
89     else
90         sprintf(newVar,"v%d",t-NUM_TEXT);       /* normal variable         */
91     return newVar;
92 }
93
94 String identToStr(v) /*find string corresp to given ident or qualified name*/
95 Cell v; {
96     if (!isPair(v)) {
97         internal("identToStr");
98     }
99     switch (fst(v)) {
100         case VARIDCELL  :
101         case VAROPCELL  : 
102         case CONIDCELL  :
103         case CONOPCELL  : return text+textOf(v);
104
105         case QUALIDENT  : {   Text pos = textHw;
106                               Text t   = qmodOf(v);
107                               while (pos+1 < savedText && text[t]!=0) {
108                                   text[pos++] = text[t++];
109                               }
110                               if (pos+1 < savedText) {
111                                   text[pos++] = '.';
112                               }
113                               t = qtextOf(v);
114                               while (pos+1 < savedText && text[t]!=0) {
115                                   text[pos++] = text[t++];
116                               }
117                               text[pos] = '\0';
118                               return text+textHw;
119                           }
120     }
121     internal("identToStr2");
122     return 0; /* NOTREACHED */
123 }
124
125 Text inventText()     {                 /* return new unused variable name */
126     return nextNewText++;
127 }
128
129 Text inventDictText() {                 /* return new unused dictvar name  */
130     return nextNewDText--;
131 }
132
133 Bool inventedText(t)                    /* Signal TRUE if text has been    */
134 Text t; {                               /* generated internally            */
135     return (t<0 || t>=NUM_TEXT);
136 }
137
138 #define MAX_FIXLIT 100
139 Text fixLitText(t)                /* fix literal text that might include \ */
140 Text t; {
141     String   s = textToStr(t);
142     char     p[MAX_FIXLIT];
143     Int      i;
144     for(i = 0;i < MAX_FIXLIT-2 && *s;s++) {
145       p[i++] = *s;
146       if (*s == '\\') {
147         p[i++] = '\\';
148       } 
149     }
150     if (i < MAX_FIXLIT-2) {
151       p[i] = 0;
152     } else {
153         ERRMSG(0) "storage space exhausted for internal literal string"
154         EEND;
155     }
156     return (findText(p));
157 }
158 #undef MAX_FIXLIT
159
160 static Int local hash(s)                /* Simple hash function on strings */
161 String s; {
162     int v, j = 3;
163
164     for (v=((int)(*s))*8; *s; s++)
165         v += ((int)(*s))*(j++);
166     if (v<0)
167         v = (-v);
168     return(v%TEXTHSZ);
169 }
170
171 Text findText(s)                       /* Locate string in Text array      */
172 String s; {
173     int    h       = hash(s);
174     int    hashno  = 0;
175     Text   textPos = textHash[h][hashno];
176
177 #define TryMatch        {   Text   originalTextPos = textPos;              \
178                             String t;                                      \
179                             for (t=s; *t==text[textPos]; textPos++,t++)    \
180                                 if (*t=='\0')                              \
181                                     return originalTextPos;                \
182                         }
183 #define Skip            while (text[textPos++]) ;
184
185     while (textPos!=NOTEXT) {
186         TryMatch
187         if (++hashno<NUM_TEXTH)         /* look in next hashtable entry    */
188             textPos = textHash[h][hashno];
189         else {
190             Skip
191             while (textPos < textHw) {
192                 TryMatch
193                 Skip
194             }
195             break;
196         }
197     }
198
199 #undef TryMatch
200 #undef Skip
201
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"
205         EEND;
206     }
207     while ((text[textHw++] = *s++) != 0) {
208     }
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;
213     }
214
215     return textPos;
216 }
217
218 static Int local saveText(t)            /* Save text value in buffer       */
219 Text t; {                               /* at top of text table            */
220     String s = textToStr(t);
221     Int    l = strlen(s);
222
223     if (textHw + l + 1 > savedText) {
224         ERRMSG(0) "Character string storage space exhausted"
225         EEND;
226     }
227     savedText -= l+1;
228     strcpy(text+savedText,s);
229     return savedText;
230 }
231
232
233 static int fromHexDigit ( char c )
234 {
235    switch (c) {
236       case '0': case '1': case '2': case '3': case '4':
237       case '5': case '6': case '7': case '8': case '9':
238          return c - '0';
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;
245       default: return -1;
246    }
247 }
248
249
250 /* returns findText (unZencode s) */
251 Text unZcodeThenFindText ( String s )
252 {
253    unsigned char* p;
254    Int            n, nn, i;
255    Text           t;
256
257    assert(s);
258    nn = 100 + 10 * strlen(s);
259    p = malloc ( nn );
260    if (!p) internal ("unZcodeThenFindText: malloc failed");
261    n = 0;
262
263    while (1) {
264       if (!(*s)) break;
265       if (n > nn-90) internal ("unZcodeThenFindText: result is too big");
266       if (*s != 'z' && *s != 'Z') {
267          p[n] = *s; n++; s++; 
268          continue;
269       }
270       s++;
271       if (!(*s)) goto parse_error;
272       switch (*s++) {
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;
297          case 'x':
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]);
301             p += 2; s += 2;
302             break;
303          case '0': case '1': case '2': case '3': case '4':
304          case '5': case '6': case '7': case '8': case '9':
305             i = 0;
306             s--;
307             while (*s && isdigit((int)(*s))) {
308                i = 10 * i + (*s - '0');
309                s++;
310             }
311             if (*s != 'T') goto parse_error;
312             s++;
313             p[n++] = '(';
314             while (i > 0) { p[n++] = ','; i--; };
315             p[n++] = ')';
316             break;
317          default: 
318             goto parse_error;
319       }      
320    }
321    p[n] = 0;
322    t = findText(p);
323    free(p);
324    return t;
325
326   parse_error:
327    free(p);
328    fprintf ( stderr, "\nstring = `%s'\n", s );
329    internal ( "unZcodeThenFindText: parse error on above string");
330    return NIL; /*notreached*/
331 }
332
333
334 Text enZcodeThenFindText ( String s )
335 {
336    unsigned char* p;
337    Int            n, nn;
338    Text           t;
339    char toHex[16] = "0123456789ABCDEF";
340
341    assert(s);
342    nn = 100 + 10 * strlen(s);
343    p = malloc ( nn );
344    if (!p) internal ("enZcodeThenFindText: malloc failed");
345    n = 0;
346    while (1) {
347       if (!(*s)) break;
348       if (n > nn-90) internal ("enZcodeThenFindText: result is too big");
349       if (*s != 'z' 
350           && *s != 'Z'
351           && (isalnum((int)(*s)) || *s == '_')) { 
352          p[n] = *s; n++; s++;
353          continue;
354       }
355       switch (*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];
383                   s++; break;
384       }
385    }
386    p[n] = 0;
387    t = findText(p);
388    free(p);
389    return t;
390 }
391
392
393 Text textOf ( Cell c )
394 {
395    Bool ok = 
396           (whatIs(c)==VARIDCELL
397            || whatIs(c)==CONIDCELL
398            || whatIs(c)==VAROPCELL
399            || whatIs(c)==CONOPCELL
400            || whatIs(c)==STRCELL
401            || whatIs(c)==DICTVAR
402           );
403    if (!ok) {
404       fprintf(stderr, "\ntextOf: bad tag %d\n",whatIs(c) );
405       internal("textOf: bad tag");
406    }
407    return snd(c);
408 }
409
410 /* --------------------------------------------------------------------------
411  * Ext storage:
412  *
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  * ------------------------------------------------------------------------*/
421
422 #if TREX
423 Text  DEFTABLE(tabExt,NUM_EXT);         /* Storage for Ext names           */
424 Ext   extHw;
425
426 Ext mkExt(t)                            /* Allocate or find an Ext value   */
427 Text t; {
428     Ext e = EXTMIN;
429     for (; e<extHw; e++)
430         if (t==extText(e))
431             return e;
432     if (extHw-EXTMIN >= NUM_EXT) {
433         ERRMSG(0) "Ext storage space exhausted"
434         EEND;
435     }
436     extText(extHw) = t;
437     return extHw++;
438 }
439 #endif
440
441 /* --------------------------------------------------------------------------
442  * Tycon storage:
443  *
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  * ------------------------------------------------------------------------*/
449
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           */
455
456 Tycon newTycon(t)                       /* add new tycon to tycon table    */
457 Text t; {
458     Int h = tHash(t);
459     if (tyconHw-TYCMIN >= NUM_TYCON) {
460         ERRMSG(0) "Type constructor storage space exhausted"
461         EEND;
462     }
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;
473
474     return tyconHw++;
475 }
476
477 Tycon findTycon(t)                      /* locate Tycon in tycon table     */
478 Text t; {
479     Tycon tc = tyconHash[tHash(t)];
480
481     while (nonNull(tc) && tycon(tc).text!=t)
482         tc = tycon(tc).nextTyconHash;
483     return tc;
484 }
485
486 Tycon addTycon(tc)  /* Insert Tycon in tycon table - if no clash is caused */
487 Tycon tc; {
488     Tycon oldtc = findTycon(tycon(tc).text);
489     if (isNull(oldtc)) {
490         hashTycon(tc);
491         module(currentModule).tycons=cons(tc,module(currentModule).tycons);
492         return tc;
493     } else
494         return oldtc;
495 }
496
497 static Void local hashTycon(tc)         /* Insert Tycon into hash table    */
498 Tycon tc; {
499    assert(isTycon(tc));
500    if (1) {
501      Text  t = tycon(tc).text;
502      Int   h = tHash(t);
503      tycon(tc).nextTyconHash = tyconHash[h];
504      tyconHash[h]            = tc;
505    }
506 }
507
508 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
509 Cell id; {
510     if (!isPair(id)) internal("findQualTycon");
511     switch (fst(id)) {
512         case CONIDCELL :
513         case CONOPCELL :
514             return findTycon(textOf(id));
515         case QUALIDENT : {
516             Text   t  = qtextOf(id);
517             Module m  = findQualifier(qmodOf(id));
518             List   es = NIL;
519             if (isNull(m)) return NIL;
520             for(es=module(m).exports; nonNull(es); es=tl(es)) {
521                 Cell e = hd(es);
522                 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t) 
523                     return fst(e);
524             }
525             return NIL;
526         }
527         default : internal("findQualTycon2");
528     }
529     return NIL; /* NOTREACHED */
530 }
531
532 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr   */
533 Text t;
534 Kind kind;
535 Int  ar;
536 Cell what;
537 Cell defn; {
538     Tycon tc        = newTycon(t);
539     tycon(tc).line  = 0;
540     tycon(tc).kind  = kind;
541     tycon(tc).what  = what;
542     tycon(tc).defn  = defn;
543     tycon(tc).arity = ar;
544     return tc;
545 }
546
547 static List local insertTycon(tc,ts)    /* insert tycon tc into sorted list*/
548 Tycon tc;                               /* ts                              */
549 List  ts; {
550     Cell   prev = NIL;
551     Cell   curr = ts;
552     String s    = textToStr(tycon(tc).text);
553
554     while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
555         if (hd(curr)==tc)               /* just in case we get duplicates! */
556             return ts;
557         prev = curr;
558         curr = tl(curr);
559     }
560     if (nonNull(prev)) {
561         tl(prev) = cons(tc,curr);
562         return ts;
563     }
564     else
565         return cons(tc,curr);
566 }
567
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);
576     return ts;
577 }
578
579 Text ghcTupleText(tup)
580 Tycon tup; {
581     Int  i;
582     char buf[103];
583     assert(isTuple(tup));
584     tup = tupleOf(tup);
585     if (tup >= 100) internal("ghcTupleText");
586     buf[0] = '(';
587     for (i = 1; i <= tup; i++) buf[i] = ',';
588     buf[i] = ')';
589     buf[i+1] = 0;
590     return findText(buf);
591 }
592
593 /* --------------------------------------------------------------------------
594  * Name storage:
595  *
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.
599  *
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
603  * list.
604  * ------------------------------------------------------------------------*/
605
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      */
611
612 Name newName(t,parent)                  /* Add new name to name table      */
613 Text t; 
614 Cell parent; {
615     Int h = nHash(t);
616     if (nameHw-NAMEMIN >= NUM_NAME) {
617         ERRMSG(0) "Name storage space exhausted"
618         EEND;
619     }
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;
635     return nameHw++;
636 }
637
638 Name findName(t)                        /* Locate name in name table       */
639 Text t; {
640     Name n = nameHash[nHash(t)];
641
642     while (nonNull(n) && name(n).text!=t)
643         n = name(n).nextNameHash;
644     return n;
645 }
646
647 Name addName(nm)                        /* Insert Name in name table - if  */
648 Name nm; {                              /* no clash is caused              */
649     Name oldnm = findName(name(nm).text);
650     if (isNull(oldnm)) {
651         hashName(nm);
652         module(currentModule).names=cons(nm,module(currentModule).names);
653         return nm;
654     } else
655         return oldnm;
656 }
657
658 static Void local hashName(nm)          /* Insert Name into hash table     */
659 Name nm; {
660     Text t;
661     Int  h;
662     assert(isName(nm));
663     t = name(nm).text;
664     h = nHash(t);
665     name(nm).nextNameHash = nameHash[h];
666     nameHash[h]           = nm;
667 }
668
669 Name findQualName(id)              /* Locate (possibly qualified) name*/
670 Cell id; {                         /* in name table                   */
671     if (!isPair(id))
672         internal("findQualName");
673     switch (fst(id)) {
674         case VARIDCELL :
675         case VAROPCELL :
676         case CONIDCELL :
677         case CONOPCELL :
678             return findName(textOf(id));
679         case QUALIDENT : {
680             Text   t  = qtextOf(id);
681             Module m  = findQualifier(qmodOf(id));
682             List   es = NIL;
683             if (isNull(m)) return NIL;
684             for(es=module(m).exports; nonNull(es); es=tl(es)) {
685                 Cell e = hd(es);
686                 if (isName(e) && name(e).text==t) 
687                     return e;
688                 else if (isPair(e) && DOTDOT==snd(e)) {
689                     List subentities = NIL;
690                     Cell c = fst(e);
691                     if (isTycon(c)
692                         && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
693                         subentities = tycon(c).defn;
694                     else if (isClass(c))
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);
701                     }
702                 }
703             }
704             return NIL;
705         }
706         default : internal("findQualName2");
707     }
708     return 0; /* NOTREACHED */
709 }
710
711
712 Name nameFromStgVar ( StgVar v )
713 {
714    Int n;
715    for (n = NAMEMIN; n < nameHw; n++)
716       if (name(n).stgVar == v) return n;
717    return NIL;
718 }
719
720 void* getHugs_AsmObject_for ( char* s )
721 {
722    StgVar v;
723    Text   t = findText(s);
724    Name   n = NIL;
725    for (n = NAMEMIN; n < nameHw; n++)
726       if (name(n).text == t) break;
727    if (n == nameHw) internal("getHugs_AsmObject_for(1)");
728    v = name(n).stgVar;
729    if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
730       internal("getHugs_AsmObject_for(2)");
731    return ptrOf(stgVarInfo(v));
732 }
733
734 /* --------------------------------------------------------------------------
735  * Primitive functions:
736  * ------------------------------------------------------------------------*/
737
738 Name addPrimCfunREP(t,arity,no,rep)     /* add primitive constructor func  */
739 Text t;                                 /* sets rep, not type              */
740 Int  arity;
741 Int  no;
742 Int  rep; { /* Really AsmRep */
743     Name n          = newName(t,NIL);
744     name(n).arity   = arity;
745     name(n).number  = cfunNo(no);
746     name(n).type    = NIL;
747     name(n).primop  = (void*)rep;
748     return n;
749 }
750
751
752 Name addPrimCfun(t,arity,no,type)       /* add primitive constructor func  */
753 Text t;
754 Int  arity;
755 Int  no;
756 Cell type; {
757     Name n         = newName(t,NIL);
758     name(n).arity  = arity;
759     name(n).number = cfunNo(no);
760     name(n).type   = type;
761     return n;
762 }
763
764
765 Int sfunPos(s,c)                        /* Find position of field with     */
766 Name s;                                 /* selector s in constructor c.    */
767 Name c; {
768     List cns;
769     cns = name(s).defn;
770     for (; nonNull(cns); cns=tl(cns))
771         if (fst(hd(cns))==c)
772             return intOf(snd(hd(cns)));
773     internal("sfunPos");
774     return 0;/* NOTREACHED */
775 }
776
777 static List local insertName(nm,ns)     /* insert name nm into sorted list */
778 Name nm;                                /* ns                              */
779 List ns; {
780     Cell   prev = NIL;
781     Cell   curr = ns;
782     String s    = textToStr(name(nm).text);
783
784     while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
785         if (hd(curr)==nm)               /* just in case we get duplicates! */
786             return ns;
787         prev = curr;
788         curr = tl(curr);
789     }
790     if (nonNull(prev)) {
791         tl(prev) = cons(nm,curr);
792         return ns;
793     }
794     else
795         return cons(nm,curr);
796 }
797
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 */
802 #if 1
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);
808         }
809     return ns;
810 #else
811     List mns = module(currentModule).names;
812     for(; nonNull(mns); mns=tl(mns)) {
813         Name nm = hd(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);
818         }
819     }
820     return ns;
821 #endif
822 }
823
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  * ------------------------------------------------------------------------*/
832
833 static Void local patternError(s)       /* report error in pattern         */
834 String s; {
835     ERRMSG(0) "%s in pattern", s
836     EEND;
837 }
838
839 static Bool local stringMatch(pat,str)  /* match string against pattern    */
840 String pat;
841 String str; {
842
843     for (;;)
844         switch (*pat) {
845             case '\0' : return (*str=='\0');
846
847             case '*'  : do {
848                             if (stringMatch(pat+1,str))
849                                 return TRUE;
850                         } while (*str++);
851                         return FALSE;
852
853             case '?'  : if (*str++=='\0')
854                             return FALSE;
855                         pat++;
856                         break;
857
858             case '['  : {   Bool found = FALSE;
859                             while (*++pat!='\0' && *pat!=']')
860                                 if (!found && ( pat[0] == *str  ||
861                                                (pat[1] == '-'   &&
862                                                 pat[2] != ']'   &&
863                                                 pat[2] != '\0'  &&
864                                                 pat[0] <= *str  &&
865                                                 pat[2] >= *str)))
866
867                                     found = TRUE;
868                             if (*pat != ']')
869                                 patternError("missing `]'");
870                             if (!found)
871                                 return FALSE;
872                             pat++;
873                             str++;
874                         }
875                         break;
876
877             case '\\' : if (*++pat == '\0')
878                             patternError("extra trailing `\\'");
879                         /*fallthru!*/
880             default   : if (*pat++ != *str++)
881                             return FALSE;
882                         break;
883         }
884 }
885
886 /* --------------------------------------------------------------------------
887  * Storage of type classes, instances etc...:
888  * ------------------------------------------------------------------------*/
889
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      */
893
894 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records  */
895 struct strInst far *tabInst;           /* (pointer to) table of instances  */
896
897 Class newClass(t)                      /* add new class to class table     */
898 Text t; {
899     if (classHw-CLASSMIN >= NUM_CLASSES) {
900         ERRMSG(0) "Class storage space exhausted"
901         EEND;
902     }
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);
918     return classHw++;
919 }
920
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 */
924
925 Class findClass(t)                     /* look for named class in table    */
926 Text t; {
927     Class cl;
928     List cs;
929     for (cs=classes; nonNull(cs); cs=tl(cs)) {
930         cl=hd(cs);
931         if (cclass(cl).text==t)
932             return cl;
933     }
934     return NIL;
935 }
936
937 Class addClass(c)                       /* Insert Class in class list      */
938 Class c; {                              /*  - if no clash caused           */
939     Class oldc = findClass(cclass(c).text);
940     if (isNull(oldc)) {
941         classes=cons(c,classes);
942         module(currentModule).classes=cons(c,module(currentModule).classes);
943         return c;
944     }
945     else
946         return oldc;
947 }
948
949 Class findQualClass(c)                  /* Look for (possibly qualified)   */
950 Cell c; {                               /* class in class list             */
951     if (!isQualIdent(c)) {
952         return findClass(textOf(c));
953     } else {
954         Text   t  = qtextOf(c);
955         Module m  = findQualifier(qmodOf(c));
956         List   es = NIL;
957         if (isNull(m))
958             return NIL;
959         for (es=module(m).exports; nonNull(es); es=tl(es)) {
960             Cell e = hd(es);
961             if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t) 
962                 return fst(e);
963         }
964     }
965     return NIL;
966 }
967
968 Inst newInst() {                       /* Add new instance to table        */
969     if (instHw-INSTMIN >= NUM_INSTS) {
970         ERRMSG(0) "Instance storage space exhausted"
971         EEND;
972     }
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;
979
980     return instHw++;
981 }
982
983 #ifdef DEBUG_DICTS
984 extern Void printInst Args((Inst));
985
986 Void printInst(in)
987 Inst in; {
988     Class cl = inst(in).c;
989     Printf("%s-", textToStr(cclass(cl).text));
990     printType(stdout,inst(in).t);
991 }
992 #endif /* DEBUG_DICTS */
993
994 Inst findFirstInst(tc)                  /* look for 1st instance involving */
995 Tycon tc; {                             /* the type constructor tc         */
996     return findNextInst(tc,INSTMIN-1);
997 }
998
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))
1006                 return in;
1007     }
1008     return NIL;
1009 }
1010
1011 static Bool local typeInvolves(ty,tc)   /* Test to see if type ty involves */
1012 Type ty;                                /* type constructor/tuple tc.      */
1013 Type tc; {
1014     return (ty==tc)
1015         || (isAp(ty) && (typeInvolves(fun(ty),tc)
1016                          || typeInvolves(arg(ty),tc)));
1017 }
1018
1019 /* --------------------------------------------------------------------------
1020  * Control stack:
1021  *
1022  * Various parts of the system use a stack of cells.  Most of the stack
1023  * operations are defined as macros, expanded inline.
1024  * ------------------------------------------------------------------------*/
1025
1026 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack          */
1027 StackPtr sp;                        /* stack pointer                       */
1028
1029 #if GIMME_STACK_DUMPS
1030
1031 #define UPPER_DISP  5               /* # display entries on top of stack   */
1032 #define LOWER_DISP  5               /* # display entries on bottom of stack*/
1033
1034 Void hugsStackOverflow() {          /* Report stack overflow               */
1035     extern Int  rootsp;
1036     extern Cell evalRoots[];
1037
1038     ERRMSG(0) "Control stack overflow" ETHEN
1039     if (rootsp>=0) {
1040         Int i;
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]);
1045             }
1046             ERRTEXT "\n..." ETHEN
1047             for (i=LOWER_DISP-1; i>=0; i--) {
1048                 ERRTEXT "\nwhile evaluating: " ETHEN
1049                 ERREXPR(evalRoots[i]);
1050             }
1051         }
1052         else {
1053             for (i=rootsp; i>=0; i--) {
1054                 ERRTEXT "\nwhile evaluating: " ETHEN
1055                 ERREXPR(evalRoots[i]);
1056             }
1057         }
1058     }
1059     ERRTEXT "\n"
1060     EEND;
1061 }
1062
1063 #else /* !GIMME_STACK_DUMPS */
1064
1065 Void hugsStackOverflow() {          /* Report stack overflow               */
1066     ERRMSG(0) "Control stack overflow"
1067     EEND;
1068 }
1069
1070 #endif /* !GIMME_STACK_DUMPS */
1071
1072 /* --------------------------------------------------------------------------
1073  * Module storage:
1074  *
1075  * A Module represents a user defined module.  
1076  *
1077  * Note: there are now two lookup mechanisms in the system:
1078  *
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.
1082  *
1083  * 2) Unqualified imports and local definitions for the current module
1084  *    are stored in hash tables (tyconHash and nameHash) or linear lists
1085  *    (classes).
1086  *
1087  * ------------------------------------------------------------------------*/
1088
1089 static  Module   moduleHw;              /* next unused Module              */
1090 struct  Module   DEFTABLE(tabModule,NUM_MODULE); /* Module storage         */
1091 Module  currentModule;                  /* Module currently being processed*/
1092
1093 Bool isValidModule(m)                  /* is m a legitimate module id?     */
1094 Module m; {
1095     return (MODMIN <= m && m < moduleHw);
1096 }
1097
1098 Module newModule(t)                     /* add new module to module table  */
1099 Text t; {
1100     if (moduleHw-MODMIN >= NUM_MODULE) {
1101         ERRMSG(0) "Module storage space exhausted"
1102         EEND;
1103     }
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;
1117     return moduleHw++;
1118 }
1119
1120 void ppModules ( void )
1121 {
1122    Int i;
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)
1128              );
1129    printf ( "end   MODULES\n" );
1130    fflush(stderr); fflush(stdout);
1131 }
1132
1133
1134 Module findModule(t)                    /* locate Module in module table  */
1135 Text t; {
1136     Module m;
1137     for(m=MODMIN; m<moduleHw; ++m) {
1138         if (module(m).text==t)
1139             return m;
1140     }
1141     return NIL;
1142 }
1143
1144 Module findModid(c)                    /* Find module by name or filename  */
1145 Cell c; {
1146     switch (whatIs(c)) {
1147         case STRCELL   : { Script s = scriptThisFile(snd(c));
1148                            return (s==-1) ? NIL : moduleOfScript(s);
1149                          }
1150         case CONIDCELL : return findModule(textOf(c));
1151         default        : internal("findModid");
1152     }
1153     return NIL;/*NOTUSED*/
1154 }
1155
1156 static local Module findQualifier(t)    /* locate Module in import list   */
1157 Text t; {
1158     Module ms;
1159     for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1160         if (textOf(fst(hd(ms)))==t)
1161             return snd(hd(ms));
1162     }
1163 #if 1 /* mpj */
1164     if (module(currentModule).text==t)
1165         return currentModule;
1166 #endif
1167     return NIL;
1168 }
1169
1170 Void setCurrModule(m)              /* set lookup tables for current module */
1171 Module m; {
1172     Int i;
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)
1177             tyconHash[i] = NIL;
1178         mapProc(hashTycon,module(m).tycons);
1179         for (i=0; i<NAMEHSZ; ++i)
1180             nameHash[i] = NIL;
1181         mapProc(hashName,module(m).names);
1182         classes = module(m).classes;
1183     }
1184 }
1185
1186 Name jrsFindQualName ( Text mn, Text sn )
1187 {
1188    Module m;
1189    List   ns;
1190
1191    for (m=MODMIN; m<moduleHw; m++)
1192       if (module(m).text == mn) break;
1193    if (m == moduleHw) return NIL;
1194    
1195    for (ns = module(m).names; nonNull(ns); ns=tl(ns)) 
1196       if (name(hd(ns)).text == sn) return hd(ns);
1197
1198    return NIL;
1199 }
1200
1201
1202 /* A bit tricky.  Assumes that if tab==NULL, then 
1203    currUsed and *currSize must be zero.
1204 */
1205 static
1206 void* genericExpand ( void* tab, 
1207                       int*  currSize, int  currUsed,
1208                       int   initSize, int  elemSize )
1209 {
1210    int   size2;
1211    void* tab2;
1212    if (currUsed < *currSize)
1213       return tab;
1214    size2 = (*currSize == 0) ? initSize : (2 * *currSize);
1215    tab2 = malloc ( size2 * elemSize );
1216    if (!tab2) {
1217       ERRMSG(0) "Can't allocate enough memory to resize a table"
1218       EEND;
1219    }
1220    if (*currSize > 0)
1221       memcpy ( tab2, tab, elemSize * *currSize );
1222    *currSize = size2;
1223    if (tab) free ( tab );
1224    return tab2;
1225 }
1226
1227 void addOTabName ( Module m, char* nm, void* ad )
1228 {
1229    module(m).oTab
1230       = genericExpand ( module(m).oTab, 
1231                         &module(m).sizeoTab,
1232                         module(m).usedoTab,
1233                         8, sizeof(OSym) );
1234
1235    module(m).oTab[ module(m).usedoTab ].nm = nm;
1236    module(m).oTab[ module(m).usedoTab ].ad = ad;
1237    module(m).usedoTab++;
1238 }
1239
1240
1241 void addDLSect ( Module m, void* start, void* end, DLSect sect )
1242 {
1243    module(m).dlTab
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++;
1252 }
1253
1254
1255 void* lookupOTabName ( Module m, char* nm )
1256 {
1257    int i;
1258    for (i = 0; i < module(m).usedoTab; i++) {
1259       if (1)
1260          fprintf ( stderr, 
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;
1265    }
1266    return NULL;
1267 }
1268
1269
1270 char* nameFromOPtr ( void* p )
1271 {
1272    int i;
1273    Module m;
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;
1278    return NULL;
1279 }
1280
1281
1282 DLSect lookupDLSect ( void* ad )
1283 {
1284    int i;
1285    Module m;
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;
1292 }
1293
1294
1295 /* --------------------------------------------------------------------------
1296  * Script file storage:
1297  *
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  * ------------------------------------------------------------------------*/
1304
1305 typedef struct {                       /* record of storage state prior to */
1306     Text  file;                        /* reading script/module            */
1307     Text  textHw;
1308     Text  nextNewText;
1309     Text  nextNewDText;
1310     Module moduleHw;
1311     Tycon tyconHw;
1312     Name  nameHw;
1313     Class classHw;
1314     Inst  instHw;
1315 #if TREX
1316     Ext   extHw;
1317 #endif
1318 } script;
1319
1320 #ifdef  DEBUG_SHOWUSE
1321 static Void local showUse(msg,val,mx)
1322 String msg;
1323 Int val, mx; {
1324     Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1325 }
1326 #endif
1327
1328 static Script scriptHw;                 /* next unused script number       */
1329 static script scripts[NUM_SCRIPTS];     /* storage for script records      */
1330
1331
1332 void ppScripts ( void )
1333 {
1334    Int i;
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 
1345              );
1346    printf ( "end   SCRIPTS\n" );
1347    fflush(stderr); fflush(stdout);
1348 }
1349
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"
1354         EEND;
1355     }
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);
1363 #if TREX
1364     showUse("Ext",    extHw-EXTMIN,     NUM_EXT);
1365 #endif
1366 #endif
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;
1376 #if TREX
1377     scripts[scriptHw].extHw        = extHw;
1378 #endif
1379     return scriptHw++;
1380 }
1381
1382 Bool isPreludeScript() {                /* Test whether this is the Prelude*/
1383     return (scriptHw==0);
1384 }
1385
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;
1389 }
1390
1391 Module lastModule() {              /* Return module in current script file */
1392     return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1393 }
1394
1395 #define scriptThis(nm,t,tag)            Script nm(x)                       \
1396                                         t x; {                             \
1397                                             Script s=0;                    \
1398                                             while (s<scriptHw              \
1399                                                    && x>=scripts[s].tag)   \
1400                                                 s++;                       \
1401                                             return s;                      \
1402                                         }
1403 scriptThis(scriptThisName,Name,nameHw)
1404 scriptThis(scriptThisTycon,Tycon,tyconHw)
1405 scriptThis(scriptThisInst,Inst,instHw)
1406 scriptThis(scriptThisClass,Class,classHw)
1407 #undef scriptThis
1408
1409 Module moduleOfScript(s)
1410 Script s; {
1411     return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1412 }
1413
1414 String fileOfModule(m)
1415 Module m; {
1416     Script s;
1417     if (m == modulePrelude) {
1418         return STD_PRELUDE;
1419     }
1420     for(s=0; s<scriptHw; ++s) {
1421         if (scripts[s].moduleHw == m) {
1422             return textToStr(scripts[s].file);
1423         }
1424     }
1425     return 0;
1426 }
1427
1428 Script scriptThisFile(f)
1429 Text f; {
1430     Script s;
1431     for (s=0; s < scriptHw; ++s) {
1432         if (scripts[s].file == f) {
1433             return s+1;
1434         }
1435     }
1436     if (f == findText(STD_PRELUDE)) {
1437         return 0;
1438     }
1439     return (-1);
1440 }
1441
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?   */
1445         int i;
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;
1454 #if USE_DICTHW
1455         dictHw       = scripts[sno].dictHw;
1456 #endif
1457 #if TREX
1458         extHw        = scripts[sno].extHw;
1459 #endif
1460
1461 #if 0
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);*/
1466             }
1467         }
1468         moduleHw = scripts[sno].moduleHw;
1469 #endif
1470         for (i=0; i<TEXTHSZ; ++i) {
1471             int j = 0;
1472             while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1473                                && textHash[i][j]<textHw)
1474                 ++j;
1475             if (j<NUM_TEXTH)
1476                 textHash[i][j] = NOTEXT;
1477         }
1478
1479         currentModule=NIL;
1480         for (i=0; i<TYCONHSZ; ++i) {
1481             tyconHash[i] = NIL;
1482         }
1483         for (i=0; i<NAMEHSZ; ++i) {
1484             nameHash[i] = NIL;
1485         }
1486
1487         for (i=CLASSMIN; i<classHw; i++) {
1488             List ins = cclass(i).instances;
1489             List is  = NIL;
1490
1491             while (nonNull(ins)) {
1492                 List temp = tl(ins);
1493                 if (hd(ins)<instHw) {
1494                     tl(ins) = is;
1495                     is      = ins;
1496                 }
1497                 ins = temp;
1498             }
1499             cclass(i).instances = rev(is);
1500         }
1501
1502         scriptHw = sno;
1503     }
1504 }
1505
1506 /* --------------------------------------------------------------------------
1507  * Heap storage:
1508  *
1509  * Provides a garbage collectable heap for storage of expressions etc.
1510  *
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  * ------------------------------------------------------------------------*/
1515
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 */
1519 #ifndef GLOBALfst
1520 Heap    heapTopFst;
1521 #endif
1522 #ifndef GLOBALsnd
1523 Heap    heapTopSnd;
1524 #endif
1525 Bool    consGC = TRUE;                  /* Set to FALSE to turn off gc from*/
1526                                         /* C stack; use with extreme care! */
1527 Long    numCells;
1528 Int     numGcs;                         /* number of garbage collections   */
1529 Int     cellsRecovered;                 /* number of cells recovered       */
1530
1531 static  Cell freeList;                  /* free list of unused cells       */
1532 static  Cell lsave, rsave;              /* save components of pair         */
1533
1534 #if GC_STATISTICS
1535
1536 static Int markCount, stackRoots;
1537
1538 #define initStackRoots() stackRoots = 0
1539 #define recordStackRoot() stackRoots++
1540
1541 #define startGC()       \
1542     if (gcMessages) {   \
1543         Printf("\n");   \
1544         fflush(stdout); \
1545     }
1546 #define endGC()         \
1547     if (gcMessages) {   \
1548         Printf("\n");   \
1549         fflush(stdout); \
1550     }
1551
1552 #define start()      markCount = 0
1553 #define end(thing,rs) \
1554     if (gcMessages) { \
1555         Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1556         fflush(stdout); \
1557     }
1558 #define recordMark() markCount++
1559
1560 #else /* !GC_STATISTICS */
1561
1562 #define startGC()
1563 #define endGC()
1564
1565 #define initStackRoots()
1566 #define recordStackRoot()
1567
1568 #define start()   
1569 #define end(thing,root) 
1570 #define recordMark() 
1571
1572 #endif /* !GC_STATISTICS */
1573
1574 Cell pair(l,r)                          /* Allocate pair (l, r) from       */
1575 Cell l, r; {                            /* heap, garbage collecting first  */
1576     Cell c = freeList;                  /* if necessary ...                */
1577
1578     if (isNull(c)) {
1579         lsave = l;
1580         rsave = r;
1581         garbageCollect();
1582         l     = lsave;
1583         lsave = NIL;
1584         r     = rsave;
1585         rsave = NIL;
1586         c     = freeList;
1587     }
1588     freeList = snd(freeList);
1589     fst(c)   = l;
1590     snd(c)   = r;
1591     numCells++;
1592     return c;
1593 }
1594
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);
1600     }
1601     else
1602         internal("overwrite");
1603 }
1604
1605 static Int *marks;
1606 static Int marksSize;
1607
1608 Cell markExpr(c)                        /* External interface to markCell  */
1609 Cell c; {
1610     return isGenPair(c) ? markCell(c) : c;
1611 }
1612
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 */
1616                                         /* is a pair                       */
1617     {   register int place = placeInSet(c);
1618         register int mask  = maskInSet(c);
1619         if (marks[place]&mask)
1620             return c;
1621         else {
1622             marks[place] |= mask;
1623             recordMark();
1624         }
1625     }
1626
1627     /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1628     if (isGenPair(fst(c))) {
1629         STACK_CHECK
1630         fst(c) = markCell(fst(c));
1631         markSnd(c);
1632     }
1633     else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1634         STACK_CHECK
1635         markSnd(c);
1636     }
1637
1638     return c;
1639 }
1640
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            */
1644
1645 ma: t = c;                              /* Keep pointer to original pair   */
1646     c = snd(c);
1647     if (!isPair(c))
1648         return;
1649
1650     {   register int place = placeInSet(c);
1651         register int mask  = maskInSet(c);
1652         if (marks[place]&mask)
1653             return;
1654         else {
1655             marks[place] |= mask;
1656             recordMark();
1657         }
1658     }
1659
1660     if (isGenPair(fst(c))) {
1661         fst(c) = markCell(fst(c));
1662         goto ma;
1663     }
1664     else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1665         goto ma;
1666     return;
1667 }
1668
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 */
1673     if (isGenPair(n)) {
1674         recordStackRoot();
1675         markCell(n); 
1676     }
1677 }
1678
1679 Void garbageCollect()     {             /* Run garbage collector ...       */
1680     Bool breakStat = breakOn(FALSE);    /* disable break checking          */
1681     Int i,j;
1682     register Int mask;
1683     register Int place;
1684     Int      recovered;
1685
1686     jmp_buf  regs;                      /* save registers on stack         */
1687     setjmp(regs);
1688
1689     gcStarted();
1690     for (i=0; i<marksSize; ++i)         /* initialise mark set to empty    */
1691         marks[i] = 0;
1692
1693     everybody(MARK);                    /* Mark all components of system   */
1694
1695     gcScanning();                       /* scan mark set                   */
1696     mask      = 1;
1697     place     = 0;
1698     recovered = 0;
1699     j         = 0;
1700
1701     freeList = NIL;
1702     for (i=1; i<=heapSize; i++) {
1703         if ((marks[place] & mask) == 0) {
1704             snd(-i)  = freeList;
1705             fst(-i)  = FREECELL;
1706             freeList = -i;
1707             recovered++;
1708         }
1709         mask <<= 1;
1710         if (++j == bitsPerWord) {
1711             place++;
1712             mask = 1;
1713             j    = 0;
1714         }
1715     }
1716
1717     gcRecovered(recovered);
1718     breakOn(breakStat);                 /* restore break trapping if nec.  */
1719
1720     everybody(GCDONE);
1721
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"
1725         EEND;
1726     }
1727     cellsRecovered = recovered;
1728 }
1729
1730 /* --------------------------------------------------------------------------
1731  * Code for saving last expression entered:
1732  *
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
1736  * the text table.
1737  * ------------------------------------------------------------------------*/
1738
1739 static Cell lastExprSaved;              /* last expression to be saved     */
1740
1741 Void setLastExpr(e)                     /* save expression for later recall*/
1742 Cell e; {
1743     lastExprSaved = NIL;                /* in case attempt to save fails   */
1744     savedText     = NUM_TEXT;
1745     lastExprSaved = lowLevelLastIn(e);
1746 }
1747
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 */
1753                 case VARIDCELL :
1754                 case VAROPCELL :
1755                 case DICTVAR   :
1756                 case CONIDCELL :
1757                 case CONOPCELL :
1758                 case STRCELL   : return pair(fst(c),saveText(textOf(c)));
1759                 default        : return pair(fst(c),snd(c));
1760             }
1761         else
1762             return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
1763     }
1764 #if TREX
1765     else if (isExt(c))
1766         return pair(EXTCOPY,saveText(extText(c)));
1767 #endif
1768     else
1769         return c;
1770 }
1771
1772 Cell getLastExpr() {                    /* recover previously saved expr   */
1773     return lowLevelLastOut(lastExprSaved);
1774 }
1775
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              */
1780             switch (fst(c)) {
1781                 case VARIDCELL :
1782                 case VAROPCELL :
1783                 case DICTVAR   :
1784                 case CONIDCELL :
1785                 case CONOPCELL :
1786                 case STRCELL   : return pair(fst(c),
1787                                              findText(text+intValOf(c)));
1788 #if TREX
1789                 case EXTCOPY   : return mkExt(findText(text+intValOf(c)));
1790 #endif
1791                 default        : return pair(fst(c),snd(c));
1792             }
1793         else
1794             return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
1795     }
1796     else
1797         return c;
1798 }
1799
1800 /* --------------------------------------------------------------------------
1801  * Miscellaneous operations on heap cells:
1802  * ------------------------------------------------------------------------*/
1803
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 */
1807
1808 Cell whatIs(c)                         /* identify type of cell            */
1809 register Cell c; {
1810     if (isPair(c)) {
1811         register Cell fstc = fst(c);
1812         return isTag(fstc) ? fstc : AP;
1813     }
1814     if (c<TUPMIN)    return c;
1815     if (c>=INTMIN)   return INTCELL;
1816
1817     if (c>=NAMEMIN){if (c>=CLASSMIN)   {if (c>=CHARMIN) return CHARCELL;
1818                                         else            return CLASS;}
1819                     else                if (c>=INSTMIN) return INSTANCE;
1820                                         else            return NAME;}
1821     else            if (c>=MODMIN)     {if (c>=TYCMIN)  return TYCON;
1822                                         else            return MODULE;}
1823                     else                if (c>=OFFMIN)  return OFFSET;
1824 #if TREX
1825                                         else            return (c>=EXTMIN) ?
1826                                                                 EXT : TUPLE;
1827 #else
1828                                         else            return TUPLE;
1829 #endif
1830
1831 /*  if (isPair(c)) {
1832         register Cell fstc = fst(c);
1833         return isTag(fstc) ? fstc : AP;
1834     }
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;
1843 #if TREX
1844     if (c>=EXTMIN)   return EXT;
1845 #endif
1846     if (c>=TUPMIN)   return TUPLE;
1847     return c;*/
1848 }
1849
1850 #if DEBUG_PRINTER
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
1854  * its type.
1855  */
1856 Void print Args((Cell, Int));
1857 Void print(c, depth)
1858 Cell c;
1859 Int  depth; {
1860     if (0 == depth) {
1861         Printf("...");
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);
1866 #endif
1867     } else {
1868         Int tag = whatIs(c);
1869         switch (tag) {
1870         case AP: 
1871                 Putchar('(');
1872                 print(fst(c), depth-1);
1873                 Putchar(',');
1874                 print(snd(c), depth-1);
1875                 Putchar(')');
1876                 break;
1877         case FREECELL:
1878                 Printf("free(%d)", c);
1879                 break;
1880         case INTCELL:
1881                 Printf("int(%d)", intOf(c));
1882                 break;
1883         case BIGCELL:
1884                 Printf("bignum(%s)", bignumToString(c));
1885                 break;
1886         case CHARCELL:
1887                 Printf("char('%c')", charOf(c));
1888                 break;
1889         case PTRCELL: 
1890                 Printf("ptr(%p)",ptrOf(c));
1891                 break;
1892         case CLASS:
1893                 Printf("class(%d)", c-CLASSMIN);
1894                 if (CLASSMIN <= c && c < classHw) {
1895                     Printf("=\"%s\"", textToStr(cclass(c).text));
1896                 }
1897                 break;
1898         case INSTANCE:
1899                 Printf("instance(%d)", c - INSTMIN);
1900                 break;
1901         case NAME:
1902                 Printf("name(%d)", c-NAMEMIN);
1903                 if (NAMEMIN <= c && c < nameHw) {
1904                     Printf("=\"%s\"", textToStr(name(c).text));
1905                 }
1906                 break;
1907         case TYCON:
1908                 Printf("tycon(%d)", c-TYCMIN);
1909                 if (TYCMIN <= c && c < tyconHw)
1910                     Printf("=\"%s\"", textToStr(tycon(c).text));
1911                 break;
1912         case MODULE:
1913                 Printf("module(%d)", c - MODMIN);
1914                 break;
1915         case OFFSET:
1916                 Printf("Offset %d", offsetOf(c));
1917                 break;
1918         case TUPLE:
1919                 Printf("Tuple %d", tupleOf(c));
1920                 break;
1921         case POLYTYPE:
1922                 Printf("Polytype");
1923                 print(snd(c),depth-1);
1924                 break;
1925         case QUAL:
1926                 Printf("Qualtype");
1927                 print(snd(c),depth-1);
1928                 break;
1929         case RANK2:
1930                 Printf("Rank2(");
1931                 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
1932                     Printf("%d ", intOf(fst(snd(c))));
1933                     print(snd(snd(c)),depth-1);
1934                 } else {
1935                     print(snd(c),depth-1);
1936                 }
1937                 Printf(")");
1938                 break;
1939         case NIL:
1940                 Printf("NIL");
1941                 break;
1942         case WILDCARD:
1943                 Printf("_");
1944                 break;
1945         case STAR:
1946                 Printf("STAR");
1947                 break;
1948         case DOTDOT:
1949                 Printf("DOTDOT");
1950                 break;
1951         case DICTVAR:
1952                 Printf("{dict %d}",textOf(c));
1953                 break;
1954         case VARIDCELL:
1955         case VAROPCELL:
1956         case CONIDCELL:
1957         case CONOPCELL:
1958                 Printf("{id %s}",textToStr(textOf(c)));
1959                 break;
1960 #if IPARAM
1961           case IPCELL :
1962               Printf("{ip %s}",textToStr(textOf(c)));
1963               break;
1964           case IPVAR :
1965               Printf("?%s",textToStr(textOf(c)));
1966               break;
1967 #endif
1968         case QUALIDENT:
1969                 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
1970                 break;
1971         case LETREC:
1972                 Printf("LetRec(");
1973                 print(fst(snd(c)),depth-1);
1974                 Putchar(',');
1975                 print(snd(snd(c)),depth-1);
1976                 Putchar(')');
1977                 break;
1978         case LAMBDA:
1979                 Printf("Lambda(");
1980                 print(snd(c),depth-1);
1981                 Putchar(')');
1982                 break;
1983         case FINLIST:
1984                 Printf("FinList(");
1985                 print(snd(c),depth-1);
1986                 Putchar(')');
1987                 break;
1988         case COMP:
1989                 Printf("Comp(");
1990                 print(fst(snd(c)),depth-1);
1991                 Putchar(',');
1992                 print(snd(snd(c)),depth-1);
1993                 Putchar(')');
1994                 break;
1995         case ASPAT:
1996                 Printf("AsPat(");
1997                 print(fst(snd(c)),depth-1);
1998                 Putchar(',');
1999                 print(snd(snd(c)),depth-1);
2000                 Putchar(')');
2001                 break;
2002         case FROMQUAL:
2003                 Printf("FromQual(");
2004                 print(fst(snd(c)),depth-1);
2005                 Putchar(',');
2006                 print(snd(snd(c)),depth-1);
2007                 Putchar(')');
2008                 break;
2009         case STGVAR:
2010                 Printf("StgVar%d=",-c);
2011                 print(snd(c), depth-1);
2012                 break;
2013         case STGAPP:
2014                 Printf("StgApp(");
2015                 print(fst(snd(c)),depth-1);
2016                 Putchar(',');
2017                 print(snd(snd(c)),depth-1);
2018                 Putchar(')');
2019                 break;
2020         case STGPRIM:
2021                 Printf("StgPrim(");
2022                 print(fst(snd(c)),depth-1);
2023                 Putchar(',');
2024                 print(snd(snd(c)),depth-1);
2025                 Putchar(')');
2026                 break;
2027         case STGCON:
2028                 Printf("StgCon(");
2029                 print(fst(snd(c)),depth-1);
2030                 Putchar(',');
2031                 print(snd(snd(c)),depth-1);
2032                 Putchar(')');
2033                 break;
2034         case PRIMCASE:
2035                 Printf("PrimCase(");
2036                 print(fst(snd(c)),depth-1);
2037                 Putchar(',');
2038                 print(snd(snd(c)),depth-1);
2039                 Putchar(')');
2040                 break;
2041         case DICTAP:
2042                 Printf("(DICTAP,");
2043                 print(snd(c),depth-1);
2044                 Putchar(')');
2045                 break;
2046         case UNBOXEDTUP:
2047                 Printf("(UNBOXEDTUP,");
2048                 print(snd(c),depth-1);
2049                 Putchar(')');
2050                 break;
2051         case BANG:
2052                 Printf("(BANG,");
2053                 print(snd(c),depth-1);
2054                 Putchar(')');
2055                 break;
2056         default:
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);
2062                     Putchar(')');
2063                     break;
2064                 } else if (c == tag) {
2065                     Printf("Tag(%d)", c);
2066                 } else {
2067                     Printf("Tag(%d)=%d", c, tag);
2068                 }
2069                 break;
2070         }
2071     }
2072     FlushStdout();
2073 }
2074 #endif
2075
2076 Bool isVar(c)                           /* is cell a VARIDCELL/VAROPCELL ? */
2077 Cell c; {                               /* also recognises DICTVAR cells   */
2078     return isPair(c) &&
2079                (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2080 }
2081
2082 Bool isCon(c)                          /* is cell a CONIDCELL/CONOPCELL ?  */
2083 Cell c; {
2084     return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2085 }
2086
2087 Bool isQVar(c)                        /* is cell a [un]qualified varop/id? */
2088 Cell c; {
2089     if (!isPair(c)) return FALSE;
2090     switch (fst(c)) {
2091         case VARIDCELL  :
2092         case VAROPCELL  : return TRUE;
2093
2094         case QUALIDENT  : return isVar(snd(snd(c)));
2095
2096         default         : return FALSE;
2097     }
2098 }
2099
2100 Bool isQCon(c)                         /*is cell a [un]qualified conop/id? */
2101 Cell c; {
2102     if (!isPair(c)) return FALSE;
2103     switch (fst(c)) {
2104         case CONIDCELL  :
2105         case CONOPCELL  : return TRUE;
2106
2107         case QUALIDENT  : return isCon(snd(snd(c)));
2108
2109         default         : return FALSE;
2110     }
2111 }
2112
2113 Bool isQualIdent(c)                    /* is cell a qualified identifier?  */
2114 Cell c; {
2115     return isPair(c) && (fst(c)==QUALIDENT);
2116 }
2117
2118 Bool isIdent(c)                        /* is cell an identifier?           */
2119 Cell c; {
2120     if (!isPair(c)) return FALSE;
2121     switch (fst(c)) {
2122         case VARIDCELL  :
2123         case VAROPCELL  :
2124         case CONIDCELL  :
2125         case CONOPCELL  : return TRUE;
2126
2127         case QUALIDENT  : return TRUE;
2128
2129         default         : return FALSE;
2130     }
2131 }
2132
2133 Bool isInt(c)                          /* cell holds integer value?        */
2134 Cell c; {
2135     return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2136 }
2137
2138 Int intOf(c)                           /* find integer value of cell?      */
2139 Cell c; {
2140   if (!isInt(c)) {
2141     assert(isInt(c)); }
2142     return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
2143 }
2144
2145 Cell mkInt(n)                          /* make cell representing integer   */
2146 Int n; {
2147     return (MINSMALLINT <= n && n <= MAXSMALLINT)
2148            ? INTZERO+n
2149            : pair(INTCELL,n);
2150 }
2151
2152 #if SIZEOF_INTP == SIZEOF_INT
2153 typedef union {Int i; Ptr p;} IntOrPtr;
2154 Cell mkPtr(p)
2155 Ptr p;
2156 {
2157     IntOrPtr x;
2158     x.p = p;
2159     return pair(PTRCELL,x.i);
2160 }
2161
2162 Ptr ptrOf(c)
2163 Cell c;
2164 {
2165     IntOrPtr x;
2166     assert(fst(c) == PTRCELL);
2167     x.i = snd(c);
2168     return x.p;
2169 }
2170 Cell mkCPtr(p)
2171 Ptr p;
2172 {
2173     IntOrPtr x;
2174     x.p = p;
2175     return pair(CPTRCELL,x.i);
2176 }
2177
2178 Ptr cptrOf(c)
2179 Cell c;
2180 {
2181     IntOrPtr x;
2182     assert(fst(c) == CPTRCELL);
2183     x.i = snd(c);
2184     return x.p;
2185 }
2186 #elif SIZEOF_INTP == 2*SIZEOF_INT
2187 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2188 Cell mkPtr(p)
2189 Ptr p;
2190 {
2191     IntOrPtr x;
2192     x.p = p;
2193     return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2194 }
2195
2196 Ptr ptrOf(c)
2197 Cell c;
2198 {
2199     IntOrPtr x;
2200     assert(fst(c) == PTRCELL);
2201     x.i.i1 = intOf(fst(snd(c)));
2202     x.i.i2 = intOf(snd(snd(c)));
2203     return x.p;
2204 }
2205 #else
2206 #warning "type Addr not supported on this architecture - don't use it"
2207 Cell mkPtr(p)
2208 Ptr p;
2209 {
2210     ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
2211     EEND;
2212 }
2213
2214 Ptr ptrOf(c)
2215 Cell c;
2216 {
2217     ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
2218     EEND;
2219 }
2220 #endif
2221
2222 String stringNegate( s )
2223 String s;
2224 {
2225     if (s[0] == '-') {
2226         return &s[1];
2227     } else {
2228         static char t[100];
2229         t[0] = '-';
2230         strcpy(&t[1],s);  /* ToDo: use strncpy instead */
2231         return t;
2232     }
2233 }
2234
2235 /* --------------------------------------------------------------------------
2236  * List operations:
2237  * ------------------------------------------------------------------------*/
2238
2239 Int length(xs)                         /* calculate length of list xs      */
2240 List xs; {
2241     Int n = 0;
2242     for (; nonNull(xs); ++n)
2243         xs = tl(xs);
2244     return n;
2245 }
2246
2247 List appendOnto(xs,ys)                 /* Destructively prepend xs onto    */
2248 List xs, ys; {                         /* ys by modifying xs ...           */
2249     if (isNull(xs))
2250         return ys;
2251     else {
2252         List zs = xs;
2253         while (nonNull(tl(zs)))
2254             zs = tl(zs);
2255         tl(zs) = ys;
2256         return xs;
2257     }
2258 }
2259
2260 List dupOnto(xs,ys)      /* non-destructively prepend xs backwards onto ys */
2261 List xs; 
2262 List ys; {
2263     for (; nonNull(xs); xs=tl(xs))
2264         ys = cons(hd(xs),ys);
2265     return ys;
2266 }
2267
2268 List dupListOnto(xs,ys)              /* Duplicate spine of list xs onto ys */
2269 List xs;
2270 List ys; {
2271     return revOnto(dupOnto(xs,NIL),ys);
2272 }
2273
2274 List dupList(xs)                       /* Duplicate spine of list xs       */
2275 List xs; {
2276     List ys = NIL;
2277     for (; nonNull(xs); xs=tl(xs))
2278         ys = cons(hd(xs),ys);
2279     return rev(ys);
2280 }
2281
2282 List revOnto(xs,ys)                    /* Destructively reverse elements of*/
2283 List xs, ys; {                         /* list xs onto list ys...          */
2284     Cell zs;
2285
2286     while (nonNull(xs)) {
2287         zs     = tl(xs);
2288         tl(xs) = ys;
2289         ys     = xs;
2290         xs     = zs;
2291     }
2292     return ys;
2293 }
2294
2295 Cell varIsMember(t,xs)                 /* Test if variable is a member of  */
2296 Text t;                                /* given list of variables          */
2297 List xs; {
2298     for (; nonNull(xs); xs=tl(xs))
2299         if (t==textOf(hd(xs)))
2300             return hd(xs);
2301     return NIL;
2302 }
2303
2304 Name nameIsMember(t,ns)                 /* Test if name with text t is a   */
2305 Text t;                                 /* member of list of names xs      */
2306 List ns; {
2307     for (; nonNull(ns); ns=tl(ns))
2308         if (t==name(hd(ns)).text)
2309             return hd(ns);
2310     return NIL;
2311 }
2312
2313 Cell intIsMember(n,xs)                 /* Test if integer n is member of   */
2314 Int  n;                                /* given list of integers           */
2315 List xs; {
2316     for (; nonNull(xs); xs=tl(xs))
2317         if (n==intOf(hd(xs)))
2318             return hd(xs);
2319     return NIL;
2320 }
2321
2322 Cell cellIsMember(x,xs)                /* Test for membership of specific  */
2323 Cell x;                                /* cell x in list xs                */
2324 List xs; {
2325     for (; nonNull(xs); xs=tl(xs))
2326         if (x==hd(xs))
2327             return hd(xs);
2328     return NIL;
2329 }
2330
2331 Cell cellAssoc(c,xs)                   /* Lookup cell in association list  */
2332 Cell c;         
2333 List xs; {
2334     for (; nonNull(xs); xs=tl(xs))
2335         if (c==fst(hd(xs)))
2336             return hd(xs);
2337     return NIL;
2338 }
2339
2340 Cell cellRevAssoc(c,xs)                /* Lookup cell in range of          */
2341 Cell c;                                /* association lists                */
2342 List xs; {
2343     for (; nonNull(xs); xs=tl(xs))
2344         if (c==snd(hd(xs)))
2345             return hd(xs);
2346     return NIL;
2347 }
2348
2349 List replicate(n,x)                     /* create list of n copies of x    */
2350 Int n;
2351 Cell x; {
2352     List xs=NIL;
2353     while (0<n--)
2354         xs = cons(x,xs);
2355     return xs;
2356 }
2357
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'   */
2361
2362     while (nonNull(from)) {
2363         List next = tl(from);
2364         if (!cellIsMember(hd(from),take)) {
2365             tl(from) = result;
2366             result   = from;
2367         }
2368         from = next;
2369     }
2370     return rev(result);
2371 }
2372
2373 List deleteCell(xs, y)                  /* copy xs deleting pointers to y  */
2374 List xs;
2375 Cell y; {
2376     List result = NIL; 
2377     for(;nonNull(xs);xs=tl(xs)) {
2378         Cell x = hd(xs);
2379         if (x != y) {
2380             result=cons(x,result);
2381         }
2382     }
2383     return rev(result);
2384 }
2385
2386 List take(n,xs)                         /* destructively truncate list to  */
2387 Int  n;                                 /* specified length                */
2388 List xs; {
2389     List ys = xs;
2390
2391     if (n==0)
2392         return NIL;
2393     while (1<n-- && nonNull(xs))
2394         xs = tl(xs);
2395     if (nonNull(xs))
2396         tl(xs) = NIL;
2397     return ys;
2398 }
2399
2400 List splitAt(n,xs)                      /* drop n things from front of list*/
2401 Int  n;       
2402 List xs; {
2403     for(; n>0; --n) {
2404         xs = tl(xs);
2405     }
2406     return xs;
2407 }
2408
2409 Cell nth(n,xs)                          /* extract n'th element of list    */
2410 Int  n;
2411 List xs; {
2412     for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2413     }
2414     if (isNull(xs))
2415         internal("nth");
2416     return hd(xs);
2417 }
2418
2419 List removeCell(x,xs)                   /* destructively remove cell from  */
2420 Cell x;                                 /* list                            */
2421 List xs; {
2422     if (nonNull(xs)) {
2423         if (hd(xs)==x)
2424             return tl(xs);              /* element at front of list        */
2425         else {
2426             List prev = xs;
2427             List curr = tl(xs);
2428             for (; nonNull(curr); prev=curr, curr=tl(prev))
2429                 if (hd(curr)==x) {
2430                     tl(prev) = tl(curr);
2431                     return xs;          /* element in middle of list       */
2432                 }
2433         }
2434     }
2435     return xs;                          /* here if element not found       */
2436 }
2437
2438 List nubList(xs)                        /* nuke dups in list               */
2439 List xs; {                              /* non destructive                 */
2440    List outs = NIL;
2441    for (; nonNull(xs); xs=tl(xs))
2442       if (isNull(cellIsMember(hd(xs),outs)))
2443          outs = cons(hd(xs),outs);
2444    outs = rev(outs);
2445    return outs;
2446 }
2447
2448 /* --------------------------------------------------------------------------
2449  * Operations on applications:
2450  * ------------------------------------------------------------------------*/
2451
2452 Int argCount;                          /* number of args in application    */
2453
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))
2457         argCount++;
2458     return e;
2459 }
2460
2461 List getArgs(e)                        /* get list of arguments in function*/
2462 Cell e; {                              /* application:                     */
2463     List as;                           /* getArgs(f e1 .. en) = [e1,..,en] */
2464
2465     for (as=NIL; isAp(e); e=fun(e))
2466         as = cons(arg(e),as);
2467     return as;
2468 }
2469
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--)
2474         e = fun(e);
2475     return arg(e);
2476 }
2477
2478 Int numArgs(e)                         /* find number of arguments to expr */
2479 Cell e; {
2480     Int n;
2481     for (n=0; isAp(e); e=fun(e))
2482         n++;
2483     return n;
2484 }
2485
2486 Cell applyToArgs(f,args)               /* destructively apply list of args */
2487 Cell f;                                /* to function f                    */
2488 List args; {
2489     while (nonNull(args)) {
2490         Cell temp = tl(args);
2491         tl(args)  = hd(args);
2492         hd(args)  = f;
2493         f         = args;
2494         args      = temp;
2495     }
2496     return f;
2497 }
2498
2499
2500 /* --------------------------------------------------------------------------
2501  * plugin support
2502  * ------------------------------------------------------------------------*/
2503
2504 /*---------------------------------------------------------------------------
2505  * GreenCard entry points
2506  *
2507  * GreenCard generated code accesses Hugs data structures and functions 
2508  * (only) via these functions (which are stored in the virtual function
2509  * table hugsAPI1.
2510  *-------------------------------------------------------------------------*/
2511
2512 #if GREENCARD
2513
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));
2522
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); }
2531
2532 HugsAPI1* hugsAPI1() {
2533     static HugsAPI1 api;
2534     static Bool initialised = FALSE;
2535     if (!initialised) {
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;
2551         api.pair            = pair;
2552         api.mkMallocPtr     = mkMallocPtr;
2553         api.derefMallocPtr  = derefMallocPtr;
2554         api.mkStablePtr     = mkStablePtr;
2555         api.derefStablePtr  = derefStablePtr;
2556         api.freeStablePtr   = freeStablePtr;
2557         api.eval            = eval;
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;
2570         api.Fst             = Fst;
2571         api.Snd             = Snd;
2572         api.cellStack       = cellStack;
2573         api.sp              = &sp;
2574     }
2575     return &api;
2576 }
2577
2578 #endif /* GREENCARD */
2579
2580
2581 /* --------------------------------------------------------------------------
2582  * storage control:
2583  * ------------------------------------------------------------------------*/
2584
2585 #if DYN_TABLES
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);
2590     if (tab==0) {
2591         ERRMSG(0) "Cannot allocate run-time tables"
2592         EEND;
2593     }
2594     return tab;
2595 }
2596 #define TABALLOC(v,t,n)                 v=(t far*)safeFarCalloc(n,sizeof(t));
2597 #else
2598 #define TABALLOC(v,t,n)
2599 #endif
2600
2601 Void storage(what)
2602 Int what; {
2603     Int i;
2604
2605     switch (what) {
2606         case RESET   : clearStack();
2607
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.
2612                         */
2613                        heapTopFst = heapFst + heapSize;
2614                        heapTopSnd = heapSnd + heapSize;
2615                        consGC = TRUE;
2616                        lsave  = NIL;
2617                        rsave  = NIL;
2618                        if (isNull(lastExprSaved))
2619                            savedText = NUM_TEXT;
2620                        break;
2621
2622         case MARK    : 
2623                        start();
2624                        for (i=NAMEMIN; i<nameHw; ++i) {
2625                            mark(name(i).parent);
2626                            mark(name(i).defn);
2627                            mark(name(i).stgVar);
2628                            mark(name(i).type);
2629                         }
2630                        end("Names", nameHw-NAMEMIN);
2631
2632                        start();
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);
2639                        }
2640                        end("Modules", moduleHw-MODMIN);
2641
2642                        start();
2643                        for (i=TYCMIN; i<tyconHw; ++i) {
2644                            mark(tycon(i).defn);
2645                            mark(tycon(i).kind);
2646                            mark(tycon(i).what);
2647                        }
2648                        end("Type constructors", tyconHw-TYCMIN);
2649
2650                        start();
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);
2661                        }
2662                        mark(classes);
2663                        end("Classes", classHw-CLASSMIN);
2664
2665                        start();
2666                        for (i=INSTMIN; i<instHw; ++i) {
2667                            mark(inst(i).head);
2668                            mark(inst(i).kinds);
2669                            mark(inst(i).specifics);
2670                            mark(inst(i).implements);
2671                        }
2672                        end("Instances", instHw-INSTMIN);
2673
2674                        start();
2675                        for (i=0; i<=sp; ++i)
2676                            mark(stack(i));
2677                        end("Stack", sp+1);
2678
2679                        start();
2680                        mark(lastExprSaved);
2681                        mark(lsave);
2682                        mark(rsave);
2683                        end("Last expression", 3);
2684
2685                        if (consGC) {
2686                            start();
2687                            gcCStack();
2688                            end("C stack", stackRoots);
2689                        }
2690
2691                        break;
2692
2693         case INSTALL : heapFst = heapAlloc(heapSize);
2694                        heapSnd = heapAlloc(heapSize);
2695
2696                        if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
2697                            ERRMSG(0) "Cannot allocate heap storage (%d cells)",
2698                                      heapSize
2699                            EEND;
2700                        }
2701
2702                        heapTopFst = heapFst + heapSize;
2703                        heapTopSnd = heapSnd + heapSize;
2704                        for (i=1; i<heapSize; ++i) {
2705                            fst(-i) = FREECELL;
2706                            snd(-i) = -(i+1);
2707                        }
2708                        snd(-heapSize) = NIL;
2709                        freeList  = -1;
2710                        numGcs    = 0;
2711                        consGC    = TRUE;
2712                        lsave     = NIL;
2713                        rsave     = NIL;
2714
2715                        marksSize  = bitArraySize(heapSize);
2716                        if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
2717                            ERRMSG(0) "Unable to allocate gc markspace"
2718                            EEND;
2719                        }
2720
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)
2729 #if TREX
2730                        TABALLOC(tabExt,    Text,             NUM_EXT)
2731 #endif
2732                        clearStack();
2733
2734                        textHw        = 0;
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;
2741
2742
2743                        moduleHw = MODMIN;
2744
2745                        tyconHw  = TYCMIN;
2746                        for (i=0; i<TYCONHSZ; ++i)
2747                            tyconHash[i] = NIL;
2748 #if TREX
2749                        extHw    = EXTMIN;
2750 #endif
2751
2752                        nameHw   = NAMEMIN;
2753                        for (i=0; i<NAMEHSZ; ++i)
2754                            nameHash[i] = NIL;
2755
2756                        classHw  = CLASSMIN;
2757
2758                        instHw   = INSTMIN;
2759
2760 #if USE_DICTHW
2761                        dictHw   = 0;
2762 #endif
2763
2764                        tabInst  = (struct strInst far *)
2765                                     farCalloc(NUM_INSTS,sizeof(struct strInst));
2766
2767                        if (tabInst==0) {
2768                            ERRMSG(0) "Cannot allocate instance tables"
2769                            EEND;
2770                        }
2771
2772                        scriptHw = 0;
2773
2774                        break;
2775     }
2776 }
2777
2778 /*-------------------------------------------------------------------------*/