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