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