[project @ 2000-05-09 17:38:19 by andy]
[ghc-hetmet.git] / ghc / interpreter / storage.c
index b052bc3..c773541 100644 (file)
@@ -2,22 +2,24 @@
 /* --------------------------------------------------------------------------
  * Primitives for manipulating global data structures
  *
- * Hugs 98 is Copyright (c) Mark P Jones, Alastair Reid and the Yale
- * Haskell Group 1994-99, and is distributed as Open Source software
- * under the Artistic License; see the file "Artistic" that is included
- * in the distribution for details.
+ * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
+ * Yale Haskell Group, and the Oregon Graduate Institute of Science and
+ * Technology, 1994-1999, All rights reserved.  It is distributed as
+ * free software under the license in the file "License", which is
+ * included in the distribution.
  *
  * $RCSfile: storage.c,v $
- * $Revision: 1.5 $
- * $Date: 1999/03/09 14:51:13 $
+ * $Revision: 1.75 $
+ * $Date: 2000/05/09 17:38:19 $
  * ------------------------------------------------------------------------*/
 
-#include "prelude.h"
+#include "hugsbasictypes.h"
 #include "storage.h"
-#include "backend.h"
 #include "connect.h"
 #include "errors.h"
+#include "object.h"
 #include <setjmp.h>
+#include "Stg.h"
 
 /*#define DEBUG_SHOWUSE*/
 
  * local function prototypes:
  * ------------------------------------------------------------------------*/
 
-static Int  local hash                  Args((String));
-static Int  local saveText              Args((Text));
-#if !IGNORE_MODULES
-static Module local findQualifier       Args((Text));
-#endif
-static Void local hashTycon             Args((Tycon));
-static List local insertTycon           Args((Tycon,List));
-static Void local hashName              Args((Name));
-static List local insertName            Args((Name,List));
-static Void local patternError          Args((String));
-static Bool local stringMatch           Args((String,String));
-static Bool local typeInvolves          Args((Type,Type));
-static Cell local markCell              Args((Cell));
-static Void local markSnd               Args((Cell));
-static Cell local lowLevelLastIn        Args((Cell));
-static Cell local lowLevelLastOut       Args((Cell));
-/* from STG */
-       Module local moduleOfScript      Args((Script));
-       Script local scriptThisFile      Args((Text));
-/* from 98 */
-#if IO_HANDLES
-static Void local freeHandle            Args((Int));
-#endif
-#if GC_STABLEPTRS
-static Void local resetStablePtrs       Args((Void));
-#endif
-/* end */
+static Int    local hash                ( String );
+static Int    local saveText            ( Text );
+static Module local findQualifier       ( Text );
+static Void   local hashTycon           ( Tycon );
+static List   local insertTycon         ( Tycon,List );
+static Void   local hashName            ( Name );
+static List   local insertName          ( Name,List );
+static Void   local patternError        ( String );
+static Bool   local stringMatch         ( String,String );
+static Bool   local typeInvolves        ( Type,Type );
+static Cell   local markCell            ( Cell );
+static Void   local markSnd             ( Cell );
+static Cell   local lowLevelLastIn      ( Cell );
+static Cell   local lowLevelLastOut     ( Cell );
+
 
 /* --------------------------------------------------------------------------
  * Text storage:
@@ -82,23 +72,29 @@ static Void local resetStablePtrs       Args((Void));
 #define TEXTHSZ 512                     /* Size of Text hash table         */
 #define NOTEXT  ((Text)(~0))            /* Empty bucket in Text hash table */
 static  Text    textHw;                 /* Next unused position            */
-static  Text    savedText = NUM_TEXT;   /* Start of saved portion of text  */
+static  Text    savedText = TEXT_SIZE;  /* Start of saved portion of text  */
 static  Text    nextNewText;            /* Next new text value             */
 static  Text    nextNewDText;           /* Next new dict text value        */
-static  char    DEFTABLE(text,NUM_TEXT);/* Storage of character strings    */
+static  char    text[TEXT_SIZE];        /* Storage of character strings    */
 static  Text    textHash[TEXTHSZ][NUM_TEXTH]; /* Hash table storage        */
 
 String textToStr(t)                    /* find string corresp to given Text*/
 Text t; {
     static char newVar[16];
 
-    if (0<=t && t<NUM_TEXT)                     /* standard char string    */
-        return text + t;
-    if (t<0)
-        sprintf(newVar,"d%d",-t);               /* dictionary variable     */
-    else
-        sprintf(newVar,"v%d",t-NUM_TEXT);       /* normal variable         */
-    return newVar;
+    if (isText(t))                              /* standard char string    */
+        return text + t - TEXT_BASE_ADDR;
+    if (isInventedDictVar(t)) {
+        sprintf(newVar,"d%d",
+                t-INDVAR_BASE_ADDR);            /* dictionary variable     */
+        return newVar;
+    }
+    if (isInventedVar(t)) {
+        sprintf(newVar,"v%d",
+                t-INVAR_BASE_ADDR);             /* normal variable         */
+       return newVar;
+    }
+    internal("textToStr");
 }
 
 String identToStr(v) /*find string corresp to given ident or qualified name*/
