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