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