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