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