[project @ 2000-03-10 20:03:36 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.50 $
13  * $Date: 2000/03/10 20:03:36 $
14  * ------------------------------------------------------------------------*/
15
16 #include "prelude.h"
17 #include "storage.h"
18 #include "connect.h"
19 #include "errors.h"
20 #include "object.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       if (*s == '(') {
356          int tup = 0;
357          char num[12];
358          s++;
359          while (*s && *s==',') { s++; tup++; };
360          if (*s != ')') internal("enZcodeThenFindText: invalid tuple type");
361          s++;
362          p[n++] = 'Z';
363          sprintf(num,"%d",tup);
364          p[n] = 0; strcat ( &(p[n]), num ); n += strlen(num);
365          p[n++] = 'T';
366          continue;         
367       }
368       switch (*s++) {
369          case '(': p[n++] = 'Z'; p[n++] = 'L'; break;
370          case ')': p[n++] = 'Z'; p[n++] = 'R'; 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++] = 'C'; break;
374          case 'Z': p[n++] = 'Z'; p[n++] = 'Z'; break;
375          case 'z': p[n++] = 'z'; p[n++] = 'z'; break;
376          case '&': p[n++] = 'z'; p[n++] = 'a'; break;
377          case '|': p[n++] = 'z'; p[n++] = 'b'; break;
378          case '$': p[n++] = 'z'; p[n++] = 'd'; break;
379          case '=': p[n++] = 'z'; p[n++] = 'e'; break;
380          case '>': p[n++] = 'z'; p[n++] = 'g'; break;
381          case '#': p[n++] = 'z'; p[n++] = 'h'; break;
382          case '.': p[n++] = 'z'; p[n++] = 'i'; break;
383          case '<': p[n++] = 'z'; p[n++] = 'l'; break;
384          case '-': p[n++] = 'z'; p[n++] = 'm'; break;
385          case '!': p[n++] = 'z'; p[n++] = 'n'; break;
386          case '+': p[n++] = 'z'; p[n++] = 'p'; break;
387          case '\'': p[n++] = 'z'; p[n++] = 'q'; break;
388          case '\\': p[n++] = 'z'; p[n++] = 'r'; break;
389          case '/': p[n++] = 'z'; p[n++] = 's'; break;
390          case '*': p[n++] = 'z'; p[n++] = 't'; break;
391          case '^': p[n++] = 'z'; p[n++] = 'u'; break;
392          case '%': p[n++] = 'z'; p[n++] = 'v'; break;
393          default: s--; p[n++] = 'z'; p[n++] = 'x';
394                        p[n++] = toHex[(int)(*s)/16];
395                        p[n++] = toHex[(int)(*s)%16];
396                   s++; break;
397       }
398    }
399    p[n] = 0;
400    t = findText(p);
401    free(p);
402    return t;
403 }
404
405
406 Text textOf ( Cell c )
407 {
408    Bool ok = 
409           (whatIs(c)==VARIDCELL
410            || whatIs(c)==CONIDCELL
411            || whatIs(c)==VAROPCELL
412            || whatIs(c)==CONOPCELL
413            || whatIs(c)==STRCELL
414            || whatIs(c)==DICTVAR
415            || whatIs(c)==IPCELL
416            || whatIs(c)==IPVAR
417           );
418    if (!ok) {
419       fprintf(stderr, "\ntextOf: bad tag %d\n",whatIs(c) );
420       internal("textOf: bad tag");
421    }
422    return snd(c);
423 }
424
425 /* --------------------------------------------------------------------------
426  * Ext storage:
427  *
428  * Currently, the only attributes that we store for each Ext value is the
429  * corresponding Text label.  At some later stage, we may decide to cache
430  * types, predicates, etc. here as a space saving gesture.  Given that Text
431  * comparison is cheap, and that this is an experimental implementation, we
432  * will use a straightforward linear search to locate Ext values from their
433  * corresponding Text labels; a hashing scheme can be introduced later if
434  * this turns out to be a problem.
435  * ------------------------------------------------------------------------*/
436
437 #if TREX
438 Text  DEFTABLE(tabExt,NUM_EXT);         /* Storage for Ext names           */
439 Ext   extHw;
440
441 Ext mkExt(t)                            /* Allocate or find an Ext value   */
442 Text t; {
443     Ext e = EXTMIN;
444     for (; e<extHw; e++)
445         if (t==extText(e))
446             return e;
447     if (extHw-EXTMIN >= NUM_EXT) {
448         ERRMSG(0) "Ext storage space exhausted"
449         EEND;
450     }
451     extText(extHw) = t;
452     return extHw++;
453 }
454 #endif
455
456 /* --------------------------------------------------------------------------
457  * Tycon storage:
458  *
459  * A Tycon represents a user defined type constructor.  Tycons are indexed
460  * by Text values ... a very simple hash function is used to improve lookup
461  * times.  Tycon entries with the same hash code are chained together, with
462  * the most recent entry at the front of the list.
463  * ------------------------------------------------------------------------*/
464
465 #define TYCONHSZ 256                            /* Size of Tycon hash table*/
466 #define tHash(x) ((x)%TYCONHSZ)                 /* Tycon hash function     */
467 static  Tycon    tyconHw;                       /* next unused Tycon       */
468 static  Tycon    DEFTABLE(tyconHash,TYCONHSZ);  /* Hash table storage      */
469 struct  strTycon DEFTABLE(tabTycon,NUM_TYCON);  /* Tycon storage           */
470
471 Tycon newTycon(t)                       /* add new tycon to tycon table    */
472 Text t; {
473     Int h = tHash(t);
474     if (tyconHw-TYCMIN >= NUM_TYCON) {
475         ERRMSG(0) "Type constructor storage space exhausted"
476         EEND;
477     }
478     tycon(tyconHw).text          = t;   /* clear new tycon record          */
479     tycon(tyconHw).kind          = NIL;
480     tycon(tyconHw).defn          = NIL;
481     tycon(tyconHw).what          = NIL;
482     tycon(tyconHw).conToTag      = NIL;
483     tycon(tyconHw).tagToCon      = NIL;
484     tycon(tyconHw).tuple         = -1;
485     tycon(tyconHw).mod           = currentModule;
486     tycon(tyconHw).itbl          = NULL;
487     module(currentModule).tycons = cons(tyconHw,module(currentModule).tycons);
488     tycon(tyconHw).nextTyconHash = tyconHash[h];
489     tyconHash[h]                 = tyconHw;
490
491     return tyconHw++;
492 }
493
494 Tycon findTycon(t)                      /* locate Tycon in tycon table     */
495 Text t; {
496     Tycon tc = tyconHash[tHash(t)];
497
498     while (nonNull(tc) && tycon(tc).text!=t)
499         tc = tycon(tc).nextTyconHash;
500     return tc;
501 }
502
503 Tycon addTycon(tc)  /* Insert Tycon in tycon table - if no clash is caused */
504 Tycon tc; {
505     Tycon oldtc; 
506     assert(whatIs(tc)==TYCON || whatIs(tc)==TUPLE);
507     oldtc = findTycon(tycon(tc).text);
508     if (isNull(oldtc)) {
509         hashTycon(tc);
510         module(currentModule).tycons=cons(tc,module(currentModule).tycons);
511         return tc;
512     } else
513         return oldtc;
514 }
515
516 static Void local hashTycon(tc)         /* Insert Tycon into hash table    */
517 Tycon tc; {
518   if (!(isTycon(tc) || isTuple(tc))) {
519     printf("\nbad stuff: " ); print(tc,10); printf("\n");
520       assert(isTycon(tc) || isTuple(tc));
521   }
522    if (1) {
523      Text  t = tycon(tc).text;
524      Int   h = tHash(t);
525      tycon(tc).nextTyconHash = tyconHash[h];
526      tyconHash[h]            = tc;
527    }
528 }
529
530 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
531 Cell id; {
532     if (!isPair(id)) internal("findQualTycon");
533     switch (fst(id)) {
534         case CONIDCELL :
535         case CONOPCELL :
536             return findTycon(textOf(id));
537         case QUALIDENT : {
538             Text   t  = qtextOf(id);
539             Module m  = findQualifier(qmodOf(id));
540             List   es = NIL;
541             if (isNull(m)) return NIL;
542             for(es=module(m).exports; nonNull(es); es=tl(es)) {
543                 Cell e = hd(es);
544                 if (isPair(e) && isTycon(fst(e)) && tycon(fst(e)).text==t) 
545                     return fst(e);
546             }
547             return NIL;
548         }
549         default : internal("findQualTycon2");
550     }
551     return NIL; /* NOTREACHED */
552 }
553
554 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr   */
555 Text t;
556 Kind kind;
557 Int  ar;
558 Cell what;
559 Cell defn; {
560     Tycon tc        = newTycon(t);
561     tycon(tc).line  = 0;
562     tycon(tc).kind  = kind;
563     tycon(tc).what  = what;
564     tycon(tc).defn  = defn;
565     tycon(tc).arity = ar;
566     return tc;
567 }
568
569 static List local insertTycon(tc,ts)    /* insert tycon tc into sorted list*/
570 Tycon tc;                               /* ts                              */
571 List  ts; {
572     Cell   prev = NIL;
573     Cell   curr = ts;
574     String s    = textToStr(tycon(tc).text);
575
576     while (nonNull(curr) && strCompare(s,textToStr(tycon(hd(curr)).text))>=0) {
577         if (hd(curr)==tc)               /* just in case we get duplicates! */
578             return ts;
579         prev = curr;
580         curr = tl(curr);
581     }
582     if (nonNull(prev)) {
583         tl(prev) = cons(tc,curr);
584         return ts;
585     }
586     else
587         return cons(tc,curr);
588 }
589
590 List addTyconsMatching(pat,ts)          /* Add tycons matching pattern pat */
591 String pat;                             /* to list of Tycons ts            */
592 List   ts; {                            /* Null pattern matches every tycon*/
593     Tycon tc;                           /* (Tycons with NIL kind excluded) */
594     for (tc=TYCMIN; tc<tyconHw; ++tc)
595         if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
596             if (nonNull(tycon(tc).kind))
597                 ts = insertTycon(tc,ts);
598     return ts;
599 }
600
601 Text ghcTupleText_n ( Int n )
602 {
603     Int i;
604     Int x = 0; 
605     char buf[104];
606     if (n < 0 || n >= 100) internal("ghcTupleText_n");
607     if (n == 1) internal("ghcTupleText_n==1");
608     buf[x++] = '(';
609     for (i = 1; i <= n-1; i++) buf[x++] = ',';
610     buf[x++] = ')';
611     buf[x++] = 0;
612     return findText(buf);
613 }
614
615 Text ghcTupleText(tup)
616 Tycon tup; {
617     if (!isTuple(tup)) {
618        assert(isTuple(tup));
619     }
620     return ghcTupleText_n ( tupleOf(tup) );
621 }
622
623
624 Tycon mkTuple ( Int n )
625 {
626    Int i;
627    if (n >= NUM_TUPLES)
628       internal("mkTuple: request for tuple of unsupported size");
629    for (i = TYCMIN; i < tyconHw; i++)
630       if (tycon(i).tuple == n) return i;
631    internal("mkTuple: request for non-existent tuple");
632 }
633
634
635 /* --------------------------------------------------------------------------
636  * Name storage:
637  *
638  * A Name represents a top level binding of a value to an identifier.
639  * Such values may be a constructor function, a member function in a
640  * class, a user-defined or primitive value/function.
641  *
642  * Names are indexed by Text values ... a very simple hash functions speeds
643  * access to the table of Names and Name entries with the same hash value
644  * are chained together, with the most recent entry at the front of the
645  * list.
646  * ------------------------------------------------------------------------*/
647
648 #define NAMEHSZ  256                            /* Size of Name hash table */
649 #define nHash(x) ((x)%NAMEHSZ)                  /* hash fn :: Text->Int    */
650         Name     nameHw;                        /* next unused name        */
651 static  Name     DEFTABLE(nameHash,NAMEHSZ);    /* Hash table storage      */
652 struct  strName  DEFTABLE(tabName,NUM_NAME);    /* Name table storage      */
653
654 Name newName(t,parent)                  /* Add new name to name table      */
655 Text t; 
656 Cell parent; {
657     Int h = nHash(t);
658     if (nameHw-NAMEMIN >= NUM_NAME) {
659         ERRMSG(0) "Name storage space exhausted"
660         EEND;
661     }
662     name(nameHw).text         = t;      /* clear new name record           */
663     name(nameHw).line         = 0;
664     name(nameHw).syntax       = NO_SYNTAX;
665     name(nameHw).parent       = parent;
666     name(nameHw).arity        = 0;
667     name(nameHw).number       = EXECNAME;
668     name(nameHw).defn         = NIL;
669     name(nameHw).stgVar       = NIL;
670     name(nameHw).callconv     = NIL;
671     name(nameHw).type         = NIL;
672     name(nameHw).primop       = 0;
673     name(nameHw).mod          = currentModule;
674     name(nameHw).itbl         = NULL;
675     module(currentModule).names=cons(nameHw,module(currentModule).names);
676     name(nameHw).nextNameHash = nameHash[h];
677     nameHash[h]               = nameHw;
678     return nameHw++;
679 }
680
681 Name findName(t)                        /* Locate name in name table       */
682 Text t; {
683     Name n = nameHash[nHash(t)];
684
685     while (nonNull(n) && name(n).text!=t)
686         n = name(n).nextNameHash;
687     return n;
688 }
689
690 Name addName(nm)                        /* Insert Name in name table - if  */
691 Name nm; {                              /* no clash is caused              */
692     Name oldnm; 
693     assert(whatIs(nm)==NAME);
694     oldnm = findName(name(nm).text);
695     if (isNull(oldnm)) {
696         hashName(nm);
697         module(currentModule).names=cons(nm,module(currentModule).names);
698         return nm;
699     } else
700         return oldnm;
701 }
702
703 static Void local hashName(nm)          /* Insert Name into hash table     */
704 Name nm; {
705     Text t;
706     Int  h;
707     assert(isName(nm));
708     t = name(nm).text;
709     h = nHash(t);
710     name(nm).nextNameHash = nameHash[h];
711     nameHash[h]           = nm;
712 }
713
714 Name findQualName(id)              /* Locate (possibly qualified) name*/
715 Cell id; {                         /* in name table                   */
716     if (!isPair(id))
717         internal("findQualName");
718     switch (fst(id)) {
719         case VARIDCELL :
720         case VAROPCELL :
721         case CONIDCELL :
722         case CONOPCELL :
723             return findName(textOf(id));
724         case QUALIDENT : {
725             Text   t  = qtextOf(id);
726             Module m  = findQualifier(qmodOf(id));
727             List   es = NIL;
728             if (isNull(m)) return NIL;
729             for(es=module(m).exports; nonNull(es); es=tl(es)) {
730                 Cell e = hd(es);
731                 if (isName(e) && name(e).text==t) 
732                     return e;
733                 else if (isPair(e) && DOTDOT==snd(e)) {
734                     List subentities = NIL;
735                     Cell c = fst(e);
736                     if (isTycon(c)
737                         && (tycon(c).what==DATATYPE || tycon(c).what==NEWTYPE))
738                         subentities = tycon(c).defn;
739                     else if (isClass(c))
740                         subentities = cclass(c).members;
741                     for(; nonNull(subentities); subentities=tl(subentities)) {
742                        if (!isName(hd(subentities)))
743                             internal("findQualName3");
744                         if (name(hd(subentities)).text == t)
745                             return hd(subentities);
746                     }
747                 }
748             }
749             return NIL;
750         }
751         default : internal("findQualName2");
752     }
753     return 0; /* NOTREACHED */
754 }
755
756
757 Name nameFromStgVar ( StgVar v )
758 {
759    Int n;
760    for (n = NAMEMIN; n < nameHw; n++)
761       if (name(n).stgVar == v) return n;
762    return NIL;
763 }
764
765 void* getHugs_AsmObject_for ( char* s )
766 {
767    StgVar v;
768    Text   t = findText(s);
769    Name   n = NIL;
770    for (n = NAMEMIN; n < nameHw; n++)
771       if (name(n).text == t) break;
772    if (n == nameHw) {
773       fprintf ( stderr, "can't find `%s' in ...\n", s );
774       internal("getHugs_AsmObject_for(1)");
775    }
776    v = name(n).stgVar;
777    if (!isStgVar(v) || !isPtr(stgVarInfo(v)))
778       internal("getHugs_AsmObject_for(2)");
779    return ptrOf(stgVarInfo(v));
780 }
781
782 /* --------------------------------------------------------------------------
783  * Primitive functions:
784  * ------------------------------------------------------------------------*/
785
786 Module findFakeModule ( Text t )
787 {
788    Module m = findModule(t);
789    if (nonNull(m)) {
790       if (!module(m).fake) internal("findFakeModule");
791    } else {
792       m = newModule(t);
793       module(m).fake = TRUE;
794    }
795    return m;
796 }
797
798
799 Name addWiredInBoxingTycon
800         ( String modNm, String typeNm, String constrNm,
801           Int rep, Kind kind )
802 {
803    Name   n;
804    Tycon  t;
805    Text   modT  = findText(modNm);
806    Text   typeT = findText(typeNm);
807    Text   conT  = findText(constrNm);
808    Module m     = findFakeModule(modT);
809    setCurrModule(m);
810    
811    n = newName(conT,NIL);
812    name(n).arity  = 1;
813    name(n).number = cfunNo(0);
814    name(n).type   = NIL;
815    name(n).primop = (void*)rep;
816
817    t = newTycon(typeT);
818    tycon(t).what = DATATYPE;
819    tycon(t).kind = kind;
820    return n;
821 }
822
823
824 Tycon addTupleTycon ( Int n )
825 {
826    Int    i;
827    Kind   k;
828    Tycon  t;
829    Module m;
830    Name   nm;
831
832    for (i = TYCMIN; i < tyconHw; i++)
833       if (tycon(i).tuple == n) return i;
834
835    if (combined)
836       m = findFakeModule(findText(n==0 ? "PrelBase" : "PrelTup")); else
837       m = findModule(findText("Prelude"));
838
839    setCurrModule(m);
840    k = STAR;
841    for (i = 0; i < n; i++) k = ap(STAR,k);
842    t = newTycon(ghcTupleText_n(n));
843    tycon(t).kind  = k;
844    tycon(t).tuple = n;
845    tycon(t).what  = DATATYPE;
846
847    if (n == 0) {
848       /* maybe we want to do this for all n ? */
849       nm = newName(ghcTupleText_n(n), t);
850       name(nm).type = t;   /* ummm ... for n > 0 */
851    }
852
853    return t;
854 }
855
856
857 Tycon addWiredInEnumTycon ( String modNm, String typeNm, 
858                             List /*of Text*/ constrs )
859 {
860    Int    i;
861    Tycon  t;
862    Text   modT  = findText(modNm);
863    Text   typeT = findText(typeNm);
864    Module m     = findFakeModule(modT);
865    setCurrModule(m);
866
867    t             = newTycon(typeT);
868    tycon(t).kind = STAR;
869    tycon(t).what = DATATYPE;
870    
871    constrs = reverse(constrs);
872    i       = length(constrs);
873    for (; nonNull(constrs); constrs=tl(constrs),i--) {
874       Text conT        = hd(constrs);
875       Name con         = newName(conT,t);
876       name(con).number = cfunNo(i);
877       name(con).type   = t;
878       name(con).parent = t;
879       tycon(t).defn    = cons(con, tycon(t).defn);      
880    }
881    return t;
882 }
883
884
885 Name addPrimCfunREP(t,arity,no,rep)     /* add primitive constructor func  */
886 Text t;                                 /* sets rep, not type              */
887 Int  arity;
888 Int  no;
889 Int  rep; { /* Really AsmRep */
890     Name n          = newName(t,NIL);
891     name(n).arity   = arity;
892     name(n).number  = cfunNo(no);
893     name(n).type    = NIL;
894     name(n).primop  = (void*)rep;
895     return n;
896 }
897
898
899 Name addPrimCfun(t,arity,no,type)       /* add primitive constructor func  */
900 Text t;
901 Int  arity;
902 Int  no;
903 Cell type; {
904     Name n         = newName(t,NIL);
905     name(n).arity  = arity;
906     name(n).number = cfunNo(no);
907     name(n).type   = type;
908     return n;
909 }
910
911
912 Int sfunPos(s,c)                        /* Find position of field with     */
913 Name s;                                 /* selector s in constructor c.    */
914 Name c; {
915     List cns;
916     cns = name(s).defn;
917     for (; nonNull(cns); cns=tl(cns))
918         if (fst(hd(cns))==c)
919             return intOf(snd(hd(cns)));
920     internal("sfunPos");
921     return 0;/* NOTREACHED */
922 }
923
924 static List local insertName(nm,ns)     /* insert name nm into sorted list */
925 Name nm;                                /* ns                              */
926 List ns; {
927     Cell   prev = NIL;
928     Cell   curr = ns;
929     String s    = textToStr(name(nm).text);
930
931     while (nonNull(curr) && strCompare(s,textToStr(name(hd(curr)).text))>=0) {
932         if (hd(curr)==nm)               /* just in case we get duplicates! */
933             return ns;
934         prev = curr;
935         curr = tl(curr);
936     }
937     if (nonNull(prev)) {
938         tl(prev) = cons(nm,curr);
939         return ns;
940     }
941     else
942         return cons(nm,curr);
943 }
944
945 List addNamesMatching(pat,ns)           /* Add names matching pattern pat  */
946 String pat;                             /* to list of names ns             */
947 List   ns; {                            /* Null pattern matches every name */
948     Name nm;                            /* (Names with NIL type, or hidden */
949 #if 1
950     for (nm=NAMEMIN; nm<nameHw; ++nm)   /* or invented names are excluded) */
951         if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
952             String str = textToStr(name(nm).text);
953             if (str[0]!='_' && (!pat || stringMatch(pat,str)))
954                 ns = insertName(nm,ns);
955         }
956     return ns;
957 #else
958     List mns = module(currentModule).names;
959     for(; nonNull(mns); mns=tl(mns)) {
960         Name nm = hd(mns);
961         if (!inventedText(name(nm).text)) {
962             String str = textToStr(name(nm).text);
963             if (str[0]!='_' && (!pat || stringMatch(pat,str)))
964                 ns = insertName(nm,ns);
965         }
966     }
967     return ns;
968 #endif
969 }
970
971 /* --------------------------------------------------------------------------
972  * A simple string matching routine
973  *     `*'    matches any sequence of zero or more characters
974  *     `?'    matches any single character exactly 
975  *     `@str' matches the string str exactly (ignoring any special chars)
976  *     `\c'   matches the character c only (ignoring special chars)
977  *     c      matches the character c only
978  * ------------------------------------------------------------------------*/
979
980 static Void local patternError(s)       /* report error in pattern         */
981 String s; {
982     ERRMSG(0) "%s in pattern", s
983     EEND;
984 }
985
986 static Bool local stringMatch(pat,str)  /* match string against pattern    */
987 String pat;
988 String str; {
989
990     for (;;)
991         switch (*pat) {
992             case '\0' : return (*str=='\0');
993
994             case '*'  : do {
995                             if (stringMatch(pat+1,str))
996                                 return TRUE;
997                         } while (*str++);
998                         return FALSE;
999
1000             case '?'  : if (*str++=='\0')
1001                             return FALSE;
1002                         pat++;
1003                         break;
1004
1005             case '['  : {   Bool found = FALSE;
1006                             while (*++pat!='\0' && *pat!=']')
1007                                 if (!found && ( pat[0] == *str  ||
1008                                                (pat[1] == '-'   &&
1009                                                 pat[2] != ']'   &&
1010                                                 pat[2] != '\0'  &&
1011                                                 pat[0] <= *str  &&
1012                                                 pat[2] >= *str)))
1013
1014                                     found = TRUE;
1015                             if (*pat != ']')
1016                                 patternError("missing `]'");
1017                             if (!found)
1018                                 return FALSE;
1019                             pat++;
1020                             str++;
1021                         }
1022                         break;
1023
1024             case '\\' : if (*++pat == '\0')
1025                             patternError("extra trailing `\\'");
1026                         /*fallthru!*/
1027             default   : if (*pat++ != *str++)
1028                             return FALSE;
1029                         break;
1030         }
1031 }
1032
1033 /* --------------------------------------------------------------------------
1034  * Storage of type classes, instances etc...:
1035  * ------------------------------------------------------------------------*/
1036
1037 static Class classHw;                  /* next unused class                */
1038 static List  classes;                  /* list of classes in current scope */
1039 static Inst  instHw;                   /* next unused instance record      */
1040
1041 struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records  */
1042 struct strInst far *tabInst;           /* (pointer to) table of instances  */
1043
1044 Class newClass(t)                      /* add new class to class table     */
1045 Text t; {
1046     if (classHw-CLASSMIN >= NUM_CLASSES) {
1047         ERRMSG(0) "Class storage space exhausted"
1048         EEND;
1049     }
1050     cclass(classHw).text      = t;
1051     cclass(classHw).arity     = 0;
1052     cclass(classHw).kinds     = NIL;
1053     cclass(classHw).head      = NIL;
1054     cclass(classHw).fds       = NIL;
1055     cclass(classHw).xfds      = NIL;
1056     cclass(classHw).dcon      = NIL;
1057     cclass(classHw).supers    = NIL;
1058     cclass(classHw).dsels     = NIL;
1059     cclass(classHw).members   = NIL;
1060     cclass(classHw).defaults  = NIL;
1061     cclass(classHw).instances = NIL;
1062     classes=cons(classHw,classes);
1063     cclass(classHw).mod       = currentModule;
1064     module(currentModule).classes=cons(classHw,module(currentModule).classes);
1065     return classHw++;
1066 }
1067
1068 Class classMax() {                      /* Return max Class in use ...     */
1069     return classHw;                     /* This is a bit ugly, but it's not*/
1070 }                                       /* worth a lot of effort right now */
1071
1072 Class findClass(t)                     /* look for named class in table    */
1073 Text t; {
1074     Class cl;
1075     List cs;
1076     for (cs=classes; nonNull(cs); cs=tl(cs)) {
1077         cl=hd(cs);
1078         if (cclass(cl).text==t)
1079             return cl;
1080     }
1081     return NIL;
1082 }
1083
1084 Class addClass(c)                       /* Insert Class in class list      */
1085 Class c; {                              /*  - if no clash caused           */
1086     Class oldc; 
1087     assert(whatIs(c)==CLASS);
1088     oldc = findClass(cclass(c).text);
1089     if (isNull(oldc)) {
1090         classes=cons(c,classes);
1091         module(currentModule).classes=cons(c,module(currentModule).classes);
1092         return c;
1093     }
1094     else
1095         return oldc;
1096 }
1097
1098 Class findQualClass(c)                  /* Look for (possibly qualified)   */
1099 Cell c; {                               /* class in class list             */
1100     if (!isQualIdent(c)) {
1101         return findClass(textOf(c));
1102     } else {
1103         Text   t  = qtextOf(c);
1104         Module m  = findQualifier(qmodOf(c));
1105         List   es = NIL;
1106         if (isNull(m))
1107             return NIL;
1108         for (es=module(m).exports; nonNull(es); es=tl(es)) {
1109             Cell e = hd(es);
1110             if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t) 
1111                 return fst(e);
1112         }
1113     }
1114     return NIL;
1115 }
1116
1117 Inst newInst() {                       /* Add new instance to table        */
1118     if (instHw-INSTMIN >= NUM_INSTS) {
1119         ERRMSG(0) "Instance storage space exhausted"
1120         EEND;
1121     }
1122     inst(instHw).kinds      = NIL;
1123     inst(instHw).head       = NIL;
1124     inst(instHw).specifics  = NIL;
1125     inst(instHw).implements = NIL;
1126     inst(instHw).builder    = NIL;
1127     inst(instHw).mod        = currentModule;
1128
1129     return instHw++;
1130 }
1131
1132 #ifdef DEBUG_DICTS
1133 extern Void printInst Args((Inst));
1134
1135 Void printInst(in)
1136 Inst in; {
1137     Class cl = inst(in).c;
1138     Printf("%s-", textToStr(cclass(cl).text));
1139     printType(stdout,inst(in).t);
1140 }
1141 #endif /* DEBUG_DICTS */
1142
1143 Inst findFirstInst(tc)                  /* look for 1st instance involving */
1144 Tycon tc; {                             /* the type constructor tc         */
1145     return findNextInst(tc,INSTMIN-1);
1146 }
1147
1148 Inst findNextInst(tc,in)                /* look for next instance involving*/
1149 Tycon tc;                               /* the type constructor tc         */
1150 Inst  in; {                             /* starting after instance in      */
1151     while (++in < instHw) {
1152         Cell pi = inst(in).head;
1153         for (; isAp(pi); pi=fun(pi))
1154             if (typeInvolves(arg(pi),tc))
1155                 return in;
1156     }
1157     return NIL;
1158 }
1159
1160 static Bool local typeInvolves(ty,tc)   /* Test to see if type ty involves */
1161 Type ty;                                /* type constructor/tuple tc.      */
1162 Type tc; {
1163     return (ty==tc)
1164         || (isAp(ty) && (typeInvolves(fun(ty),tc)
1165                          || typeInvolves(arg(ty),tc)));
1166 }
1167
1168
1169 /* Needed by finishGHCInstance to find classes, before the
1170    export list has been built -- so we can't use 
1171    findQualClass.
1172 */
1173 Class findQualClassWithoutConsultingExportList ( QualId q )
1174 {
1175    Class cl;
1176    Text t_mod;
1177    Text t_class;
1178
1179    assert(isQCon(q));
1180
1181    if (isCon(q)) {
1182       t_mod   = NIL;
1183       t_class = textOf(q);
1184    } else {
1185       t_mod   = qmodOf(q);
1186       t_class = qtextOf(q);
1187    }
1188
1189    for (cl = CLASSMIN; cl < classHw; cl++) {
1190       if (cclass(cl).text == t_class) {
1191          /* Class name is ok, but is this the right module? */
1192          if (isNull(t_mod)   /* no module name specified */
1193              || (nonNull(t_mod) 
1194                  && t_mod == module(cclass(cl).mod).text)
1195             )
1196             return cl;
1197       }
1198    }
1199    return NIL;
1200 }
1201
1202
1203 /* Same deal, except for Tycons. */
1204 Tycon findQualTyconWithoutConsultingExportList ( QualId q )
1205 {
1206    Tycon tc;
1207    Text t_mod;
1208    Text t_tycon;
1209
1210    assert(isQCon(q));
1211
1212    if (isCon(q)) {
1213       t_mod   = NIL;
1214       t_tycon = textOf(q);
1215    } else {
1216       t_mod   = qmodOf(q);
1217       t_tycon = qtextOf(q);
1218    }
1219
1220    for (tc = TYCMIN; tc < tyconHw; tc++) {
1221       if (tycon(tc).text == t_tycon) {
1222          /* Tycon name is ok, but is this the right module? */
1223          if (isNull(t_mod)   /* no module name specified */
1224              || (nonNull(t_mod) 
1225                  && t_mod == module(tycon(tc).mod).text)
1226             )
1227             return tc;
1228       }
1229    }
1230    return NIL;
1231 }
1232
1233 Tycon findTyconInAnyModule ( Text t )
1234 {
1235    Tycon tc;
1236    for (tc = TYCMIN; tc < tyconHw; tc++)
1237       if (tycon(tc).text == t) return tc;
1238    return NIL;
1239 }
1240
1241 Class findClassInAnyModule ( Text t )
1242 {
1243    Class cc;
1244    for (cc = CLASSMIN; cc < classHw; cc++)
1245       if (cclass(cc).text == t) return cc;
1246    return NIL;
1247 }
1248
1249 Name findNameInAnyModule ( Text t )
1250 {
1251    Name nm;
1252    for (nm = NAMEMIN; nm < nameHw; nm++)
1253       if (name(nm).text == t) return nm;
1254    return NIL;
1255 }
1256
1257 /* Same deal, except for Names. */
1258 Name findQualNameWithoutConsultingExportList ( QualId q )
1259 {
1260    Name nm;
1261    Text t_mod;
1262    Text t_name;
1263
1264    assert(isQVar(q) || isQCon(q));
1265
1266    if (isCon(q) || isVar(q)) {
1267       t_mod  = NIL;
1268       t_name = textOf(q);
1269    } else {
1270       t_mod  = qmodOf(q);
1271       t_name = qtextOf(q);
1272    }
1273
1274    for (nm = NAMEMIN; nm < nameHw; nm++) {
1275       if (name(nm).text == t_name) {
1276          /* Name is ok, but is this the right module? */
1277          if (isNull(t_mod)   /* no module name specified */
1278              || (nonNull(t_mod) 
1279                  && t_mod == module(name(nm).mod).text)
1280             )
1281             return nm;
1282       }
1283    }
1284    return NIL;
1285 }
1286
1287
1288 /* returns List of QualId */
1289 List getAllKnownTyconsAndClasses ( void )
1290 {
1291    Tycon tc;
1292    Class nw;
1293    List  xs = NIL;
1294    for (tc = TYCMIN; tc < tyconHw; tc++) {
1295       /* almost certainly undue paranoia about duplicate avoidance, but .. */
1296       QualId q = mkQCon( module(tycon(tc).mod).text, tycon(tc).text );
1297       if (!qualidIsMember(q,xs))
1298          xs = cons ( q, xs );
1299    }
1300    for (nw = CLASSMIN; nw < classHw; nw++) {
1301       QualId q = mkQCon( module(cclass(nw).mod).text, cclass(nw).text );
1302       if (!qualidIsMember(q,xs))
1303          xs = cons ( q, xs );
1304    }
1305    return xs;
1306 }
1307
1308 /* Purely for debugging. */
1309 void locateSymbolByName ( Text t )
1310 {
1311    Int i;
1312    for (i = NAMEMIN; i < nameHw; i++)
1313       if (name(i).text == t)
1314          fprintf ( stderr, "name(%d)\n", i-NAMEMIN);
1315    for (i = TYCMIN; i < tyconHw; i++)
1316       if (tycon(i).text == t)
1317          fprintf ( stderr, "tycon(%d)\n", i-TYCMIN);
1318    for (i = CLASSMIN; i < classHw; i++)
1319       if (cclass(i).text == t)
1320          fprintf ( stderr, "class(%d)\n", i-CLASSMIN);
1321 }
1322
1323 /* --------------------------------------------------------------------------
1324  * Control stack:
1325  *
1326  * Various parts of the system use a stack of cells.  Most of the stack
1327  * operations are defined as macros, expanded inline.
1328  * ------------------------------------------------------------------------*/
1329
1330 Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack          */
1331 StackPtr sp;                        /* stack pointer                       */
1332
1333 #if GIMME_STACK_DUMPS
1334
1335 #define UPPER_DISP  5               /* # display entries on top of stack   */
1336 #define LOWER_DISP  5               /* # display entries on bottom of stack*/
1337
1338 Void hugsStackOverflow() {          /* Report stack overflow               */
1339     extern Int  rootsp;
1340     extern Cell evalRoots[];
1341
1342     ERRMSG(0) "Control stack overflow" ETHEN
1343     if (rootsp>=0) {
1344         Int i;
1345         if (rootsp>=UPPER_DISP+LOWER_DISP) {
1346             for (i=0; i<UPPER_DISP; i++) {
1347                 ERRTEXT "\nwhile evaluating: " ETHEN
1348                 ERREXPR(evalRoots[rootsp-i]);
1349             }
1350             ERRTEXT "\n..." ETHEN
1351             for (i=LOWER_DISP-1; i>=0; i--) {
1352                 ERRTEXT "\nwhile evaluating: " ETHEN
1353                 ERREXPR(evalRoots[i]);
1354             }
1355         }
1356         else {
1357             for (i=rootsp; i>=0; i--) {
1358                 ERRTEXT "\nwhile evaluating: " ETHEN
1359                 ERREXPR(evalRoots[i]);
1360             }
1361         }
1362     }
1363     ERRTEXT "\n"
1364     EEND;
1365 }
1366
1367 #else /* !GIMME_STACK_DUMPS */
1368
1369 Void hugsStackOverflow() {          /* Report stack overflow               */
1370     ERRMSG(0) "Control stack overflow"
1371     EEND;
1372 }
1373
1374 #endif /* !GIMME_STACK_DUMPS */
1375
1376 /* --------------------------------------------------------------------------
1377  * Module storage:
1378  *
1379  * A Module represents a user defined module.  
1380  *
1381  * Note: there are now two lookup mechanisms in the system:
1382  *
1383  * 1) The exports from a module are stored in a big list.
1384  *    We resolve qualified names, and import lists by linearly scanning
1385  *    through this list.
1386  *
1387  * 2) Unqualified imports and local definitions for the current module
1388  *    are stored in hash tables (tyconHash and nameHash) or linear lists
1389  *    (classes).
1390  *
1391  * ------------------------------------------------------------------------*/
1392
1393 static  Module   moduleHw;              /* next unused Module              */
1394 struct  Module   DEFTABLE(tabModule,NUM_MODULE); /* Module storage         */
1395 Module  currentModule;                  /* Module currently being processed*/
1396
1397 Bool isValidModule(m)                  /* is m a legitimate module id?     */
1398 Module m; {
1399     return (MODMIN <= m && m < moduleHw);
1400 }
1401
1402 Module newModule(t)                     /* add new module to module table  */
1403 Text t; {
1404     if (moduleHw-MODMIN >= NUM_MODULE) {
1405         ERRMSG(0) "Module storage space exhausted"
1406         EEND;
1407     }
1408     module(moduleHw).text             = t; /* clear new module record      */
1409     module(moduleHw).qualImports      = NIL;
1410     module(moduleHw).fake             = FALSE;
1411     module(moduleHw).exports          = NIL;
1412     module(moduleHw).tycons           = NIL;
1413     module(moduleHw).names            = NIL;
1414     module(moduleHw).classes          = NIL;
1415     module(moduleHw).object           = NULL;
1416     module(moduleHw).objectExtras     = NULL;
1417     module(moduleHw).objectExtraNames = NIL;
1418     return moduleHw++;
1419 }
1420
1421 void ppModules ( void )
1422 {
1423    Int i;
1424    fflush(stderr); fflush(stdout);
1425    printf ( "begin MODULES\n" );
1426    for (i = moduleHw-1; i >= MODMIN; i--)
1427       printf ( " %2d: %16s\n",
1428                i-MODMIN, textToStr(module(i).text)
1429              );
1430    printf ( "end   MODULES\n" );
1431    fflush(stderr); fflush(stdout);
1432 }
1433
1434
1435 Module findModule(t)                    /* locate Module in module table  */
1436 Text t; {
1437     Module m;
1438     for(m=MODMIN; m<moduleHw; ++m) {
1439         if (module(m).text==t)
1440             return m;
1441     }
1442     return NIL;
1443 }
1444
1445 Module findModid(c)                    /* Find module by name or filename  */
1446 Cell c; {
1447     switch (whatIs(c)) {
1448         case STRCELL   : { Script s = scriptThisFile(snd(c));
1449                            return (s==-1) ? NIL : moduleOfScript(s);
1450                          }
1451         case CONIDCELL : return findModule(textOf(c));
1452         default        : internal("findModid");
1453     }
1454     return NIL;/*NOTUSED*/
1455 }
1456
1457 static local Module findQualifier(t)    /* locate Module in import list   */
1458 Text t; {
1459     Module ms;
1460     for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1461         if (textOf(fst(hd(ms)))==t)
1462             return snd(hd(ms));
1463     }
1464 #if 1 /* mpj */
1465     if (module(currentModule).text==t)
1466         return currentModule;
1467 #endif
1468     return NIL;
1469 }
1470
1471 Void setCurrModule(m)              /* set lookup tables for current module */
1472 Module m; {
1473     Int i;
1474     assert(isModule(m));
1475     if (m!=currentModule) {
1476         currentModule = m; /* This is the only assignment to currentModule */
1477         for (i=0; i<TYCONHSZ; ++i)
1478             tyconHash[i] = NIL;
1479         mapProc(hashTycon,module(m).tycons);
1480         for (i=0; i<NAMEHSZ; ++i)
1481             nameHash[i] = NIL;
1482         mapProc(hashName,module(m).names);
1483         classes = module(m).classes;
1484     }
1485 }
1486
1487 Name jrsFindQualName ( Text mn, Text sn )
1488 {
1489    Module m;
1490    List   ns;
1491
1492    for (m=MODMIN; m<moduleHw; m++)
1493       if (module(m).text == mn) break;
1494    if (m == moduleHw) return NIL;
1495    
1496    for (ns = module(m).names; nonNull(ns); ns=tl(ns)) 
1497       if (name(hd(ns)).text == sn) return hd(ns);
1498
1499    return NIL;
1500 }
1501
1502
1503 char* nameFromOPtr ( void* p )
1504 {
1505    int i;
1506    Module m;
1507    for (m=MODMIN; m<moduleHw; m++) {
1508       if (module(m).object) {
1509          char* nm = ocLookupAddr ( module(m).object, p );
1510          if (nm) return nm;
1511       }
1512    }
1513 #  if 0
1514    /* A kludge to assist Win32 debugging; not actually necessary. */
1515    { char* nm = nameFromStaticOPtr(p);
1516      if (nm) return nm;
1517    }
1518 #  endif
1519    return NULL;
1520 }
1521
1522
1523 void* lookupOTabName ( Module m, char* sym )
1524 {
1525    if (module(m).object)
1526       return ocLookupSym ( module(m).object, sym );
1527    return NULL;
1528 }
1529
1530
1531 void* lookupOExtraTabName ( char* sym )
1532 {
1533    ObjectCode* oc;
1534    Module      m;
1535    for (m = MODMIN; m < moduleHw; m++) {
1536       for (oc = module(m).objectExtras; oc; oc=oc->next) {
1537          void* ad = ocLookupSym ( oc, sym );
1538          if (ad) return ad;
1539       }
1540    }
1541    return NULL;
1542 }
1543
1544
1545 OSectionKind lookupSection ( void* ad )
1546 {
1547    int          i;
1548    Module       m;
1549    ObjectCode*  oc;
1550    OSectionKind sect;
1551
1552    for (m=MODMIN; m<moduleHw; m++) {
1553       if (module(m).object) {
1554          sect = ocLookupSection ( module(m).object, ad );
1555          if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1556             return sect;
1557       }
1558       for (oc = module(m).objectExtras; oc; oc=oc->next) {
1559          sect = ocLookupSection ( oc, ad );
1560          if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1561             return sect;
1562       }
1563    }
1564    return HUGS_SECTIONKIND_OTHER;
1565 }
1566
1567
1568 /* --------------------------------------------------------------------------
1569  * Script file storage:
1570  *
1571  * script files are read into the system one after another.  The state of
1572  * the stored data structures (except the garbage-collected heap) is recorded
1573  * before reading a new script.  In the event of being unable to read the
1574  * script, or if otherwise requested, the system can be restored to its
1575  * original state immediately before the file was read.
1576  * ------------------------------------------------------------------------*/
1577
1578 typedef struct {                       /* record of storage state prior to */
1579     Text  file;                        /* reading script/module            */
1580     Text  textHw;
1581     Text  nextNewText;
1582     Text  nextNewDText;
1583     Module moduleHw;
1584     Tycon tyconHw;
1585     Name  nameHw;
1586     Class classHw;
1587     Inst  instHw;
1588 #if TREX
1589     Ext   extHw;
1590 #endif
1591 } script;
1592
1593 #ifdef  DEBUG_SHOWUSE
1594 static Void local showUse(msg,val,mx)
1595 String msg;
1596 Int val, mx; {
1597     Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
1598 }
1599 #endif
1600
1601 static Script scriptHw;                 /* next unused script number       */
1602 static script scripts[NUM_SCRIPTS];     /* storage for script records      */
1603
1604
1605 void ppScripts ( void )
1606 {
1607    Int i;
1608    fflush(stderr); fflush(stdout);
1609    printf ( "begin SCRIPTS\n" );
1610    for (i = scriptHw-1; i >= 0; i--)
1611       printf ( " %2d: %16s  tH=%d  mH=%d  yH=%d  "
1612                "nH=%d  cH=%d  iH=%d  nnS=%d,%d\n",
1613                i, textToStr(scripts[i].file),
1614                scripts[i].textHw, scripts[i].moduleHw,
1615                scripts[i].tyconHw, scripts[i].nameHw, 
1616                scripts[i].classHw, scripts[i].instHw,
1617                scripts[i].nextNewText, scripts[i].nextNewDText 
1618              );
1619    printf ( "end   SCRIPTS\n" );
1620    fflush(stderr); fflush(stdout);
1621 }
1622
1623 Script startNewScript(f)                /* start new script, keeping record */
1624 String f; {                             /* of status for later restoration  */
1625     if (scriptHw >= NUM_SCRIPTS) {
1626         ERRMSG(0) "Too many script files in use"
1627         EEND;
1628     }
1629 #ifdef DEBUG_SHOWUSE
1630     showUse("Text",   textHw,           NUM_TEXT);
1631     showUse("Module", moduleHw-MODMIN,  NUM_MODULE);
1632     showUse("Tycon",  tyconHw-TYCMIN,   NUM_TYCON);
1633     showUse("Name",   nameHw-NAMEMIN,   NUM_NAME);
1634     showUse("Class",  classHw-CLASSMIN, NUM_CLASSES);
1635     showUse("Inst",   instHw-INSTMIN,   NUM_INSTS);
1636 #if TREX
1637     showUse("Ext",    extHw-EXTMIN,     NUM_EXT);
1638 #endif
1639 #endif
1640     scripts[scriptHw].file         = findText( f ? f : "<nofile>" );
1641     scripts[scriptHw].textHw       = textHw;
1642     scripts[scriptHw].nextNewText  = nextNewText;
1643     scripts[scriptHw].nextNewDText = nextNewDText;
1644     scripts[scriptHw].moduleHw     = moduleHw;
1645     scripts[scriptHw].tyconHw      = tyconHw;
1646     scripts[scriptHw].nameHw       = nameHw;
1647     scripts[scriptHw].classHw      = classHw;
1648     scripts[scriptHw].instHw       = instHw;
1649 #if TREX
1650     scripts[scriptHw].extHw        = extHw;
1651 #endif
1652     return scriptHw++;
1653 }
1654
1655 Bool isPreludeScript() {                /* Test whether this is the Prelude*/
1656     return (scriptHw < N_PRELUDE_SCRIPTS /*==0*/ );
1657 }
1658
1659 Bool moduleThisScript(m)                /* Test if given module is defined */
1660 Module m; {                             /* in current script file          */
1661     return scriptHw < 1
1662            || m>=scripts[scriptHw-1].moduleHw;
1663 }
1664
1665 Module lastModule() {              /* Return module in current script file */
1666     return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
1667 }
1668
1669 #define scriptThis(nm,t,tag)            Script nm(x)                       \
1670                                         t x; {                             \
1671                                             Script s=0;                    \
1672                                             while (s<scriptHw              \
1673                                                    && x>=scripts[s].tag)   \
1674                                                 s++;                       \
1675                                             return s;                      \
1676                                         }
1677 scriptThis(scriptThisName,Name,nameHw)
1678 scriptThis(scriptThisTycon,Tycon,tyconHw)
1679 scriptThis(scriptThisInst,Inst,instHw)
1680 scriptThis(scriptThisClass,Class,classHw)
1681 #undef scriptThis
1682
1683 Module moduleOfScript(s)
1684 Script s; {
1685     return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
1686 }
1687
1688 String fileOfModule(m)
1689 Module m; {
1690     Script s;
1691     if (m == modulePrelude) {
1692         return STD_PRELUDE;
1693     }
1694     for(s=0; s<scriptHw; ++s) {
1695         if (scripts[s].moduleHw == m) {
1696             return textToStr(scripts[s].file);
1697         }
1698     }
1699     return 0;
1700 }
1701
1702 Script scriptThisFile(f)
1703 Text f; {
1704     Script s;
1705     for (s=0; s < scriptHw; ++s) {
1706         if (scripts[s].file == f) {
1707             return s+1;
1708         }
1709     }
1710     if (f == findText(STD_PRELUDE)) {
1711         return 0;
1712     }
1713     return (-1);
1714 }
1715
1716 Void dropScriptsFrom(sno)               /* Restore storage to state prior  */
1717 Script sno; {                           /* to reading script sno           */
1718     if (sno<scriptHw) {                 /* is there anything to restore?   */
1719         int i;
1720         textHw       = scripts[sno].textHw;
1721         nextNewText  = scripts[sno].nextNewText;
1722         nextNewDText = scripts[sno].nextNewDText;
1723         moduleHw     = scripts[sno].moduleHw;
1724         tyconHw      = scripts[sno].tyconHw;
1725         nameHw       = scripts[sno].nameHw;
1726         classHw      = scripts[sno].classHw;
1727         instHw       = scripts[sno].instHw;
1728 #if USE_DICTHW
1729         dictHw       = scripts[sno].dictHw;
1730 #endif
1731 #if TREX
1732         extHw        = scripts[sno].extHw;
1733 #endif
1734
1735 #if 0
1736         for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
1737             if (module(i).objectFile) {
1738                 printf("[bogus] closing objectFile for module %d\n",i);
1739                 /*dlclose(module(i).objectFile);*/
1740             }
1741         }
1742         moduleHw = scripts[sno].moduleHw;
1743 #endif
1744         for (i=0; i<TEXTHSZ; ++i) {
1745             int j = 0;
1746             while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
1747                                && textHash[i][j]<textHw)
1748                 ++j;
1749             if (j<NUM_TEXTH)
1750                 textHash[i][j] = NOTEXT;
1751         }
1752
1753         currentModule=NIL;
1754         for (i=0; i<TYCONHSZ; ++i) {
1755             tyconHash[i] = NIL;
1756         }
1757         for (i=0; i<NAMEHSZ; ++i) {
1758             nameHash[i] = NIL;
1759         }
1760
1761         for (i=CLASSMIN; i<classHw; i++) {
1762             List ins = cclass(i).instances;
1763             List is  = NIL;
1764
1765             while (nonNull(ins)) {
1766                 List temp = tl(ins);
1767                 if (hd(ins)<instHw) {
1768                     tl(ins) = is;
1769                     is      = ins;
1770                 }
1771                 ins = temp;
1772             }
1773             cclass(i).instances = rev(is);
1774         }
1775
1776         scriptHw = sno;
1777     }
1778 }
1779
1780 /* --------------------------------------------------------------------------
1781  * Heap storage:
1782  *
1783  * Provides a garbage collectable heap for storage of expressions etc.
1784  *
1785  * Now incorporates a flat resource:  A two-space collected extension of
1786  * the heap that provides storage for contiguous arrays of Cell storage,
1787  * cooperating with the garbage collection mechanisms for the main heap.
1788  * ------------------------------------------------------------------------*/
1789
1790 Int     heapSize = DEFAULTHEAP;         /* number of cells in heap         */
1791 Heap    heapFst;                        /* array of fst component of pairs */
1792 Heap    heapSnd;                        /* array of snd component of pairs */
1793 #ifndef GLOBALfst
1794 Heap    heapTopFst;
1795 #endif
1796 #ifndef GLOBALsnd
1797 Heap    heapTopSnd;
1798 #endif
1799 Bool    consGC = TRUE;                  /* Set to FALSE to turn off gc from*/
1800                                         /* C stack; use with extreme care! */
1801 Long    numCells;
1802 Int     numGcs;                         /* number of garbage collections   */
1803 Int     cellsRecovered;                 /* number of cells recovered       */
1804
1805 static  Cell freeList;                  /* free list of unused cells       */
1806 static  Cell lsave, rsave;              /* save components of pair         */
1807
1808 #if GC_STATISTICS
1809
1810 static Int markCount, stackRoots;
1811
1812 #define initStackRoots() stackRoots = 0
1813 #define recordStackRoot() stackRoots++
1814
1815 #define startGC()       \
1816     if (gcMessages) {   \
1817         Printf("\n");   \
1818         fflush(stdout); \
1819     }
1820 #define endGC()         \
1821     if (gcMessages) {   \
1822         Printf("\n");   \
1823         fflush(stdout); \
1824     }
1825
1826 #define start()      markCount = 0
1827 #define end(thing,rs) \
1828     if (gcMessages) { \
1829         Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1830         fflush(stdout); \
1831     }
1832 #define recordMark() markCount++
1833
1834 #else /* !GC_STATISTICS */
1835
1836 #define startGC()
1837 #define endGC()
1838
1839 #define initStackRoots()
1840 #define recordStackRoot()
1841
1842 #define start()   
1843 #define end(thing,root) 
1844 #define recordMark() 
1845
1846 #endif /* !GC_STATISTICS */
1847
1848 Cell pair(l,r)                          /* Allocate pair (l, r) from       */
1849 Cell l, r; {                            /* heap, garbage collecting first  */
1850     Cell c = freeList;                  /* if necessary ...                */
1851
1852     if (isNull(c)) {
1853         lsave = l;
1854         rsave = r;
1855         garbageCollect();
1856         l     = lsave;
1857         lsave = NIL;
1858         r     = rsave;
1859         rsave = NIL;
1860         c     = freeList;
1861     }
1862     freeList = snd(freeList);
1863     fst(c)   = l;
1864     snd(c)   = r;
1865     numCells++;
1866     return c;
1867 }
1868
1869 Void overwrite(dst,src)                 /* overwrite dst cell with src cell*/
1870 Cell dst, src; {                        /* both *MUST* be pairs            */
1871     if (isPair(dst) && isPair(src)) {
1872         fst(dst) = fst(src);
1873         snd(dst) = snd(src);
1874     }
1875     else
1876         internal("overwrite");
1877 }
1878
1879 static Int *marks;
1880 static Int marksSize;
1881
1882 Cell markExpr(c)                        /* External interface to markCell  */
1883 Cell c; {
1884     return isGenPair(c) ? markCell(c) : c;
1885 }
1886
1887 static Cell local markCell(c)           /* Traverse part of graph marking  */
1888 Cell c; {                               /* cells reachable from given root */
1889                                         /* markCell(c) is only called if c */
1890                                         /* is a pair                       */
1891     {   register int place = placeInSet(c);
1892         register int mask  = maskInSet(c);
1893         if (marks[place]&mask)
1894             return c;
1895         else {
1896             marks[place] |= mask;
1897             recordMark();
1898         }
1899     }
1900
1901     /* STACK_CHECK: Avoid stack overflows during recursive marking. */
1902     if (isGenPair(fst(c))) {
1903         STACK_CHECK
1904         fst(c) = markCell(fst(c));
1905         markSnd(c);
1906     }
1907     else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
1908         STACK_CHECK
1909         markSnd(c);
1910     }
1911
1912     return c;
1913 }
1914
1915 static Void local markSnd(c)            /* Variant of markCell used to     */
1916 Cell c; {                               /* update snd component of cell    */
1917     Cell t;                             /* using tail recursion            */
1918
1919 ma: t = c;                              /* Keep pointer to original pair   */
1920     c = snd(c);
1921     if (!isPair(c))
1922         return;
1923
1924     {   register int place = placeInSet(c);
1925         register int mask  = maskInSet(c);
1926         if (marks[place]&mask)
1927             return;
1928         else {
1929             marks[place] |= mask;
1930             recordMark();
1931         }
1932     }
1933
1934     if (isGenPair(fst(c))) {
1935         fst(c) = markCell(fst(c));
1936         goto ma;
1937     }
1938     else if (isNull(fst(c)) || fst(c)>=BCSTAG)
1939         goto ma;
1940     return;
1941 }
1942
1943 Void markWithoutMove(n)                 /* Garbage collect cell at n, as if*/
1944 Cell n; {                               /* it was a cell ref, but don't    */
1945                                         /* move cell so we don't have      */
1946                                         /* to modify the stored value of n */
1947     if (isGenPair(n)) {
1948         recordStackRoot();
1949         markCell(n); 
1950     }
1951 }
1952
1953 Void garbageCollect()     {             /* Run garbage collector ...       */
1954     Bool breakStat = breakOn(FALSE);    /* disable break checking          */
1955     Int i,j;
1956     register Int mask;
1957     register Int place;
1958     Int      recovered;
1959
1960     jmp_buf  regs;                      /* save registers on stack         */
1961     setjmp(regs);
1962
1963     gcStarted();
1964     for (i=0; i<marksSize; ++i)         /* initialise mark set to empty    */
1965         marks[i] = 0;
1966
1967     everybody(MARK);                    /* Mark all components of system   */
1968
1969     gcScanning();                       /* scan mark set                   */
1970     mask      = 1;
1971     place     = 0;
1972     recovered = 0;
1973     j         = 0;
1974
1975     freeList = NIL;
1976     for (i=1; i<=heapSize; i++) {
1977         if ((marks[place] & mask) == 0) {
1978             snd(-i)  = freeList;
1979             fst(-i)  = FREECELL;
1980             freeList = -i;
1981             recovered++;
1982         }
1983         mask <<= 1;
1984         if (++j == bitsPerWord) {
1985             place++;
1986             mask = 1;
1987             j    = 0;
1988         }
1989     }
1990
1991     gcRecovered(recovered);
1992     breakOn(breakStat);                 /* restore break trapping if nec.  */
1993
1994     everybody(GCDONE);
1995
1996     /* can only return if freeList is nonempty on return. */
1997     if (recovered<minRecovery || isNull(freeList)) {
1998         ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
1999         EEND;
2000     }
2001     cellsRecovered = recovered;
2002 }
2003
2004 /* --------------------------------------------------------------------------
2005  * Code for saving last expression entered:
2006  *
2007  * This is a little tricky because some text values (e.g. strings or variable
2008  * names) may not be defined or have the same value when the expression is
2009  * recalled.  These text values are therefore saved in the top portion of
2010  * the text table.
2011  * ------------------------------------------------------------------------*/
2012
2013 static Cell lastExprSaved;              /* last expression to be saved     */
2014
2015 Void setLastExpr(e)                     /* save expression for later recall*/
2016 Cell e; {
2017     lastExprSaved = NIL;                /* in case attempt to save fails   */
2018     savedText     = NUM_TEXT;
2019     lastExprSaved = lowLevelLastIn(e);
2020 }
2021
2022 static Cell local lowLevelLastIn(c)     /* Duplicate expression tree (i.e. */
2023 Cell c; {                               /* acyclic graph) for later recall */
2024     if (isPair(c)) {                    /* Duplicating any text strings    */
2025         if (isBoxTag(fst(c)))           /* in case these are lost at some  */
2026             switch (fst(c)) {           /* point before the expr is reused */
2027                 case VARIDCELL :
2028                 case VAROPCELL :
2029                 case DICTVAR   :
2030                 case CONIDCELL :
2031                 case CONOPCELL :
2032                 case STRCELL   : return pair(fst(c),saveText(textOf(c)));
2033                 default        : return pair(fst(c),snd(c));
2034             }
2035         else
2036             return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2037     }
2038 #if TREX
2039     else if (isExt(c))
2040         return pair(EXTCOPY,saveText(extText(c)));
2041 #endif
2042     else
2043         return c;
2044 }
2045
2046 Cell getLastExpr() {                    /* recover previously saved expr   */
2047     return lowLevelLastOut(lastExprSaved);
2048 }
2049
2050 static Cell local lowLevelLastOut(c)    /* As with lowLevelLastIn() above  */
2051 Cell c; {                               /* except that Cells refering to   */
2052     if (isPair(c)) {                    /* Text values are restored to     */
2053         if (isBoxTag(fst(c)))           /* appropriate values              */
2054             switch (fst(c)) {
2055                 case VARIDCELL :
2056                 case VAROPCELL :
2057                 case DICTVAR   :
2058                 case CONIDCELL :
2059                 case CONOPCELL :
2060                 case STRCELL   : return pair(fst(c),
2061                                              findText(text+intValOf(c)));
2062 #if TREX
2063                 case EXTCOPY   : return mkExt(findText(text+intValOf(c)));
2064 #endif
2065                 default        : return pair(fst(c),snd(c));
2066             }
2067         else
2068             return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2069     }
2070     else
2071         return c;
2072 }
2073
2074 /* --------------------------------------------------------------------------
2075  * Miscellaneous operations on heap cells:
2076  * ------------------------------------------------------------------------*/
2077
2078 /* Profiling suggests that the number of calls to whatIs() is typically    */
2079 /* rather high.  The recoded version below attempts to improve the average */
2080 /* performance for whatIs() using a binary search for part of the analysis */
2081
2082 Cell whatIs(c)                         /* identify type of cell            */
2083 register Cell c; {
2084     if (isPair(c)) {
2085         register Cell fstc = fst(c);
2086         return isTag(fstc) ? fstc : AP;
2087     }
2088     if (c<OFFMIN)    return c;
2089 #if TREX
2090     if (isExt(c))    return EXT;
2091 #endif
2092     if (c>=INTMIN)   return INTCELL;
2093
2094     if (c>=NAMEMIN){if (c>=CLASSMIN)   {if (c>=CHARMIN) return CHARCELL;
2095                                         else            return CLASS;}
2096                     else                if (c>=INSTMIN) return INSTANCE;
2097                                         else            return NAME;}
2098     else            if (c>=MODMIN)     {if (c>=TYCMIN)  return isTuple(c) ? TUPLE : TYCON;
2099                                         else            return MODULE;}
2100                     else                if (c>=OFFMIN)  return OFFSET;
2101 #if TREX
2102                                         else            return (c>=EXTMIN) ?
2103                                                                 EXT : TUPLE;
2104 #else
2105                                         else            return TUPLE;
2106 #endif
2107
2108 /*  if (isPair(c)) {
2109         register Cell fstc = fst(c);
2110         return isTag(fstc) ? fstc : AP;
2111     }
2112     if (c>=INTMIN)   return INTCELL;
2113     if (c>=CHARMIN)  return CHARCELL;
2114     if (c>=CLASSMIN) return CLASS;
2115     if (c>=INSTMIN)  return INSTANCE;
2116     if (c>=NAMEMIN)  return NAME;
2117     if (c>=TYCMIN)   return TYCON;
2118     if (c>=MODMIN)   return MODULE;
2119     if (c>=OFFMIN)   return OFFSET;
2120 #if TREX
2121     if (c>=EXTMIN)   return EXT;
2122 #endif
2123     if (c>=TUPMIN)   return TUPLE;
2124     return c;*/
2125 }
2126
2127 /* A very, very simple printer.
2128  * Output is uglier than from printExp - but the printer is more
2129  * robust and can be used on any data structure irrespective of
2130  * its type.
2131  */
2132 Void print Args((Cell, Int));
2133 Void print(c, depth)
2134 Cell c;
2135 Int  depth; {
2136     if (0 == depth) {
2137         Printf("...");
2138     } else {
2139         Int tag = whatIs(c);
2140         switch (tag) {
2141         case AP: 
2142                 Putchar('(');
2143                 print(fst(c), depth-1);
2144                 Putchar(',');
2145                 print(snd(c), depth-1);
2146                 Putchar(')');
2147                 break;
2148         case FREECELL:
2149                 Printf("free(%d)", c);
2150                 break;
2151         case INTCELL:
2152                 Printf("int(%d)", intOf(c));
2153                 break;
2154         case BIGCELL:
2155                 Printf("bignum(%s)", bignumToString(c));
2156                 break;
2157         case CHARCELL:
2158                 Printf("char('%c')", charOf(c));
2159                 break;
2160         case PTRCELL: 
2161                 Printf("ptr(%p)",ptrOf(c));
2162                 break;
2163         case CLASS:
2164                 Printf("class(%d)", c-CLASSMIN);
2165                 if (CLASSMIN <= c && c < classHw) {
2166                     Printf("=\"%s\"", textToStr(cclass(c).text));
2167                 }
2168                 break;
2169         case INSTANCE:
2170                 Printf("instance(%d)", c - INSTMIN);
2171                 break;
2172         case NAME:
2173                 Printf("name(%d)", c-NAMEMIN);
2174                 if (NAMEMIN <= c && c < nameHw) {
2175                     Printf("=\"%s\"", textToStr(name(c).text));
2176                 }
2177                 break;
2178         case TYCON:
2179                 Printf("tycon(%d)", c-TYCMIN);
2180                 if (TYCMIN <= c && c < tyconHw)
2181                     Printf("=\"%s\"", textToStr(tycon(c).text));
2182                 break;
2183         case MODULE:
2184                 Printf("module(%d)", c - MODMIN);
2185                 break;
2186         case OFFSET:
2187                 Printf("Offset %d", offsetOf(c));
2188                 break;
2189         case TUPLE:
2190                 Printf("%s", textToStr(ghcTupleText(c)));
2191                 break;
2192         case POLYTYPE:
2193                 Printf("Polytype");
2194                 print(snd(c),depth-1);
2195                 break;
2196         case QUAL:
2197                 Printf("Qualtype");
2198                 print(snd(c),depth-1);
2199                 break;
2200         case RANK2:
2201                 Printf("Rank2(");
2202                 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2203                     Printf("%d ", intOf(fst(snd(c))));
2204                     print(snd(snd(c)),depth-1);
2205                 } else {
2206                     print(snd(c),depth-1);
2207                 }
2208                 Printf(")");
2209                 break;
2210         case NIL:
2211                 Printf("NIL");
2212                 break;
2213         case WILDCARD:
2214                 Printf("_");
2215                 break;
2216         case STAR:
2217                 Printf("STAR");
2218                 break;
2219         case DOTDOT:
2220                 Printf("DOTDOT");
2221                 break;
2222         case DICTVAR:
2223                 Printf("{dict %d}",textOf(c));
2224                 break;
2225         case VARIDCELL:
2226         case VAROPCELL:
2227         case CONIDCELL:
2228         case CONOPCELL:
2229                 Printf("{id %s}",textToStr(textOf(c)));
2230                 break;
2231 #if IPARAM
2232           case IPCELL :
2233               Printf("{ip %s}",textToStr(textOf(c)));
2234               break;
2235           case IPVAR :
2236               Printf("?%s",textToStr(textOf(c)));
2237               break;
2238 #endif
2239         case QUALIDENT:
2240                 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2241                 break;
2242         case LETREC:
2243                 Printf("LetRec(");
2244                 print(fst(snd(c)),depth-1);
2245                 Putchar(',');
2246                 print(snd(snd(c)),depth-1);
2247                 Putchar(')');
2248                 break;
2249         case LAMBDA:
2250                 Printf("Lambda(");
2251                 print(snd(c),depth-1);
2252                 Putchar(')');
2253                 break;
2254         case FINLIST:
2255                 Printf("FinList(");
2256                 print(snd(c),depth-1);
2257                 Putchar(')');
2258                 break;
2259         case COMP:
2260                 Printf("Comp(");
2261                 print(fst(snd(c)),depth-1);
2262                 Putchar(',');
2263                 print(snd(snd(c)),depth-1);
2264                 Putchar(')');
2265                 break;
2266         case ASPAT:
2267                 Printf("AsPat(");
2268                 print(fst(snd(c)),depth-1);
2269                 Putchar(',');
2270                 print(snd(snd(c)),depth-1);
2271                 Putchar(')');
2272                 break;
2273         case FROMQUAL:
2274                 Printf("FromQual(");
2275                 print(fst(snd(c)),depth-1);
2276                 Putchar(',');
2277                 print(snd(snd(c)),depth-1);
2278                 Putchar(')');
2279                 break;
2280         case STGVAR:
2281                 Printf("StgVar%d=",-c);
2282                 print(snd(c), depth-1);
2283                 break;
2284         case STGAPP:
2285                 Printf("StgApp(");
2286                 print(fst(snd(c)),depth-1);
2287                 Putchar(',');
2288                 print(snd(snd(c)),depth-1);
2289                 Putchar(')');
2290                 break;
2291         case STGPRIM:
2292                 Printf("StgPrim(");
2293                 print(fst(snd(c)),depth-1);
2294                 Putchar(',');
2295                 print(snd(snd(c)),depth-1);
2296                 Putchar(')');
2297                 break;
2298         case STGCON:
2299                 Printf("StgCon(");
2300                 print(fst(snd(c)),depth-1);
2301                 Putchar(',');
2302                 print(snd(snd(c)),depth-1);
2303                 Putchar(')');
2304                 break;
2305         case PRIMCASE:
2306                 Printf("PrimCase(");
2307                 print(fst(snd(c)),depth-1);
2308                 Putchar(',');
2309                 print(snd(snd(c)),depth-1);
2310                 Putchar(')');
2311                 break;
2312         case DICTAP:
2313                 Printf("(DICTAP,");
2314                 print(snd(c),depth-1);
2315                 Putchar(')');
2316                 break;
2317         case UNBOXEDTUP:
2318                 Printf("(UNBOXEDTUP,");
2319                 print(snd(c),depth-1);
2320                 Putchar(')');
2321                 break;
2322         case ZTUP2:
2323                 Printf("<ZPair ");
2324                 print(zfst(c),depth-1);
2325                 Putchar(' ');
2326                 print(zsnd(c),depth-1);
2327                 Putchar('>');
2328                 break;
2329         case ZTUP3:
2330                 Printf("<ZTriple ");
2331                 print(zfst3(c),depth-1);
2332                 Putchar(' ');
2333                 print(zsnd3(c),depth-1);
2334                 Putchar(' ');
2335                 print(zthd3(c),depth-1);
2336                 Putchar('>');
2337                 break;
2338         case BANG:
2339                 Printf("(BANG,");
2340                 print(snd(c),depth-1);
2341                 Putchar(')');
2342                 break;
2343         default:
2344                 if (isBoxTag(tag)) {
2345                     Printf("Tag(%d)=%d", c, tag);
2346                 } else if (isConTag(tag)) {
2347                     Printf("%d@(%d,",c,tag);
2348                     print(snd(c), depth-1);
2349                     Putchar(')');
2350                     break;
2351                 } else if (c == tag) {
2352                     Printf("Tag(%d)", c);
2353                 } else {
2354                     Printf("Tag(%d)=%d", c, tag);
2355                 }
2356                 break;
2357         }
2358     }
2359     FlushStdout();
2360 }
2361
2362
2363 Bool isVar(c)                           /* is cell a VARIDCELL/VAROPCELL ? */
2364 Cell c; {                               /* also recognises DICTVAR cells   */
2365     return isPair(c) &&
2366                (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2367 }
2368
2369 Bool isCon(c)                          /* is cell a CONIDCELL/CONOPCELL ?  */
2370 Cell c; {
2371     return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2372 }
2373
2374 Bool isQVar(c)                        /* is cell a [un]qualified varop/id? */
2375 Cell c; {
2376     if (!isPair(c)) return FALSE;
2377     switch (fst(c)) {
2378         case VARIDCELL  :
2379         case VAROPCELL  : return TRUE;
2380
2381         case QUALIDENT  : return isVar(snd(snd(c)));
2382
2383         default         : return FALSE;
2384     }
2385 }
2386
2387 Bool isQCon(c)                         /*is cell a [un]qualified conop/id? */
2388 Cell c; {
2389     if (!isPair(c)) return FALSE;
2390     switch (fst(c)) {
2391         case CONIDCELL  :
2392         case CONOPCELL  : return TRUE;
2393
2394         case QUALIDENT  : return isCon(snd(snd(c)));
2395
2396         default         : return FALSE;
2397     }
2398 }
2399
2400 Bool isQualIdent(c)                    /* is cell a qualified identifier?  */
2401 Cell c; {
2402     return isPair(c) && (fst(c)==QUALIDENT);
2403 }
2404
2405 Bool eqQualIdent ( QualId c1, QualId c2 )
2406 {
2407    assert(isQualIdent(c1));
2408    if (!isQualIdent(c2)) {
2409    assert(isQualIdent(c2));
2410    }
2411    return qmodOf(c1)==qmodOf(c2) &&
2412           qtextOf(c1)==qtextOf(c2);
2413 }
2414
2415 Bool isIdent(c)                        /* is cell an identifier?           */
2416 Cell c; {
2417     if (!isPair(c)) return FALSE;
2418     switch (fst(c)) {
2419         case VARIDCELL  :
2420         case VAROPCELL  :
2421         case CONIDCELL  :
2422         case CONOPCELL  : return TRUE;
2423
2424         case QUALIDENT  : return TRUE;
2425
2426         default         : return FALSE;
2427     }
2428 }
2429
2430 Bool isInt(c)                          /* cell holds integer value?        */
2431 Cell c; {
2432     return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2433 }
2434
2435 Int intOf(c)                           /* find integer value of cell?      */
2436 Cell c; {
2437     assert(isInt(c));
2438     return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
2439 }
2440
2441 Cell mkInt(n)                          /* make cell representing integer   */
2442 Int n; {
2443     return (MINSMALLINT <= n && n <= MAXSMALLINT)
2444            ? INTZERO+n
2445            : pair(INTCELL,n);
2446 }
2447
2448 #if SIZEOF_VOID_P == SIZEOF_INT
2449
2450 typedef union {Int i; Ptr p;} IntOrPtr;
2451
2452 Cell mkPtr(p)
2453 Ptr p;
2454 {
2455     IntOrPtr x;
2456     x.p = p;
2457     return pair(PTRCELL,x.i);
2458 }
2459
2460 Ptr ptrOf(c)
2461 Cell c;
2462 {
2463     IntOrPtr x;
2464     assert(fst(c) == PTRCELL);
2465     x.i = snd(c);
2466     return x.p;
2467 }
2468
2469 Cell mkCPtr(p)
2470 Ptr p;
2471 {
2472     IntOrPtr x;
2473     x.p = p;
2474     return pair(CPTRCELL,x.i);
2475 }
2476
2477 Ptr cptrOf(c)
2478 Cell c;
2479 {
2480     IntOrPtr x;
2481     assert(fst(c) == CPTRCELL);
2482     x.i = snd(c);
2483     return x.p;
2484 }
2485
2486 #elif SIZEOF_VOID_P == 2*SIZEOF_INT
2487
2488 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2489
2490 Cell mkPtr(p)
2491 Ptr p;
2492 {
2493     IntOrPtr x;
2494     x.p = p;
2495     return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2496 }
2497
2498 Ptr ptrOf(c)
2499 Cell c;
2500 {
2501     IntOrPtr x;
2502     assert(fst(c) == PTRCELL);
2503     x.i.i1 = intOf(fst(snd(c)));
2504     x.i.i2 = intOf(snd(snd(c)));
2505     return x.p;
2506 }
2507
2508 Cell mkCPtr(p)
2509 Ptr p;
2510 {
2511     IntOrPtr x;
2512     x.p = p;
2513     return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2514 }
2515
2516 Ptr cptrOf(c)
2517 Cell c;
2518 {
2519     IntOrPtr x;
2520     assert(fst(c) == CPTRCELL);
2521     x.i.i1 = intOf(fst(snd(c)));
2522     x.i.i2 = intOf(snd(snd(c)));
2523     return x.p;
2524 }
2525
2526 #else
2527
2528 #error "Can't implement mkPtr/ptrOf on this architecture."
2529
2530 #endif
2531
2532
2533 String stringNegate( s )
2534 String s;
2535 {
2536     if (s[0] == '-') {
2537         return &s[1];
2538     } else {
2539         static char t[100];
2540         t[0] = '-';
2541         strcpy(&t[1],s);  /* ToDo: use strncpy instead */
2542         return t;
2543     }
2544 }
2545
2546 /* --------------------------------------------------------------------------
2547  * List operations:
2548  * ------------------------------------------------------------------------*/
2549
2550 Int length(xs)                         /* calculate length of list xs      */
2551 List xs; {
2552     Int n = 0;
2553     for (; nonNull(xs); ++n)
2554         xs = tl(xs);
2555     return n;
2556 }
2557
2558 List appendOnto(xs,ys)                 /* Destructively prepend xs onto    */
2559 List xs, ys; {                         /* ys by modifying xs ...           */
2560     if (isNull(xs))
2561         return ys;
2562     else {
2563         List zs = xs;
2564         while (nonNull(tl(zs)))
2565             zs = tl(zs);
2566         tl(zs) = ys;
2567         return xs;
2568     }
2569 }
2570
2571 List dupOnto(xs,ys)      /* non-destructively prepend xs backwards onto ys */
2572 List xs; 
2573 List ys; {
2574     for (; nonNull(xs); xs=tl(xs))
2575         ys = cons(hd(xs),ys);
2576     return ys;
2577 }
2578
2579 List dupListOnto(xs,ys)              /* Duplicate spine of list xs onto ys */
2580 List xs;
2581 List ys; {
2582     return revOnto(dupOnto(xs,NIL),ys);
2583 }
2584
2585 List dupList(xs)                       /* Duplicate spine of list xs       */
2586 List xs; {
2587     List ys = NIL;
2588     for (; nonNull(xs); xs=tl(xs))
2589         ys = cons(hd(xs),ys);
2590     return rev(ys);
2591 }
2592
2593 List revOnto(xs,ys)                    /* Destructively reverse elements of*/
2594 List xs, ys; {                         /* list xs onto list ys...          */
2595     Cell zs;
2596
2597     while (nonNull(xs)) {
2598         zs     = tl(xs);
2599         tl(xs) = ys;
2600         ys     = xs;
2601         xs     = zs;
2602     }
2603     return ys;
2604 }
2605
2606 QualId qualidIsMember ( QualId q, List xs )
2607 {
2608    for (; nonNull(xs); xs=tl(xs)) {
2609       if (eqQualIdent(q, hd(xs)))
2610          return hd(xs);
2611    }
2612    return NIL;
2613 }  
2614
2615 Cell varIsMember(t,xs)                 /* Test if variable is a member of  */
2616 Text t;                                /* given list of variables          */
2617 List xs; {
2618     for (; nonNull(xs); xs=tl(xs))
2619         if (t==textOf(hd(xs)))
2620             return hd(xs);
2621     return NIL;
2622 }
2623
2624 Name nameIsMember(t,ns)                 /* Test if name with text t is a   */
2625 Text t;                                 /* member of list of names xs      */
2626 List ns; {
2627     for (; nonNull(ns); ns=tl(ns))
2628         if (t==name(hd(ns)).text)
2629             return hd(ns);
2630     return NIL;
2631 }
2632
2633 Cell intIsMember(n,xs)                 /* Test if integer n is member of   */
2634 Int  n;                                /* given list of integers           */
2635 List xs; {
2636     for (; nonNull(xs); xs=tl(xs))
2637         if (n==intOf(hd(xs)))
2638             return hd(xs);
2639     return NIL;
2640 }
2641
2642 Cell cellIsMember(x,xs)                /* Test for membership of specific  */
2643 Cell x;                                /* cell x in list xs                */
2644 List xs; {
2645     for (; nonNull(xs); xs=tl(xs))
2646         if (x==hd(xs))
2647             return hd(xs);
2648     return NIL;
2649 }
2650
2651 Cell cellAssoc(c,xs)                   /* Lookup cell in association list  */
2652 Cell c;         
2653 List xs; {
2654     for (; nonNull(xs); xs=tl(xs))
2655         if (c==fst(hd(xs)))
2656             return hd(xs);
2657     return NIL;
2658 }
2659
2660 Cell cellRevAssoc(c,xs)                /* Lookup cell in range of          */
2661 Cell c;                                /* association lists                */
2662 List xs; {
2663     for (; nonNull(xs); xs=tl(xs))
2664         if (c==snd(hd(xs)))
2665             return hd(xs);
2666     return NIL;
2667 }
2668
2669 List replicate(n,x)                     /* create list of n copies of x    */
2670 Int n;
2671 Cell x; {
2672     List xs=NIL;
2673     while (0<n--)
2674         xs = cons(x,xs);
2675     return xs;
2676 }
2677
2678 List diffList(from,take)               /* list difference: from\take       */
2679 List from, take; {                     /* result contains all elements of  */
2680     List result = NIL;                 /* `from' not appearing in `take'   */
2681
2682     while (nonNull(from)) {
2683         List next = tl(from);
2684         if (!cellIsMember(hd(from),take)) {
2685             tl(from) = result;
2686             result   = from;
2687         }
2688         from = next;
2689     }
2690     return rev(result);
2691 }
2692
2693 List deleteCell(xs, y)                  /* copy xs deleting pointers to y  */
2694 List xs;
2695 Cell y; {
2696     List result = NIL; 
2697     for(;nonNull(xs);xs=tl(xs)) {
2698         Cell x = hd(xs);
2699         if (x != y) {
2700             result=cons(x,result);
2701         }
2702     }
2703     return rev(result);
2704 }
2705
2706 List take(n,xs)                         /* destructively truncate list to  */
2707 Int  n;                                 /* specified length                */
2708 List xs; {
2709     List ys = xs;
2710
2711     if (n==0)
2712         return NIL;
2713     while (1<n-- && nonNull(xs))
2714         xs = tl(xs);
2715     if (nonNull(xs))
2716         tl(xs) = NIL;
2717     return ys;
2718 }
2719
2720 List splitAt(n,xs)                      /* drop n things from front of list*/
2721 Int  n;       
2722 List xs; {
2723     for(; n>0; --n) {
2724         xs = tl(xs);
2725     }
2726     return xs;
2727 }
2728
2729 Cell nth(n,xs)                          /* extract n'th element of list    */
2730 Int  n;
2731 List xs; {
2732     for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2733     }
2734     if (isNull(xs))
2735         internal("nth");
2736     return hd(xs);
2737 }
2738
2739 List removeCell(x,xs)                   /* destructively remove cell from  */
2740 Cell x;                                 /* list                            */
2741 List xs; {
2742     if (nonNull(xs)) {
2743         if (hd(xs)==x)
2744             return tl(xs);              /* element at front of list        */
2745         else {
2746             List prev = xs;
2747             List curr = tl(xs);
2748             for (; nonNull(curr); prev=curr, curr=tl(prev))
2749                 if (hd(curr)==x) {
2750                     tl(prev) = tl(curr);
2751                     return xs;          /* element in middle of list       */
2752                 }
2753         }
2754     }
2755     return xs;                          /* here if element not found       */
2756 }
2757
2758 List nubList(xs)                        /* nuke dups in list               */
2759 List xs; {                              /* non destructive                 */
2760    List outs = NIL;
2761    for (; nonNull(xs); xs=tl(xs))
2762       if (isNull(cellIsMember(hd(xs),outs)))
2763          outs = cons(hd(xs),outs);
2764    outs = rev(outs);
2765    return outs;
2766 }
2767
2768
2769 /* --------------------------------------------------------------------------
2770  * Strongly-typed lists (z-lists) and tuples (experimental)
2771  * ------------------------------------------------------------------------*/
2772
2773 static void z_tag_check ( Cell x, int tag, char* caller )
2774 {
2775    char buf[100];
2776    if (isNull(x)) {
2777       sprintf(buf,"z_tag_check(%s): null\n", caller);
2778       internal(buf);
2779    }
2780    if (whatIs(x) != tag) {
2781       sprintf(buf, 
2782           "z_tag_check(%s): tag was %d, expected %d\n",
2783           caller, whatIs(x), tag );
2784       internal(buf);
2785    }  
2786 }
2787
2788 #if 0
2789 Cell zcons ( Cell x, Cell xs )
2790 {
2791    if (!(isNull(xs) || whatIs(xs)==ZCONS)) 
2792       internal("zcons: ill typed tail");
2793    return ap(ZCONS,ap(x,xs));
2794 }
2795
2796 Cell zhd ( Cell xs )
2797 {
2798    if (isNull(xs)) internal("zhd: empty list");
2799    z_tag_check(xs,ZCONS,"zhd");
2800    return fst( snd(xs) );
2801 }
2802
2803 Cell ztl ( Cell xs )
2804 {
2805    if (isNull(xs)) internal("ztl: empty list");
2806    z_tag_check(xs,ZCONS,"zhd");
2807    return snd( snd(xs) );
2808 }
2809
2810 Int zlength ( ZList xs )
2811 {
2812    Int n = 0;
2813    while (nonNull(xs)) {
2814       z_tag_check(xs,ZCONS,"zlength");
2815       n++;
2816       xs = snd( snd(xs) );
2817    }
2818    return n;
2819 }
2820
2821 ZList zreverse ( ZList xs )
2822 {
2823    ZList rev = NIL;
2824    while (nonNull(xs)) {
2825       z_tag_check(xs,ZCONS,"zreverse");
2826       rev = zcons(zhd(xs),rev);
2827       xs = ztl(xs);
2828    }
2829    return rev;
2830 }
2831
2832 Cell zsingleton ( Cell x )
2833 {
2834    return zcons (x,NIL);
2835 }
2836
2837 Cell zdoubleton ( Cell x, Cell y )
2838 {
2839    return zcons(x,zcons(y,NIL));
2840 }
2841 #endif
2842
2843 Cell zpair ( Cell x1, Cell x2 )
2844 { return ap(ZTUP2,ap(x1,x2)); }
2845 Cell zfst ( Cell zpair )
2846 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2847 Cell zsnd ( Cell zpair )
2848 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2849
2850 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2851 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2852 Cell zfst3 ( Cell zpair )
2853 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2854 Cell zsnd3 ( Cell zpair )
2855 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2856 Cell zthd3 ( Cell zpair )
2857 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2858
2859 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2860 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2861 Cell zsel14 ( Cell zpair )
2862 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2863 Cell zsel24 ( Cell zpair )
2864 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2865 Cell zsel34 ( Cell zpair )
2866 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2867 Cell zsel44 ( Cell zpair )
2868 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2869
2870 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2871 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2872 Cell zsel15 ( Cell zpair )
2873 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2874 Cell zsel25 ( Cell zpair )
2875 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2876 Cell zsel35 ( Cell zpair )
2877 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2878 Cell zsel45 ( Cell zpair )
2879 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2880 Cell zsel55 ( Cell zpair )
2881 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2882
2883
2884 Cell unap ( int tag, Cell c )
2885 {
2886    char buf[100];
2887    if (whatIs(c) != tag) {
2888       sprintf(buf, "unap: specified %d, actual %d\n",
2889                    tag, whatIs(c) );
2890       internal(buf);
2891    }
2892    return snd(c);
2893 }
2894
2895 /* --------------------------------------------------------------------------
2896  * Operations on applications:
2897  * ------------------------------------------------------------------------*/
2898
2899 Int argCount;                          /* number of args in application    */
2900
2901 Cell getHead(e)                        /* get head cell of application     */
2902 Cell e; {                              /* set number of args in argCount   */
2903     for (argCount=0; isAp(e); e=fun(e))
2904         argCount++;
2905     return e;
2906 }
2907
2908 List getArgs(e)                        /* get list of arguments in function*/
2909 Cell e; {                              /* application:                     */
2910     List as;                           /* getArgs(f e1 .. en) = [e1,..,en] */
2911
2912     for (as=NIL; isAp(e); e=fun(e))
2913         as = cons(arg(e),as);
2914     return as;
2915 }
2916
2917 Cell nthArg(n,e)                       /* return nth arg in application    */
2918 Int  n;                                /* of function to m args (m>=n)     */
2919 Cell e; {                              /* nthArg n (f x0 x1 ... xm) = xn   */
2920     for (n=numArgs(e)-n-1; n>0; n--)
2921         e = fun(e);
2922     return arg(e);
2923 }
2924
2925 Int numArgs(e)                         /* find number of arguments to expr */
2926 Cell e; {
2927     Int n;
2928     for (n=0; isAp(e); e=fun(e))
2929         n++;
2930     return n;
2931 }
2932
2933 Cell applyToArgs(f,args)               /* destructively apply list of args */
2934 Cell f;                                /* to function f                    */
2935 List args; {
2936     while (nonNull(args)) {
2937         Cell temp = tl(args);
2938         tl(args)  = hd(args);
2939         hd(args)  = f;
2940         f         = args;
2941         args      = temp;
2942     }
2943     return f;
2944 }
2945
2946 /* --------------------------------------------------------------------------
2947  * debugging support
2948  * ------------------------------------------------------------------------*/
2949
2950 static String maybeModuleStr ( Module m )
2951 {
2952    if (isModule(m)) return textToStr(module(m).text); else return "??";
2953 }
2954
2955 static String maybeNameStr ( Name n )
2956 {
2957    if (isName(n)) return textToStr(name(n).text); else return "??";
2958 }
2959
2960 static String maybeTyconStr ( Tycon t )
2961 {
2962    if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
2963 }
2964
2965 static String maybeClassStr ( Class c )
2966 {
2967    if (isClass(c)) return textToStr(cclass(c).text); else return "??";
2968 }
2969
2970 static String maybeText ( Text t )
2971 {
2972    if (isNull(t)) return "(nil)";
2973    return textToStr(t);
2974 }
2975
2976 static void print100 ( Int x )
2977 {
2978    print ( x, 100); printf("\n");
2979 }
2980
2981 void dumpTycon ( Int t )
2982 {
2983    if (isTycon(TYCMIN+t) && !isTycon(t)) t += TYCMIN;
2984    if (!isTycon(t)) {
2985       printf ( "dumpTycon %d: not a tycon\n", t);
2986       return;
2987    }
2988    printf ( "{\n" );
2989    printf ( "    text: %s\n",     textToStr(tycon(t).text) );
2990    printf ( "    line: %d\n",     tycon(t).line );
2991    printf ( "     mod: %s\n",     maybeModuleStr(tycon(t).mod));
2992    printf ( "   tuple: %d\n",     tycon(t).tuple);
2993    printf ( "   arity: %d\n",     tycon(t).arity);
2994    printf ( "    kind: ");        print100(tycon(t).kind);
2995    printf ( "    what: %d\n",     tycon(t).what);
2996    printf ( "    defn: ");        print100(tycon(t).defn);
2997    printf ( "    cToT: %d %s\n",  tycon(t).conToTag, 
2998                                   maybeNameStr(tycon(t).conToTag));
2999    printf ( "    tToC: %d %s\n",  tycon(t).tagToCon, 
3000                                   maybeNameStr(tycon(t).tagToCon));
3001    printf ( "    itbl: %p\n",     tycon(t).itbl);
3002    printf ( "  nextTH: %d %s\n",  tycon(t).nextTyconHash,
3003                                   maybeTyconStr(tycon(t).nextTyconHash));
3004    printf ( "}\n" );
3005 }
3006
3007 void dumpName ( Int n )
3008 {
3009    if (isName(NAMEMIN+n) && !isName(n)) n += NAMEMIN;
3010    if (!isName(n)) {
3011       printf ( "dumpName %d: not a name\n", n);
3012       return;
3013    }
3014    printf ( "{\n" );
3015    printf ( "    text: %s\n",     textToStr(name(n).text) );
3016    printf ( "    line: %d\n",     name(n).line );
3017    printf ( "     mod: %s\n",     maybeModuleStr(name(n).mod));
3018    printf ( "  syntax: %d\n",     name(n).syntax );
3019    printf ( "  parent: %d\n",     name(n).parent );
3020    printf ( "   arity: %d\n",     name(n).arity );
3021    printf ( "  number: %d\n",     name(n).number );
3022    printf ( "    type: ");        print100(name(n).type);
3023    printf ( "    defn: %d\n",     name(n).defn );
3024    printf ( "  stgVar: ");        print100(name(n).stgVar);
3025    printf ( "   cconv: %d\n",     name(n).callconv );
3026    printf ( "  primop: %p\n",     name(n).primop );
3027    printf ( "    itbl: %p\n",     name(n).itbl );
3028    printf ( "  nextNH: %d\n",     name(n).nextNameHash );
3029    printf ( "}\n" );
3030 }
3031
3032
3033 void dumpClass ( Int c )
3034 {
3035    if (isClass(CLASSMIN+c) && !isClass(c)) c += CLASSMIN;
3036    if (!isClass(c)) {
3037       printf ( "dumpClass %d: not a class\n", c);
3038       return;
3039    }
3040    printf ( "{\n" );
3041    printf ( "    text: %s\n",     textToStr(cclass(c).text) );
3042    printf ( "    line: %d\n",     cclass(c).line );
3043    printf ( "     mod: %s\n",     maybeModuleStr(cclass(c).mod));
3044    printf ( "   arity: %d\n",     cclass(c).arity );
3045    printf ( "   level: %d\n",     cclass(c).level );
3046    printf ( "   kinds: ");        print100( cclass(c).kinds );
3047    printf ( "     fds: %d\n",     cclass(c).fds );
3048    printf ( "    xfds: %d\n",     cclass(c).xfds );
3049    printf ( "    head: ");        print100( cclass(c).head );
3050    printf ( "    dcon: ");        print100( cclass(c).dcon );
3051    printf ( "  supers: ");        print100( cclass(c).supers );
3052    printf ( " #supers: %d\n",     cclass(c).numSupers );
3053    printf ( "   dsels: ");        print100( cclass(c).dsels );
3054    printf ( " members: ");        print100( cclass(c).members );
3055    printf ( "#members: %d\n",     cclass(c).numMembers );
3056    printf ( "defaults: ");        print100( cclass(c).defaults );
3057    printf ( "   insts: ");        print100( cclass(c).instances );
3058    printf ( "}\n" );
3059 }
3060
3061
3062 void dumpInst ( Int i )
3063 {
3064    if (isInst(INSTMIN+i) && !isInst(i)) i += INSTMIN;
3065    if (!isInst(i)) {
3066       printf ( "dumpInst %d: not an instance\n", i);
3067       return;
3068    }
3069    printf ( "{\n" );
3070    printf ( "   class: %s\n",     maybeClassStr(inst(i).c) );
3071    printf ( "    line: %d\n",     inst(i).line );
3072    printf ( "     mod: %s\n",     maybeModuleStr(inst(i).mod));
3073    printf ( "   kinds: ");        print100( inst(i).kinds );
3074    printf ( "    head: ");        print100( inst(i).head );
3075    printf ( "   specs: ");        print100( inst(i).specifics );
3076    printf ( "  #specs: %d\n",     inst(i).numSpecifics );
3077    printf ( "   impls: ");        print100( inst(i).implements );
3078    printf ( " builder: %s\n",     maybeNameStr( inst(i).builder ) );
3079    printf ( "}\n" );
3080 }
3081
3082
3083 /* --------------------------------------------------------------------------
3084  * storage control:
3085  * ------------------------------------------------------------------------*/
3086
3087 #if DYN_TABLES
3088 static void far* safeFarCalloc Args((Int,Int));
3089 static void far* safeFarCalloc(n,s)     /* allocate table storage and check*/
3090 Int n, s; {                             /* for non-null return             */
3091     void far* tab = farCalloc(n,s);
3092     if (tab==0) {
3093         ERRMSG(0) "Cannot allocate run-time tables"
3094         EEND;
3095     }
3096     return tab;
3097 }
3098 #define TABALLOC(v,t,n)                 v=(t far*)safeFarCalloc(n,sizeof(t));
3099 #else
3100 #define TABALLOC(v,t,n)
3101 #endif
3102
3103 Void storage(what)
3104 Int what; {
3105     Int i;
3106
3107     switch (what) {
3108         case POSTPREL: break;
3109
3110         case RESET   : clearStack();
3111
3112                        /* the next 2 statements are particularly important
3113                         * if you are using GLOBALfst or GLOBALsnd since the
3114                         * corresponding registers may be reset to their
3115                         * uninitialised initial values by a longjump.
3116                         */
3117                        heapTopFst = heapFst + heapSize;
3118                        heapTopSnd = heapSnd + heapSize;
3119                        consGC = TRUE;
3120                        lsave  = NIL;
3121                        rsave  = NIL;
3122                        if (isNull(lastExprSaved))
3123                            savedText = NUM_TEXT;
3124                        break;
3125
3126         case MARK    : 
3127                        start();
3128                        for (i=NAMEMIN; i<nameHw; ++i) {
3129                            mark(name(i).parent);
3130                            mark(name(i).defn);
3131                            mark(name(i).stgVar);
3132                            mark(name(i).type);
3133                         }
3134                        end("Names", nameHw-NAMEMIN);
3135
3136                        start();
3137                        for (i=MODMIN; i<moduleHw; ++i) {
3138                            mark(module(i).tycons);
3139                            mark(module(i).names);
3140                            mark(module(i).classes);
3141                            mark(module(i).exports);
3142                            mark(module(i).qualImports);
3143                            mark(module(i).objectExtraNames);
3144                        }
3145                        end("Modules", moduleHw-MODMIN);
3146
3147                        start();
3148                        for (i=TYCMIN; i<tyconHw; ++i) {
3149                            mark(tycon(i).defn);
3150                            mark(tycon(i).kind);
3151                            mark(tycon(i).what);
3152                        }
3153                        end("Type constructors", tyconHw-TYCMIN);
3154
3155                        start();
3156                        for (i=CLASSMIN; i<classHw; ++i) {
3157                            mark(cclass(i).head);
3158                            mark(cclass(i).kinds);
3159                            mark(cclass(i).fds);
3160                            mark(cclass(i).xfds);
3161                            mark(cclass(i).dsels);
3162                            mark(cclass(i).supers);
3163                            mark(cclass(i).members);
3164                            mark(cclass(i).defaults);
3165                            mark(cclass(i).instances);
3166                        }
3167                        mark(classes);
3168                        end("Classes", classHw-CLASSMIN);
3169
3170                        start();
3171                        for (i=INSTMIN; i<instHw; ++i) {
3172                            mark(inst(i).head);
3173                            mark(inst(i).kinds);
3174                            mark(inst(i).specifics);
3175                            mark(inst(i).implements);
3176                        }
3177                        end("Instances", instHw-INSTMIN);
3178
3179                        start();
3180                        for (i=0; i<=sp; ++i)
3181                            mark(stack(i));
3182                        end("Stack", sp+1);
3183
3184                        start();
3185                        mark(lastExprSaved);
3186                        mark(lsave);
3187                        mark(rsave);
3188                        end("Last expression", 3);
3189
3190                        if (consGC) {
3191                            start();
3192                            gcCStack();
3193                            end("C stack", stackRoots);
3194                        }
3195
3196                        break;
3197
3198         case PREPREL : heapFst = heapAlloc(heapSize);
3199                        heapSnd = heapAlloc(heapSize);
3200
3201                        if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3202                            ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3203                                      heapSize
3204                            EEND;
3205                        }
3206
3207                        heapTopFst = heapFst + heapSize;
3208                        heapTopSnd = heapSnd + heapSize;
3209                        for (i=1; i<heapSize; ++i) {
3210                            fst(-i) = FREECELL;
3211                            snd(-i) = -(i+1);
3212                        }
3213                        snd(-heapSize) = NIL;
3214                        freeList  = -1;
3215                        numGcs    = 0;
3216                        consGC    = TRUE;
3217                        lsave     = NIL;
3218                        rsave     = NIL;
3219
3220                        marksSize  = bitArraySize(heapSize);
3221                        if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3222                            ERRMSG(0) "Unable to allocate gc markspace"
3223                            EEND;
3224                        }
3225
3226                        TABALLOC(text,      char,             NUM_TEXT)
3227                        TABALLOC(tyconHash, Tycon,            TYCONHSZ)
3228                        TABALLOC(tabTycon,  struct strTycon,  NUM_TYCON)
3229                        TABALLOC(nameHash,  Name,             NAMEHSZ)
3230                        TABALLOC(tabName,   struct strName,   NUM_NAME)
3231                        TABALLOC(tabClass,  struct strClass,  NUM_CLASSES)
3232                        TABALLOC(cellStack, Cell,             NUM_STACK)
3233                        TABALLOC(tabModule, struct Module,    NUM_SCRIPTS)
3234 #if TREX
3235                        TABALLOC(tabExt,    Text,             NUM_EXT)
3236 #endif
3237                        clearStack();
3238
3239                        textHw        = 0;
3240                        nextNewText   = NUM_TEXT;
3241                        nextNewDText  = (-1);
3242                        lastExprSaved = NIL;
3243                        savedText     = NUM_TEXT;
3244                        for (i=0; i<TEXTHSZ; ++i)
3245                            textHash[i][0] = NOTEXT;
3246
3247
3248                        moduleHw = MODMIN;
3249
3250                        tyconHw  = TYCMIN;
3251                        for (i=0; i<TYCONHSZ; ++i)
3252                            tyconHash[i] = NIL;
3253 #if TREX
3254                        extHw    = EXTMIN;
3255 #endif
3256
3257                        nameHw   = NAMEMIN;
3258                        for (i=0; i<NAMEHSZ; ++i)
3259                            nameHash[i] = NIL;
3260
3261                        classHw  = CLASSMIN;
3262
3263                        instHw   = INSTMIN;
3264
3265 #if USE_DICTHW
3266                        dictHw   = 0;
3267 #endif
3268
3269                        tabInst  = (struct strInst far *)
3270                                     farCalloc(NUM_INSTS,sizeof(struct strInst));
3271
3272                        if (tabInst==0) {
3273                            ERRMSG(0) "Cannot allocate instance tables"
3274                            EEND;
3275                        }
3276
3277                        scriptHw = 0;
3278
3279                        break;
3280     }
3281 }
3282
3283 /*-------------------------------------------------------------------------*/