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