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