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