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