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