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