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