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