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