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