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