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