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