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