[project @ 2000-04-17 11:39:23 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.71 $
13  * $Date: 2000/04/14 15:18:06 $
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    /* fprintf ( stderr, "NUKE MODULE %s\n", textToStr(module(m).text) ); */
1644
1645    /* see comment in compiler.c about this, 
1646       and interaction with info tables */
1647    if (nukeModule_needs_major_gc) {
1648       /* fprintf ( stderr, "doing major GC in nukeModule\n"); */
1649       /* performMajorGC(); */
1650       nukeModule_needs_major_gc = FALSE;
1651    }
1652
1653    oc = module(m).object;
1654    while (oc) {
1655       oc2 = oc->next;
1656       ocFree(oc);
1657       oc = oc2;
1658    }
1659    oc = module(m).objectExtras;
1660    while (oc) {
1661       oc2 = oc->next;
1662       ocFree(oc);
1663       oc = oc2;
1664    }
1665
1666    for (i = NAME_BASE_ADDR; i < NAME_BASE_ADDR+tabNameSz; i++)
1667       if (tabName[i-NAME_BASE_ADDR].inUse && name(i).mod == m) {
1668          if (name(i).itbl && 
1669              module(name(i).mod).mode == FM_SOURCE) {
1670             free(name(i).itbl);
1671          }
1672          name(i).itbl = NULL;
1673          freeName(i);
1674       }
1675
1676    for (i = TYCON_BASE_ADDR; i < TYCON_BASE_ADDR+tabTyconSz; i++)
1677       if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).mod == m) {
1678          if (tycon(i).itbl &&
1679              module(tycon(i).mod).mode == FM_SOURCE) {
1680             free(tycon(i).itbl);
1681          }
1682          tycon(i).itbl = NULL;
1683          freeTycon(i);
1684       }
1685
1686    for (i = CCLASS_BASE_ADDR; i < CCLASS_BASE_ADDR+tabClassSz; i++)
1687       if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
1688          if (cclass(i).mod == m) {
1689             freeClass(i);
1690          } else {
1691             List /* Inst */ ins;
1692             List /* Inst */ ins2 = NIL;
1693             for (ins = cclass(i).instances; nonNull(ins); ins=tl(ins))
1694                if (inst(hd(ins)).mod != m) 
1695                   ins2 = cons(hd(ins),ins2);
1696             cclass(i).instances = ins2;
1697          }
1698       }
1699
1700
1701    for (i = INST_BASE_ADDR; i < INST_BASE_ADDR+tabInstSz; i++)
1702       if (tabInst[i-INST_BASE_ADDR].inUse && inst(i).mod == m)
1703          freeInst(i);
1704
1705    freeModule(m);
1706    //for (i = 0; i < TYCONHSZ; i++) tyconHash[i] = 0;
1707    //for (i = 0; i < NAMEHSZ; i++)  nameHash[i] = 0;
1708    //classes = NIL;
1709    //hashSanity();
1710 }
1711
1712 void ppModules ( void )
1713 {
1714    Int i;
1715    fflush(stderr); fflush(stdout);
1716    printf ( "begin MODULES\n" );
1717    for (i  = MODULE_BASE_ADDR+tabModuleSz-1;
1718         i >= MODULE_BASE_ADDR; i--)
1719       if (tabModule[i-MODULE_BASE_ADDR].inUse)
1720          printf ( " %2d: %16s\n",
1721                   i-MODULE_BASE_ADDR, textToStr(module(i).text)
1722                 );
1723    printf ( "end   MODULES\n" );
1724    fflush(stderr); fflush(stdout);
1725 }
1726
1727
1728 Module findModule(t)                    /* locate Module in module table  */
1729 Text t; {
1730     Module m;
1731     for(m = MODULE_BASE_ADDR; 
1732         m < MODULE_BASE_ADDR+tabModuleSz; ++m) {
1733         if (tabModule[m-MODULE_BASE_ADDR].inUse)
1734             if (module(m).text==t)
1735                 return m;
1736     }
1737     return NIL;
1738 }
1739
1740 Module findModid(c)                    /* Find module by name or filename  */
1741 Cell c; {
1742     switch (whatIs(c)) {
1743         case STRCELL   : internal("findModid-STRCELL unimp");
1744         case CONIDCELL : return findModule(textOf(c));
1745         default        : internal("findModid");
1746     }
1747     return NIL;/*NOTUSED*/
1748 }
1749
1750 static local Module findQualifier(t)    /* locate Module in import list   */
1751 Text t; {
1752     Module ms;
1753     for (ms=module(currentModule).qualImports; nonNull(ms); ms=tl(ms)) {
1754         if (textOf(fst(hd(ms)))==t)
1755             return snd(hd(ms));
1756     }
1757     if (module(currentModule).text==t)
1758         return currentModule;
1759     return NIL;
1760 }
1761
1762 Void setCurrModule(m)              /* set lookup tables for current module */
1763 Module m; {
1764     Int i;
1765     assert(isModule(m));
1766     /* fprintf(stderr, "SET CURR MODULE %s %d\n", textToStr(module(m).text),m); */
1767     {List t;
1768      for (t = module(m).names; nonNull(t); t=tl(t))
1769         assert(isName(hd(t)));
1770      for (t = module(m).tycons; nonNull(t); t=tl(t))
1771         assert(isTycon(hd(t)) || isTuple(hd(t)));
1772      for (t = module(m).classes; nonNull(t); t=tl(t))
1773         assert(isClass(hd(t)));
1774     }
1775
1776     currentModule = m; /* This is the only assignment to currentModule */
1777     for (i=0; i<TYCONHSZ; ++i)
1778        tyconHash[RC_T(i)] = NIL;
1779     mapProc(hashTycon,module(m).tycons);
1780     for (i=0; i<NAMEHSZ; ++i)
1781        nameHash[RC_N(i)] = NIL;
1782     mapProc(hashName,module(m).names);
1783     classes = module(m).classes;
1784     hashSanity();
1785 }
1786
1787 Name jrsFindQualName ( Text mn, Text sn )
1788 {
1789    Module m;
1790    List   ns;
1791
1792    for (m = MODULE_BASE_ADDR; 
1793         m < MODULE_BASE_ADDR+tabModuleSz; m++)
1794       if (tabModule[m-MODULE_BASE_ADDR].inUse 
1795           && module(m).text == mn) break;
1796
1797    if (m == MODULE_BASE_ADDR+tabModuleSz) return NIL;
1798    
1799    for (ns = module(m).names; nonNull(ns); ns=tl(ns)) 
1800       if (name(hd(ns)).text == sn) return hd(ns);
1801
1802    return NIL;
1803 }
1804
1805
1806 char* nameFromOPtr ( void* p )
1807 {
1808    int i;
1809    Module m;
1810    for (m = MODULE_BASE_ADDR; 
1811         m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1812       if (tabModule[m-MODULE_BASE_ADDR].inUse && module(m).object) {
1813          char* nm = ocLookupAddr ( module(m).object, p );
1814          if (nm) return nm;
1815       }
1816    }
1817 #  if 0
1818    /* A kludge to assist Win32 debugging; not actually necessary. */
1819    { char* nm = nameFromStaticOPtr(p);
1820      if (nm) return nm;
1821    }
1822 #  endif
1823    return NULL;
1824 }
1825
1826
1827 void* lookupOTabName ( Module m, char* sym )
1828 {
1829    assert(isModule(m));
1830    if (module(m).object)
1831       return ocLookupSym ( module(m).object, sym );
1832    return NULL;
1833 }
1834
1835
1836 void* lookupOExtraTabName ( char* sym )
1837 {
1838    ObjectCode* oc;
1839    Module      m;
1840    for (m = MODULE_BASE_ADDR; 
1841         m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1842       if (tabModule[m-MODULE_BASE_ADDR].inUse)
1843          for (oc = module(m).objectExtras; oc; oc=oc->next) {
1844             void* ad = ocLookupSym ( oc, sym );
1845             if (ad) return ad;
1846          }
1847    }
1848    return NULL;
1849 }
1850
1851
1852 /* Only call this if in dire straits; searches every object symtab
1853    in the system -- so is therefore slow.
1854 */
1855 void* lookupOTabNameAbsolutelyEverywhere ( char* sym )
1856 {
1857    ObjectCode* oc;
1858    Module      m;
1859    void*       ad;
1860    for (m = MODULE_BASE_ADDR; 
1861         m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1862       if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1863          if (module(m).object) {
1864             ad = ocLookupSym ( module(m).object, sym );
1865             if (ad) return ad;
1866          }
1867          for (oc = module(m).objectExtras; oc; oc=oc->next) {
1868             ad = ocLookupSym ( oc, sym );
1869             if (ad) return ad;
1870          }
1871       }
1872    }
1873    return NULL;
1874 }
1875
1876
1877 OSectionKind lookupSection ( void* ad )
1878 {
1879    int          i;
1880    Module       m;
1881    ObjectCode*  oc;
1882    OSectionKind sect;
1883
1884    for (m = MODULE_BASE_ADDR; 
1885         m < MODULE_BASE_ADDR+tabModuleSz; m++) {
1886       if (tabModule[m-MODULE_BASE_ADDR].inUse) {
1887          if (module(m).object) {
1888             sect = ocLookupSection ( module(m).object, ad );
1889             if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1890                return sect;
1891          }
1892          for (oc = module(m).objectExtras; oc; oc=oc->next) {
1893             sect = ocLookupSection ( oc, ad );
1894             if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
1895                return sect;
1896          }
1897       }
1898    }
1899    return HUGS_SECTIONKIND_OTHER;
1900 }
1901
1902
1903 /* --------------------------------------------------------------------------
1904  * Heap storage:
1905  *
1906  * Provides a garbage collectable heap for storage of expressions etc.
1907  *
1908  * Now incorporates a flat resource:  A two-space collected extension of
1909  * the heap that provides storage for contiguous arrays of Cell storage,
1910  * cooperating with the garbage collection mechanisms for the main heap.
1911  * ------------------------------------------------------------------------*/
1912
1913 Int     heapSize = DEFAULTHEAP;         /* number of cells in heap         */
1914 Heap    heapFst;                        /* array of fst component of pairs */
1915 Heap    heapSnd;                        /* array of snd component of pairs */
1916 Heap    heapTopFst;
1917 Heap    heapTopSnd;
1918 Bool    consGC = TRUE;                  /* Set to FALSE to turn off gc from*/
1919                                         /* C stack; use with extreme care! */
1920 Long    numCells;
1921 Int     numGcs;                         /* number of garbage collections   */
1922 Int     cellsRecovered;                 /* number of cells recovered       */
1923
1924 static  Cell freeList;                  /* free list of unused cells       */
1925 static  Cell lsave, rsave;              /* save components of pair         */
1926
1927 #if GC_STATISTICS
1928
1929 static Int markCount, stackRoots;
1930
1931 #define initStackRoots() stackRoots = 0
1932 #define recordStackRoot() stackRoots++
1933
1934 #define startGC()       \
1935     if (gcMessages) {   \
1936         Printf("\n");   \
1937         fflush(stdout); \
1938     }
1939 #define endGC()         \
1940     if (gcMessages) {   \
1941         Printf("\n");   \
1942         fflush(stdout); \
1943     }
1944
1945 #define start()      markCount = 0
1946 #define end(thing,rs) \
1947     if (gcMessages) { \
1948         Printf("GC: %-18s: %4d cells, %4d roots.\n", thing, markCount, rs); \
1949         fflush(stdout); \
1950     }
1951 #define recordMark() markCount++
1952
1953 #else /* !GC_STATISTICS */
1954
1955 #define startGC()
1956 #define endGC()
1957
1958 #define initStackRoots()
1959 #define recordStackRoot()
1960
1961 #define start()   
1962 #define end(thing,root) 
1963 #define recordMark() 
1964
1965 #endif /* !GC_STATISTICS */
1966
1967 Cell pair(l,r)                          /* Allocate pair (l, r) from       */
1968 Cell l, r; {                            /* heap, garbage collecting first  */
1969     Cell c = freeList;                  /* if necessary ...                */
1970     if (isNull(c)) {
1971         lsave = l;
1972         rsave = r;
1973         garbageCollect();
1974         l     = lsave;
1975         lsave = NIL;
1976         r     = rsave;
1977         rsave = NIL;
1978         c     = freeList;
1979     }
1980     freeList = snd(freeList);
1981     fst(c)   = l;
1982     snd(c)   = r;
1983     numCells++;
1984     return c;
1985 }
1986
1987 static Int *marks;
1988 static Int marksSize;
1989
1990 void mark ( Cell root )
1991 {
1992    Cell c;
1993    Cell mstack[NUM_MSTACK];
1994    Int  msp     = -1;
1995    Int  msp_max = -1;
1996
1997    mstack[++msp] = root;
1998
1999    while (msp >= 0) {
2000       if (msp > msp_max) msp_max = msp;
2001       c = mstack[msp--];
2002       if (!isGenPair(c)) continue;
2003       if (fst(c)==FREECELL) continue;
2004       {
2005          register int place = placeInSet(c);
2006          register int mask  = maskInSet(c);
2007          if (!(marks[place]&mask)) {
2008             marks[place] |= mask;
2009             if (msp >= NUM_MSTACK-5) {
2010                fprintf ( stderr, 
2011                          "hugs: fatal stack overflow during GC.  "
2012                          "Increase NUM_MSTACK.\n" );
2013                exit(9);
2014             }
2015             mstack[++msp] = fst(c);
2016             mstack[++msp] = snd(c);
2017          }
2018       }
2019    }
2020    //   fprintf(stderr, "%d ",msp_max);
2021 }
2022
2023
2024 Void garbageCollect()     {             /* Run garbage collector ...       */
2025                                         /* disable break checking          */
2026     Int i,j;
2027     register Int mask;
2028     register Int place;
2029     Int      recovered;
2030     jmp_buf  regs;                      /* save registers on stack         */
2031     HugsBreakAction oldBrk
2032        = setBreakAction ( HugsIgnoreBreak );
2033
2034     setjmp(regs);
2035
2036     gcStarted();
2037
2038     for (i=0; i<marksSize; ++i)         /* initialise mark set to empty    */
2039         marks[i] = 0;
2040
2041     everybody(MARK);                    /* Mark all components of system   */
2042
2043     gcScanning();                       /* scan mark set                   */
2044     mask      = 1;
2045     place     = 0;
2046     recovered = 0;
2047     j         = 0;
2048
2049     freeList = NIL;
2050     for (i=1; i<=heapSize; i++) {
2051         if ((marks[place] & mask) == 0) {
2052             snd(-i)  = freeList;
2053             fst(-i)  = FREECELL;
2054             freeList = -i;
2055             recovered++;
2056         }
2057         mask <<= 1;
2058         if (++j == bitsPerWord) {
2059             place++;
2060             mask = 1;
2061             j    = 0;
2062         }
2063     }
2064
2065     gcRecovered(recovered);
2066     setBreakAction ( oldBrk );
2067
2068     everybody(GCDONE);
2069
2070 #if defined(DEBUG_STORAGE) || defined(DEBUG_STORAGE_EXTRA)
2071     /* fprintf(stderr, "\n--- GC recovered %d\n",recovered ); */
2072 #endif
2073
2074     /* can only return if freeList is nonempty on return. */
2075     if (recovered<minRecovery || isNull(freeList)) {
2076         ERRMSG(0) "Garbage collection fails to reclaim sufficient space"
2077         EEND;
2078     }
2079     cellsRecovered = recovered;
2080 }
2081
2082 /* --------------------------------------------------------------------------
2083  * Code for saving last expression entered:
2084  *
2085  * This is a little tricky because some text values (e.g. strings or variable
2086  * names) may not be defined or have the same value when the expression is
2087  * recalled.  These text values are therefore saved in the top portion of
2088  * the text table.
2089  * ------------------------------------------------------------------------*/
2090
2091 static Cell lastExprSaved;              /* last expression to be saved     */
2092
2093 Void setLastExpr(e)                     /* save expression for later recall*/
2094 Cell e; {
2095     lastExprSaved = NIL;                /* in case attempt to save fails   */
2096     savedText     = TEXT_SIZE;
2097     lastExprSaved = lowLevelLastIn(e);
2098 }
2099
2100 static Cell local lowLevelLastIn(c)     /* Duplicate expression tree (i.e. */
2101 Cell c; {                               /* acyclic graph) for later recall */
2102     if (isPair(c)) {                    /* Duplicating any text strings    */
2103         if (isTagNonPtr(fst(c)))        /* in case these are lost at some  */
2104             switch (fst(c)) {           /* point before the expr is reused */
2105                 case VARIDCELL :
2106                 case VAROPCELL :
2107                 case DICTVAR   :
2108                 case CONIDCELL :
2109                 case CONOPCELL :
2110                 case STRCELL   : return pair(fst(c),saveText(textOf(c)));
2111                 default        : return pair(fst(c),snd(c));
2112             }
2113         else
2114             return pair(lowLevelLastIn(fst(c)),lowLevelLastIn(snd(c)));
2115     }
2116 #if TREX
2117     else if (isExt(c))
2118         return pair(EXTCOPY,saveText(extText(c)));
2119 #endif
2120     else
2121         return c;
2122 }
2123
2124 Cell getLastExpr() {                    /* recover previously saved expr   */
2125     return lowLevelLastOut(lastExprSaved);
2126 }
2127
2128 static Cell local lowLevelLastOut(c)    /* As with lowLevelLastIn() above  */
2129 Cell c; {                               /* except that Cells refering to   */
2130     if (isPair(c)) {                    /* Text values are restored to     */
2131         if (isTagNonPtr(fst(c)))        /* appropriate values              */
2132             switch (fst(c)) {
2133                 case VARIDCELL :
2134                 case VAROPCELL :
2135                 case DICTVAR   :
2136                 case CONIDCELL :
2137                 case CONOPCELL :
2138                 case STRCELL   : return pair(fst(c),
2139                                              findText(text+intValOf(c)));
2140 #if TREX
2141                 case EXTCOPY   : return mkExt(findText(text+intValOf(c)));
2142 #endif
2143                 default        : return pair(fst(c),snd(c));
2144             }
2145         else
2146             return pair(lowLevelLastOut(fst(c)),lowLevelLastOut(snd(c)));
2147     }
2148     else
2149         return c;
2150 }
2151
2152 /* --------------------------------------------------------------------------
2153  * Miscellaneous operations on heap cells:
2154  * ------------------------------------------------------------------------*/
2155
2156 Cell whatIs ( register Cell c )
2157 {
2158     if (isPair(c)) {
2159         register Cell fstc = fst(c);
2160         return isTag(fstc) ? fstc : AP;
2161     }
2162     if (isOffset(c))           return OFFSET;
2163     if (isChar(c))             return CHARCELL;
2164     if (isInt(c))              return INTCELL;
2165     if (isName(c))             return NAME;
2166     if (isTycon(c))            return TYCON;
2167     if (isTuple(c))            return TUPLE;
2168     if (isClass(c))            return CLASS;
2169     if (isInst(c))             return INSTANCE;
2170     if (isModule(c))           return MODULE;
2171     if (isText(c))             return TEXTCELL;
2172     if (isInventedVar(c))      return INVAR;
2173     if (isInventedDictVar(c))  return INDVAR;
2174     if (isSpec(c))             return c;
2175     if (isNull(c))             return c;
2176     fprintf ( stderr, "whatIs: unknown %d\n", c );
2177     internal("whatIs");
2178 }
2179
2180
2181 #if 0
2182 Cell whatIs(c)                         /* identify type of cell            */
2183 register Cell c; {
2184     if (isPair(c)) {
2185         register Cell fstc = fst(c);
2186         return isTag(fstc) ? fstc : AP;
2187     }
2188     if (c<OFFMIN)    return c;
2189 #if TREX
2190     if (isExt(c))    return EXT;
2191 #endif
2192     if (c>=INTMIN)   return INTCELL;
2193
2194     if (c>=NAMEMIN){if (c>=CLASSMIN)   {if (c>=CHARMIN) return CHARCELL;
2195                                         else            return CLASS;}
2196                     else                if (c>=INSTMIN) return INSTANCE;
2197                                         else            return NAME;}
2198     else            if (c>=MODMIN)     {if (c>=TYCMIN)  return isTuple(c) ? TUPLE : TYCON;
2199                                         else            return MODULE;}
2200                     else                if (c>=OFFMIN)  return OFFSET;
2201 #if TREX
2202                                         else            return (c>=EXTMIN) ?
2203                                                                 EXT : TUPLE;
2204 #else
2205                                         else            return TUPLE;
2206 #endif
2207
2208
2209 /*  if (isPair(c)) {
2210         register Cell fstc = fst(c);
2211         return isTag(fstc) ? fstc : AP;
2212     }
2213     if (c>=INTMIN)   return INTCELL;
2214     if (c>=CHARMIN)  return CHARCELL;
2215     if (c>=CLASSMIN) return CLASS;
2216     if (c>=INSTMIN)  return INSTANCE;
2217     if (c>=NAMEMIN)  return NAME;
2218     if (c>=TYCMIN)   return TYCON;
2219     if (c>=MODMIN)   return MODULE;
2220     if (c>=OFFMIN)   return OFFSET;
2221 #if TREX
2222     if (c>=EXTMIN)   return EXT;
2223 #endif
2224     if (c>=TUPMIN)   return TUPLE;
2225     return c;*/
2226 }
2227 #endif
2228
2229
2230 /* A very, very simple printer.
2231  * Output is uglier than from printExp - but the printer is more
2232  * robust and can be used on any data structure irrespective of
2233  * its type.
2234  */
2235 Void print ( Cell c, Int depth )
2236 {
2237     if (0 == depth) {
2238         Printf("...");
2239     }
2240     else if (isNull(c)) {
2241        Printf("NIL");
2242     }
2243     else if (isTagPtr(c)) {
2244         Printf("TagP(%d)", c);
2245     }
2246     else if (isTagNonPtr(c)) {
2247         Printf("TagNP(%d)", c);
2248     }
2249     else if (isSpec(c) && c != STAR) {
2250         Printf("TagS(%d)", c);
2251     }
2252     else if (isText(c)) {
2253         Printf("text(%d)=\"%s\"",c-TEXT_BASE_ADDR,textToStr(c));
2254     }
2255     else if (isInventedVar(c)) {
2256         Printf("invented(%d)", c-INVAR_BASE_ADDR);
2257     }
2258     else if (isInventedDictVar(c)) {
2259         Printf("inventedDict(%d)",c-INDVAR_BASE_ADDR);
2260     }
2261     else {
2262         Int tag = whatIs(c);
2263         switch (tag) {
2264         case AP: 
2265                 Putchar('(');
2266                 print(fst(c), depth-1);
2267                 Putchar(',');
2268                 print(snd(c), depth-1);
2269                 Putchar(')');
2270                 break;
2271         case FREECELL:
2272                 Printf("free(%d)", c);
2273                 break;
2274         case INTCELL:
2275                 Printf("int(%d)", intOf(c));
2276                 break;
2277         case BIGCELL:
2278                 Printf("bignum(%s)", bignumToString(c));
2279                 break;
2280         case CHARCELL:
2281                 Printf("char('%c')", charOf(c));
2282                 break;
2283         case PTRCELL: 
2284                 Printf("ptr(%p)",ptrOf(c));
2285                 break;
2286         case CLASS:
2287                 Printf("class(%d)", c-CCLASS_BASE_ADDR);
2288                 Printf("=\"%s\"", textToStr(cclass(c).text));
2289                 break;
2290         case INSTANCE:
2291                 Printf("instance(%d)", c - INST_BASE_ADDR);
2292                 break;
2293         case NAME:
2294                 Printf("name(%d)", c-NAME_BASE_ADDR);
2295                 Printf("=\"%s\"", textToStr(name(c).text));
2296                 break;
2297         case TYCON:
2298                 Printf("tycon(%d)", c-TYCON_BASE_ADDR);
2299                 Printf("=\"%s\"", textToStr(tycon(c).text));
2300                 break;
2301         case MODULE:
2302                 Printf("module(%d)", c - MODULE_BASE_ADDR);
2303                 Printf("=\"%s\"", textToStr(module(c).text));
2304                 break;
2305         case OFFSET:
2306                 Printf("Offset %d", offsetOf(c));
2307                 break;
2308         case TUPLE:
2309                 Printf("%s", textToStr(ghcTupleText(c)));
2310                 break;
2311         case POLYTYPE:
2312                 Printf("Polytype");
2313                 print(snd(c),depth-1);
2314                 break;
2315         case QUAL:
2316                 Printf("Qualtype");
2317                 print(snd(c),depth-1);
2318                 break;
2319         case RANK2:
2320                 Printf("Rank2(");
2321                 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
2322                     Printf("%d ", intOf(fst(snd(c))));
2323                     print(snd(snd(c)),depth-1);
2324                 } else {
2325                     print(snd(c),depth-1);
2326                 }
2327                 Printf(")");
2328                 break;
2329         case WILDCARD:
2330                 Printf("_");
2331                 break;
2332         case STAR:
2333                 Printf("STAR");
2334                 break;
2335         case DOTDOT:
2336                 Printf("DOTDOT");
2337                 break;
2338         case DICTVAR:
2339                 Printf("{dict %d}",textOf(c));
2340                 break;
2341         case VARIDCELL:
2342         case VAROPCELL:
2343         case CONIDCELL:
2344         case CONOPCELL:
2345                 Printf("{id %s}",textToStr(textOf(c)));
2346                 break;
2347 #if IPARAM
2348           case IPCELL :
2349               Printf("{ip %s}",textToStr(textOf(c)));
2350               break;
2351           case IPVAR :
2352               Printf("?%s",textToStr(textOf(c)));
2353               break;
2354 #endif
2355         case QUALIDENT:
2356                 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
2357                 break;
2358         case LETREC:
2359                 Printf("LetRec(");
2360                 print(fst(snd(c)),depth-1);
2361                 Putchar(',');
2362                 print(snd(snd(c)),depth-1);
2363                 Putchar(')');
2364                 break;
2365         case LAMBDA:
2366                 Printf("Lambda(");
2367                 print(snd(c),depth-1);
2368                 Putchar(')');
2369                 break;
2370         case FINLIST:
2371                 Printf("FinList(");
2372                 print(snd(c),depth-1);
2373                 Putchar(')');
2374                 break;
2375         case COMP:
2376                 Printf("Comp(");
2377                 print(fst(snd(c)),depth-1);
2378                 Putchar(',');
2379                 print(snd(snd(c)),depth-1);
2380                 Putchar(')');
2381                 break;
2382         case ASPAT:
2383                 Printf("AsPat(");
2384                 print(fst(snd(c)),depth-1);
2385                 Putchar(',');
2386                 print(snd(snd(c)),depth-1);
2387                 Putchar(')');
2388                 break;
2389         case FROMQUAL:
2390                 Printf("FromQual(");
2391                 print(fst(snd(c)),depth-1);
2392                 Putchar(',');
2393                 print(snd(snd(c)),depth-1);
2394                 Putchar(')');
2395                 break;
2396         case STGVAR:
2397                 Printf("StgVar%d=",-c);
2398                 print(snd(c), depth-1);
2399                 break;
2400         case STGAPP:
2401                 Printf("StgApp(");
2402                 print(fst(snd(c)),depth-1);
2403                 Putchar(',');
2404                 print(snd(snd(c)),depth-1);
2405                 Putchar(')');
2406                 break;
2407         case STGPRIM:
2408                 Printf("StgPrim(");
2409                 print(fst(snd(c)),depth-1);
2410                 Putchar(',');
2411                 print(snd(snd(c)),depth-1);
2412                 Putchar(')');
2413                 break;
2414         case STGCON:
2415                 Printf("StgCon(");
2416                 print(fst(snd(c)),depth-1);
2417                 Putchar(',');
2418                 print(snd(snd(c)),depth-1);
2419                 Putchar(')');
2420                 break;
2421         case PRIMCASE:
2422                 Printf("PrimCase(");
2423                 print(fst(snd(c)),depth-1);
2424                 Putchar(',');
2425                 print(snd(snd(c)),depth-1);
2426                 Putchar(')');
2427                 break;
2428         case DICTAP:
2429                 Printf("(DICTAP,");
2430                 print(snd(c),depth-1);
2431                 Putchar(')');
2432                 break;
2433         case UNBOXEDTUP:
2434                 Printf("(UNBOXEDTUP,");
2435                 print(snd(c),depth-1);
2436                 Putchar(')');
2437                 break;
2438         case ZTUP2:
2439                 Printf("<ZPair ");
2440                 print(zfst(c),depth-1);
2441                 Putchar(' ');
2442                 print(zsnd(c),depth-1);
2443                 Putchar('>');
2444                 break;
2445         case ZTUP3:
2446                 Printf("<ZTriple ");
2447                 print(zfst3(c),depth-1);
2448                 Putchar(' ');
2449                 print(zsnd3(c),depth-1);
2450                 Putchar(' ');
2451                 print(zthd3(c),depth-1);
2452                 Putchar('>');
2453                 break;
2454         case BANG:
2455                 Printf("(BANG,");
2456                 print(snd(c),depth-1);
2457                 Putchar(')');
2458                 break;
2459         default:
2460                 if (isTagNonPtr(tag)) {
2461                     Printf("(TagNP=%d,%d)", c, tag);
2462                 } else if (isTagPtr(tag)) {
2463                     Printf("(TagP=%d,",tag);
2464                     print(snd(c), depth-1);
2465                     Putchar(')');
2466                     break;
2467                 } else if (c == tag) {
2468                     Printf("Tag(%d)", c);
2469                 } else {
2470                     Printf("Tag(%d)=%d", c, tag);
2471                 }
2472                 break;
2473         }
2474     }
2475     FlushStdout();
2476 }
2477
2478
2479 Bool isVar(c)                           /* is cell a VARIDCELL/VAROPCELL ? */
2480 Cell c; {                               /* also recognises DICTVAR cells   */
2481     return isPair(c) &&
2482                (fst(c)==VARIDCELL || fst(c)==VAROPCELL || fst(c)==DICTVAR);
2483 }
2484
2485 Bool isCon(c)                          /* is cell a CONIDCELL/CONOPCELL ?  */
2486 Cell c; {
2487     return isPair(c) && (fst(c)==CONIDCELL || fst(c)==CONOPCELL);
2488 }
2489
2490 Bool isQVar(c)                        /* is cell a [un]qualified varop/id? */
2491 Cell c; {
2492     if (!isPair(c)) return FALSE;
2493     switch (fst(c)) {
2494         case VARIDCELL  :
2495         case VAROPCELL  : return TRUE;
2496
2497         case QUALIDENT  : return isVar(snd(snd(c)));
2498
2499         default         : return FALSE;
2500     }
2501 }
2502
2503 Bool isQCon(c)                         /*is cell a [un]qualified conop/id? */
2504 Cell c; {
2505     if (!isPair(c)) return FALSE;
2506     switch (fst(c)) {
2507         case CONIDCELL  :
2508         case CONOPCELL  : return TRUE;
2509
2510         case QUALIDENT  : return isCon(snd(snd(c)));
2511
2512         default         : return FALSE;
2513     }
2514 }
2515
2516 Bool isQualIdent(c)                    /* is cell a qualified identifier?  */
2517 Cell c; {
2518     return isPair(c) && (fst(c)==QUALIDENT);
2519 }
2520
2521 Bool eqQualIdent ( QualId c1, QualId c2 )
2522 {
2523    assert(isQualIdent(c1));
2524    if (!isQualIdent(c2)) {
2525    assert(isQualIdent(c2));
2526    }
2527    return qmodOf(c1)==qmodOf(c2) &&
2528           qtextOf(c1)==qtextOf(c2);
2529 }
2530
2531 Bool isIdent(c)                        /* is cell an identifier?           */
2532 Cell c; {
2533     if (!isPair(c)) return FALSE;
2534     switch (fst(c)) {
2535         case VARIDCELL  :
2536         case VAROPCELL  :
2537         case CONIDCELL  :
2538         case CONOPCELL  : return TRUE;
2539
2540         case QUALIDENT  : return TRUE;
2541
2542         default         : return FALSE;
2543     }
2544 }
2545
2546 Bool isInt(c)                          /* cell holds integer value?        */
2547 Cell c; {
2548     return isSmall(c) || (isPair(c) && fst(c)==INTCELL);
2549 }
2550
2551 Int intOf(c)                           /* find integer value of cell?      */
2552 Cell c; {
2553     assert(isInt(c));
2554     return isPair(c) ? (Int)(snd(c)) : (Int)(c-SMALL_INT_ZERO);
2555 }
2556
2557 Cell mkInt(n)                          /* make cell representing integer   */
2558 Int n; {
2559     return (SMALL_INT_MIN    <= SMALL_INT_ZERO+n &&
2560             SMALL_INT_ZERO+n <= SMALL_INT_MAX)
2561            ? SMALL_INT_ZERO+n
2562            : pair(INTCELL,n);
2563 }
2564
2565 #if SIZEOF_VOID_P == SIZEOF_INT
2566
2567 typedef union {Int i; Ptr p;} IntOrPtr;
2568
2569 Cell mkPtr(p)
2570 Ptr p;
2571 {
2572     IntOrPtr x;
2573     x.p = p;
2574     return pair(PTRCELL,x.i);
2575 }
2576
2577 Ptr ptrOf(c)
2578 Cell c;
2579 {
2580     IntOrPtr x;
2581     assert(fst(c) == PTRCELL);
2582     x.i = snd(c);
2583     return x.p;
2584 }
2585
2586 Cell mkCPtr(p)
2587 Ptr p;
2588 {
2589     IntOrPtr x;
2590     x.p = p;
2591     return pair(CPTRCELL,x.i);
2592 }
2593
2594 Ptr cptrOf(c)
2595 Cell c;
2596 {
2597     IntOrPtr x;
2598     assert(fst(c) == CPTRCELL);
2599     x.i = snd(c);
2600     return x.p;
2601 }
2602
2603 #elif SIZEOF_VOID_P == 2*SIZEOF_INT
2604
2605 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
2606
2607 Cell mkPtr(p)
2608 Ptr p;
2609 {
2610     IntOrPtr x;
2611     x.p = p;
2612     return pair(PTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2613 }
2614
2615 Ptr ptrOf(c)
2616 Cell c;
2617 {
2618     IntOrPtr x;
2619     assert(fst(c) == PTRCELL);
2620     x.i.i1 = intOf(fst(snd(c)));
2621     x.i.i2 = intOf(snd(snd(c)));
2622     return x.p;
2623 }
2624
2625 Cell mkCPtr(p)
2626 Ptr p;
2627 {
2628     IntOrPtr x;
2629     x.p = p;
2630     return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
2631 }
2632
2633 Ptr cptrOf(c)
2634 Cell c;
2635 {
2636     IntOrPtr x;
2637     assert(fst(c) == CPTRCELL);
2638     x.i.i1 = intOf(fst(snd(c)));
2639     x.i.i2 = intOf(snd(snd(c)));
2640     return x.p;
2641 }
2642
2643 #else
2644
2645 #error "Can't implement mkPtr/ptrOf on this architecture."
2646
2647 #endif
2648
2649
2650 String stringNegate( s )
2651 String s;
2652 {
2653     if (s[0] == '-') {
2654         return &s[1];
2655     } else {
2656         static char t[100];
2657         t[0] = '-';
2658         strcpy(&t[1],s);  /* ToDo: use strncpy instead */
2659         return t;
2660     }
2661 }
2662
2663 /* --------------------------------------------------------------------------
2664  * List operations:
2665  * ------------------------------------------------------------------------*/
2666
2667 Int length(xs)                         /* calculate length of list xs      */
2668 List xs; {
2669     Int n = 0;
2670     for (; nonNull(xs); ++n)
2671         xs = tl(xs);
2672     return n;
2673 }
2674
2675 List appendOnto(xs,ys)                 /* Destructively prepend xs onto    */
2676 List xs, ys; {                         /* ys by modifying xs ...           */
2677     if (isNull(xs))
2678         return ys;
2679     else {
2680         List zs = xs;
2681         while (nonNull(tl(zs)))
2682             zs = tl(zs);
2683         tl(zs) = ys;
2684         return xs;
2685     }
2686 }
2687
2688 List dupOnto(xs,ys)      /* non-destructively prepend xs backwards onto ys */
2689 List xs; 
2690 List ys; {
2691     for (; nonNull(xs); xs=tl(xs))
2692         ys = cons(hd(xs),ys);
2693     return ys;
2694 }
2695
2696 List dupListOnto(xs,ys)              /* Duplicate spine of list xs onto ys */
2697 List xs;
2698 List ys; {
2699     return revOnto(dupOnto(xs,NIL),ys);
2700 }
2701
2702 List dupList(xs)                       /* Duplicate spine of list xs       */
2703 List xs; {
2704     List ys = NIL;
2705     for (; nonNull(xs); xs=tl(xs))
2706         ys = cons(hd(xs),ys);
2707     return rev(ys);
2708 }
2709
2710 List revOnto(xs,ys)                    /* Destructively reverse elements of*/
2711 List xs, ys; {                         /* list xs onto list ys...          */
2712     Cell zs;
2713
2714     while (nonNull(xs)) {
2715         zs     = tl(xs);
2716         tl(xs) = ys;
2717         ys     = xs;
2718         xs     = zs;
2719     }
2720     return ys;
2721 }
2722
2723 QualId qualidIsMember ( QualId q, List xs )
2724 {
2725    for (; nonNull(xs); xs=tl(xs)) {
2726       if (eqQualIdent(q, hd(xs)))
2727          return hd(xs);
2728    }
2729    return NIL;
2730 }  
2731
2732 Cell varIsMember(t,xs)                 /* Test if variable is a member of  */
2733 Text t;                                /* given list of variables          */
2734 List xs; {
2735     assert(isText(t) || isInventedVar(t) || isInventedDictVar(t));
2736     for (; nonNull(xs); xs=tl(xs))
2737         if (t==textOf(hd(xs)))
2738             return hd(xs);
2739     return NIL;
2740 }
2741
2742 Name nameIsMember(t,ns)                 /* Test if name with text t is a   */
2743 Text t;                                 /* member of list of names xs      */
2744 List ns; {
2745     for (; nonNull(ns); ns=tl(ns))
2746         if (t==name(hd(ns)).text)
2747             return hd(ns);
2748     return NIL;
2749 }
2750
2751 Cell intIsMember(n,xs)                 /* Test if integer n is member of   */
2752 Int  n;                                /* given list of integers           */
2753 List xs; {
2754     for (; nonNull(xs); xs=tl(xs))
2755         if (n==intOf(hd(xs)))
2756             return hd(xs);
2757     return NIL;
2758 }
2759
2760 Cell cellIsMember(x,xs)                /* Test for membership of specific  */
2761 Cell x;                                /* cell x in list xs                */
2762 List xs; {
2763     for (; nonNull(xs); xs=tl(xs))
2764         if (x==hd(xs))
2765             return hd(xs);
2766     return NIL;
2767 }
2768
2769 Cell cellAssoc(c,xs)                   /* Lookup cell in association list  */
2770 Cell c;         
2771 List xs; {
2772     for (; nonNull(xs); xs=tl(xs))
2773         if (c==fst(hd(xs)))
2774             return hd(xs);
2775     return NIL;
2776 }
2777
2778 Cell cellRevAssoc(c,xs)                /* Lookup cell in range of          */
2779 Cell c;                                /* association lists                */
2780 List xs; {
2781     for (; nonNull(xs); xs=tl(xs))
2782         if (c==snd(hd(xs)))
2783             return hd(xs);
2784     return NIL;
2785 }
2786
2787 List replicate(n,x)                     /* create list of n copies of x    */
2788 Int n;
2789 Cell x; {
2790     List xs=NIL;
2791     while (0<n--)
2792         xs = cons(x,xs);
2793     return xs;
2794 }
2795
2796 List diffList(from,take)               /* list difference: from\take       */
2797 List from, take; {                     /* result contains all elements of  */
2798     List result = NIL;                 /* `from' not appearing in `take'   */
2799
2800     while (nonNull(from)) {
2801         List next = tl(from);
2802         if (!cellIsMember(hd(from),take)) {
2803             tl(from) = result;
2804             result   = from;
2805         }
2806         from = next;
2807     }
2808     return rev(result);
2809 }
2810
2811 List deleteCell(xs, y)                  /* copy xs deleting pointers to y  */
2812 List xs;
2813 Cell y; {
2814     List result = NIL; 
2815     for(;nonNull(xs);xs=tl(xs)) {
2816         Cell x = hd(xs);
2817         if (x != y) {
2818             result=cons(x,result);
2819         }
2820     }
2821     return rev(result);
2822 }
2823
2824 List take(n,xs)                         /* destructively truncate list to  */
2825 Int  n;                                 /* specified length                */
2826 List xs; {
2827     List ys = xs;
2828
2829     if (n==0)
2830         return NIL;
2831     while (1<n-- && nonNull(xs))
2832         xs = tl(xs);
2833     if (nonNull(xs))
2834         tl(xs) = NIL;
2835     return ys;
2836 }
2837
2838 List splitAt(n,xs)                      /* drop n things from front of list*/
2839 Int  n;       
2840 List xs; {
2841     for(; n>0; --n) {
2842         xs = tl(xs);
2843     }
2844     return xs;
2845 }
2846
2847 Cell nth(n,xs)                          /* extract n'th element of list    */
2848 Int  n;
2849 List xs; {
2850     for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
2851     }
2852     if (isNull(xs))
2853         internal("nth");
2854     return hd(xs);
2855 }
2856
2857 List removeCell(x,xs)                   /* destructively remove cell from  */
2858 Cell x;                                 /* list                            */
2859 List xs; {
2860     if (nonNull(xs)) {
2861         if (hd(xs)==x)
2862             return tl(xs);              /* element at front of list        */
2863         else {
2864             List prev = xs;
2865             List curr = tl(xs);
2866             for (; nonNull(curr); prev=curr, curr=tl(prev))
2867                 if (hd(curr)==x) {
2868                     tl(prev) = tl(curr);
2869                     return xs;          /* element in middle of list       */
2870                 }
2871         }
2872     }
2873     return xs;                          /* here if element not found       */
2874 }
2875
2876 List nubList(xs)                        /* nuke dups in list               */
2877 List xs; {                              /* non destructive                 */
2878    List outs = NIL;
2879    for (; nonNull(xs); xs=tl(xs))
2880       if (isNull(cellIsMember(hd(xs),outs)))
2881          outs = cons(hd(xs),outs);
2882    outs = rev(outs);
2883    return outs;
2884 }
2885
2886
2887 /* --------------------------------------------------------------------------
2888  * Tagged tuples (experimental)
2889  * ------------------------------------------------------------------------*/
2890
2891 static void z_tag_check ( Cell x, int tag, char* caller )
2892 {
2893    char buf[100];
2894    if (isNull(x)) {
2895       sprintf(buf,"z_tag_check(%s): null\n", caller);
2896       internal(buf);
2897    }
2898    if (whatIs(x) != tag) {
2899       sprintf(buf, 
2900           "z_tag_check(%s): tag was %d, expected %d\n",
2901           caller, whatIs(x), tag );
2902       internal(buf);
2903    }  
2904 }
2905
2906 Cell zpair ( Cell x1, Cell x2 )
2907 { return ap(ZTUP2,ap(x1,x2)); }
2908 Cell zfst ( Cell zpair )
2909 { z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
2910 Cell zsnd ( Cell zpair )
2911 { z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
2912
2913 Cell ztriple ( Cell x1, Cell x2, Cell x3 )
2914 { return ap(ZTUP3,ap(x1,ap(x2,x3))); }
2915 Cell zfst3 ( Cell zpair )
2916 { z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
2917 Cell zsnd3 ( Cell zpair )
2918 { z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
2919 Cell zthd3 ( Cell zpair )
2920 { z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
2921
2922 Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
2923 { return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
2924 Cell zsel14 ( Cell zpair )
2925 { z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
2926 Cell zsel24 ( Cell zpair )
2927 { z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
2928 Cell zsel34 ( Cell zpair )
2929 { z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
2930 Cell zsel44 ( Cell zpair )
2931 { z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
2932
2933 Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
2934 { return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
2935 Cell zsel15 ( Cell zpair )
2936 { z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
2937 Cell zsel25 ( Cell zpair )
2938 { z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
2939 Cell zsel35 ( Cell zpair )
2940 { z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
2941 Cell zsel45 ( Cell zpair )
2942 { z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
2943 Cell zsel55 ( Cell zpair )
2944 { z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
2945
2946
2947 Cell unap ( int tag, Cell c )
2948 {
2949    char buf[100];
2950    if (whatIs(c) != tag) {
2951       sprintf(buf, "unap: specified %d, actual %d\n",
2952                    tag, whatIs(c) );
2953       internal(buf);
2954    }
2955    return snd(c);
2956 }
2957
2958 /* --------------------------------------------------------------------------
2959  * Operations on applications:
2960  * ------------------------------------------------------------------------*/
2961
2962 Int argCount;                          /* number of args in application    */
2963
2964 Cell getHead(e)                        /* get head cell of application     */
2965 Cell e; {                              /* set number of args in argCount   */
2966     for (argCount=0; isAp(e); e=fun(e))
2967         argCount++;
2968     return e;
2969 }
2970
2971 List getArgs(e)                        /* get list of arguments in function*/
2972 Cell e; {                              /* application:                     */
2973     List as;                           /* getArgs(f e1 .. en) = [e1,..,en] */
2974
2975     for (as=NIL; isAp(e); e=fun(e))
2976         as = cons(arg(e),as);
2977     return as;
2978 }
2979
2980 Cell nthArg(n,e)                       /* return nth arg in application    */
2981 Int  n;                                /* of function to m args (m>=n)     */
2982 Cell e; {                              /* nthArg n (f x0 x1 ... xm) = xn   */
2983     for (n=numArgs(e)-n-1; n>0; n--)
2984         e = fun(e);
2985     return arg(e);
2986 }
2987
2988 Int numArgs(e)                         /* find number of arguments to expr */
2989 Cell e; {
2990     Int n;
2991     for (n=0; isAp(e); e=fun(e))
2992         n++;
2993     return n;
2994 }
2995
2996 Cell applyToArgs(f,args)               /* destructively apply list of args */
2997 Cell f;                                /* to function f                    */
2998 List args; {
2999     while (nonNull(args)) {
3000         Cell temp = tl(args);
3001         tl(args)  = hd(args);
3002         hd(args)  = f;
3003         f         = args;
3004         args      = temp;
3005     }
3006     return f;
3007 }
3008
3009 /* --------------------------------------------------------------------------
3010  * debugging support
3011  * ------------------------------------------------------------------------*/
3012
3013 /* Given the address of an info table, find the constructor/tuple
3014    that it belongs to, and return the name.  Only needed for debugging.
3015 */
3016 char* lookupHugsItblName ( void* v )
3017 {
3018    int i;
3019    for (i = TYCON_BASE_ADDR; 
3020         i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3021       if (tabTycon[i-TYCON_BASE_ADDR].inUse
3022           && tycon(i).itbl == v)
3023          return textToStr(tycon(i).text);
3024    }
3025    for (i = NAME_BASE_ADDR; 
3026         i < NAME_BASE_ADDR+tabNameSz; ++i) {
3027       if (tabName[i-NAME_BASE_ADDR].inUse
3028           && name(i).itbl == v)
3029          return textToStr(name(i).text);
3030    }
3031    return NULL;
3032 }
3033
3034 static String maybeModuleStr ( Module m )
3035 {
3036    if (isModule(m)) return textToStr(module(m).text); else return "??";
3037 }
3038
3039 static String maybeNameStr ( Name n )
3040 {
3041    if (isName(n)) return textToStr(name(n).text); else return "??";
3042 }
3043
3044 static String maybeTyconStr ( Tycon t )
3045 {
3046    if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
3047 }
3048
3049 static String maybeClassStr ( Class c )
3050 {
3051    if (isClass(c)) return textToStr(cclass(c).text); else return "??";
3052 }
3053
3054 static String maybeText ( Text t )
3055 {
3056    if (isNull(t)) return "(nil)";
3057    return textToStr(t);
3058 }
3059
3060 static void print100 ( Int x )
3061 {
3062    print ( x, 100); printf("\n");
3063 }
3064
3065 void dumpTycon ( Int t )
3066 {
3067    if (isTycon(TYCON_BASE_ADDR+t) && !isTycon(t)) t += TYCON_BASE_ADDR;
3068    if (!isTycon(t)) {
3069       printf ( "dumpTycon %d: not a tycon\n", t);
3070       return;
3071    }
3072    printf ( "{\n" );
3073    printf ( "    text: %s\n",     textToStr(tycon(t).text) );
3074    printf ( "    line: %d\n",     tycon(t).line );
3075    printf ( "     mod: %s\n",     maybeModuleStr(tycon(t).mod));
3076    printf ( "   tuple: %d\n",     tycon(t).tuple);
3077    printf ( "   arity: %d\n",     tycon(t).arity);
3078    printf ( "    kind: ");        print100(tycon(t).kind);
3079    printf ( "    what: %d\n",     tycon(t).what);
3080    printf ( "    defn: ");        print100(tycon(t).defn);
3081    printf ( "    cToT: %d %s\n",  tycon(t).conToTag, 
3082                                   maybeNameStr(tycon(t).conToTag));
3083    printf ( "    tToC: %d %s\n",  tycon(t).tagToCon, 
3084                                   maybeNameStr(tycon(t).tagToCon));
3085    printf ( "    itbl: %p\n",     tycon(t).itbl);
3086    printf ( "  nextTH: %d %s\n",  tycon(t).nextTyconHash,
3087                                   maybeTyconStr(tycon(t).nextTyconHash));
3088    printf ( "}\n" );
3089 }
3090
3091 void dumpName ( Int n )
3092 {
3093    if (isName(NAME_BASE_ADDR+n) && !isName(n)) n += NAME_BASE_ADDR;
3094    if (!isName(n)) {
3095       printf ( "dumpName %d: not a name\n", n);
3096       return;
3097    }
3098    printf ( "{\n" );
3099    printf ( "    text: %s\n",     textToStr(name(n).text) );
3100    printf ( "    line: %d\n",     name(n).line );
3101    printf ( "     mod: %s\n",     maybeModuleStr(name(n).mod));
3102    printf ( "  syntax: %d\n",     name(n).syntax );
3103    printf ( "  parent: %d\n",     name(n).parent );
3104    printf ( "   arity: %d\n",     name(n).arity );
3105    printf ( "  number: %d\n",     name(n).number );
3106    printf ( "    type: ");        print100(name(n).type);
3107    printf ( "    defn: %d\n",     name(n).defn );
3108    printf ( "  stgVar: ");        print100(name(n).stgVar);
3109    printf ( "   cconv: %d\n",     name(n).callconv );
3110    printf ( "  primop: %p\n",     name(n).primop );
3111    printf ( "    itbl: %p\n",     name(n).itbl );
3112    printf ( "  nextNH: %d\n",     name(n).nextNameHash );
3113    printf ( "}\n" );
3114 }
3115
3116
3117 void dumpClass ( Int c )
3118 {
3119    if (isClass(CCLASS_BASE_ADDR+c) && !isClass(c)) c += CCLASS_BASE_ADDR;
3120    if (!isClass(c)) {
3121       printf ( "dumpClass %d: not a class\n", c);
3122       return;
3123    }
3124    printf ( "{\n" );
3125    printf ( "    text: %s\n",     textToStr(cclass(c).text) );
3126    printf ( "    line: %d\n",     cclass(c).line );
3127    printf ( "     mod: %s\n",     maybeModuleStr(cclass(c).mod));
3128    printf ( "   arity: %d\n",     cclass(c).arity );
3129    printf ( "   level: %d\n",     cclass(c).level );
3130    printf ( "   kinds: ");        print100( cclass(c).kinds );
3131    printf ( "     fds: %d\n",     cclass(c).fds );
3132    printf ( "    xfds: %d\n",     cclass(c).xfds );
3133    printf ( "    head: ");        print100( cclass(c).head );
3134    printf ( "    dcon: ");        print100( cclass(c).dcon );
3135    printf ( "  supers: ");        print100( cclass(c).supers );
3136    printf ( " #supers: %d\n",     cclass(c).numSupers );
3137    printf ( "   dsels: ");        print100( cclass(c).dsels );
3138    printf ( " members: ");        print100( cclass(c).members );
3139    printf ( "#members: %d\n",     cclass(c).numMembers );
3140    printf ( "defaults: ");        print100( cclass(c).defaults );
3141    printf ( "   insts: ");        print100( cclass(c).instances );
3142    printf ( "}\n" );
3143 }
3144
3145
3146 void dumpInst ( Int i )
3147 {
3148    if (isInst(INST_BASE_ADDR+i) && !isInst(i)) i += INST_BASE_ADDR;
3149    if (!isInst(i)) {
3150       printf ( "dumpInst %d: not an instance\n", i);
3151       return;
3152    }
3153    printf ( "{\n" );
3154    printf ( "   class: %s\n",     maybeClassStr(inst(i).c) );
3155    printf ( "    line: %d\n",     inst(i).line );
3156    printf ( "     mod: %s\n",     maybeModuleStr(inst(i).mod));
3157    printf ( "   kinds: ");        print100( inst(i).kinds );
3158    printf ( "    head: ");        print100( inst(i).head );
3159    printf ( "   specs: ");        print100( inst(i).specifics );
3160    printf ( "  #specs: %d\n",     inst(i).numSpecifics );
3161    printf ( "   impls: ");        print100( inst(i).implements );
3162    printf ( " builder: %s\n",     maybeNameStr( inst(i).builder ) );
3163    printf ( "}\n" );
3164 }
3165
3166
3167 /* --------------------------------------------------------------------------
3168  * storage control:
3169  * ------------------------------------------------------------------------*/
3170
3171 Void storage(what)
3172 Int what; {
3173     Int i;
3174
3175     switch (what) {
3176         case POSTPREL: break;
3177
3178         case RESET   : clearStack();
3179
3180                        /* the next 2 statements are particularly important
3181                         * if you are using GLOBALfst or GLOBALsnd since the
3182                         * corresponding registers may be reset to their
3183                         * uninitialised initial values by a longjump.
3184                         */
3185                        heapTopFst = heapFst + heapSize;
3186                        heapTopSnd = heapSnd + heapSize;
3187                        consGC = TRUE;
3188                        lsave  = NIL;
3189                        rsave  = NIL;
3190                        if (isNull(lastExprSaved))
3191                            savedText = TEXT_SIZE;
3192                        break;
3193
3194         case MARK    : 
3195                        start();
3196                        for (i = NAME_BASE_ADDR; 
3197                             i < NAME_BASE_ADDR+tabNameSz; ++i) {
3198                           if (tabName[i-NAME_BASE_ADDR].inUse) {
3199                              mark(name(i).parent);
3200                              mark(name(i).type);
3201                              mark(name(i).defn);
3202                              mark(name(i).stgVar);
3203                           }
3204                        }
3205                        end("Names", nameHw-NAMEMIN);
3206
3207                        start();
3208                        for (i = MODULE_BASE_ADDR; 
3209                             i < MODULE_BASE_ADDR+tabModuleSz; ++i) {
3210                           if (tabModule[i-MODULE_BASE_ADDR].inUse) {
3211                              mark(module(i).tycons);
3212                              mark(module(i).names);
3213                              mark(module(i).classes);
3214                              mark(module(i).exports);
3215                              mark(module(i).qualImports);
3216                              mark(module(i).tree);
3217                              mark(module(i).uses);
3218                              mark(module(i).objectExtraNames);
3219                           }
3220                        }
3221                        mark(moduleGraph);
3222                        mark(prelModules);
3223                        mark(targetModules);
3224                        end("Modules", moduleHw-MODMIN);
3225
3226                        start();
3227                        for (i = TYCON_BASE_ADDR; 
3228                             i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
3229                           if (tabTycon[i-TYCON_BASE_ADDR].inUse) {
3230                              mark(tycon(i).kind);
3231                              mark(tycon(i).what);
3232                              mark(tycon(i).defn);
3233                           }
3234                        }
3235                        end("Type constructors", tyconHw-TYCMIN);
3236
3237                        start();
3238                        for (i = CCLASS_BASE_ADDR; 
3239                             i < CCLASS_BASE_ADDR+tabClassSz; ++i) {
3240                           if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
3241                              mark(cclass(i).kinds);
3242                              mark(cclass(i).fds);
3243                              mark(cclass(i).xfds);
3244                              mark(cclass(i).head);
3245                              mark(cclass(i).supers);
3246                              mark(cclass(i).dsels);
3247                              mark(cclass(i).members);
3248                              mark(cclass(i).defaults);
3249                              mark(cclass(i).instances);
3250                           }
3251                        }
3252                        mark(classes);
3253                        end("Classes", classHw-CLASSMIN);
3254
3255                        start();
3256                        for (i = INST_BASE_ADDR; 
3257                             i < INST_BASE_ADDR+tabInstSz; ++i) {
3258                           if (tabInst[i-INST_BASE_ADDR].inUse) {
3259                              mark(inst(i).kinds);
3260                              mark(inst(i).head);
3261                              mark(inst(i).specifics);
3262                              mark(inst(i).implements);
3263                           }
3264                        }
3265                        end("Instances", instHw-INSTMIN);
3266
3267                        start();
3268                        for (i=0; i<=sp; ++i)
3269                            mark(stack(i));
3270                        end("Stack", sp+1);
3271
3272                        start();
3273                        mark(lastExprSaved);
3274                        mark(lsave);
3275                        mark(rsave);
3276                        end("Last expression", 3);
3277
3278                        if (consGC) {
3279                            start();
3280                            gcCStack();
3281                            end("C stack", stackRoots);
3282                        }
3283
3284                        break;
3285
3286         case PREPREL : heapFst = heapAlloc(heapSize);
3287                        heapSnd = heapAlloc(heapSize);
3288
3289                        if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
3290                            ERRMSG(0) "Cannot allocate heap storage (%d cells)",
3291                                      heapSize
3292                            EEND;
3293                        }
3294
3295                        heapTopFst = heapFst + heapSize;
3296                        heapTopSnd = heapSnd + heapSize;
3297                        for (i=1; i<heapSize; ++i) {
3298                            fst(-i) = FREECELL;
3299                            snd(-i) = -(i+1);
3300                        }
3301                        snd(-heapSize) = NIL;
3302                        freeList  = -1;
3303                        numGcs    = 0;
3304                        consGC    = TRUE;
3305                        lsave     = NIL;
3306                        rsave     = NIL;
3307
3308                        marksSize  = bitArraySize(heapSize);
3309                        if ((marks=(Int *)calloc(marksSize, sizeof(Int)))==0) {
3310                            ERRMSG(0) "Unable to allocate gc markspace"
3311                            EEND;
3312                        }
3313
3314                        clearStack();
3315
3316                        textHw        = 0;
3317                        nextNewText   = INVAR_BASE_ADDR;
3318                        nextNewDText  = INDVAR_BASE_ADDR;
3319                        lastExprSaved = NIL;
3320                        savedText     = TEXT_SIZE;
3321
3322                        for (i=0; i<TEXTHSZ;  ++i) textHash[i][0] = NOTEXT;
3323                        for (i=0; i<TYCONHSZ; ++i) tyconHash[RC_T(i)] = NIL;
3324                        for (i=0; i<NAMEHSZ;  ++i) nameHash[RC_N(i)] = NIL;
3325
3326                        break;
3327     }
3328 }
3329
3330 /*-------------------------------------------------------------------------*/