@@ -106,23 +102,24 @@ Cell v; {
     if (!isPair(v)) {
         internal("identToStr");
     }
-    switch (fst(v)) {
+    switch (whatIs(v)) {
         case VARIDCELL  :
         case VAROPCELL  : 
         case CONIDCELL  :
-        case CONOPCELL  : return text+textOf(v);
-
-        case QUALIDENT  : {   Text pos = textHw;
-                              Text t   = qmodOf(v);
-                              while (pos+1 < savedText && text[t]!=0) {
-                                  text[pos++] = text[t++];
+        case CONOPCELL  : return textToStr(textOf(v));
+
+        case QUALIDENT  : {   String qmod = textToStr(qmodOf(v));
+                             String qtext = textToStr(qtextOf(v));
+                             Text pos = textHw;
+                             
+                             while (pos+1 < savedText && *qmod!=0) {
+                                  text[pos++] = *qmod++;
                               }
                               if (pos+1 < savedText) {
                                   text[pos++] = '.';
                               }
-                              t = qtextOf(v);
-                              while (pos+1 < savedText && text[t]!=0) {
-                                  text[pos++] = text[t++];
+                              while (pos+1 < savedText && *qtext!=0) {
+                                  text[pos++] = *qtext++;
                               }
                               text[pos] = '\0';
                               return text+textHw;
@@ -133,18 +130,44 @@ Cell v; {
 }
 
 Text inventText()     {                 /* return new unused variable name */
-    return nextNewText++;
+   if (nextNewText >= INVAR_BASE_ADDR+INVAR_MAX_AVAIL)
+      internal("inventText: too many invented variables");
+   return nextNewText++;
 }
 
 Text inventDictText() {                 /* return new unused dictvar name  */
-    return nextNewDText--;
+   if (nextNewDText >= INDVAR_BASE_ADDR+INDVAR_MAX_AVAIL)
+     internal("inventDictText: too many invented variables");
+   return nextNewDText++;
 }
 
 Bool inventedText(t)                    /* Signal TRUE if text has been    */
 Text t; {                               /* generated internally            */
-    return (t<0 || t>=NUM_TEXT);
+    return isInventedVar(t) || isInventedDictVar(t);
 }
 
+#define MAX_FIXLIT 100
+Text fixLitText(t)                /* fix literal text that might include \ */
+Text t; {
+    String   s = textToStr(t);
+    char     p[MAX_FIXLIT];
+    Int      i;
+    for(i = 0;i < MAX_FIXLIT-2 && *s;s++) {
+      p[i++] = *s;
+      if (*s == '\\') {
+       p[i++] = '\\';
+      } 
+    }
+    if (i < MAX_FIXLIT-2) {
+      p[i] = 0;
+    } else {
+       ERRMSG(0) "storage space exhausted for internal literal string"
+       EEND;
+    }
+    return (findText(p));
+}
+#undef MAX_FIXLIT
+
 static Int local hash(s)                /* Simple hash function on strings */
 String s; {
     int v, j = 3;
@@ -162,13 +185,13 @@ String s; {
     int    hashno  = 0;
     Text   textPos = textHash[h][hashno];
 
-#define TryMatch        {   Text   originalTextPos = textPos;              \
+#   define TryMatch     {   Text   originalTextPos = textPos;              \
                             String t;                                      \
                             for (t=s; *t==text[textPos]; textPos++,t++)    \
                                 if (*t=='\0')                              \
-                                    return originalTextPos;                \
+                                    return originalTextPos+TEXT_BASE_ADDR; \
                         }
-#define Skip            while (text[textPos++]) ;
+#   define Skip         while (text[textPos++]) ;
 
     while (textPos!=NOTEXT) {
         TryMatch
@@ -200,14 +223,13 @@ String s; {
             textHash[h][hashno+1] = NOTEXT;
     }
 
-    return textPos;
+    return textPos+TEXT_BASE_ADDR;
 }
 
 static Int local saveText(t)            /* Save text value in buffer       */
 Text t; {                               /* at top of text table            */
     String s = textToStr(t);
     Int    l = strlen(s);
-
     if (textHw + l + 1 > savedText) {
         ERRMSG(0) "Character string storage space exhausted"
         EEND;
@@ -218,6 +240,199 @@ Text t; {                               /* at top of text table            */
 }
 
 
+static int fromHexDigit ( char c )
+{
+   switch (c) {
+      case '0': case '1': case '2': case '3': case '4':
+      case '5': case '6': case '7': case '8': case '9':
+         return c - '0';
+      case 'a': case 'A': return 10;
+      case 'b': case 'B': return 11;
+      case 'c': case 'C': return 12;
+      case 'd': case 'D': return 13;
+      case 'e': case 'E': return 14;
+      case 'f': case 'F': return 15;
+      default: return -1;
+   }
+}
+
+
+/* returns findText (unZencode s) */
+Text unZcodeThenFindText ( String s )
+{
+   unsigned char* p;
+   Int            n, nn, i;
+   Text           t;
+
+   assert(s);
+   nn = 100 + 10 * strlen(s);
+   p = malloc ( nn );
+   if (!p) internal ("unZcodeThenFindText: malloc failed");
+   n = 0;
+
+   while (1) {
+      if (!(*s)) break;
+      if (n > nn-90) internal ("unZcodeThenFindText: result is too big");
+      if (*s != 'z' && *s != 'Z') {
+         p[n] = *s; n++; s++; 
+         continue;
+      }
+      s++;
+      if (!(*s)) goto parse_error;
+      switch (*s++) {
+         case 'Z': p[n++] = 'Z'; break;
+         case 'C': p[n++] = ':'; break;
+         case 'L': p[n++] = '('; break;
+         case 'R': p[n++] = ')'; break;
+         case 'M': p[n++] = '['; break;
+         case 'N': p[n++] = ']'; break;
+         case 'z': p[n++] = 'z'; break;
+         case 'a': p[n++] = '&'; break;
+         case 'b': p[n++] = '|'; break;
+         case 'd': p[n++] = '$'; break;
+         case 'e': p[n++] = '='; break;
+         case 'g': p[n++] = '>'; break;
+         case 'h': p[n++] = '#'; break;
+         case 'i': p[n++] = '.'; break;
+         case 'l': p[n++] = '<'; break;
+         case 'm': p[n++] = '-'; break;
+         case 'n': p[n++] = '!'; break;
+         case 'p': p[n++] = '+'; break;
+         case 'q': p[n++] = '\\'; break;
+         case 'r': p[n++] = '\''; break;
+         case 's': p[n++] = '/'; break;
+         case 't': p[n++] = '*'; break;
+         case 'u': p[n++] = '^'; break;
+         case 'v': p[n++] = '%'; break;
+         case 'x':
+            if (!s[0] || !s[1]) goto parse_error;
+            if (fromHexDigit(s[0]) < 0 || fromHexDigit(s[1]) < 0) goto parse_error;
+            p[n++] = 16 * fromHexDigit(s[0]) + fromHexDigit(s[1]);
+            p += 2; s += 2;
+            break;
+         case '0': case '1': case '2': case '3': case '4':
+         case '5': case '6': case '7': case '8': case '9':
+            i = 0;
+            s--;
+            while (*s && isdigit((int)(*s))) {
+               i = 10 * i + (*s - '0');
+               s++;
+            }
+            if (*s != 'T') goto parse_error;
+            s++;
+            p[n++] = '(';
+            while (i > 0) { p[n++] = ','; i--; };
+            p[n++] = ')';
+            break;
+         default: 
+            goto parse_error;
+      }      
+   }
+   p[n] = 0;
+   t = findText(p);
+   free(p);
+   return t;
+
+  parse_error:
+   free(p);
+   fprintf ( stderr, "\nstring = `%s'\n", s );
+   internal ( "unZcodeThenFindText: parse error on above string");
+   return NIL; /*notreached*/
+}
+
+
+Text enZcodeThenFindText ( String s )
+{
+   unsigned char* p;
+   Int            n, nn;
+   Text           t;
+   char toHex[16] = "0123456789ABCDEF";
+
+   assert(s);
+   nn = 100 + 10 * strlen(s);
+   p = malloc ( nn );
+   if (!p) internal ("enZcodeThenFindText: malloc failed");
+   n = 0;
+   while (1) {
+      if (!(*s)) break;
+      if (n > nn-90) internal ("enZcodeThenFindText: result is too big");
+      if (*s != 'z' 
+          && *s != 'Z'
+          && (isalnum((int)(*s)) || *s == '_')) { 
+         p[n] = *s; n++; s++;
+         continue;
+      }
+      if (*s == '(') {
+         int tup = 0;
+         char num[12];
+         s++;
+         while (*s && *s==',') { s++; tup++; };
+         if (*s != ')') internal("enZcodeThenFindText: invalid tuple type");
+         s++;
+         p[n++] = 'Z';
+         sprintf(num,"%d",tup);
+         p[n] = 0; strcat ( &(p[n]), num ); n += strlen(num);
+         p[n++] = 'T';
+         continue;         
+      }
+      switch (*s++) {
+         case '(': p[n++] = 'Z'; p[n++] = 'L'; break;
+         case ')': p[n++] = 'Z'; p[n++] = 'R'; break;
+         case '[': p[n++] = 'Z'; p[n++] = 'M'; break;
+         case ']': p[n++] = 'Z'; p[n++] = 'N'; break;
+         case ':': p[n++] = 'Z'; p[n++] = 'C'; break;
+         case 'Z': p[n++] = 'Z'; p[n++] = 'Z'; break;
+         case 'z': p[n++] = 'z'; p[n++] = 'z'; break;
+         case '&': p[n++] = 'z'; p[n++] = 'a'; break;
+         case '|': p[n++] = 'z'; p[n++] = 'b'; break;
+         case '$': p[n++] = 'z'; p[n++] = 'd'; break;
+         case '=': p[n++] = 'z'; p[n++] = 'e'; break;
+         case '>': p[n++] = 'z'; p[n++] = 'g'; break;
+         case '#': p[n++] = 'z'; p[n++] = 'h'; break;
+         case '.': p[n++] = 'z'; p[n++] = 'i'; break;
+         case '<': p[n++] = 'z'; p[n++] = 'l'; break;
+         case '-': p[n++] = 'z'; p[n++] = 'm'; break;
+         case '!': p[n++] = 'z'; p[n++] = 'n'; break;
+         case '+': p[n++] = 'z'; p[n++] = 'p'; break;
+         case '\'': p[n++] = 'z'; p[n++] = 'q'; break;
+         case '\\': p[n++] = 'z'; p[n++] = 'r'; break;
+         case '/': p[n++] = 'z'; p[n++] = 's'; break;
+         case '*': p[n++] = 'z'; p[n++] = 't'; break;
+         case '^': p[n++] = 'z'; p[n++] = 'u'; break;
+         case '%': p[n++] = 'z'; p[n++] = 'v'; break;
+         default: s--; p[n++] = 'z'; p[n++] = 'x';
+                       p[n++] = toHex[(int)(*s)/16];
+                       p[n++] = toHex[(int)(*s)%16];
+                  s++; break;
+      }
+   }
+   p[n] = 0;
+   t = findText(p);
+   free(p);
+   return t;
+}
+
+
+Text textOf ( Cell c )
+{
+   Int  wot = whatIs(c);
+   Bool ok = 
+          (wot==VARIDCELL
+           || wot==CONIDCELL
+           || wot==VAROPCELL
+           || wot==CONOPCELL
+           || wot==STRCELL
+           || wot==DICTVAR
+           || wot==IPCELL
+           || wot==IPVAR
+          );
+   if (!ok) {
+      fprintf(stderr, "\ntextOf: bad tag %d\n",wot );
+      internal("textOf: bad tag");
+   }
+   return snd(c);
+}
+
 /* --------------------------------------------------------------------------
  * Ext storage:
  *
@@ -249,6 +464,156 @@ Text t; {
 }
 #endif
 
+
+/* --------------------------------------------------------------------------
+ * Expandable symbol tables.  A template, which is instantiated for the name, 
+ * tycon, class, instance and module tables.  Also, potentially, TREX Exts.
+ * ------------------------------------------------------------------------*/
+
+#ifdef DEBUG_STORAGE_EXTRA
+static Bool debugStorageExtra = TRUE;
+#else
+static Bool debugStorageExtra = FALSE;
+#endif
+
+
+#define EXPANDABLE_SYMBOL_TABLE(type_name,struct_name,                  \
+                                proc_name,free_proc_name,               \
+                                free_list,tab_name,tab_size,err_msg,    \
+                                TAB_INIT_SIZE,TAB_MAX_SIZE,             \
+                                TAB_BASE_ADDR)                          \
+                                                                        \
+             struct struct_name* tab_name  = NULL;                      \
+             int                 tab_size  = 0;                         \
+      static type_name           free_list = TAB_BASE_ADDR-1;           \
+                                                                        \
+      void free_proc_name ( type_name n )                               \
+      {                                                                 \
+         assert(TAB_BASE_ADDR <= n);                                    \
+         assert(n < TAB_BASE_ADDR+tab_size);                            \
+         assert(tab_name[n-TAB_BASE_ADDR].inUse);                       \
+         tab_name[n-TAB_BASE_ADDR].inUse = FALSE;                       \
+         if (!debugStorageExtra) {                                      \
+            tab_name[n-TAB_BASE_ADDR].nextFree = free_list;             \
+            free_list = n;                                              \
+         }                                                              \
+      }                                                                 \
+                                                                        \
+      type_name proc_name ( void )                                      \
+      {                                                                 \
+         Int    i;                                                      \
+         Int    newSz;                                                  \
+         struct struct_name* newTab;                                    \
+         struct struct_name* temp;                                      \
+         try_again:                                                     \
+         if (free_list != TAB_BASE_ADDR-1) {                            \
+            type_name t = free_list;                                    \
+            free_list = tab_name[free_list-TAB_BASE_ADDR].nextFree;     \
+            assert (!(tab_name[t-TAB_BASE_ADDR].inUse));                \
+            tab_name[t-TAB_BASE_ADDR].inUse = TRUE;                     \
+            return t;                                                   \
+         }                                                              \
+                                                                        \
+         newSz = (tab_size == 0 ? TAB_INIT_SIZE : 2 * tab_size);        \
+         if (newSz > TAB_MAX_SIZE) goto cant_allocate;                  \
+         newTab = malloc(newSz * sizeof(struct struct_name));           \
+         if (!newTab) goto cant_allocate;                               \
+         for (i = 0; i < tab_size; i++)                                 \
+            newTab[i] = tab_name[i];                                    \
+         for (i = tab_size; i < newSz; i++) {                           \
+            newTab[i].inUse = FALSE;                                    \
+            newTab[i].nextFree = i-1+TAB_BASE_ADDR;                     \
+         }                                                              \
+         if (0 && debugStorageExtra)                                    \
+            fprintf(stderr, "Expanding " #type_name                     \
+                            "table to size %d\n", newSz );              \
+         newTab[tab_size].nextFree = TAB_BASE_ADDR-1;                   \
+         free_list = newSz-1+TAB_BASE_ADDR;                             \
+         tab_size = newSz;                                              \
+         temp = tab_name;                                               \
+         tab_name = newTab;                                             \
+         if (temp) free(temp);                                          \
+         goto try_again;                                                \
+                                                                        \
+         cant_allocate:                                                 \
+         ERRMSG(0) err_msg                                              \
+         EEND;                                                          \
+      }                                                                 \
+
+
+
+EXPANDABLE_SYMBOL_TABLE(Name,strName,allocNewName,freeName,
+                        nameFL,tabName,tabNameSz,
+                        "Name storage space exhausted",
+                        NAME_INIT_SIZE,NAME_MAX_SIZE,NAME_BASE_ADDR)
+
+
+EXPANDABLE_SYMBOL_TABLE(Tycon,strTycon,allocNewTycon,freeTycon,
+                        tyconFL,tabTycon,tabTyconSz,
+                        "Type constructor storage space exhausted",
+                        TYCON_INIT_SIZE,TYCON_MAX_SIZE,TYCON_BASE_ADDR)
+
+
+EXPANDABLE_SYMBOL_TABLE(Class,strClass,allocNewClass,freeClass,
+                        classFL,tabClass,tabClassSz,
+                        "Class storage space exhausted",
+                        CCLASS_INIT_SIZE,CCLASS_MAX_SIZE,CCLASS_BASE_ADDR)
+
+
+EXPANDABLE_SYMBOL_TABLE(Inst,strInst,allocNewInst,freeInst,
+                        instFL,tabInst,tabInstSz,
+                        "Instance storage space exhausted",
+                        INST_INIT_SIZE,INST_MAX_SIZE,INST_BASE_ADDR)
+
+
+EXPANDABLE_SYMBOL_TABLE(Module,strModule,allocNewModule,freeModule,
+                        moduleFL,tabModule,tabModuleSz,
+                        "Module storage space exhausted",
+                        MODULE_INIT_SIZE,MODULE_MAX_SIZE,MODULE_BASE_ADDR)
+
+#ifdef DEBUG_STORAGE
+struct strName* generate_name_ref ( Cell nm )
+{
+   assert(isName(nm));
+   nm -= NAME_BASE_ADDR;
+   assert(tabName[nm].inUse);
+   assert(isModule(tabName[nm].mod));
+   return & tabName[nm]; 
+}
+struct strTycon* generate_tycon_ref ( Cell tc )
+{
+   assert(isTycon(tc) || isTuple(tc));
+   tc -= TYCON_BASE_ADDR;
+   assert(tabTycon[tc].inUse);
+   assert(isModule(tabTycon[tc].mod));
+   return & tabTycon[tc]; 
+}
+struct strClass* generate_cclass_ref ( Cell cl )
+{
+   assert(isClass(cl));
+   cl -= CCLASS_BASE_ADDR;
+   assert(tabClass[cl].inUse);
+   assert(isModule(tabClass[cl].mod));
+   return & tabClass[cl]; 
+}
+struct strInst* generate_inst_ref ( Cell in )
+{  
+   assert(isInst(in));
+   in -= INST_BASE_ADDR;
+   assert(tabInst[in].inUse);
+   assert(isModule(tabInst[in].mod));
+   return & tabInst[in]; 
+}
+struct strModule* generate_module_ref ( Cell mo )
+{  
+   assert(isModule(mo));
+   mo -= MODULE_BASE_ADDR;
+   assert(tabModule[mo].inUse);
+   return & tabModule[mo]; 
+}
+#endif
+
+
 /* --------------------------------------------------------------------------
  * Tycon storage:
  *
@@ -259,38 +624,53 @@ Text t; {
  * ------------------------------------------------------------------------*/
 
 #define TYCONHSZ 256                            /* Size of Tycon hash table*/
-#define tHash(x) ((x)%TYCONHSZ)                 /* Tycon hash function     */
-static  Tycon    tyconHw;                       /* next unused Tycon       */
-static  Tycon    DEFTABLE(tyconHash,TYCONHSZ);  /* Hash table storage      */
-struct  strTycon DEFTABLE(tabTycon,NUM_TYCON);  /* Tycon storage           */
+static  Tycon    tyconHash[TYCONHSZ];           /* Hash table storage      */
 
-Tycon newTycon(t)                       /* add new tycon to tycon table    */
-Text t; {
-    Int h = tHash(t);
-    if (tyconHw-TYCMIN >= NUM_TYCON) {
-        ERRMSG(0) "Type constructor storage space exhausted"
-        EEND;
-    }
-    tycon(tyconHw).text          = t;   /* clear new tycon record          */
-    tycon(tyconHw).kind          = NIL;
-    tycon(tyconHw).defn          = NIL;
-    tycon(tyconHw).what          = NIL;
-    tycon(tyconHw).conToTag      = NIL;
-    tycon(tyconHw).tagToCon      = NIL;
-#if !IGNORE_MODULES
-    tycon(tyconHw).mod           = currentModule;
-    module(currentModule).tycons = cons(tyconHw,module(currentModule).tycons);
-#endif
-    tycon(tyconHw).nextTyconHash = tyconHash[h];
-    tyconHash[h]                 = tyconHw;
+static int tHash(Text x)
+{
+   int r;
+   assert(isText(x) || inventedText(x));
+   x -= TEXT_BASE_ADDR;
+   if (x < 0) x = -x;
+   r= x%TYCONHSZ;
+   assert(r>=0);
+   assert(r<TYCONHSZ);
+   return r;
+}
 
-    return tyconHw++;
+static int RC_T ( int x ) 
+{
+   assert (x >= 0 && x < TYCONHSZ);
+   return x;
+}
+
+Tycon newTycon ( Text t )               /* add new tycon to tycon table    */
+{
+    Int   h                      = tHash(t);
+    Tycon tc                     = allocNewTycon();
+    tabTycon
+      [tc-TYCON_BASE_ADDR].tuple = -1;
+    tabTycon
+      [tc-TYCON_BASE_ADDR].mod   = currentModule;
+    tycon(tc).text               = t;   /* clear new tycon record          */
+    tycon(tc).kind               = NIL;
+    tycon(tc).defn               = NIL;
+    tycon(tc).what               = NIL;
+    tycon(tc).conToTag           = NIL;
+    tycon(tc).tagToCon           = NIL;
+    tycon(tc).itbl               = NULL;
+    tycon(tc).arity              = 0;
+    tycon(tc).closure            = NIL;
+    module(currentModule).tycons = cons(tc,module(currentModule).tycons);
+    tycon(tc).nextTyconHash      = tyconHash[RC_T(h)];
+    tyconHash[RC_T(h)]                 = tc;
+    return tc;
 }
 
 Tycon findTycon(t)                      /* locate Tycon in tycon table     */
 Text t; {
-    Tycon tc = tyconHash[tHash(t)];
-
+    Tycon tc = tyconHash[RC_T(tHash(t))];
+    assert(isTycon(tc) || isTuple(tc) || isNull(tc));
     while (nonNull(tc) && tycon(tc).text!=t)
        tc = tycon(tc).nextTyconHash;
     return tc;
@@ -298,12 +678,12 @@ Text t; {
 
 Tycon addTycon(tc)  /* Insert Tycon in tycon table - if no clash is caused */
 Tycon tc; {
-    Tycon oldtc = findTycon(tycon(tc).text);
+    Tycon oldtc; 
+    assert(isTycon(tc) || isTuple(tc));
+    oldtc = findTycon(tycon(tc).text);
     if (isNull(oldtc)) {
         hashTycon(tc);
-#if !IGNORE_MODULES
         module(currentModule).tycons=cons(tc,module(currentModule).tycons);
-#endif
         return tc;
     } else
         return oldtc;
@@ -311,10 +691,18 @@ Tycon tc; {
 
 static Void local hashTycon(tc)         /* Insert Tycon into hash table    */
 Tycon tc; {
-    Text  t = tycon(tc).text;
-    Int   h = tHash(t);
-    tycon(tc).nextTyconHash = tyconHash[h];
-    tyconHash[h]            = tc;
+   Text t;
+   Int  h;
+   assert(isTycon(tc) || isTuple(tc));
+   {int i; for (i = 0; i < TYCONHSZ; i++)
+       assert (tyconHash[i] == 0 
+               || isTycon(tyconHash[i])
+               || isTuple(tyconHash[i]));
+   }
+   t = tycon(tc).text;
+   h = tHash(t);
+   tycon(tc).nextTyconHash = tyconHash[RC_T(h)];
+   tyconHash[RC_T(h)]            = tc;
 }
 
 Tycon findQualTycon(id) /*locate (possibly qualified) Tycon in tycon table */
@@ -325,9 +713,6 @@ Cell id; {
         case CONOPCELL :
             return findTycon(textOf(id));
         case QUALIDENT : {
-#if IGNORE_MODULES
-            return findTycon(qtextOf(id));
-#else /* !IGNORE_MODULES */
             Text   t  = qtextOf(id);
             Module m  = findQualifier(qmodOf(id));
             List   es = NIL;
@@ -338,11 +723,10 @@ Cell id; {
                     return fst(e);
             }
             return NIL;
-#endif /* !IGNORE_MODULES */
         }
         default : internal("findQualTycon2");
     }
-    return 0; /* NOTREACHED */
+    return NIL; /* NOTREACHED */
 }
 
 Tycon addPrimTycon(t,kind,ar,what,defn) /* add new primitive type constr   */
@@ -385,13 +769,51 @@ List addTyconsMatching(pat,ts)          /* Add tycons matching pattern pat */
 String pat;                             /* to list of Tycons ts            */
 List   ts; {                            /* Null pattern matches every tycon*/
     Tycon tc;                           /* (Tycons with NIL kind excluded) */
-    for (tc=TYCMIN; tc<tyconHw; ++tc)
-        if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
-            if (nonNull(tycon(tc).kind))
-                ts = insertTycon(tc,ts);
+    for (tc = TYCON_BASE_ADDR;
+         tc < TYCON_BASE_ADDR+tabTyconSz; ++tc)
+        if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
+           if (!pat || stringMatch(pat,textToStr(tycon(tc).text)))
+               if (nonNull(tycon(tc).kind))
+                  ts = insertTycon(tc,ts);
     return ts;
 }
 
+Text ghcTupleText_n ( Int n )
+{
+    Int i;
+    Int x = 0; 
+    char buf[104];
+    if (n < 0 || n >= 100) internal("ghcTupleText_n");
+    if (n == 1) internal("ghcTupleText_n==1");
+    buf[x++] = '(';
+    for (i = 1; i <= n-1; i++) buf[x++] = ',';
+    buf[x++] = ')';
+    buf[x++] = 0;
+    return findText(buf);
+}
+
+Text ghcTupleText(tup)
+Tycon tup; {
+    if (!isTuple(tup)) {
+       assert(isTuple(tup));
+    }
+    return ghcTupleText_n ( tupleOf(tup) );
+}
+
+
+Tycon mkTuple ( Int n )
+{
+   Int i;
+   if (n >= NUM_TUPLES)
+      internal("mkTuple: request for tuple of unsupported size");
+   for (i = TYCON_BASE_ADDR;
+        i < TYCON_BASE_ADDR+tabTyconSz; i++)
+      if (tabTycon[i-TYCON_BASE_ADDR].inUse)
+         if (tycon(i).tuple == n) return i;
+   internal("mkTuple: request for non-existent tuple");
+}
+
+
 /* --------------------------------------------------------------------------
  * Name storage:
  *
@@ -406,41 +828,71 @@ List   ts; {                            /* Null pattern matches every tycon*/
  * ------------------------------------------------------------------------*/
 
 #define NAMEHSZ  256                            /* Size of Name hash table */
-#define nHash(x) ((x)%NAMEHSZ)                  /* hash fn :: Text->Int    */
-        Name     nameHw;                        /* next unused name        */
-static  Name     DEFTABLE(nameHash,NAMEHSZ);    /* Hash table storage      */
-struct  strName  DEFTABLE(tabName,NUM_NAME);    /* Name table storage      */
-
-Name newName(t,parent)                  /* Add new name to name table      */
-Text t; 
-Cell parent; {
+static  Name     nameHash[NAMEHSZ];             /* Hash table storage      */
+
+static int nHash(Text x)
+{
+   assert(isText(x) || inventedText(x));
+   x -= TEXT_BASE_ADDR;
+   if (x < 0) x = -x;
+   return x%NAMEHSZ;
+}
+
+int RC_N ( int x ) 
+{
+   assert (x >= 0 && x < NAMEHSZ);
+   return x;
+}
+
+void hashSanity ( void )
+{
+   Int i, j;
+   for (i = 0; i < TYCONHSZ; i++) {
+      j = tyconHash[i];
+      while (nonNull(j)) {
+         assert(isTycon(j) || isTuple(j));
+         j = tycon(j).nextTyconHash;
+      }
+   }
+   for (i = 0; i < NAMEHSZ; i++) {
+      j = nameHash[i];
+      while (nonNull(j)) {
+         assert(isName(j));
+         j = name(j).nextNameHash;
+      }
+   }
+}
+
+Name newName ( Text t, Cell parent )    /* Add new name to name table      */
+{
     Int h = nHash(t);
-    if (nameHw-NAMEMIN >= NUM_NAME) {
-        ERRMSG(0) "Name storage space exhausted"
-        EEND;
-    }
-    name(nameHw).text         = t;      /* clear new name record           */
-    name(nameHw).line         = 0;
-    name(nameHw).syntax       = NO_SYNTAX;
-    name(nameHw).parent       = parent;
-    name(nameHw).arity        = 0;
-    name(nameHw).number       = EXECNAME;
-    name(nameHw).defn         = NIL;
-    name(nameHw).stgVar       = NIL;
-    name(nameHw).type         = NIL;
-    name(nameHw).primop       = 0;
-    name(nameHw).mod          = currentModule;
-    module(currentModule).names=cons(nameHw,module(currentModule).names);
-    name(nameHw).nextNameHash = nameHash[h];
-    nameHash[h]               = nameHw;
-assert ( name(nameHw).nextNameHash != nameHash[h] );
-    return nameHw++;
+    Name nm = allocNewName();
+    tabName
+       [nm-NAME_BASE_ADDR].mod  = currentModule;
+    name(nm).text               = t;    /* clear new name record           */
+    name(nm).line               = 0;
+    name(nm).syntax             = NO_SYNTAX;
+    name(nm).parent             = parent;
+    name(nm).arity              = 0;
+    name(nm).number             = EXECNAME;
+    name(nm).defn               = NIL;
+    name(nm).hasStrict          = FALSE;
+    name(nm).callconv           = NIL;
+    name(nm).type               = NIL;
+    name(nm).primop             = NULL;
+    name(nm).itbl               = NULL;
+    name(nm).closure            = NIL;
+    module(currentModule).names = cons(nm,module(currentModule).names);
+    name(nm).nextNameHash       = nameHash[RC_N(h)];
+    nameHash[RC_N(h)]           = nm;
+    return nm;
 }
 
 Name findName(t)                        /* Locate name in name table       */
 Text t; {
-    Name n = nameHash[nHash(t)];
-
+    Name n = nameHash[RC_N(nHash(t))];
+    assert(isText(t) || isInventedVar(t) || isInventedDictVar(t));
+    assert(isName(n) || isNull(n));
     while (nonNull(n) && name(n).text!=t)
        n = name(n).nextNameHash;
     return n;
@@ -448,12 +900,12 @@ Text t; {
 
 Name addName(nm)                        /* Insert Name in name table - if  */
 Name nm; {                              /* no clash is caused              */
-    Name oldnm = findName(name(nm).text);
+    Name oldnm; 
+    assert(isName(nm));
+    oldnm = findName(name(nm).text);
     if (isNull(oldnm)) {
         hashName(nm);
-#if !IGNORE_MODULES
         module(currentModule).names=cons(nm,module(currentModule).names);
-#endif
         return nm;
     } else
         return oldnm;
@@ -461,10 +913,13 @@ Name nm; {                              /* no clash is caused              */
 
 static Void local hashName(nm)          /* Insert Name into hash table    */
 Name nm; {
-    Text t               = name(nm).text;
-    Int  h               = nHash(t);
-    name(nm).nextNameHash = nameHash[h];
-    nameHash[h]           = nm;
+    Text t;
+    Int  h;
+    assert(isName(nm));
+    t = name(nm).text;
+    h = nHash(t);
+    name(nm).nextNameHash = nameHash[RC_N(h)];
+    nameHash[RC_N(h)]           = nm;
 }
 
 Name findQualName(id)              /* Locate (possibly qualified) name*/
@@ -478,9 +933,6 @@ Cell id; {                         /* in name table                   */
         case CONOPCELL :
             return findName(textOf(id));
         case QUALIDENT : {
-#if IGNORE_MODULES
-            return findName(qtextOf(id));
-#else /* !IGNORE_MODULES */
             Text   t  = qtextOf(id);
             Module m  = findQualifier(qmodOf(id));
             List   es = NIL;
@@ -506,17 +958,135 @@ Cell id; {                         /* in name table                   */
                 }
             }
             return NIL;
-#endif /* !IGNORE_MODULES */
         }
         default : internal("findQualName2");
     }
     return 0; /* NOTREACHED */
 }
 
+
+void* /* StgClosure* */ getHugs_BCO_cptr_for ( char* s )
+{
+   Text   t = findText(s);
+   Name   n = NIL;
+   for (n = NAME_BASE_ADDR; 
+        n < NAME_BASE_ADDR+tabNameSz; n++)
+      if (tabName[n-NAME_BASE_ADDR].inUse && name(n).text == t) 
+         break;
+   if (n == NAME_BASE_ADDR+tabNameSz) {
+      fprintf ( stderr, "can't find `%s' in ...\n", s );
+      internal("getHugs_BCO_cptr_for(1)");
+   }
+   if (!isCPtr(name(n).closure))
+      internal("getHugs_BCO_cptr_for(2)");
+   return cptrOf(name(n).closure);
+}
+
 /* --------------------------------------------------------------------------
  * Primitive functions:
  * ------------------------------------------------------------------------*/
 
+Module findFakeModule ( Text t )
+{
+   Module m = findModule(t);
+   if (nonNull(m)) {
+      if (!module(m).fake) internal("findFakeModule");
+   } else {
+      m = newModule(t);
+      module(m).fake = TRUE;
+   }
+   return m;
+}
+
+
+Name addWiredInBoxingTycon
+        ( String modNm, String typeNm, String constrNm,
+          Int rep, Kind kind )
+{
+   Name   n;
+   Tycon  t;
+   Text   modT  = findText(modNm);
+   Text   typeT = findText(typeNm);
+   Text   conT  = findText(constrNm);
+   Module m     = findFakeModule(modT);
+   setCurrModule(m);
+   
+   n = newName(conT,NIL);
+   name(n).arity  = 1;
+   name(n).number = cfunNo(0);
+   name(n).type   = NIL;
+   name(n).primop = (void*)rep;
+
+   t = newTycon(typeT);
+   tycon(t).what = DATATYPE;
+   tycon(t).kind = kind;
+   return n;
+}
+
+
+Tycon addTupleTycon ( Int n )
+{
+   Int    i;
+   Kind   k;
+   Tycon  t;
+   Module m;
+   Name   nm;
+
+   for (i = TYCON_BASE_ADDR; 
+        i < TYCON_BASE_ADDR+tabTyconSz; i++)
+      if (tabTycon[i-TYCON_BASE_ADDR].inUse)
+         if (tycon(i).tuple == n) return i;
+
+   if (combined)
+      m = findFakeModule(findText(n==0 ? "PrelBase" : "PrelTup")); else
+      m = findModule(findText("PrelPrim"));
+
+   setCurrModule(m);
+   k = STAR;
+   for (i = 0; i < n; i++) k = ap(STAR,k);
+   t = newTycon(ghcTupleText_n(n));
+   tycon(t).kind  = k;
+   tycon(t).tuple = n;
+   tycon(t).what  = DATATYPE;
+
+   if (n == 0) {
+      /* maybe we want to do this for all n ? */
+      nm = newName(ghcTupleText_n(n), t);
+      name(nm).type = t;   /* ummm ... for n > 0 */
+   }
+
+   return t;
+}
+
+
+Tycon addWiredInEnumTycon ( String modNm, String typeNm, 
+                            List /*of Text*/ constrs )
+{
+   Int    i;
+   Tycon  t;
+   Text   modT  = findText(modNm);
+   Text   typeT = findText(typeNm);
+   Module m     = findFakeModule(modT);
+   setCurrModule(m);
+
+   t             = newTycon(typeT);
+   tycon(t).kind = STAR;
+   tycon(t).what = DATATYPE;
+   
+   constrs = reverse(constrs);
+   i       = length(constrs);
+   for (; nonNull(constrs); constrs=tl(constrs),i--) {
+      Text conT        = hd(constrs);
+      Name con         = newName(conT,t);
+      name(con).number = cfunNo(i);
+      name(con).type   = t;
+      name(con).parent = t;
+      tycon(t).defn    = cons(con, tycon(t).defn);      
+   }
+   return t;
+}
+
+
 Name addPrimCfunREP(t,arity,no,rep)     /* add primitive constructor func  */
 Text t;                                 /* sets rep, not type              */
 Int  arity;
@@ -581,13 +1151,17 @@ List addNamesMatching(pat,ns)           /* Add names matching pattern pat  */
 String pat;                             /* to list of names ns             */
 List   ns; {                            /* Null pattern matches every name */
     Name nm;                            /* (Names with NIL type, or hidden */
+                                        /* or invented names are excluded) */
 #if 1
-    for (nm=NAMEMIN; nm<nameHw; ++nm)   /* or invented names are excluded) */
-        if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
-            String str = textToStr(name(nm).text);
-            if (str[0]!='_' && (!pat || stringMatch(pat,str)))
-                ns = insertName(nm,ns);
-        }
+    for (nm = NAME_BASE_ADDR;
+         nm < NAME_BASE_ADDR+tabNameSz; ++nm)
+       if (tabName[nm-NAME_BASE_ADDR].inUse) {
+          if (!inventedText(name(nm).text) && nonNull(name(nm).type)) {
+             String str = textToStr(name(nm).text);
+             if (str[0]!='_' && (!pat || stringMatch(pat,str)))
+                 ns = insertName(nm,ns);
+          }
+       }
     return ns;
 #else
     List mns = module(currentModule).names;
@@ -669,42 +1243,31 @@ String str; {
  * Storage of type classes, instances etc...:
  * ------------------------------------------------------------------------*/
 
-static Class classHw;                  /* next unused class                */
 static List  classes;                  /* list of classes in current scope */
-static Inst  instHw;                   /* next unused instance record      */
 
-struct strClass DEFTABLE(tabClass,NUM_CLASSES); /* table of class records  */
-struct strInst far *tabInst;           /* (pointer to) table of instances  */
-
-Class newClass(t)                      /* add new class to class table     */
-Text t; {
-    if (classHw-CLASSMIN >= NUM_CLASSES) {
-        ERRMSG(0) "Class storage space exhausted"
-        EEND;
-    }
-    cclass(classHw).text      = t;
-    cclass(classHw).arity     = 0;
-    cclass(classHw).kinds     = NIL;
-    cclass(classHw).head      = NIL;
-    cclass(classHw).dcon      = NIL;
-    cclass(classHw).supers    = NIL;
-    cclass(classHw).dsels     = NIL;
-    cclass(classHw).members   = NIL;
-    cclass(classHw).dbuild    = NIL;
-    cclass(classHw).defaults  = NIL;
-    cclass(classHw).instances = NIL;
-    classes=cons(classHw,classes);
-#if !IGNORE_MODULES
-    cclass(classHw).mod       = currentModule;
-    module(currentModule).classes=cons(classHw,module(currentModule).classes);
-#endif
-    return classHw++;
+Class newClass ( Text t )              /* add new class to class table     */
+{
+    Class cl                     = allocNewClass();
+    tabClass
+      [cl-CCLASS_BASE_ADDR].mod  = currentModule;
+    cclass(cl).text              = t;
+    cclass(cl).arity             = 0;
+    cclass(cl).kinds             = NIL;
+    cclass(cl).head              = NIL;
+    cclass(cl).fds               = NIL;
+    cclass(cl).xfds              = NIL;
+    cclass(cl).dcon              = NIL;
+    cclass(cl).supers            = NIL;
+    cclass(cl).dsels             = NIL;
+    cclass(cl).members           = NIL;
+    cclass(cl).defaults          = NIL;
+    cclass(cl).instances         = NIL;
+    classes                      = cons(cl,classes);
+    module(currentModule).classes
+       = cons(cl,module(currentModule).classes);
+    return cl;
 }
 
-Class classMax() {                      /* Return max Class in use ...     */
-    return classHw;                     /* This is a bit ugly, but it's not*/
-}                                       /* worth a lot of effort right now */
-
 Class findClass(t)                     /* look for named class in table    */
 Text t; {
     Class cl;
@@ -719,12 +1282,12 @@ Text t; {
 
 Class addClass(c)                       /* Insert Class in class list      */
 Class c; {                              /*  - if no clash caused           */
-    Class oldc = findClass(cclass(c).text);
+    Class oldc; 
+    assert(whatIs(c)==CLASS);
+    oldc = findClass(cclass(c).text);
     if (isNull(oldc)) {
         classes=cons(c,classes);
-#if !IGNORE_MODULES
         module(currentModule).classes=cons(c,module(currentModule).classes);
-#endif
         return c;
     }
     else
@@ -736,9 +1299,6 @@ Cell c; {                               /* class in class list             */
     if (!isQualIdent(c)) {
         return findClass(textOf(c));
     } else {
-#if IGNORE_MODULES
-        return findClass(qtextOf(c));
-#else /* !IGNORE_MODULES */
         Text   t  = qtextOf(c);
         Module m  = findQualifier(qmodOf(c));
         List   es = NIL;
@@ -749,27 +1309,25 @@ Cell c; {                               /* class in class list             */
             if (isPair(e) && isClass(fst(e)) && cclass(fst(e)).text==t) 
                 return fst(e);
         }
-#endif
     }
     return NIL;
 }
 
 Inst newInst() {                       /* Add new instance to table        */
-    if (instHw-INSTMIN >= NUM_INSTS) {
-        ERRMSG(0) "Instance storage space exhausted"
-        EEND;
-    }
-    inst(instHw).kinds      = NIL;
-    inst(instHw).head       = NIL;
-    inst(instHw).specifics  = NIL;
-    inst(instHw).implements = NIL;
-    inst(instHw).builder    = NIL;
-
-    return instHw++;
+    Inst in                    = allocNewInst();
+    tabInst
+       [in-INST_BASE_ADDR].mod = currentModule;
+    inst(in).kinds             = NIL;
+    inst(in).head              = NIL;
+    inst(in).specifics         = NIL;
+    inst(in).numSpecifics      = 0;
+    inst(in).implements        = NIL;
+    inst(in).builder           = NIL;
+    return in;
 }
 
 #ifdef DEBUG_DICTS
-extern Void printInst Args((Inst));
+extern Void printInst ( Inst));
 
 Void printInst(in)
 Inst in; {
@@ -781,14 +1339,17 @@ Inst in; {
 
 Inst findFirstInst(tc)                  /* look for 1st instance involving */
 Tycon tc; {                             /* the type constructor tc         */
-    return findNextInst(tc,INSTMIN-1);
+    return findNextInst(tc,INST_BASE_ADDR-1);
 }
 
 Inst findNextInst(tc,in)                /* look for next instance involving*/
 Tycon tc;                               /* the type constructor tc         */
 Inst  in; {                             /* starting after instance in      */
-    while (++in < instHw) {
-        Cell pi = inst(in).head;
+    Cell pi;
+    while (++in < INST_BASE_ADDR+tabInstSz) {
+        if (!tabInst[in-INST_BASE_ADDR].inUse) continue;
+        assert(isModule(inst(in).mod));
+        pi = inst(in).head;
         for (; isAp(pi); pi=fun(pi))
             if (typeInvolves(arg(pi),tc))
                 return in;
@@ -804,6 +1365,191 @@ Type tc; {
                          || typeInvolves(arg(ty),tc)));
 }
 
+
+/* Needed by finishGHCInstance to find classes, before the
+   export list has been built -- so we can't use 
+   findQualClass.
+*/
+Class findQualClassWithoutConsultingExportList ( QualId q )
+{
+   Class cl;
+   Text t_mod;
+   Text t_class;
+
+   assert(isQCon(q));
+
+   if (isCon(q)) {
+      t_mod   = NIL;
+      t_class = textOf(q);
+   } else {
+      t_mod   = qmodOf(q);
+      t_class = qtextOf(q);
+   }
+
+   for (cl = CCLASS_BASE_ADDR; 
+        cl < CCLASS_BASE_ADDR+tabClassSz; cl++) {
+      if (tabClass[cl-CCLASS_BASE_ADDR].inUse)
+         if (cclass(cl).text == t_class) {
+            /* Class name is ok, but is this the right module? */
+            if (isNull(t_mod)   /* no module name specified */
+                || (nonNull(t_mod) 
+                    && t_mod == module(cclass(cl).mod).text)
+               )
+               return cl;
+         }
+   }
+   return NIL;
+}
+
+/* Same deal, except for Tycons. */
+Tycon findQualTyconWithoutConsultingExportList ( QualId q )
+{
+   Tycon tc;
+   Text t_mod;
+   Text t_tycon;
+
+   assert(isQCon(q));
+
+   if (isCon(q)) {
+      t_mod   = NIL;
+      t_tycon = textOf(q);
+   } else {
+      t_mod   = qmodOf(q);
+      t_tycon = qtextOf(q);
+   }
+
+   for (tc = TYCON_BASE_ADDR; 
+        tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
+      if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
+         if (tycon(tc).text == t_tycon) {
+            /* Tycon name is ok, but is this the right module? */
+            if (isNull(t_mod)   /* no module name specified */
+                || (nonNull(t_mod) 
+                    && t_mod == module(tycon(tc).mod).text)
+               )
+               return tc;
+         }
+   }
+   return NIL;
+}
+
+/* Same deal, except for Names. */
+Name findQualNameWithoutConsultingExportList ( QualId q )
+{
+   Name nm;
+   Text t_mod;
+   Text t_name;
+
+   assert(isQVar(q) || isQCon(q));
+
+   if (isCon(q) || isVar(q)) {
+      t_mod  = NIL;
+      t_name = textOf(q);
+   } else {
+      t_mod  = qmodOf(q);
+      t_name = qtextOf(q);
+   }
+
+   for (nm = NAME_BASE_ADDR; 
+        nm < NAME_BASE_ADDR+tabNameSz; nm++) {
+      if (tabName[nm-NAME_BASE_ADDR].inUse)
+         if (name(nm).text == t_name) {
+            /* Name is ok, but is this the right module? */
+            if (isNull(t_mod)   /* no module name specified */
+                || (nonNull(t_mod) 
+                    && t_mod == module(name(nm).mod).text)
+               )
+               return nm;
+         }
+   }
+   return NIL;
+}
+
+
+Tycon findTyconInAnyModule ( Text t )
+{
+   Tycon tc;
+   for (tc = TYCON_BASE_ADDR; 
+        tc < TYCON_BASE_ADDR+tabTyconSz; tc++)
+      if (tabTycon[tc-TYCON_BASE_ADDR].inUse)
+         if (tycon(tc).text == t) return tc;
+   return NIL;
+}
+
+Class findClassInAnyModule ( Text t )
+{
+   Class cc;
+   for (cc = CCLASS_BASE_ADDR; 
+        cc < CCLASS_BASE_ADDR+tabClassSz; cc++)
+      if (tabClass[cc-CCLASS_BASE_ADDR].inUse)
+         if (cclass(cc).text == t) return cc;
+   return NIL;
+}
+
+Name findNameInAnyModule ( Text t )
+{
+   Name nm;
+   for (nm = NAME_BASE_ADDR; 
+        nm < NAME_BASE_ADDR+tabNameSz; nm++)
+      if (tabName[nm-NAME_BASE_ADDR].inUse)
+         if (name(nm).text == t) return nm;
+   return NIL;
+}
+
+
+/* returns List of QualId */
+List getAllKnownTyconsAndClasses ( void )
+{
+   Tycon tc;
+   Class nw;
+   List  xs = NIL;
+   for (tc = TYCON_BASE_ADDR; 
+        tc < TYCON_BASE_ADDR+tabTyconSz; tc++) {
+      if (tabTycon[tc-TYCON_BASE_ADDR].inUse) {
+         /* almost certainly undue paranoia about duplicate avoidance */
+         QualId q = mkQCon( module(tycon(tc).mod).text, tycon(tc).text );
+         if (!qualidIsMember(q,xs))
+            xs = cons ( q, xs );
+      }
+   }
+   for (nw = CCLASS_BASE_ADDR; 
+        nw < CCLASS_BASE_ADDR+tabClassSz; nw++) {
+      if (tabClass[nw-CCLASS_BASE_ADDR].inUse) {
+         QualId q = mkQCon( module(cclass(nw).mod).text, cclass(nw).text );
+         if (!qualidIsMember(q,xs))
+            xs = cons ( q, xs );
+      }
+   }
+   return xs;
+}
+
+Int numQualifiers ( Type t )
+{
+   if (isPolyType(t)) t = monotypeOf(t);
+   if (isQualType(t)) 
+       return length ( fst(snd(t)) ); else
+       return 0;
+}
+
+
+/* Purely for debugging. */
+void locateSymbolByName ( Text t )
+{
+   Int i;
+   for (i = NAME_BASE_ADDR; 
+        i < NAME_BASE_ADDR+tabNameSz; i++)
+      if (tabName[i-NAME_BASE_ADDR].inUse && name(i).text == t)
+         fprintf ( stderr, "name(%d)\n", i-NAME_BASE_ADDR);
+   for (i = TYCON_BASE_ADDR; 
+        i < TYCON_BASE_ADDR+tabTyconSz; i++)
+      if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).text == t)
+         fprintf ( stderr, "tycon(%d)\n", i-TYCON_BASE_ADDR);
+   for (i = CCLASS_BASE_ADDR; 
+        i < CCLASS_BASE_ADDR+tabClassSz; i++)
+      if (tabClass[i-CCLASS_BASE_ADDR].inUse && cclass(i).text == t)
+         fprintf ( stderr, "class(%d)\n", i-CCLASS_BASE_ADDR);
+}
+
 /* --------------------------------------------------------------------------
  * Control stack:
  *
@@ -811,51 +1557,14 @@ Type tc; {
  * operations are defined as macros, expanded inline.
  * ------------------------------------------------------------------------*/
 
-Cell DEFTABLE(cellStack,NUM_STACK); /* Storage for cells on stack          */
+Cell cellStack[NUM_STACK];          /* Storage for cells on stack          */
 StackPtr sp;                        /* stack pointer                       */
 
-#if GIMME_STACK_DUMPS
-
-#define UPPER_DISP  5               /* # display entries on top of stack   */
-#define LOWER_DISP  5               /* # display entries on bottom of stack*/
-
-Void hugsStackOverflow() {          /* Report stack overflow               */
-    extern Int  rootsp;
-    extern Cell evalRoots[];
-
-    ERRMSG(0) "Control stack overflow" ETHEN
-    if (rootsp>=0) {
-        Int i;
-        if (rootsp>=UPPER_DISP+LOWER_DISP) {
-            for (i=0; i<UPPER_DISP; i++) {
-                ERRTEXT "\nwhile evaluating: " ETHEN
-                ERREXPR(evalRoots[rootsp-i]);
-            }
-            ERRTEXT "\n..." ETHEN
-            for (i=LOWER_DISP-1; i>=0; i--) {
-                ERRTEXT "\nwhile evaluating: " ETHEN
-                ERREXPR(evalRoots[i]);
-            }
-        }
-        else {
-            for (i=rootsp; i>=0; i--) {
-                ERRTEXT "\nwhile evaluating: " ETHEN
-                ERREXPR(evalRoots[i]);
-            }
-        }
-    }
-    ERRTEXT "\n"
-    EEND;
-}
-
-#else /* !GIMME_STACK_DUMPS */
-
 Void hugsStackOverflow() {          /* Report stack overflow               */
     ERRMSG(0) "Control stack overflow"
     EEND;
 }
 
-#endif /* !GIMME_STACK_DUMPS */
 
 /* --------------------------------------------------------------------------
  * Module storage:
@@ -874,38 +1583,148 @@ Void hugsStackOverflow() {          /* Report stack overflow               */
  *
  * ------------------------------------------------------------------------*/
 
-#if !IGNORE_MODULES
-static  Module   moduleHw;              /* next unused Module              */
-struct  Module   DEFTABLE(tabModule,NUM_MODULE); /* Module storage         */
 Module  currentModule;                  /* Module currently being processed*/
 
-Bool isValidModule(m)                  /* is m a legitimate module id?     */
+Bool isValidModule(m)                   /* is m a legitimate module id?    */
 Module m; {
-    return (MODMIN <= m && m < moduleHw);
+    return isModule(m);
 }
 
-Module newModule(t)                     /* add new module to module table  */
-Text t; {
-    if (moduleHw-MODMIN >= NUM_MODULE) {
-        ERRMSG(0) "Module storage space exhausted"
-        EEND;
-    }
-    module(moduleHw).text          = t; /* clear new module record         */
-    module(moduleHw).qualImports   = NIL;
-    module(moduleHw).exports       = NIL;
-    module(moduleHw).tycons        = NIL;
-    module(moduleHw).names         = NIL;
-    module(moduleHw).classes       = NIL;
-    module(moduleHw).objectFile    = 0;
-    return moduleHw++;
+Module newModule ( Text t )             /* add new module to module table  */
+{
+    Module mod                   = allocNewModule();
+    module(mod).text             = t;      /* clear new module record      */
+
+    module(mod).tycons           = NIL;
+    module(mod).names            = NIL;
+    module(mod).classes          = NIL;
+    module(mod).exports          = NIL;
+    module(mod).qualImports      = NIL;
+    module(mod).codeList         = NIL;
+    module(mod).fake             = FALSE;
+
+    module(mod).tree             = NIL;
+    module(mod).completed        = FALSE;
+    module(mod).lastStamp        = 0; /* ???? */
+
+    module(mod).mode             = NIL;
+    module(mod).srcExt           = findText("");
+    module(mod).uses             = NIL;
+
+    module(mod).objName          = findText("");
+    module(mod).objSize          = 0;
+
+    module(mod).object           = NULL;
+    module(mod).objectExtras     = NULL;
+    module(mod).objectExtraNames = NIL;
+    return mod;
 }
 
+
+Bool nukeModule_needs_major_gc = TRUE;
+
+void nukeModule ( Module m )
+{
+   ObjectCode* oc;
+   ObjectCode* oc2;
+   Int         i;
+
+   if (!isModule(m)) internal("nukeModule");
+
+   /* fprintf ( stderr, "NUKE MODULE %s\n", textToStr(module(m).text) ); */
+
+   /* see comment in compiler.c about this, 
+      and interaction with info tables */
+   if (nukeModule_needs_major_gc) {
+      /* fprintf ( stderr, "doing major GC in nukeModule\n"); */
+      /* performMajorGC(); */
+      nukeModule_needs_major_gc = FALSE;
+   }
+
+   oc = module(m).object;
+   while (oc) {
+      oc2 = oc->next;
+      ocFree(oc);
+      oc = oc2;
+   }
+   oc = module(m).objectExtras;
+   while (oc) {
+      oc2 = oc->next;
+      ocFree(oc);
+      oc = oc2;
+   }
+
+   for (i = NAME_BASE_ADDR; i < NAME_BASE_ADDR+tabNameSz; i++)
+      if (tabName[i-NAME_BASE_ADDR].inUse && name(i).mod == m) {
+         if (name(i).itbl && 
+             module(name(i).mod).mode == FM_SOURCE) {
+            free(name(i).itbl);
+         }
+         name(i).itbl    = NULL;
+         name(i).closure = NIL;
+         freeName(i);
+      }
+
+   for (i = TYCON_BASE_ADDR; i < TYCON_BASE_ADDR+tabTyconSz; i++)
+      if (tabTycon[i-TYCON_BASE_ADDR].inUse && tycon(i).mod == m) {
+         if (tycon(i).itbl &&
+             module(tycon(i).mod).mode == FM_SOURCE) {
+            free(tycon(i).itbl);
+         }
+         tycon(i).itbl = NULL;
+         freeTycon(i);
+      }
+
+   for (i = CCLASS_BASE_ADDR; i < CCLASS_BASE_ADDR+tabClassSz; i++)
+      if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
+         if (cclass(i).mod == m) {
+            freeClass(i);
+         } else {
+            List /* Inst */ ins;
+            List /* Inst */ ins2 = NIL;
+            for (ins = cclass(i).instances; nonNull(ins); ins=tl(ins))
+               if (inst(hd(ins)).mod != m) 
+                  ins2 = cons(hd(ins),ins2);
+            cclass(i).instances = ins2;
+         }
+      }
+
+
+   for (i = INST_BASE_ADDR; i < INST_BASE_ADDR+tabInstSz; i++)
+      if (tabInst[i-INST_BASE_ADDR].inUse && inst(i).mod == m)
+         freeInst(i);
+
+   freeModule(m);
+   //for (i = 0; i < TYCONHSZ; i++) tyconHash[i] = 0;
+   //for (i = 0; i < NAMEHSZ; i++)  nameHash[i] = 0;
+   //classes = NIL;
+   //hashSanity();
+}
+
+void ppModules ( void )
+{
+   Int i;
+   fflush(stderr); fflush(stdout);
+   printf ( "begin MODULES\n" );
+   for (i  = MODULE_BASE_ADDR+tabModuleSz-1;
+        i >= MODULE_BASE_ADDR; i--)
+      if (tabModule[i-MODULE_BASE_ADDR].inUse)
+         printf ( " %2d: %16s\n",
+                  i-MODULE_BASE_ADDR, textToStr(module(i).text)
+                );
+   printf ( "end   MODULES\n" );
+   fflush(stderr); fflush(stdout);
+}
+
+
 Module findModule(t)                    /* locate Module in module table  */
 Text t; {
     Module m;
-    for(m=MODMIN; m<moduleHw; ++m) {
-        if (module(m).text==t)
-            return m;
+    for(m = MODULE_BASE_ADDR; 
+        m < MODULE_BASE_ADDR+tabModuleSz; ++m) {
+        if (tabModule[m-MODULE_BASE_ADDR].inUse)
+            if (module(m).text==t)
+                return m;
     }
     return NIL;
 }
@@ -913,13 +1732,11 @@ Text t; {
 Module findModid(c)                    /* Find module by name or filename  */
 Cell c; {
     switch (whatIs(c)) {
-        case STRCELL   : { Script s = scriptThisFile(snd(c));
-                           return (s==-1) ? NIL : moduleOfScript(s);
-                         }
+        case STRCELL   : internal("findModid-STRCELL unimp");
         case CONIDCELL : return findModule(textOf(c));
         default        : internal("findModid");
     }
-    assert(0); return 0; /* NOTREACHED */
+    return NIL;/*NOTUSED*/
 }
 
 static local Module findQualifier(t)    /* locate Module in import list   */
@@ -929,250 +1746,226 @@ Text t; {
         if (textOf(fst(hd(ms)))==t)
             return snd(hd(ms));
     }
-#if 1 /* mpj */
     if (module(currentModule).text==t)
         return currentModule;
-#endif
     return NIL;
 }
 
 Void setCurrModule(m)              /* set lookup tables for current module */
 Module m; {
     Int i;
-    if (m!=currentModule) {
-        currentModule = m; /* This is the only assignment to currentModule */
-        for (i=0; i<TYCONHSZ; ++i)
-            tyconHash[i] = NIL;
-        mapProc(hashTycon,module(m).tycons);
-        for (i=0; i<NAMEHSZ; ++i)
-            nameHash[i] = NIL;
-        mapProc(hashName,module(m).names);
-        classes = module(m).classes;
-    }
+    assert(isModule(m));
+    /* fprintf(stderr, "SET CURR MODULE %s %d\n", textToStr(module(m).text),m); */
+    {List t;
+     for (t = module(m).names; nonNull(t); t=tl(t))
+        assert(isName(hd(t)));
+     for (t = module(m).tycons; nonNull(t); t=tl(t))
+        assert(isTycon(hd(t)) || isTuple(hd(t)));
+     for (t = module(m).classes; nonNull(t); t=tl(t))
+        assert(isClass(hd(t)));
+    }
+
+    currentModule = m; /* This is the only assignment to currentModule */
+    for (i=0; i<TYCONHSZ; ++i)
+       tyconHash[RC_T(i)] = NIL;
+    mapProc(hashTycon,module(m).tycons);
+    for (i=0; i<NAMEHSZ; ++i)
+       nameHash[RC_N(i)] = NIL;
+    mapProc(hashName,module(m).names);
+    classes = module(m).classes;
+    hashSanity();
+}
+
+void addToCodeList   ( Module m, Cell c )
+{
+   assert(isName(c) || isTuple(c));
+   if (nonNull(getNameOrTupleClosure(c)))
+      module(m).codeList = cons ( c, module(m).codeList );
+   /* fprintf ( stderr, "addToCodeList %s %s\n",
+                textToStr(module(m).text), 
+                textToStr( isTuple(c) ? tycon(c).text : name(c).text ) );
+   */
 }
-#endif /* !IGNORE_MODULES */
-
-/* --------------------------------------------------------------------------
- * Script file storage:
- *
- * script files are read into the system one after another.  The state of
- * the stored data structures (except the garbage-collected heap) is recorded
- * before reading a new script.  In the event of being unable to read the
- * script, or if otherwise requested, the system can be restored to its
- * original state immediately before the file was read.
- * ------------------------------------------------------------------------*/
 
-typedef struct {                       /* record of storage state prior to */
-    Text  file;                        /* reading script/module            */
-    Text  textHw;
-    Text  nextNewText;
-    Text  nextNewDText;
-#if !IGNORE_MODULES
-    Module moduleHw;
-#endif
-    Tycon tyconHw;
-    Name  nameHw;
-    Class classHw;
-    Inst  instHw;
-#if TREX
-    Ext   extHw;
-#endif
-} script;
-
-#ifdef  DEBUG_SHOWUSE
-static Void local showUse(msg,val,mx)
-String msg;
-Int val, mx; {
-    Printf("%6s : %5d of %5d (%2d%%)\n",msg,val,mx,(100*val)/mx);
+Cell getNameOrTupleClosure ( Cell c )
+{
+   if (isName(c)) return name(c).closure; 
+   else if (isTuple(c)) return tycon(c).closure;
+   else internal("getNameOrTupleClosure");
 }
-#endif
 
-static Script scriptHw;                 /* next unused script number       */
-static script scripts[NUM_SCRIPTS];     /* storage for script records      */
-
-Script startNewScript(f)                /* start new script, keeping record */
-String f; {                             /* of status for later restoration  */
-    if (scriptHw >= NUM_SCRIPTS) {
-        ERRMSG(0) "Too many script files in use"
-        EEND;
-    }
-#ifdef DEBUG_SHOWUSE
-    showUse("Text",   textHw,           NUM_TEXT);
-#if !IGNORE_MODULES
-    showUse("Module", moduleHw-MODMIN,  NUM_MODULE);
-#endif
-    showUse("Tycon",  tyconHw-TYCMIN,   NUM_TYCON);
-    showUse("Name",   nameHw-NAMEMIN,   NUM_NAME);
-    showUse("Class",  classHw-CLASSMIN, NUM_CLASSES);
-    showUse("Inst",   instHw-INSTMIN,   NUM_INSTS);
-#if TREX
-    showUse("Ext",    extHw-EXTMIN,     NUM_EXT);
-#endif
-#endif
-
-    scripts[scriptHw].file         = findText( f ? f : "<nofile>" );
-    scripts[scriptHw].textHw       = textHw;
-    scripts[scriptHw].nextNewText  = nextNewText;
-    scripts[scriptHw].nextNewDText = nextNewDText;
-#if !IGNORE_MODULES
-    scripts[scriptHw].moduleHw     = moduleHw;
-#endif
-    scripts[scriptHw].tyconHw      = tyconHw;
-    scripts[scriptHw].nameHw       = nameHw;
-    scripts[scriptHw].classHw      = classHw;
-    scripts[scriptHw].instHw       = instHw;
-#if TREX
-    scripts[scriptHw].extHw        = extHw;
-#endif
-    return scriptHw++;
+void setNameOrTupleClosure ( Cell c, Cell closure )
+{
+   if (isName(c)) name(c).closure = closure;
+   else if (isTuple(c)) tycon(c).closure = closure;
+   else internal("setNameOrTupleClosure");
 }
 
-Bool isPreludeScript() {                /* Test whether this is the Prelude*/
-    return (scriptHw==0);
+/* This function is used in ghc/rts/Assembler.c. */
+void* /* StgClosure* */ getNameOrTupleClosureCPtr ( Cell c )
+{
+   return cptrOf(getNameOrTupleClosure(c));
 }
 
-#if !IGNORE_MODULES
-Bool moduleThisScript(m)                /* Test if given module is defined */
-Module m; {                             /* in current script file          */
-    return scriptHw<1 || m>=scripts[scriptHw-1].moduleHw;
+/* used in codegen.c */
+void setNameOrTupleClosureCPtr ( Cell c, void* /* StgClosure* */ cptr )
+{
+   if (isName(c)) name(c).closure = mkCPtr(cptr);
+   else if (isTuple(c)) tycon(c).closure = mkCPtr(cptr);
+   else internal("setNameOrTupleClosureCPtr");
 }
 
-Module lastModule() {              /* Return module in current script file */
-    return (moduleHw>MODMIN ? moduleHw-1 : modulePrelude);
-}
-#endif /* !IGNORE_MODULES */
 
-#define scriptThis(nm,t,tag)            Script nm(x)                       \
-                                        t x; {                             \
-                                            Script s=0;                    \
-                                            while (s<scriptHw              \
-                                                   && x>=scripts[s].tag)   \
-                                                s++;                       \
-                                            return s;                      \
-                                        }
-scriptThis(scriptThisName,Name,nameHw)
-scriptThis(scriptThisTycon,Tycon,tyconHw)
-scriptThis(scriptThisInst,Inst,instHw)
-scriptThis(scriptThisClass,Class,classHw)
-#undef scriptThis
 
-Module moduleOfScript(s)
-Script s; {
-    return (s==0) ? modulePrelude : scripts[s-1].moduleHw;
-}
+Name jrsFindQualName ( Text mn, Text sn )
+{
+   Module m;
+   List   ns;
 
-#if !IGNORE_MODULES
-String fileOfModule(m)
-Module m; {
-    Script s;
-    if (m == modulePrelude) {
-        return STD_PRELUDE;
-    }
-    for(s=0; s<scriptHw; ++s) {
-        if (scripts[s].moduleHw == m) {
-            return textToStr(scripts[s].file);
-        }
-    }
-    return 0;
-}
-#endif
+   for (m = MODULE_BASE_ADDR; 
+        m < MODULE_BASE_ADDR+tabModuleSz; m++)
+      if (tabModule[m-MODULE_BASE_ADDR].inUse 
+          && module(m).text == mn) break;
 
-Script scriptThisFile(f)
-Text f; {
-    Script s;
-    for (s=0; s < scriptHw; ++s) {
-        if (scripts[s].file == f) {
-            return s+1;
-        }
-    }
-    if (f == findText(STD_PRELUDE)) {
-        return 0;
-    }
-    return (-1);
-}
-
-Void dropScriptsFrom(sno)               /* Restore storage to state prior  */
-Script sno; {                           /* to reading script sno           */
-    if (sno<scriptHw) {                 /* is there anything to restore?   */
-        int i;
-        textHw       = scripts[sno].textHw;
-        nextNewText  = scripts[sno].nextNewText;
-        nextNewDText = scripts[sno].nextNewDText;
-#if !IGNORE_MODULES
-        moduleHw     = scripts[sno].moduleHw;
-#endif
-        tyconHw      = scripts[sno].tyconHw;
-        nameHw       = scripts[sno].nameHw;
-        classHw      = scripts[sno].classHw;
-        instHw       = scripts[sno].instHw;
-#if USE_DICTHW
-        dictHw       = scripts[sno].dictHw;
-#endif
-#if TREX
-        extHw        = scripts[sno].extHw;
-#endif
+   if (m == MODULE_BASE_ADDR+tabModuleSz) return NIL;
+   
+   for (ns = module(m).names; nonNull(ns); ns=tl(ns)) 
+      if (name(hd(ns)).text == sn) return hd(ns);
 
-#if 0  //zzzzzzzzzzzzzzzzz
-        for (i=moduleHw; i >= scripts[sno].moduleHw; --i) {
-            if (module(i).objectFile) {
-                printf("[bogus] closing objectFile for module %d\n",i);
-                /*dlclose(module(i).objectFile);*/
-            }
-        }
-        moduleHw = scripts[sno].moduleHw;
-#endif
-        for (i=0; i<TEXTHSZ; ++i) {
-            int j = 0;
-            while (j<NUM_TEXTH && textHash[i][j]!=NOTEXT
-                               && textHash[i][j]<textHw)
-                ++j;
-            if (j<NUM_TEXTH)
-                textHash[i][j] = NOTEXT;
-        }
+   return NIL;
+}
 
-#if IGNORE_MODULES
-        for (i=0; i<TYCONHSZ; ++i) {
-            Tycon tc = tyconHash[i];
-            while (nonNull(tc) && tc>=tyconHw)
-                tc = tycon(tc).nextTyconHash;
-            tyconHash[i] = tc;
-        }
 
-        for (i=0; i<NAMEHSZ; ++i) {
-            Name n = nameHash[i];
-            while (nonNull(n) && n>=nameHw)
-                n = name(n).nextNameHash;
-            nameHash[i] = n;
-        }
-#else /* !IGNORE_MODULES */
-        currentModule=NIL;
-        for (i=0; i<TYCONHSZ; ++i) {
-            tyconHash[i] = NIL;
-        }
-        for (i=0; i<NAMEHSZ; ++i) {
-            nameHash[i] = NIL;
-        }
-#endif /* !IGNORE_MODULES */
+char* nameFromOPtr ( void* p )
+{
+   int i;
+   Module m;
+   for (m = MODULE_BASE_ADDR; 
+        m < MODULE_BASE_ADDR+tabModuleSz; m++) {
+      if (tabModule[m-MODULE_BASE_ADDR].inUse && module(m).object) {
+         char* nm = ocLookupAddr ( module(m).object, p );
+         if (nm) return nm;
+      }
+   }
+#  if 0
+   /* A kludge to assist Win32 debugging; not actually necessary. */
+   { char* nm = nameFromStaticOPtr(p);
+     if (nm) return nm;
+   }
+#  endif
+   return NULL;
+}
+
+
+void* lookupOTabName ( Module m, char* sym )
+{
+   assert(isModule(m));
+   if (module(m).object)
+      return ocLookupSym ( module(m).object, sym );
+   return NULL;
+}
 
-        for (i=CLASSMIN; i<classHw; i++) {
-            List ins = cclass(i).instances;
-            List is  = NIL;
 
-            while (nonNull(ins)) {
-                List temp = tl(ins);
-                if (hd(ins)<instHw) {
-                    tl(ins) = is;
-                    is      = ins;
-                }
-                ins = temp;
-            }
-            cclass(i).instances = rev(is);
-        }
+void* lookupOExtraTabName ( char* sym )
+{
+   ObjectCode* oc;
+   Module      m;
+   for (m = MODULE_BASE_ADDR; 
+        m < MODULE_BASE_ADDR+tabModuleSz; m++) {
+      if (tabModule[m-MODULE_BASE_ADDR].inUse)
+         for (oc = module(m).objectExtras; oc; oc=oc->next) {
+            void* ad = ocLookupSym ( oc, sym );
+            if (ad) return ad;
+         }
+   }
+   return NULL;
+}
+
+
+/* Only call this if in dire straits; searches every object symtab
+   in the system -- so is therefore slow.
+*/
+void* lookupOTabNameAbsolutelyEverywhere ( char* sym )
+{
+   ObjectCode* oc;
+   Module      m;
+   void*       ad;
+   for (m = MODULE_BASE_ADDR; 
+        m < MODULE_BASE_ADDR+tabModuleSz; m++) {
+      if (tabModule[m-MODULE_BASE_ADDR].inUse) {
+         if (module(m).object) {
+            ad = ocLookupSym ( module(m).object, sym );
+            if (ad) return ad;
+         }
+         for (oc = module(m).objectExtras; oc; oc=oc->next) {
+            ad = ocLookupSym ( oc, sym );
+            if (ad) return ad;
+         }
+      }
+   }
+   return NULL;
+}
+
+
+OSectionKind lookupSection ( void* ad )
+{
+   int          i;
+   Module       m;
+   ObjectCode*  oc;
+   OSectionKind sect;
+
+   for (m = MODULE_BASE_ADDR; 
+        m < MODULE_BASE_ADDR+tabModuleSz; m++) {
+      if (tabModule[m-MODULE_BASE_ADDR].inUse) {
+         if (module(m).object) {
+            sect = ocLookupSection ( module(m).object, ad );
+            if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
+               return sect;
+         }
+         for (oc = module(m).objectExtras; oc; oc=oc->next) {
+            sect = ocLookupSection ( oc, ad );
+            if (sect != HUGS_SECTIONKIND_NOINFOAVAIL)
+               return sect;
+         }
+      }
+   }
+   return HUGS_SECTIONKIND_OTHER;
+}
+
+
+/* Called by the evaluator's GC to tell Hugs to mark stuff in the
+   run-time heap.
+*/
+void markHugsObjects( void )
+{
+    Name  nm;
+    Tycon tc;
 
-        scriptHw = sno;
+    for ( nm = NAME_BASE_ADDR; 
+          nm < NAME_BASE_ADDR+tabNameSz; ++nm ) {
+       if (tabName[nm-NAME_BASE_ADDR].inUse) {
+           Cell cl = name(nm).closure;
+           if (nonNull(cl)) {
+              assert(isCPtr(cl));
+              snd(cl) = (Cell)MarkRoot ( (StgClosure*)(snd(cl)) );
+          }
+       }
     }
+
+    for ( tc = TYCON_BASE_ADDR; 
+          tc < TYCON_BASE_ADDR+tabTyconSz; ++tc ) {
+       if (tabTycon[tc-TYCON_BASE_ADDR].inUse) {
+           Cell cl = tycon(tc).closure;
+           if (nonNull(cl)) {
+              assert(isCPtr(cl));
+              snd(cl) = (Cell)MarkRoot ( (StgClosure*)(snd(cl)) );
+          }
+       }
+    }
+
 }
 
+
 /* --------------------------------------------------------------------------
  * Heap storage:
  *
@@ -1186,36 +1979,18 @@ Script sno; {                           /* to reading script sno           */
 Int     heapSize = DEFAULTHEAP;         /* number of cells in heap         */
 Heap    heapFst;                        /* array of fst component of pairs */
 Heap    heapSnd;                        /* array of snd component of pairs */
-#ifndef GLOBALfst
 Heap    heapTopFst;
-#endif
-#ifndef GLOBALsnd
 Heap    heapTopSnd;
-#endif
 Bool    consGC = TRUE;                  /* Set to FALSE to turn off gc from*/
                                         /* C stack; use with extreme care! */
-#if     PROFILING
-Heap    heapThd, heapTopThd;            /* to keep record of producers     */
-Int     sysCount;                       /* record unattached cells         */
-Name    producer;                       /* current producer, if any        */
-Bool    profiling = FALSE;              /* should profiling be performed   */
-Int     profInterval = MAXPOSINT;       /* interval between samples        */
-FILE    *profile = 0;                   /* pointer to profiler log, if any */
-#endif
 Long    numCells;
+int     numEnters;
 Int     numGcs;                         /* number of garbage collections   */
 Int     cellsRecovered;                 /* number of cells recovered       */
 
 static  Cell freeList;                  /* free list of unused cells       */
 static  Cell lsave, rsave;              /* save components of pair         */
 
-#if GC_WEAKPTRS
-static List weakPtrs;                   /* list of weak ptrs               */
-                                        /* reconstructed during every GC   */
-List   finalizers = NIL;
-List   liveWeakPtrs = NIL;
-#endif
-
 #if GC_STATISTICS
 
 static Int markCount, stackRoots;
@@ -1259,7 +2034,6 @@ static Int markCount, stackRoots;
 Cell pair(l,r)                          /* Allocate pair (l, r) from       */
 Cell l, r; {                            /* heap, garbage collecting first  */
     Cell c = freeList;                  /* if necessary ...                */
-
     if (isNull(c)) {
         lsave = l;
         rsave = r;
@@ -1273,231 +2047,72 @@ Cell l, r; {                            /* heap, garbage collecting first  */
     freeList = snd(freeList);
     fst(c)   = l;
     snd(c)   = r;
-#if PROFILING
-    thd(c)   = producer;
-#endif
     numCells++;
     return c;
 }
 
-Void overwrite(dst,src)                 /* overwrite dst cell with src cell*/
-Cell dst, src; {                        /* both *MUST* be pairs            */
-    if (isPair(dst) && isPair(src)) {
-        fst(dst) = fst(src);
-        snd(dst) = snd(src);
-    }
-    else
-        internal("overwrite");
-}
-
 static Int *marks;
 static Int marksSize;
 
-Cell markExpr(c)                        /* External interface to markCell  */
-Cell c; {
-    return isGenPair(c) ? markCell(c) : c;
-}
-
-static Cell local markCell(c)           /* Traverse part of graph marking  */
-Cell c; {                               /* cells reachable from given root */
-                                        /* markCell(c) is only called if c */
-                                        /* is a pair                       */
-    {   register int place = placeInSet(c);
-        register int mask  = maskInSet(c);
-        if (marks[place]&mask)
-            return c;
-        else {
+void mark ( Cell root )
+{
+   Cell c;
+   Cell mstack[NUM_MSTACK];
+   Int  msp     = -1;
+   Int  msp_max = -1;
+
+   mstack[++msp] = root;
+
+   while (msp >= 0) {
+      if (msp > msp_max) msp_max = msp;
+      c = mstack[msp--];
+      if (!isGenPair(c)) continue;
+      if (fst(c)==FREECELL) continue;
+      {
+         register int place = placeInSet(c);
+         register int mask  = maskInSet(c);
+         if (!(marks[place]&mask)) {
             marks[place] |= mask;
-            recordMark();
-        }
-    }
-
-    if (isGenPair(fst(c))) {
-        fst(c) = markCell(fst(c));
-        markSnd(c);
-    }
-    else if (isNull(fst(c)) || fst(c)>=BCSTAG) {
-        markSnd(c);
-    }
-
-    return c;
+            if (msp >= NUM_MSTACK-5) {
+               fprintf ( stderr, 
+                         "hugs: fatal stack overflow during GC.  "
+                         "Increase NUM_MSTACK.\n" );
+               exit(9);
+            }
+            mstack[++msp] = fst(c);
+            mstack[++msp] = snd(c);
+         }
+      }
+   }
+   //   fprintf(stderr, "%d ",msp_max);
 }
 
-static Void local markSnd(c)            /* Variant of markCell used to     */
-Cell c; {                               /* update snd component of cell    */
-    Cell t;                             /* using tail recursion            */
-
-ma: t = c;                              /* Keep pointer to original pair   */
-    c = snd(c);
-    if (!isPair(c))
-        return;
-
-    {   register int place = placeInSet(c);
-        register int mask  = maskInSet(c);
-        if (marks[place]&mask)
-            return;
-        else {
-            marks[place] |= mask;
-            recordMark();
-        }
-    }
-
-    if (isGenPair(fst(c))) {
-        fst(c) = markCell(fst(c));
-        goto ma;
-    }
-    else if (isNull(fst(c)) || fst(c)>=BCSTAG)
-        goto ma;
-    return;
-}
-
-Void markWithoutMove(n)                 /* Garbage collect cell at n, as if*/
-Cell n; {                               /* it was a cell ref, but don't    */
-                                        /* move cell so we don't have      */
-                                        /* to modify the stored value of n */
-    if (isGenPair(n)) {
-        recordStackRoot();
-        markCell(n); 
-    }
-}
 
 Void garbageCollect()     {             /* Run garbage collector ...       */
-    Bool breakStat = breakOn(FALSE);    /* disable break checking          */
+                                        /* disable break checking          */
     Int i,j;
     register Int mask;
     register Int place;
     Int      recovered;
-
     jmp_buf  regs;                      /* save registers on stack         */
-printf("\n\n$$$$$$$$$$$ GARBAGE COLLECTION; aborting\n\n");
-exit(1);
+    HugsBreakAction oldBrk
+       = setBreakAction ( HugsIgnoreBreak );
+
     setjmp(regs);
 
     gcStarted();
+
     for (i=0; i<marksSize; ++i)         /* initialise mark set to empty    */
         marks[i] = 0;
-#if GC_WEAKPTRS
-    weakPtrs = NIL;                     /* clear list of weak pointers     */
-#endif
-    everybody(MARK);                    /* Mark all components of system   */
-
-#if IO_HANDLES
-    for (i=0; i<NUM_HANDLES; ++i)       /* release any unused handles      */
-        if (nonNull(handles[i].hcell)) {
-            register place = placeInSet(handles[i].hcell);
-            register mask  = maskInSet(handles[i].hcell);
-            if ((marks[place]&mask)==0)
-                freeHandle(i);
-        }
-#endif
-#if GC_MALLOCPTRS
-    for (i=0; i<NUM_MALLOCPTRS; ++i)    /* release any unused mallocptrs   */
-        if (isPair(mallocPtrs[i].mpcell)) {
-            register place = placeInSet(mallocPtrs[i].mpcell);
-            register mask  = maskInSet(mallocPtrs[i].mpcell);
-            if ((marks[place]&mask)==0)
-                incMallocPtrRefCnt(i,-1);
-        }
-#endif /* GC_MALLOCPTRS */
-#if GC_WEAKPTRS
-    /* After GC completes, we scan the list of weak pointers that are
-     * still live and zap their contents unless the contents are still
-     * live (by some other means).
-     * Note that this means the contents must itself be heap allocated.
-     * This means it can't be a nullary constructor or an Int or a Name
-     * or lots of other things - hope this doesn't bite too hard.
-     */
-    for (; nonNull(weakPtrs); weakPtrs=nextWeakPtr(weakPtrs)) {
-        Cell ptr = derefWeakPtr(weakPtrs);
-        if (isGenPair(ptr)) {
-            Int  place = placeInSet(ptr);
-            Int  mask  = maskInSet(ptr);
-            if ((marks[place]&mask)==0) {
-                /* printf("Zapping weak pointer %d\n", ptr); */
-                derefWeakPtr(weakPtrs) = NIL;
-            } else {
-                /* printf("Keeping weak pointer %d\n", ptr); */
-            }
-        } else if (nonNull(ptr)) {
-            printf("Weak ptr contains object which isn't heap allocated %d\n", ptr);
-        }
-    }
-
-    if (nonNull(liveWeakPtrs) || nonNull(finalizers)) {
-        Bool anyMarked;                 /* Weak pointers with finalizers   */
-        List wps;
-        List newFins = NIL;
-
-        /* Step 1: iterate until we've found out what is reachable         */
-        do {
-            anyMarked = FALSE;
-            for (wps=liveWeakPtrs; nonNull(wps); wps=tl(wps)) {
-                Cell wp = hd(wps);
-                Cell k  = fst(snd(wp));
-                if (isNull(k)) {
-                    internal("bad weak ptr");
-                }
-                if (isMarked(k)) {
-                    Cell vf = snd(snd(wp));
-                    if (!isMarked(fst(vf)) || !isMarked(snd(vf))) {
-                        mark(fst(vf));
-                        mark(snd(vf));
-                        anyMarked = TRUE;
-                    }
-                }
-            }
-        } while (anyMarked);
-
-        /* Step 2: Now we know which weak pointers will die, so we can     */
-        /* remove them from the live set and gather their finalizers.  But */
-        /* note that we mustn't mark *anything* at this stage or we will   */
-        /* corrupt our view of what's alive, and what's dead.              */
-        wps = NIL;
-        while (nonNull(liveWeakPtrs)) {
-            Cell wp = hd(liveWeakPtrs);
-            List nx = tl(liveWeakPtrs);
-            Cell k  = fst(snd(wp));
-            if (!isMarked(k)) {                 /* If the key is dead, then*/
-                Cell vf      = snd(snd(wp));    /* stomp on weak pointer   */
-                fst(vf)      = snd(vf);
-                snd(vf)      = newFins;
-                newFins      = vf;              /* reuse because we can't  */
-                fst(snd(wp)) = NIL;             /* reallocate here ...     */
-                snd(snd(wp)) = NIL;
-                snd(wp)      = NIL;
-                liveWeakPtrs = nx;
-            } else {
-                tl(liveWeakPtrs) = wps;         /* Otherwise, weak pointer */
-                wps              = liveWeakPtrs;/* survives to face another*/
-                liveWeakPtrs     = nx;          /* garbage collection      */
-            }
-        }
 
-        /* Step 3: Now we've identified the live cells and the newly       */
-        /* scheduled finalizers, but we had better make sure that they are */
-        /* all marked now, including any internal structure, to ensure that*/
-        /* they make it to the other side of gc.                           */
-        for (liveWeakPtrs=wps; nonNull(wps); wps=tl(wps)) {
-            mark(snd(hd(wps)));
-        }
-        mark(liveWeakPtrs);
-        mark(newFins);
-        finalizers = revOnto(newFins,finalizers);
-    }
+    everybody(MARK);                    /* Mark all components of system   */
 
-#endif /* GC_WEAKPTRS */
     gcScanning();                       /* scan mark set                   */
     mask      = 1;
     place     = 0;
     recovered = 0;
     j         = 0;
-#if PROFILING
-    if (profile) {
-        sysCount = 0;
-        for (i=NAMEMIN; i<nameHw; i++)
-            name(i).count = 0;
-    }
-#endif
+
     freeList = NIL;
     for (i=1; i<=heapSize; i++) {
         if ((marks[place] & mask) == 0) {
@@ -1506,12 +2121,6 @@ exit(1);
             freeList = -i;
             recovered++;
         }
-#if PROFILING
-        else if (nonNull(thd(-i)))
-            name(thd(-i)).count++;
-        else
-            sysCount++;
-#endif
         mask <<= 1;
         if (++j == bitsPerWord) {
             place++;
@@ -1521,49 +2130,12 @@ exit(1);
     }
 
     gcRecovered(recovered);
-    breakOn(breakStat);                 /* restore break trapping if nec.  */
-
-#if PROFILING
-    if (profile) {
-        fprintf(profile,"BEGIN_SAMPLE %ld.00\n",numReductions);
-/* For the time being, we won't include the system count in the output:
-        if (sysCount>0)
-            fprintf(profile,"  SYSTEM %d\n",sysCount);
-*/
-        /* Accumulate costs in top level objects */
-        for (i=NAMEMIN; i<nameHw; i++) {
-            Name cc = i;
-            /* Use of "while" instead of "if" is pure paranoia - ADR */
-            while (isName(name(cc).parent)) 
-                cc = name(cc).parent;
-            if (i != cc) {
-                name(cc).count += name(i).count;
-                name(i).count = 0;
-            }
-        }
-        for (i=NAMEMIN; i<nameHw; i++)
-            if (name(i).count>0) 
-                if (isPair(name(i).parent)) {
-                    Pair p = name(i).parent;
-                    Cell f = fst(p);
-                    fprintf(profile,"  ");
-                    if (isClass(f))
-                        fprintf(profile,"%s",textToStr(cclass(f).text));
-                    else {
-                        fprintf(profile,"%s_",textToStr(cclass(inst(f).c).text));
-                        /* Will hp2ps accept the spaces produced by this? */
-                        printPred(profile,inst(f).head);
-                    }
-                    fprintf(profile,"_%s %d\n",
-                            textToStr(name(snd(p)).text),
-                            name(i).count);
-                } else {
-                    fprintf(profile,"  %s %d\n",
-                            textToStr(name(i).text),
-                            name(i).count);
-                }
-        fprintf(profile,"END_SAMPLE %ld.00\n",numReductions);
-    }
+    setBreakAction ( oldBrk );
+
+    everybody(GCDONE);
+
+#if defined(DEBUG_STORAGE) || defined(DEBUG_STORAGE_EXTRA)
+    /* fprintf(stderr, "\n--- GC recovered %d\n",recovered ); */
 #endif
 
     /* can only return if freeList is nonempty on return. */
@@ -1574,22 +2146,6 @@ exit(1);
     cellsRecovered = recovered;
 }
 
-#if PROFILING
-Void profilerLog(s)                     /* turn heap profiling on, saving log*/
-String s; {                             /* in specified file                 */
-    if ((profile=fopen(s,"w")) != NULL) {
-        fprintf(profile,"JOB \"Hugs Heap Profile\"\n");
-        fprintf(profile,"DATE \"%s\"\n",timeString());
-        fprintf(profile,"SAMPLE_UNIT \"reductions\"\n");
-        fprintf(profile,"VALUE_UNIT \"cells\"\n");
-    }
-    else {
-        ERRMSG(0) "Cannot open profile log file \"%s\"", s
-        EEND;
-    }
-}
-#endif
-
 /* --------------------------------------------------------------------------
  * Code for saving last expression entered:
  *
@@ -1604,14 +2160,14 @@ static Cell lastExprSaved;              /* last expression to be saved     */
 Void setLastExpr(e)                     /* save expression for later recall*/
 Cell e; {
     lastExprSaved = NIL;                /* in case attempt to save fails   */
-    savedText     = NUM_TEXT;
+    savedText     = TEXT_SIZE;
     lastExprSaved = lowLevelLastIn(e);
 }
 
 static Cell local lowLevelLastIn(c)     /* Duplicate expression tree (i.e. */
 Cell c; {                               /* acyclic graph) for later recall */
     if (isPair(c)) {                    /* Duplicating any text strings    */
-        if (isBoxTag(fst(c)))           /* in case these are lost at some  */
+        if (isTagNonPtr(fst(c)))        /* in case these are lost at some  */
             switch (fst(c)) {           /* point before the expr is reused */
                 case VARIDCELL :
                 case VAROPCELL :
@@ -1639,7 +2195,7 @@ Cell getLastExpr() {                    /* recover previously saved expr   */
 static Cell local lowLevelLastOut(c)    /* As with lowLevelLastIn() above  */
 Cell c; {                               /* except that Cells refering to   */
     if (isPair(c)) {                    /* Text values are restored to     */
-        if (isBoxTag(fst(c)))           /* appropriate values              */
+        if (isTagNonPtr(fst(c)))        /* appropriate values              */
             switch (fst(c)) {
                 case VARIDCELL :
                 case VAROPCELL :
@@ -1664,70 +2220,65 @@ Cell c; {                               /* except that Cells refering to   */
  * Miscellaneous operations on heap cells:
  * ------------------------------------------------------------------------*/
 
-/* Profiling suggests that the number of calls to whatIs() is typically    */
-/* rather high.  The recoded version below attempts to improve the average */
-/* performance for whatIs() using a binary search for part of the analysis */
-
-Cell whatIs(c)                         /* identify type of cell            */
-register Cell c; {
+/* Reordered 2 May 00 to have most common options first. */
+Cell whatIs ( register Cell c )
+{
     if (isPair(c)) {
         register Cell fstc = fst(c);
         return isTag(fstc) ? fstc : AP;
     }
-    if (c<TUPMIN)    return c;
-    if (c>=INTMIN)   return INTCELL;
-
-    if (c>=NAMEMIN){if (c>=CLASSMIN)   {if (c>=CHARMIN) return CHARCELL;
-                                        else            return CLASS;}
-                    else                if (c>=INSTMIN) return INSTANCE;
-                                        else            return NAME;}
-    else            if (c>=MODMIN)     {if (c>=TYCMIN)  return TYCON;
-                                        else            return MODULE;}
-                    else                if (c>=OFFMIN)  return OFFSET;
-#if TREX
-                                        else            return (c>=EXTMIN) ?
-                                                                EXT : TUPLE;
-#else
-                                        else            return TUPLE;
-#endif
-
-/*  if (isPair(c)) {
-        register Cell fstc = fst(c);
-        return isTag(fstc) ? fstc : AP;
-    }
-    if (c>=INTMIN)   return INTCELL;
-    if (c>=CHARMIN)  return CHARCELL;
-    if (c>=CLASSMIN) return CLASS;
-    if (c>=INSTMIN)  return INSTANCE;
-    if (c>=NAMEMIN)  return NAME;
-    if (c>=TYCMIN)   return TYCON;
-    if (c>=MODMIN)   return MODULE;
-    if (c>=OFFMIN)   return OFFSET;
-#if TREX
-    if (c>=EXTMIN)   return EXT;
-#endif
-    if (c>=TUPMIN)   return TUPLE;
-    return c;*/
+    if (isTycon(c))            return TYCON;
+    if (isOffset(c))           return OFFSET;
+    if (isName(c))             return NAME;
+    if (isInt(c))              return INTCELL;
+    if (isTuple(c))            return TUPLE;
+    if (isSpec(c))             return c;
+    if (isClass(c))            return CLASS;
+    if (isChar(c))             return CHARCELL;
+    if (isNull(c))             return c;
+    if (isInst(c))             return INSTANCE;
+    if (isModule(c))           return MODULE;
+    if (isText(c))             return TEXTCELL;
+    if (isInventedVar(c))      return INVAR;
+    if (isInventedDictVar(c))  return INDVAR;
+    fprintf ( stderr, "whatIs: unknown %d\n", c );
+    internal("whatIs");
 }
 
-#if DEBUG_PRINTER
+
+
 /* A very, very simple printer.
  * Output is uglier than from printExp - but the printer is more
  * robust and can be used on any data structure irrespective of
  * its type.
  */
-Void print Args((Cell, Int));
-Void print(c, depth)
-Cell c;
-Int  depth; {
+Void print ( Cell c, Int depth )
+{
     if (0 == depth) {
         Printf("...");
-#if 0 /* Not in this version of Hugs */
-    } else if (isPair(c) && !isGenPair(c)) {
-        extern Void printEvalCell Args((Cell, Int));
-        printEvalCell(c,depth);
-#endif
-    } else {
+    }
+    else if (isNull(c)) {
+       Printf("NIL");
+    }
+    else if (isTagPtr(c)) {
+        Printf("TagP(%d)", c);
+    }
+    else if (isTagNonPtr(c)) {
+        Printf("TagNP(%d)", c);
+    }
+    else if (isSpec(c) && c != STAR) {
+        Printf("TagS(%d)", c);
+    }
+    else if (isText(c)) {
+        Printf("text(%d)=\"%s\"",c-TEXT_BASE_ADDR,textToStr(c));
+    }
+    else if (isInventedVar(c)) {
+        Printf("invented(%d)", c-INVAR_BASE_ADDR);
+    }
+    else if (isInventedDictVar(c)) {
+        Printf("inventedDict(%d)",c-INDVAR_BASE_ADDR);
+    }
+    else {
         Int tag = whatIs(c);
         switch (tag) {
         case AP: 
@@ -1749,42 +2300,51 @@ Int  depth; {
         case CHARCELL:
                 Printf("char('%c')", charOf(c));
                 break;
-        case PTRCELL: 
-                Printf("ptr(%p)",ptrOf(c));
+        case STRCELL:
+                Printf("strcell(\"%s\")",textToStr(snd(c)));
+                break;
+        case MPTRCELL: 
+                Printf("mptr(%p)",mptrOf(c));
+                break;
+        case CPTRCELL: 
+                Printf("cptr(%p)",cptrOf(c));
+                break;
+        case ADDRCELL: 
+                Printf("addr(%p)",addrOf(c));
                 break;
         case CLASS:
-                Printf("class(%d)", c-CLASSMIN);
-                if (CLASSMIN <= c && c < classHw) {
-                    Printf("=\"%s\"", textToStr(cclass(c).text));
-                }
+                Printf("class(%d)", c-CCLASS_BASE_ADDR);
+                Printf("=\"%s\"", textToStr(cclass(c).text));
                 break;
         case INSTANCE:
-                Printf("instance(%d)", c - INSTMIN);
+                Printf("instance(%d)", c - INST_BASE_ADDR);
                 break;
         case NAME:
-                Printf("name(%d)", c-NAMEMIN);
-                if (NAMEMIN <= c && c < nameHw) {
-                    Printf("=\"%s\"", textToStr(name(c).text));
-                }
+                Printf("name(%d)", c-NAME_BASE_ADDR);
+                Printf("=\"%s\"", textToStr(name(c).text));
                 break;
         case TYCON:
-                Printf("tycon(%d)", c-TYCMIN);
-                if (TYCMIN <= c && c < tyconHw)
-                    Printf("=\"%s\"", textToStr(tycon(c).text));
+                Printf("tycon(%d)", c-TYCON_BASE_ADDR);
+                Printf("=\"%s\"", textToStr(tycon(c).text));
                 break;
         case MODULE:
-                Printf("module(%d)", c - MODMIN);
+                Printf("module(%d)", c - MODULE_BASE_ADDR);
+                Printf("=\"%s\"", textToStr(module(c).text));
                 break;
         case OFFSET:
                 Printf("Offset %d", offsetOf(c));
                 break;
         case TUPLE:
-                Printf("Tuple %d", tupleOf(c));
+                Printf("%s", textToStr(ghcTupleText(c)));
                 break;
         case POLYTYPE:
                 Printf("Polytype");
                 print(snd(c),depth-1);
                 break;
+        case QUAL:
+                Printf("Qualtype");
+                print(snd(c),depth-1);
+                break;
         case RANK2:
                 Printf("Rank2(");
                 if (isPair(snd(c)) && isInt(fst(snd(c)))) {
@@ -1795,9 +2355,6 @@ Int  depth; {
                 }
                 Printf(")");
                 break;
-        case NIL:
-                Printf("NIL");
-                break;
         case WILDCARD:
                 Printf("_");
                 break;
@@ -1816,6 +2373,14 @@ Int  depth; {
         case CONOPCELL:
                 Printf("{id %s}",textToStr(textOf(c)));
                 break;
+#if IPARAM
+         case IPCELL :
+             Printf("{ip %s}",textToStr(textOf(c)));
+             break;
+         case IPVAR :
+             Printf("?%s",textToStr(textOf(c)));
+             break;
+#endif
         case QUALIDENT:
                 Printf("{qid %s.%s}",textToStr(qmodOf(c)),textToStr(qtextOf(c)));
                 break;
@@ -1889,11 +2454,42 @@ Int  depth; {
                 print(snd(snd(c)),depth-1);
                 Putchar(')');
                 break;
+        case DICTAP:
+                Printf("(DICTAP,");
+                print(snd(c),depth-1);
+                Putchar(')');
+                break;
+        case UNBOXEDTUP:
+                Printf("(UNBOXEDTUP,");
+                print(snd(c),depth-1);
+                Putchar(')');
+                break;
+        case ZTUP2:
+                Printf("<ZPair ");
+                print(zfst(c),depth-1);
+                Putchar(' ');
+                print(zsnd(c),depth-1);
+                Putchar('>');
+                break;
+        case ZTUP3:
+                Printf("<ZTriple ");
+                print(zfst3(c),depth-1);
+                Putchar(' ');
+                print(zsnd3(c),depth-1);
+                Putchar(' ');
+                print(zthd3(c),depth-1);
+                Putchar('>');
+                break;
+        case BANG:
+                Printf("(BANG,");
+                print(snd(c),depth-1);
+                Putchar(')');
+                break;
         default:
-                if (isBoxTag(tag)) {
-                    Printf("Tag(%d)=%d", c, tag);
-                } else if (isConTag(tag)) {
-                    Printf("%d@(%d,",c,tag);
+                if (isTagNonPtr(tag)) {
+                    Printf("(TagNP=%d,%d)", c, tag);
+                } else if (isTagPtr(tag)) {
+                    Printf("(TagP=%d,",tag);
                     print(snd(c), depth-1);
                     Putchar(')');
                     break;
@@ -1907,7 +2503,7 @@ Int  depth; {
     }
     FlushStdout();
 }
-#endif
+
 
 Bool isVar(c)                           /* is cell a VARIDCELL/VAROPCELL ? */
 Cell c; {                               /* also recognises DICTVAR cells   */
@@ -1951,6 +2547,16 @@ Cell c; {
     return isPair(c) && (fst(c)==QUALIDENT);
 }
 
+Bool eqQualIdent ( QualId c1, QualId c2 )
+{
+   assert(isQualIdent(c1));
+   if (!isQualIdent(c2)) {
+   assert(isQualIdent(c2));
+   }
+   return qmodOf(c1)==qmodOf(c2) &&
+          qtextOf(c1)==qtextOf(c2);
+}
+
 Bool isIdent(c)                        /* is cell an identifier?           */
 Cell c; {
     if (!isPair(c)) return FALSE;
@@ -1974,43 +2580,76 @@ Cell c; {
 Int intOf(c)                           /* find integer value of cell?      */
 Cell c; {
     assert(isInt(c));
-    return isPair(c) ? (Int)(snd(c)) : (Int)(c-INTZERO);
+    return isPair(c) ? (Int)(snd(c)) : (Int)(c-SMALL_INT_ZERO);
 }
 
 Cell mkInt(n)                          /* make cell representing integer   */
 Int n; {
-    return (MINSMALLINT <= n && n <= MAXSMALLINT)
-           ? INTZERO+n
+    return (SMALL_INT_MIN    <= SMALL_INT_ZERO+n &&
+            SMALL_INT_ZERO+n <= SMALL_INT_MAX)
+           ? SMALL_INT_ZERO+n
            : pair(INTCELL,n);
 }
 
-#if BIGNUMS
-Bool isBignum(c)                       /* cell holds bignum value?         */
-Cell c; {
-    return c==ZERONUM || (isPair(c) && (fst(c)==POSNUM || fst(c)==NEGNUM));
-}
-#endif
+#if SIZEOF_VOID_P == SIZEOF_INT
 
-#if SIZEOF_INTP == SIZEOF_INT
 typedef union {Int i; Ptr p;} IntOrPtr;
-Cell mkPtr(p)
+
+Cell mkAddr(p)
 Ptr p;
 {
     IntOrPtr x;
     x.p = p;
-    return pair(PTRCELL,x.i);
+    return pair(ADDRCELL,x.i);
 }
 
-Ptr ptrOf(c)
+Ptr addrOf(c)
 Cell c;
 {
     IntOrPtr x;
-    assert(fst(c) == PTRCELL);
+    assert(fst(c) == ADDRCELL);
+    x.i = snd(c);
+    return x.p;
+}
+
+Cell mkMPtr(p)
+Ptr p;
+{
+    IntOrPtr x;
+    x.p = p;
+    return pair(MPTRCELL,x.i);
+}
+
+Ptr mptrOf(c)
+Cell c;
+{
+    IntOrPtr x;
+    assert(fst(c) == MPTRCELL);
+    x.i = snd(c);
+    return x.p;
+}
+
+Cell mkCPtr(p)
+Ptr p;
+{
+    IntOrPtr x;
+    x.p = p;
+    return pair(CPTRCELL,x.i);
+}
+
+Ptr cptrOf(c)
+Cell c;
+{
+    IntOrPtr x;
+    assert(fst(c) == CPTRCELL);
     x.i = snd(c);
     return x.p;
 }
-#elif SIZEOF_INTP == 2*SIZEOF_INT
+
+#elif SIZEOF_VOID_P == 2*SIZEOF_INT
+
 typedef union {struct {Int i1; Int i2;} i; Ptr p;} IntOrPtr;
+
 Cell mkPtr(p)
 Ptr p;
 {
@@ -2028,23 +2667,32 @@ Cell c;
     x.i.i2 = intOf(snd(snd(c)));
     return x.p;
 }
-#else
-#warning "type Addr not supported on this architecture - don't use it"
-Cell mkPtr(p)
+
+Cell mkCPtr(p)
 Ptr p;
 {
-    ERRMSG(0) "mkPtr: type Addr not supported on this architecture"
-    EEND;
+    IntOrPtr x;
+    x.p = p;
+    return pair(CPTRCELL,pair(mkInt(x.i.i1),mkInt(x.i.i2)));
 }
 
-Ptr ptrOf(c)
+Ptr cptrOf(c)
 Cell c;
 {
-    ERRMSG(0) "ptrOf: type Addr not supported on this architecture"
-    EEND;
+    IntOrPtr x;
+    assert(fst(c) == CPTRCELL);
+    x.i.i1 = intOf(fst(snd(c)));
+    x.i.i2 = intOf(snd(snd(c)));
+    return x.p;
 }
+
+#else
+
+#error "Can't implement mkPtr/ptrOf on this architecture."
+
 #endif
 
+
 String stringNegate( s )
 String s;
 {
@@ -2118,30 +2766,19 @@ List xs, ys; {                         /* list xs onto list ys...          */
     return ys;
 }
 
-#if 0
-List delete(xs,y)                      /* Delete first use of y from xs    */
-List xs;
-Cell y; {
-    if (isNull(xs)) {
-        return xs;
-    } else if (hs(xs) == y) {
-        return tl(xs);
-    } else {
-        tl(xs) = delete(tl(xs),y);
-        return xs;
-    }
-}
-
-List minus(xs,ys)                      /* Delete members of ys from xs     */
-List xs, ys; {
-    mapAccum(delete,xs,ys);
-    return xs;
-}
-#endif
+QualId qualidIsMember ( QualId q, List xs )
+{
+   for (; nonNull(xs); xs=tl(xs)) {
+      if (eqQualIdent(q, hd(xs)))
+         return hd(xs);
+   }
+   return NIL;
+}  
 
 Cell varIsMember(t,xs)                 /* Test if variable is a member of  */
 Text t;                                /* given list of variables          */
 List xs; {
+    assert(isText(t) || isInventedVar(t) || isInventedDictVar(t));
     for (; nonNull(xs); xs=tl(xs))
         if (t==textOf(hd(xs)))
             return hd(xs);
@@ -2244,7 +2881,7 @@ List xs; {
     return ys;
 }
 
-List splitAt(n,xs)                         /* drop n things from front of list*/
+List splitAt(n,xs)                      /* drop n things from front of list*/
 Int  n;       
 List xs; {
     for(; n>0; --n) {
@@ -2253,7 +2890,7 @@ List xs; {
     return xs;
 }
 
-Cell nth(n,xs)                         /* extract n'th element of list    */
+Cell nth(n,xs)                          /* extract n'th element of list    */
 Int  n;
 List xs; {
     for(; n>0 && nonNull(xs); --n, xs=tl(xs)) {
@@ -2282,6 +2919,88 @@ List xs; {
     return xs;                          /* here if element not found       */
 }
 
+List nubList(xs)                        /* nuke dups in list               */
+List xs; {                              /* non destructive                 */
+   List outs = NIL;
+   for (; nonNull(xs); xs=tl(xs))
+      if (isNull(cellIsMember(hd(xs),outs)))
+         outs = cons(hd(xs),outs);
+   outs = rev(outs);
+   return outs;
+}
+
+
+/* --------------------------------------------------------------------------
+ * Tagged tuples (experimental)
+ * ------------------------------------------------------------------------*/
+
+static void z_tag_check ( Cell x, int tag, char* caller )
+{
+   char buf[100];
+   if (isNull(x)) {
+      sprintf(buf,"z_tag_check(%s): null\n", caller);
+      internal(buf);
+   }
+   if (whatIs(x) != tag) {
+      sprintf(buf, 
+          "z_tag_check(%s): tag was %d, expected %d\n",
+          caller, whatIs(x), tag );
+      internal(buf);
+   }  
+}
+
+Cell zpair ( Cell x1, Cell x2 )
+{ return ap(ZTUP2,ap(x1,x2)); }
+Cell zfst ( Cell zpair )
+{ z_tag_check(zpair,ZTUP2,"zfst"); return fst( snd(zpair) ); }
+Cell zsnd ( Cell zpair )
+{ z_tag_check(zpair,ZTUP2,"zsnd"); return snd( snd(zpair) ); }
+
+Cell ztriple ( Cell x1, Cell x2, Cell x3 )
+{ return ap(ZTUP3,ap(x1,ap(x2,x3))); }
+Cell zfst3 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP3,"zfst3"); return fst( snd(zpair) ); }
+Cell zsnd3 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP3,"zsnd3"); return fst(snd( snd(zpair) )); }
+Cell zthd3 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP3,"zthd3"); return snd(snd( snd(zpair) )); }
+
+Cell z4ble ( Cell x1, Cell x2, Cell x3, Cell x4 )
+{ return ap(ZTUP4,ap(x1,ap(x2,ap(x3,x4)))); }
+Cell zsel14 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP4,"zsel14"); return fst( snd(zpair) ); }
+Cell zsel24 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP4,"zsel24"); return fst(snd( snd(zpair) )); }
+Cell zsel34 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP4,"zsel34"); return fst(snd(snd( snd(zpair) ))); }
+Cell zsel44 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP4,"zsel44"); return snd(snd(snd( snd(zpair) ))); }
+
+Cell z5ble ( Cell x1, Cell x2, Cell x3, Cell x4, Cell x5 )
+{ return ap(ZTUP5,ap(x1,ap(x2,ap(x3,ap(x4,x5))))); }
+Cell zsel15 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP5,"zsel15"); return fst( snd(zpair) ); }
+Cell zsel25 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP5,"zsel25"); return fst(snd( snd(zpair) )); }
+Cell zsel35 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP5,"zsel35"); return fst(snd(snd( snd(zpair) ))); }
+Cell zsel45 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP5,"zsel45"); return fst(snd(snd(snd( snd(zpair) )))); }
+Cell zsel55 ( Cell zpair )
+{ z_tag_check(zpair,ZTUP5,"zsel55"); return snd(snd(snd(snd( snd(zpair) )))); }
+
+
+Cell unap ( int tag, Cell c )
+{
+   char buf[100];
+   if (whatIs(c) != tag) {
+      sprintf(buf, "unap: specified %d, actual %d\n",
+                   tag, whatIs(c) );
+      internal(buf);
+   }
+   return snd(c);
+}
+
 /* --------------------------------------------------------------------------
  * Operations on applications:
  * ------------------------------------------------------------------------*/
@@ -2334,278 +3053,174 @@ List args; {
 }
 
 /* --------------------------------------------------------------------------
- * Handle operations:
+ * debugging support
  * ------------------------------------------------------------------------*/
 
-#if IO_HANDLES
-struct strHandle DEFTABLE(handles,NUM_HANDLES);
-
-Cell openHandle(s,hmode,binary)         /* open handle to file named s in  */
-String s;                               /* the specified hmode             */
-Int    hmode; 
-Bool   binary; {
-    Int i;
-
-    for (i=0; i<NUM_HANDLES && nonNull(handles[i].hcell); ++i)
-        ;                                       /* Search for unused handle*/
-    if (i>=NUM_HANDLES) {                       /* If at first we don't    */
-        garbageCollect();                       /* succeed, garbage collect*/
-        for (i=0; i<NUM_HANDLES && nonNull(handles[i].hcell); ++i)
-            ;                                   /* and try again ...       */
-    }
-    if (i>=NUM_HANDLES) {                       /* ... before we give up   */
-        ERRMSG(0) "Too many handles open; cannot open \"%s\"", s
-        EEND;
-    }
-    else {                                      /* prepare to open file    */
-        String stmode;
-        if (binary) {
-            stmode = (hmode&HAPPEND) ? "ab+" :
-                     (hmode&HWRITE)  ? "wb+" :
-                     (hmode&HREAD)   ? "rb" : (String)0;
-        } else {
-            stmode = (hmode&HAPPEND) ? "a+"  :
-                     (hmode&HWRITE)  ? "w+"  :
-                     (hmode&HREAD)   ? "r"  : (String)0;
-        }
-        if (stmode && (handles[i].hfp=fopen(s,stmode))) {
-            handles[i].hmode = hmode;
-            return (handles[i].hcell = ap(HANDCELL,i));
-        }
-    }
-    return NIL;
-}
-
-static Void local freeHandle(n)         /* release handle storage when no  */
-Int n; {                                /* heap references to it remain    */
-    if (0<=n && n<NUM_HANDLES && nonNull(handles[n].hcell)) {
-        if (n>HSTDERR && handles[n].hmode!=HCLOSED && handles[n].hfp) {
-            fclose(handles[n].hfp);
-            handles[n].hfp = 0;
-        }
-        fst(handles[n].hcell) = snd(handles[n].hcell) = NIL;
-        handles[n].hcell      = NIL;
-    }
+/* Given the address of an info table, find the constructor/tuple
+   that it belongs to, and return the name.  Only needed for debugging.
+*/
+char* lookupHugsItblName ( void* v )
+{
+   int i;
+   for (i = TYCON_BASE_ADDR; 
+        i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
+      if (tabTycon[i-TYCON_BASE_ADDR].inUse
+          && tycon(i).itbl == v)
+         return textToStr(tycon(i).text);
+   }
+   for (i = NAME_BASE_ADDR; 
+        i < NAME_BASE_ADDR+tabNameSz; ++i) {
+      if (tabName[i-NAME_BASE_ADDR].inUse
+          && name(i).itbl == v)
+         return textToStr(name(i).text);
+   }
+   return NULL;
+}
+
+static String maybeModuleStr ( Module m )
+{
+   if (isModule(m)) return textToStr(module(m).text); else return "??";
 }
-#endif
-
-#if GC_MALLOCPTRS
-/* --------------------------------------------------------------------------
- * Malloc Ptrs:
- * ------------------------------------------------------------------------*/
-
-struct strMallocPtr mallocPtrs[NUM_MALLOCPTRS];
 
-/* It might GC (because it uses a table not a list) which will trash any
- * unstable pointers.  
- * (It happens that we never use it with unstable pointers.)
- */
-Cell mkMallocPtr(ptr,cleanup)            /* create a new malloc pointer    */
-Ptr ptr;
-Void (*cleanup) Args((Ptr)); {
-    Int i;
-    for (i=0; i<NUM_MALLOCPTRS && mallocPtrs[i].refCount!=0; ++i)
-        ;                                       /* Search for unused entry */
-    if (i>=NUM_MALLOCPTRS) {                    /* If at first we don't    */
-        garbageCollect();                       /* succeed, garbage collect*/
-        for (i=0; i<NUM_MALLOCPTRS && mallocPtrs[i].refCount!=0; ++i)
-            ;                                   /* and try again ...       */
-    }
-    if (i>=NUM_MALLOCPTRS) {                    /* ... before we give up   */
-        ERRMSG(0) "Too many ForeignObjs open"
-        EEND;
-    }
-    mallocPtrs[i].ptr      = ptr;
-    mallocPtrs[i].cleanup  = cleanup;
-    mallocPtrs[i].refCount = 1;
-    return (mallocPtrs[i].mpcell = ap(MPCELL,i));
+static String maybeNameStr ( Name n )
+{
+   if (isName(n)) return textToStr(name(n).text); else return "??";
 }
 
-Void incMallocPtrRefCnt(n,i)             /* change ref count of MallocPtr */
-Int n;
-Int i; {        
-    if (!(0<=n && n<NUM_MALLOCPTRS && mallocPtrs[n].refCount > 0))
-        internal("freeMallocPtr");
-    mallocPtrs[n].refCount += i;
-    if (mallocPtrs[n].refCount <= 0) {
-        mallocPtrs[n].cleanup(mallocPtrs[n].ptr);
-
-        mallocPtrs[n].ptr      = 0;
-        mallocPtrs[n].cleanup  = 0;
-        mallocPtrs[n].refCount = 0;
-        mallocPtrs[n].mpcell   = NIL;
-    }
+static String maybeTyconStr ( Tycon t )
+{
+   if (isTycon(t)) return textToStr(tycon(t).text); else return "??";
 }
-#endif /* GC_MALLOCPTRS */
-
-/* --------------------------------------------------------------------------
- * Stable pointers
- * This is a mechanism that allows the C world to manipulate pointers into the
- * Haskell heap without having to worry that the garbage collector is going
- * to delete it or move it around.
- * The implementation and interface is based on my implementation in
- * GHC - but, at least for now, is simplified by using a fixed size
- * table of stable pointers.
- * ------------------------------------------------------------------------*/
-
-#if GC_STABLEPTRS
-
-/* Each entry in the stable pointer table is either a heap pointer
- * or is not currently allocated.
- * Unallocated entries are threaded together into a freelist.
- * The last entry in the list contains the Cell 0; all other values
- * contain a Cell whose value is the next free stable ptr in the list.
- * It follows that stable pointers are strictly positive (>0).
- */
-static Cell stablePtrTable[NUM_STABLEPTRS];
-static Int  sptFreeList;
-#define SPT(sp) stablePtrTable[(sp)-1]
 
-static Void local resetStablePtrs() {
-    Int i;
-    /* It would be easier to build the free list in the other direction
-     * but, when debugging, it's way easier to understand if the first
-     * pointer allocated is "1".
-     */
-    for(i=1; i < NUM_STABLEPTRS; ++i)
-        SPT(i) = i+1;
-    SPT(NUM_STABLEPTRS) = 0;
-    sptFreeList = 1;
+static String maybeClassStr ( Class c )
+{
+   if (isClass(c)) return textToStr(cclass(c).text); else return "??";
 }
 
-Int mkStablePtr(c)                  /* Create a stable pointer            */
-Cell c; {
-    Int i = sptFreeList;
-    if (i == 0)
-        return 0;
-    sptFreeList = SPT(i);
-    SPT(i) = c;
-    return i;
-}
-
-Cell derefStablePtr(p)              /* Dereference a stable pointer       */
-Int p; {
-    if (!(1 <= p && p <= NUM_STABLEPTRS)) {
-        internal("derefStablePtr");
-    }
-    return SPT(p);
+static String maybeText ( Text t )
+{
+   if (isNull(t)) return "(nil)";
+   return textToStr(t);
 }
 
-Void freeStablePtr(i)               /* Free a stable pointer             */
-Int i; {
-    SPT(i) = sptFreeList;
-    sptFreeList = i;
+static void print100 ( Int x )
+{
+   print ( x, 100); printf("\n");
 }
 
-#undef SPT
-#endif /* GC_STABLEPTRS */
-
-/* --------------------------------------------------------------------------
- * plugin support
- * ------------------------------------------------------------------------*/
-
-/*---------------------------------------------------------------------------
- * GreenCard entry points
- *
- * GreenCard generated code accesses Hugs data structures and functions 
- * (only) via these functions (which are stored in the virtual function
- * table hugsAPI1.
- *-------------------------------------------------------------------------*/
-
-#if GREENCARD
-
-static Cell  makeTuple      Args((Int));
-static Cell  makeInt        Args((Int));
-static Cell  makeChar       Args((Char));
-static Char  CharOf         Args((Cell));
-static Cell  makeFloat      Args((FloatPro));
-static Void* derefMallocPtr Args((Cell));
-static Cell* Fst            Args((Cell));
-static Cell* Snd            Args((Cell));
-
-static Cell  makeTuple(n)      Int      n; { return mkTuple(n); }
-static Cell  makeInt(n)        Int      n; { return mkInt(n); }
-static Cell  makeChar(n)       Char     n; { return mkChar(n); }
-static Char  CharOf(n)         Cell     n; { return charOf(n); }
-static Cell  makeFloat(n)      FloatPro n; { return mkFloat(n); }
-static Void* derefMallocPtr(n) Cell     n; { return derefMP(n); }
-static Cell* Fst(n)            Cell     n; { return (Cell*)&fst(n); }
-static Cell* Snd(n)            Cell     n; { return (Cell*)&snd(n); }
-
-HugsAPI1* hugsAPI1() {
-    static HugsAPI1 api;
-    static Bool initialised = FALSE;
-    if (!initialised) {
-        api.nameTrue        = nameTrue;
-        api.nameFalse       = nameFalse;
-        api.nameNil         = nameNil;
-        api.nameCons        = nameCons;
-        api.nameJust        = nameJust;
-        api.nameNothing     = nameNothing;
-        api.nameLeft        = nameLeft;
-        api.nameRight       = nameRight;
-        api.nameUnit        = nameUnit;
-        api.nameIORun       = nameIORun;
-        api.makeInt         = makeInt;
-        api.makeChar        = makeChar;
-        api.CharOf          = CharOf;
-        api.makeFloat       = makeFloat;
-        api.makeTuple       = makeTuple;
-        api.pair            = pair;
-        api.mkMallocPtr     = mkMallocPtr;
-        api.derefMallocPtr  = derefMallocPtr;
-        api.mkStablePtr     = mkStablePtr;
-        api.derefStablePtr  = derefStablePtr;
-        api.freeStablePtr   = freeStablePtr;
-        api.eval            = eval;
-        api.evalWithNoError = evalWithNoError;
-        api.evalFails       = evalFails;
-        api.whnfArgs        = &whnfArgs;
-        api.whnfHead        = &whnfHead;
-        api.whnfInt         = &whnfInt;
-        api.whnfFloat       = &whnfFloat;
-        api.garbageCollect  = garbageCollect;
-        api.stackOverflow   = hugsStackOverflow;
-        api.internal        = internal;
-        api.registerPrims   = registerPrims;
-        api.addPrimCfun     = addPrimCfun;
-        api.inventText      = inventText;
-        api.Fst             = Fst;
-        api.Snd             = Snd;
-        api.cellStack       = cellStack;
-        api.sp              = &sp;
-    }
-    return &api;
+void dumpTycon ( Int t )
+{
+   if (isTycon(TYCON_BASE_ADDR+t) && !isTycon(t)) t += TYCON_BASE_ADDR;
+   if (!isTycon(t)) {
+      printf ( "dumpTycon %d: not a tycon\n", t);
+      return;
+   }
+   printf ( "{\n" );
+   printf ( "    text: %s\n",     textToStr(tycon(t).text) );
+   printf ( "    line: %d\n",     tycon(t).line );
+   printf ( "     mod: %s\n",     maybeModuleStr(tycon(t).mod));
+   printf ( "   tuple: %d\n",     tycon(t).tuple);
+   printf ( "   arity: %d\n",     tycon(t).arity);
+   printf ( "    kind: ");        print100(tycon(t).kind);
+   printf ( "    what: %d\n",     tycon(t).what);
+   printf ( "    defn: ");        print100(tycon(t).defn);
+   printf ( "    cToT: %d %s\n",  tycon(t).conToTag, 
+                                  maybeNameStr(tycon(t).conToTag));
+   printf ( "    tToC: %d %s\n",  tycon(t).tagToCon, 
+                                  maybeNameStr(tycon(t).tagToCon));
+   printf ( "    itbl: %p\n",     tycon(t).itbl);
+   printf ( "  nextTH: %d %s\n",  tycon(t).nextTyconHash,
+                                  maybeTyconStr(tycon(t).nextTyconHash));
+   printf ( "}\n" );
+}
+
+void dumpName ( Int n )
+{
+   if (isName(NAME_BASE_ADDR+n) && !isName(n)) n += NAME_BASE_ADDR;
+   if (!isName(n)) {
+      printf ( "dumpName %d: not a name\n", n);
+      return;
+   }
+   printf ( "{\n" );
+   printf ( "    text: %s\n",     textToStr(name(n).text) );
+   printf ( "    line: %d\n",     name(n).line );
+   printf ( "     mod: %s\n",     maybeModuleStr(name(n).mod));
+   printf ( "  syntax: %d\n",     name(n).syntax );
+   printf ( "  parent: %d\n",     name(n).parent );
+   printf ( "   arity: %d\n",     name(n).arity );
+   printf ( "  number: %d\n",     name(n).number );
+   printf ( "    type: ");        print100(name(n).type);
+   printf ( "    defn: %d\n",     name(n).defn );
+   printf ( "   cconv: %d\n",     name(n).callconv );
+   printf ( "  primop: %p\n",     name(n).primop );
+   printf ( "    itbl: %p\n",     name(n).itbl );
+   printf ( " closure: %d\n",     name(n).closure );
+   printf ( "  nextNH: %d\n",     name(n).nextNameHash );
+   printf ( "}\n" );
+}
+
+
+void dumpClass ( Int c )
+{
+   if (isClass(CCLASS_BASE_ADDR+c) && !isClass(c)) c += CCLASS_BASE_ADDR;
+   if (!isClass(c)) {
+      printf ( "dumpClass %d: not a class\n", c);
+      return;
+   }
+   printf ( "{\n" );
+   printf ( "    text: %s\n",     textToStr(cclass(c).text) );
+   printf ( "    line: %d\n",     cclass(c).line );
+   printf ( "     mod: %s\n",     maybeModuleStr(cclass(c).mod));
+   printf ( "   arity: %d\n",     cclass(c).arity );
+   printf ( "   level: %d\n",     cclass(c).level );
+   printf ( "   kinds: ");        print100( cclass(c).kinds );
+   printf ( "     fds: %d\n",     cclass(c).fds );
+   printf ( "    xfds: %d\n",     cclass(c).xfds );
+   printf ( "    head: ");        print100( cclass(c).head );
+   printf ( "    dcon: ");        print100( cclass(c).dcon );
+   printf ( "  supers: ");        print100( cclass(c).supers );
+   printf ( " #supers: %d\n",     cclass(c).numSupers );
+   printf ( "   dsels: ");        print100( cclass(c).dsels );
+   printf ( " members: ");        print100( cclass(c).members );
+   printf ( "#members: %d\n",     cclass(c).numMembers );
+   printf ( "defaults: ");        print100( cclass(c).defaults );
+   printf ( "   insts: ");        print100( cclass(c).instances );
+   printf ( "}\n" );
+}
+
+
+void dumpInst ( Int i )
+{
+   if (isInst(INST_BASE_ADDR+i) && !isInst(i)) i += INST_BASE_ADDR;
+   if (!isInst(i)) {
+      printf ( "dumpInst %d: not an instance\n", i);
+      return;
+   }
+   printf ( "{\n" );
+   printf ( "   class: %s\n",     maybeClassStr(inst(i).c) );
+   printf ( "    line: %d\n",     inst(i).line );
+   printf ( "     mod: %s\n",     maybeModuleStr(inst(i).mod));
+   printf ( "   kinds: ");        print100( inst(i).kinds );
+   printf ( "    head: ");        print100( inst(i).head );
+   printf ( "   specs: ");        print100( inst(i).specifics );
+   printf ( "  #specs: %d\n",     inst(i).numSpecifics );
+   printf ( "   impls: ");        print100( inst(i).implements );
+   printf ( " builder: %s\n",     maybeNameStr( inst(i).builder ) );
+   printf ( "}\n" );
 }
 
-#endif /* GREENCARD */
-
 
 /* --------------------------------------------------------------------------
  * storage control:
  * ------------------------------------------------------------------------*/
 
-#if DYN_TABLES
-static void far* safeFarCalloc Args((Int,Int));
-static void far* safeFarCalloc(n,s)     /* allocate table storage and check*/
-Int n, s; {                             /* for non-null return             */
-    void far* tab = farCalloc(n,s);
-    if (tab==0) {
-        ERRMSG(0) "Cannot allocate run-time tables"
-        EEND;
-    }
-    return tab;
-}
-#define TABALLOC(v,t,n)                 v=(t far*)safeFarCalloc(n,sizeof(t));
-#else
-#define TABALLOC(v,t,n)
-#endif
-
 Void storage(what)
 Int what; {
     Int i;
 
     switch (what) {
+        case POSTPREL: break;
+
         case RESET   : clearStack();
 
                        /* the next 2 statements are particularly important
@@ -2615,87 +3230,85 @@ Int what; {
                         */
                        heapTopFst = heapFst + heapSize;
                        heapTopSnd = heapSnd + heapSize;
-#if PROFILING
-                       heapTopThd = heapThd + heapSize;
-                       if (profile) {
-                           garbageCollect();
-                           fclose(profile);
-#if HAVE_HP2PS
-                           system("hp2ps profile.hp");
-#endif
-                           profile = 0;
-                       }
-#endif
-#if IO_HANDLES
-                       handles[HSTDIN].hmode  = HREAD;
-                       handles[HSTDOUT].hmode = HAPPEND;
-                       handles[HSTDERR].hmode = HAPPEND;
-#endif
-#if GC_MALLOCPTRS
-                       for (i=0; i<NUM_MALLOCPTRS; i++)
-                           mallocPtrs[i].mpcell = NIL;
-#endif
-#if !HSCRIPT
-#if GC_STABLEPTRS
-                       resetStablePtrs();
-#endif
-#endif
                        consGC = TRUE;
                        lsave  = NIL;
                        rsave  = NIL;
                        if (isNull(lastExprSaved))
-                           savedText = NUM_TEXT;
+                           savedText = TEXT_SIZE;
                        break;
 
         case MARK    : 
                        start();
-                       for (i=NAMEMIN; i<nameHw; ++i) {
-                           mark(name(i).parent);
-                           mark(name(i).defn);
-                           mark(name(i).stgVar);
-                           mark(name(i).type);
+                       for (i = NAME_BASE_ADDR; 
+                            i < NAME_BASE_ADDR+tabNameSz; ++i) {
+                          if (tabName[i-NAME_BASE_ADDR].inUse) {
+                             mark(name(i).parent);
+                             mark(name(i).type);
+                             mark(name(i).defn);
+                             mark(name(i).closure);
+                          }
                        }
                        end("Names", nameHw-NAMEMIN);
 
-#if !IGNORE_MODULES
                        start();
-                       for (i=MODMIN; i<moduleHw; ++i) {
-                           mark(module(i).tycons);
-                           mark(module(i).names);
-                           mark(module(i).classes);
-                           mark(module(i).exports);
-                           mark(module(i).qualImports);
+                       for (i = MODULE_BASE_ADDR; 
+                            i < MODULE_BASE_ADDR+tabModuleSz; ++i) {
+                          if (tabModule[i-MODULE_BASE_ADDR].inUse) {
+                             mark(module(i).tycons);
+                             mark(module(i).names);
+                             mark(module(i).classes);
+                             mark(module(i).exports);
+                             mark(module(i).qualImports);
+                             mark(module(i).codeList);
+                             mark(module(i).tree);
+                             mark(module(i).uses);
+                             mark(module(i).objectExtraNames);
+                          }
                        }
+                       mark(moduleGraph);
+                       mark(prelModules);
+                       mark(targetModules);
                        end("Modules", moduleHw-MODMIN);
-#endif
 
                        start();
-                       for (i=TYCMIN; i<tyconHw; ++i) {
-                           mark(tycon(i).defn);
-                           mark(tycon(i).kind);
-                           mark(tycon(i).what);
+                       for (i = TYCON_BASE_ADDR; 
+                            i < TYCON_BASE_ADDR+tabTyconSz; ++i) {
+                          if (tabTycon[i-TYCON_BASE_ADDR].inUse) {
+                             mark(tycon(i).kind);
+                             mark(tycon(i).what);
+                             mark(tycon(i).defn);
+                             mark(tycon(i).closure);
+                          }
                        }
                        end("Type constructors", tyconHw-TYCMIN);
 
                        start();
-                       for (i=CLASSMIN; i<classHw; ++i) {
-                           mark(cclass(i).head);
-                           mark(cclass(i).kinds);
-                           mark(cclass(i).dsels);
-                           mark(cclass(i).supers);
-                           mark(cclass(i).members);
-                           mark(cclass(i).defaults);
-                           mark(cclass(i).instances);
+                       for (i = CCLASS_BASE_ADDR; 
+                            i < CCLASS_BASE_ADDR+tabClassSz; ++i) {
+                          if (tabClass[i-CCLASS_BASE_ADDR].inUse) {
+                             mark(cclass(i).kinds);
+                            mark(cclass(i).fds);
+                            mark(cclass(i).xfds);
+                             mark(cclass(i).head);
+                             mark(cclass(i).supers);
+                             mark(cclass(i).dsels);
+                             mark(cclass(i).members);
+                             mark(cclass(i).defaults);
+                             mark(cclass(i).instances);
+                          }
                        }
                        mark(classes);
                        end("Classes", classHw-CLASSMIN);
 
                        start();
-                       for (i=INSTMIN; i<instHw; ++i) {
-                           mark(inst(i).head);
-                           mark(inst(i).kinds);
-                           mark(inst(i).specifics);
-                           mark(inst(i).implements);
+                       for (i = INST_BASE_ADDR; 
+                            i < INST_BASE_ADDR+tabInstSz; ++i) {
+                          if (tabInst[i-INST_BASE_ADDR].inUse) {
+                             mark(inst(i).kinds);
+                             mark(inst(i).head);
+                             mark(inst(i).specifics);
+                             mark(inst(i).implements);
+                          }
                        }
                        end("Instances", instHw-INSTMIN);
 
@@ -2709,24 +3322,6 @@ Int what; {
                        mark(lsave);
                        mark(rsave);
                        end("Last expression", 3);
-#if IO_HANDLES
-                       start();
-                       mark(handles[HSTDIN].hcell);
-                       mark(handles[HSTDOUT].hcell);
-                       mark(handles[HSTDERR].hcell);
-                       end("Standard handles", 3);
-#endif
-
-#if GC_STABLEPTRS
-                       start();
-                       for (i=0; i<NUM_STABLEPTRS; ++i)
-                           mark(stablePtrTable[i]);
-                       end("Stable pointers", NUM_STABLEPTRS);
-#endif
-
-#if GC_WEAKPTRS
-                       mark(finalizers);
-#endif
 
                        if (consGC) {
                            start();
@@ -2736,7 +3331,7 @@ Int what; {
 
                        break;
 
-        case INSTALL : heapFst = heapAlloc(heapSize);
+        case PREPREL : heapFst = heapAlloc(heapSize);
                        heapSnd = heapAlloc(heapSize);
 
                        if (heapFst==(Heap)0 || heapSnd==(Heap)0) {
@@ -2747,17 +3342,6 @@ Int what; {
 
                        heapTopFst = heapFst + heapSize;
                        heapTopSnd = heapSnd + heapSize;
-#if PROFILING
-                       heapThd = heapAlloc(heapSize);
-                       if (heapThd==(Heap)0) {
-                           ERRMSG(0) "Cannot allocate profiler storage space"
-                           EEND;
-                       }
-                       heapTopThd   = heapThd + heapSize;
-                       profile      = 0;
-                       if (0 == profInterval)
-                           profInterval = heapSize / DEF_PROFINTDIV;
-#endif
                        for (i=1; i<heapSize; ++i) {
                            fst(-i) = FREECELL;
                            snd(-i) = -(i+1);
@@ -2775,82 +3359,17 @@ Int what; {
                            EEND;
                        }
 
-                       TABALLOC(text,      char,             NUM_TEXT)
-                       TABALLOC(tyconHash, Tycon,            TYCONHSZ)
-                       TABALLOC(tabTycon,  struct strTycon,  NUM_TYCON)
-                       TABALLOC(nameHash,  Name,             NAMEHSZ)
-                       TABALLOC(tabName,   struct strName,   NUM_NAME)
-                       TABALLOC(tabClass,  struct strClass,  NUM_CLASSES)
-                       TABALLOC(cellStack, Cell,             NUM_STACK)
-                       TABALLOC(tabModule, struct Module,    NUM_SCRIPTS)
-#if TREX
-                       TABALLOC(tabExt,    Text,             NUM_EXT)
-#endif
                        clearStack();
 
-#if IO_HANDLES
-                       TABALLOC(handles,   struct strHandle, NUM_HANDLES)
-                       for (i=0; i<NUM_HANDLES; i++)
-                           handles[i].hcell = NIL;
-                       handles[HSTDIN].hcell  = ap(HANDCELL,HSTDIN);
-                       handles[HSTDIN].hfp    = stdin;
-                       handles[HSTDOUT].hcell = ap(HANDCELL,HSTDOUT);
-                       handles[HSTDOUT].hfp   = stdout;
-                       handles[HSTDERR].hcell = ap(HANDCELL,HSTDERR);
-                       handles[HSTDERR].hfp   = stderr;
-#endif
-
                        textHw        = 0;
-                       nextNewText   = NUM_TEXT;
-                       nextNewDText  = (-1);
+                       nextNewText   = INVAR_BASE_ADDR;
+                       nextNewDText  = INDVAR_BASE_ADDR;
                        lastExprSaved = NIL;
-                       savedText     = NUM_TEXT;
-                       for (i=0; i<TEXTHSZ; ++i)
-                           textHash[i][0] = NOTEXT;
-
-
-#if !IGNORE_MODULES
-                       moduleHw = MODMIN;
-#endif
-
-                       tyconHw  = TYCMIN;
-                       for (i=0; i<TYCONHSZ; ++i)
-                           tyconHash[i] = NIL;
-
-#if GC_WEAKPTRS
-                       finalizers   = NIL;
-                       liveWeakPtrs = NIL;
-#endif
-
-#if GC_STABLEPTRS
-                       resetStablePtrs();
-#endif
-
-#if TREX
-                       extHw    = EXTMIN;
-#endif
-
-                       nameHw   = NAMEMIN;
-                       for (i=0; i<NAMEHSZ; ++i)
-                           nameHash[i] = NIL;
-
-                       classHw  = CLASSMIN;
-
-                       instHw   = INSTMIN;
-
-#if USE_DICTHW
-                       dictHw   = 0;
-#endif
-
-                       tabInst  = (struct strInst far *)
-                                    farCalloc(NUM_INSTS,sizeof(struct strInst));
-
-                       if (tabInst==0) {
-                           ERRMSG(0) "Cannot allocate instance tables"
-                           EEND;
-                       }
+                       savedText     = TEXT_SIZE;
 
-                       scriptHw = 0;
+                       for (i=0; i<TEXTHSZ;  ++i) textHash[i][0] = NOTEXT;
+                       for (i=0; i<TYCONHSZ; ++i) tyconHash[RC_T(i)] = NIL;
+                       for (i=0; i<NAMEHSZ;  ++i) nameHash[RC_N(i)] = NIL;
 
                        break;
     }