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