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