[project @ 1999-11-17 16:57:38 by andy]
[ghc-hetmet.git] / ghc / interpreter / storage.h
1
2 /* --------------------------------------------------------------------------
3  * Defines storage datatypes: Text, Name, Module, Tycon, Cell, List, Pair,
4  * Triple, ...
5  *
6  * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
7  * Yale Haskell Group, and the Oregon Graduate Institute of Science and
8  * Technology, 1994-1999, All rights reserved.  It is distributed as
9  * free software under the license in the file "License", which is
10  * included in the distribution.
11  *
12  * $RCSfile: storage.h,v $
13  * $Revision: 1.13 $
14  * $Date: 1999/11/17 16:57:48 $
15  * ------------------------------------------------------------------------*/
16
17 /* --------------------------------------------------------------------------
18  * Typedefs for main data types:
19  * Many of these type names are used to indicate the intended us of a data
20  * item, rather than for type checking purposes.  Sadly (although sometimes,
21  * fortunately), the C compiler cannot distinguish between the use of two
22  * different names defined to be synonyms for the same types.
23  * ------------------------------------------------------------------------*/
24
25 typedef Int          Text;                       /* text string            */
26 typedef Unsigned     Syntax;                     /* syntax (assoc,preced)  */
27 typedef Int          Cell;                       /* general cell value     */
28 typedef Cell far     *Heap;                      /* storage of heap        */
29 typedef Cell         Pair;                       /* pair cell              */
30 typedef Int          StackPtr;                   /* stack pointer          */
31 typedef Cell         Offset;                     /* offset/generic variable*/
32 typedef Int          Script;                     /* script file number     */
33 typedef Int          Module;                     /* module                 */
34 typedef Cell         Tycon;                      /* type constructor       */
35 typedef Cell         Type;                       /* type expression        */
36 typedef Cell         Kind;                       /* kind expression        */
37 typedef Cell         Kinds;                      /* list of kinds          */
38 typedef Cell         Constr;                     /* constructor expression */
39 typedef Cell         Name;                       /* named value            */
40 typedef Cell         Class;                      /* type class             */
41 typedef Cell         Inst;                       /* instance of type class */
42 typedef Cell         Triple;                     /* triple of cell values  */
43 typedef Cell         List;                       /* list of cells          */
44 typedef Cell         Bignum;                     /* bignum integer         */
45 typedef Cell         Float;                      /* floating pt literal    */
46 #if TREX
47 typedef Cell         Ext;                        /* extension label        */
48 #endif
49
50 /* --------------------------------------------------------------------------
51  * Text storage:
52  * provides storage for the characters making up identifier and symbol
53  * names, string literals, character constants etc...
54  * ------------------------------------------------------------------------*/
55
56 extern  String       textToStr          Args((Text));
57 extern  Text         findText           Args((String));
58 extern  Text         inventText         Args((Void));
59 extern  Text         inventDictText     Args((Void));
60 extern  Bool         inventedText       Args((Text));
61
62 /* Variants of textToStr and syntaxOf which work for idents, ops whether
63  * qualified or unqualified.
64  */
65 extern  String       identToStr         Args((Cell));
66 extern  Text         fixLitText         Args((Text));
67 extern  Syntax       identSyntax        Args((Cell));
68 extern  Syntax       defaultSyntax      Args((Text));
69
70 /* --------------------------------------------------------------------------
71  * Specification of syntax (i.e. default written form of application)
72  * ------------------------------------------------------------------------*/
73
74 #define MIN_PREC  0                    /* weakest binding operator         */
75 #define MAX_PREC  9                    /* strongest binding operator       */
76 #define FUN_PREC  (MAX_PREC+2)         /* binding of function symbols      */
77 #define DEF_PREC  MAX_PREC
78 #define APPLIC    0                    /* written applicatively            */
79 #define LEFT_ASS  1                    /* left associative infix           */
80 #define RIGHT_ASS 2                    /* right associative infix          */
81 #define NON_ASS   3                    /* non associative infix            */
82 #define DEF_ASS   LEFT_ASS
83
84 #define UMINUS_PREC  6                  /* Change these settings at your   */
85 #define UMINUS_ASSOC LEFT_ASS           /* own risk; they may not work!    */
86
87 #define assocOf(x)      ((x)&NON_ASS)
88 #define precOf(x)       ((x)>>2)
89 #define mkSyntax(a,p)   ((a)|((p)<<2))
90 #define DEF_OPSYNTAX    mkSyntax(DEF_ASS,DEF_PREC)
91 #define NO_SYNTAX       (-1)
92
93 extern  Void   addSyntax  Args((Int,Text,Syntax));
94 extern  Syntax syntaxOf   Args((Text));
95
96 /* --------------------------------------------------------------------------
97  * Heap storage:
98  * Provides a garbage collectable heap for storage of expressions etc.
99  * ------------------------------------------------------------------------*/
100
101 #define heapAlloc(s) (Heap)(farCalloc(s,sizeof(Cell)))
102 #define heapBuilt()  (heapFst)
103 extern  Int          heapSize;
104 extern  Heap         heapFst, heapSnd;
105 extern  Heap         heapTopFst;
106 extern  Heap         heapTopSnd;
107 extern  Bool         consGC;            /* Set to FALSE to turn off gc from*/
108                                         /* C stack; use with extreme care! */
109 extern Int   cellsRecovered;            /* cells recovered by last gc      */
110
111 #define fst(c)       heapTopFst[c]
112 #define snd(c)       heapTopSnd[c]
113
114 extern  Pair         pair            Args((Cell,Cell));
115 extern  Void         garbageCollect  Args((Void));
116
117 extern  Void         overwrite       Args((Pair,Pair));
118 extern  Void         overwrite2      Args((Pair,Cell,Cell));
119 extern  Cell         markExpr        Args((Cell));
120 extern  Void         markWithoutMove Args((Cell));
121
122 #define mark(v)      v=markExpr(v)
123
124 #define isPair(c)    ((c)<0)
125 #define isGenPair(c) ((c)<0 && -heapSize<=(c))
126
127 extern  Cell         whatIs    Args((Cell));
128
129 /* --------------------------------------------------------------------------
130  * Box cell tags are used as the fst element of a pair to indicate that
131  * the snd element of the pair is to be treated in some special way, other
132  * than as a Cell.  Examples include holding integer values, variable name
133  * and string text etc.
134  * ------------------------------------------------------------------------*/
135
136 #define TAGMIN       1            /* Box and constructor cell tag values   */
137 #define BCSTAG       30           /* Box=TAGMIN..BCSTAG-1                  */
138 #define isTag(c)     (TAGMIN<=(c) && (c)<SPECMIN) /* Tag cell values       */
139 #define isBoxTag(c)  (TAGMIN<=(c) && (c)<BCSTAG)  /* Box cell tag values   */
140 #define isConTag(c)  (BCSTAG<=(c) && (c)<SPECMIN) /* Constr cell tag values*/
141
142 #define FREECELL     3            /* Free list cell:          snd :: Cell  */
143 #define VARIDCELL    4            /* Identifier variable:     snd :: Text  */
144 #define VAROPCELL    5            /* Operator variable:       snd :: Text  */
145 #define DICTVAR      6            /* Dictionary variable:     snd :: Text  */
146 #define CONIDCELL    7            /* Identifier constructor:  snd :: Text  */
147 #define CONOPCELL    8            /* Operator constructor:    snd :: Text  */
148 #define STRCELL      9            /* String literal:          snd :: Text  */
149 #define INTCELL      10           /* Int literal:             snd :: Int   */
150 #define ADDPAT       11           /* (_+k) pattern discr:     snd :: Int   */
151 #define FLOATCELL    15           /* Floating Pt literal:     snd :: Text  */
152 #define BIGCELL      16           /* Integer literal:         snd :: Text  */
153 #if PTR_ON_HEAP
154 #define PTRCELL      17           /* C Heap Pointer           snd :: Ptr   */
155 #if IPARAM
156 #define IPCELL       19           /* Imp Param Cell:          snd :: Text  */
157 #define IPVAR        20           /* ?x:                      snd :: Text  */
158 #endif
159 #define CPTRCELL     21           /* Native code pointer      snd :: Ptr   */
160 #endif
161 #if TREX
162 #define EXTCOPY      22           /* Copy of an Ext:          snd :: Text  */
163 #endif
164
165 //#define textOf(c)       ((Text)(snd(c)))         /* c ::  (VAR|CON)(ID|OP) */
166
167 #if 1
168 static Text textOf( Cell c )
169 {
170    Bool ok = 
171           (whatIs(c)==VARIDCELL
172            || whatIs(c)==CONIDCELL
173            || whatIs(c)==VAROPCELL
174            || whatIs(c)==CONOPCELL
175            || whatIs(c)==STRCELL
176            || whatIs(c)==DICTVAR
177           );
178    if (!ok) {
179 fprintf(stderr, "\ntextOf -- tag %d\n",whatIs(c) );
180       assert(ok);
181    }
182    return snd(c);
183 }
184 #endif
185
186 #define qmodOf(c)       (textOf(fst(snd(c))))    /* c ::  QUALIDENT        */
187 #define qtextOf(c)      (textOf(snd(snd(c))))    /* c ::  QUALIDENT        */
188 #define mkVar(t)        ap(VARIDCELL,t)
189 #define mkVarop(t)      ap(VAROPCELL,t)
190 #define mkCon(t)        ap(CONIDCELL,t)
191 #define mkConop(t)      ap(CONOPCELL,t)
192 #define mkQVar(m,t)     ap(QUALIDENT,pair(mkCon(m),mkVar(t)))
193 #define mkQCon(m,t)     ap(QUALIDENT,pair(mkCon(m),mkCon(t)))
194 #define mkQVarOp(m,t)   ap(QUALIDENT,pair(mkCon(m),mkVarop(t)))
195 #define mkQConOp(m,t)   ap(QUALIDENT,pair(mkCon(m),mkConop(t)))
196 #define intValOf(c)     (snd(c))
197 #define inventVar()     mkVar(inventText())
198 #define mkDictVar(t)    ap(DICTVAR,t)
199 #define inventDictVar() mkDictVar(inventDictText())
200 #define mkStr(t)        ap(STRCELL,t)
201 #if IPARAM
202 #define mkIParam(c)     ap(IPCELL,snd(c))
203 #define isIP(p)         (whatIs(p) == IPCELL)
204 #define ipMatch(pi, t)  (isIP(fun(pi)) && textOf(fun(pi)) == t)
205 #define ipVar(pi)       textOf(fun(pi))
206 #else
207 #define isIP(p)         FALSE
208 #endif
209 extern  Bool            isVar       Args((Cell));
210 extern  Bool            isCon       Args((Cell));
211 extern  Bool            isQVar      Args((Cell));
212 extern  Bool            isQCon      Args((Cell));
213 extern  Bool            isQualIdent Args((Cell));
214 extern  Bool            isIdent     Args((Cell));
215
216 extern  String           stringNegate Args((String));
217
218 #define isFloat(c)       (isPair(c) && fst(c)==FLOATCELL)
219 #define stringToFloat(s) pair(FLOATCELL,findText(s))
220 #define floatToString(f) textToStr(snd(f))
221 #define floatOf(f)       atof(floatToString(f))
222 #define mkFloat(f)       (f)  /* ToDo: is this right? */
223 #define floatNegate(f)   stringToFloat(stringNegate(floatToString(f)))
224
225 #define stringToBignum(s) pair(BIGCELL,findText(s))
226 #define bignumToString(b) textToStr(snd(b))
227
228
229 #if PTR_ON_HEAP
230 #define isPtr(c)        (isPair(c) && fst(c)==PTRCELL)
231 extern  Cell            mkPtr           Args((Ptr));
232 extern  Ptr             ptrOf           Args((Cell));
233 #define isCPtr(c)       (isPair(c) && fst(c)==CPTRCELL)
234 extern  Cell            mkCPtr          Args((Ptr));
235 extern  Ptr             cptrOf          Args((Cell));
236 #endif
237
238 /* --------------------------------------------------------------------------
239  * Constructor cell tags are used as the fst element of a pair to indicate
240  * a particular syntactic construct described by the snd element of the
241  * pair.
242  * Note that a cell c will not be treated as an application (AP/isAp) node
243  * if its first element is a constructor cell tag, whereas a cell whose fst
244  * element is a special cell will be treated as an application node.
245  * ------------------------------------------------------------------------*/
246
247 #define LETREC       30           /* LETREC     snd :: ([Decl],Exp)        */
248 #define COND         31           /* COND       snd :: (Exp,Exp,Exp)       */
249 #define LAMBDA       32           /* LAMBDA     snd :: Alt                 */
250 #define FINLIST      33           /* FINLIST    snd :: [Exp]               */
251 #define DOCOMP       34           /* DOCOMP     snd :: (Exp,[Qual])        */
252 #define BANG         35           /* BANG       snd :: Type                */
253 #define COMP         36           /* COMP       snd :: (Exp,[Qual])        */
254 #define ASPAT        37           /* ASPAT      snd :: (Var,Exp)           */
255 #define ESIGN        38           /* ESIGN      snd :: (Exp,Type)          */
256 #define RSIGN        39           /* RSIGN      snd :: (Rhs,Type)          */
257 #define CASE         40           /* CASE       snd :: (Exp,[Alt])         */
258 #define NUMCASE      41           /* NUMCASE    snd :: (Exp,Disc,Rhs)      */
259 #define FATBAR       42           /* FATBAR     snd :: (Exp,Exp)           */
260 #define LAZYPAT      43           /* LAZYPAT    snd :: Exp                 */
261 #define DERIVE       45           /* DERIVE     snd :: Cell                */
262 #if BREAK_FLOATS
263 #define FLOATCELL    46           /* FLOATCELL  snd :: (Int,Int)           */
264 #endif
265
266 #define BOOLQUAL     49           /* BOOLQUAL   snd :: Exp                 */
267 #define QWHERE       50           /* QWHERE     snd :: [Decl]              */
268 #define FROMQUAL     51           /* FROMQUAL   snd :: (Exp,Exp)           */
269 #define DOQUAL       52           /* DOQUAL     snd :: Exp                 */
270 #define MONADCOMP    53           /* MONADCOMP  snd :: ((m,m0),(Exp,[Qual])*/
271
272 #define GUARDED      54           /* GUARDED    snd :: [guarded exprs]     */
273
274 #define ARRAY        55           /* Array      snd :: (Bounds,[Values])   */
275 #define MUTVAR       56           /* Mutvar     snd :: Cell                */
276 #if INTERNAL_PRIMS
277 #define HUGSOBJECT   57           /* HUGSOBJECT snd :: Cell                */
278 #endif
279
280 #if IPARAM
281 #define WITHEXP      58           /* WITHEXP    snd :: [(Var,Exp)]         */
282 #endif
283
284
285 #define POLYTYPE     60           /* POLYTYPE   snd :: (Kind,Type)         */
286 #define QUAL         61           /* QUAL       snd :: ([Classes],Type)    */
287 #define RANK2        62           /* RANK2      snd :: (Int,Type)          */
288 #define EXIST        63           /* EXIST      snd :: (Int,Type)          */
289 #define POLYREC      64           /* POLYREC    snd :: (Int,Type)          */
290 #define BIGLAM       65           /* BIGLAM     snd :: (vars,patterns)     */
291 #define CDICTS       66           /* CDICTS     snd :: ([Pred],Type)       */
292
293 #define LABC         67           /* LABC       snd :: (con,[(Vars,Type)]) */
294 #define CONFLDS      68           /* CONFLDS    snd :: (con,[Field])       */
295 #define UPDFLDS      69           /* UPDFLDS    snd :: (Exp,[con],[Field]) */
296 #if TREX
297 #define RECORD       70           /* RECORD     snd :: [Val]               */
298 #define EXTCASE      71           /* EXTCASE    snd :: (Exp,Disc,Rhs)      */
299 #define RECSEL       72           /* RECSEL     snd :: Ext                 */
300 #endif
301 #define IMPDEPS      73           /* IMPDEPS    snd :: [Binding]           */
302
303 #define QUALIDENT    74           /* Qualified identifier  snd :: (Id,Id)  */
304 #define HIDDEN       75           /* hiding import list    snd :: [Entity] */
305 #define MODULEENT    76           /* module in export list snd :: con      */
306
307 #define INFIX        77           /* INFIX      snd :: (see tidyInfix)     */
308 #define ONLY         78           /* ONLY       snd :: Exp                 */
309 #define NEG          79           /* NEG        snd :: Exp                 */
310
311 /* Used when parsing GHC interface files */
312 #define DICTAP       80          /* DICTTYPE   snd :: (QClassId,[Type])   */
313
314 #if SIZEOF_INTP != SIZEOF_INT
315 #define PTRCELL      81           /* C Heap Pointer snd :: (Int,Int)       */
316 #endif
317
318 #define STGVAR       92           /* STGVAR     snd :: (StgRhs,info)       */
319 #define STGAPP       93           /* STGAPP     snd :: (StgVar,[Arg])      */
320 #define STGPRIM      94           /* STGPRIM    snd :: (PrimOp,[Arg])      */
321 #define STGCON       95           /* STGCON     snd :: (StgCon,[Arg])      */
322 #define PRIMCASE     96           /* PRIMCASE   snd :: (Expr,[PrimAlt])    */
323 #define DEEFALT      97           /* DEEFALT    snd :: (Var,Expr)          */
324 #define CASEALT      98           /* CASEALT    snd :: (Con,[Var],Expr)    */
325 #define PRIMALT      99           /* PRIMALT    snd :: ([Var],Expr)        */
326 /* Last constructor tag must be less than SPECMIN */
327
328 /* --------------------------------------------------------------------------
329  * Special cell values:
330  * ------------------------------------------------------------------------*/
331
332 #define SPECMIN      101
333 #define isSpec(c)    (SPECMIN<=(c) && (c)<TUPMIN)/* Special cell values    */
334
335 #define NONE         101          /* Dummy stub                            */
336 #define STAR         102          /* Representing the kind of types        */
337 #if TREX
338 #define ROW          103          /* Representing the kind of rows         */
339 #endif
340 #define WILDCARD     104          /* Wildcard pattern                      */
341 #define SKOLEM       105          /* Skolem constant                       */
342
343 #define DOTDOT       106          /* ".." in import/export list            */
344
345 #define NAME         110          /* whatIs code for isName                */
346 #define TYCON        111          /* whatIs code for isTycon               */
347 #define CLASS        112          /* whatIs code for isClass               */
348 #define MODULE       113          /* whatIs code for isModule              */
349 #define INSTANCE     114          /* whatIs code for isInst                */
350 #define TUPLE        115          /* whatIs code for tuple constructor     */
351 #define OFFSET       116          /* whatis code for offset                */
352 #define AP           117          /* whatIs code for application node      */
353 #define CHARCELL     118          /* whatIs code for isChar                */
354 #if TREX
355 #define EXT          119          /* whatIs code for isExt                 */
356 #endif
357
358 #define SIGDECL      120          /* Signature declaration                 */
359 #define FIXDECL      121          /* Fixity declaration                    */
360 #define FUNBIND      122          /* Function binding                      */
361 #define PATBIND      123          /* Pattern binding                       */
362
363 #define DATATYPE     130          /* Datatype type constructor             */
364 #define NEWTYPE      131          /* Newtype type constructor              */
365 #define SYNONYM      132          /* Synonym type constructor              */
366 #define RESTRICTSYN  133          /* Synonym with restricted scope         */
367
368 #define NODEPENDS    135          /* Stop calculation of deps in type check*/
369 #define PREDEFINED   136          /* Predefined name, not yet filled       */
370
371 /* --------------------------------------------------------------------------
372  * Tuple data/type constructors:
373  * ------------------------------------------------------------------------*/
374
375 #define TUPMIN       201
376 #if TREX
377 #define isTuple(c)   (TUPMIN<=(c) && (c)<EXTMIN)
378 #else
379 #define isTuple(c)   (TUPMIN<=(c) && (c)<OFFMIN)
380 #endif
381 #define mkTuple(n)   (TUPMIN+(n))
382 #define tupleOf(n)   ((Int)((n)-TUPMIN))
383
384 #if TREX
385 #define EXTMIN       (TUPMIN+NUM_TUPLES)
386 #define isExt(c)     (EXTMIN<=(c) && (c)<OFFMIN)
387 #define extText(e)   tabExt[(e)-EXTMIN]
388 #define extField(c)  arg(fun(c))
389 #define extRow(c)    arg(c)
390
391 extern Text          DECTABLE(tabExt);
392 extern Ext           mkExt Args((Text));
393 #else
394 #define mkExt(t) NIL
395 #endif
396
397 /* --------------------------------------------------------------------------
398  * Offsets: (generic types/stack offsets)
399  * ------------------------------------------------------------------------*/
400
401 #if TREX
402 #define OFFMIN       (EXTMIN+NUM_EXT)
403 #else
404 #define OFFMIN       (TUPMIN+NUM_TUPLES)
405 #endif
406 #define isOffset(c)  (OFFMIN<=(c) && (c)<MODMIN)
407 #define offsetOf(c)  ((c)-OFFMIN)
408 #define mkOffset(o)  (OFFMIN+(o))
409
410 /* --------------------------------------------------------------------------
411  * Object symbols:
412  * ------------------------------------------------------------------------*/
413
414 /* An entry in a very crude object symbol table */
415 typedef struct { char* nm; void* ad; } 
416    OSym;
417
418 /* Indication of section kinds for loaded objects.  Needed by
419    the GC for deciding whether or not a pointer on the stack
420    is a code pointer.
421 */
422 typedef enum { HUGS_DL_SECTION_CODE_OR_RODATA,
423                HUGS_DL_SECTION_RWDATA,
424                HUGS_DL_SECTION_OTHER } 
425    DLSect;
426
427 typedef struct { void* start; void* end; DLSect sect; } 
428    DLTabEnt;
429
430 /* --------------------------------------------------------------------------
431  * Modules:
432  * ------------------------------------------------------------------------*/
433
434 #define MODMIN        (OFFMIN+NUM_OFFSETS)
435
436 #define isModule(c)   (MODMIN<=(c) && (c)<TYCMIN)
437 #define mkModule(n)   (MODMIN+(n))
438 #define module(n)     tabModule[(n)-MODMIN]
439
440 /* Under Haskell 1.3, the list of qualified imports is always a subset
441  * of the list of unqualified imports.  For simplicity and flexibility,
442  * we do not attempt to exploit this fact - when a module is imported
443  * unqualified, it is added to both the qualified and unqualified
444  * import lists.
445  * Similarily, Haskell 1.3 does not allow a constructor to be imported
446  * or exported without exporting the type it belongs to but the export
447  * list is just a flat list of Texts (before static analysis) or
448  * Tycons, Names and Classes (after static analysis).
449  */
450 struct Module {
451     Text  text;
452     /* Lists of top level objects (local defns + imports)                  */
453     List  tycons;
454     List  names;
455     List  classes;
456     List  exports; /* [ Entity | (Entity, NIL|DOTDOT) ] */
457     /* List of qualified imports.  Used both during compilation and when
458      * evaluating an expression in the context of the current module.
459      */
460     List  qualImports;
461
462     /* ptr to malloc'd lump of memory holding the obj file */
463     void* oImage;
464
465     /* ptr to object symbol table; lives in mallocville.  
466        Dynamically expands. */
467     OSym* oTab;
468     Int   sizeoTab;
469     Int   usedoTab;
470
471     /* The section-kind entries for this object module.  Dynamically expands. */    
472     DLTabEnt* dlTab;
473     Int       sizedlTab;
474     Int       useddlTab;        
475 };
476
477 extern Module currentModule;           /* Module currently being processed */
478 extern struct Module DECTABLE(tabModule);
479
480 extern Bool   isValidModule Args((Module));
481 extern Module newModule     Args((Text));
482 extern Module findModule    Args((Text));
483 extern Module findModid     Args((Cell));
484 extern Void   setCurrModule Args((Module));
485
486 extern void      addOTabName     Args((Module,char*,void*));
487 extern void*     lookupOTabName  Args((Module,char*));
488 extern char*     nameFromOPtr    Args((void*));
489
490 extern void      addDLSect    Args((Module,void*,void*,DLSect));
491 extern DLSect    lookupDLSect Args((void*));
492
493
494 #define isPrelude(m) (m==modulePrelude)
495
496 /* --------------------------------------------------------------------------
497  * Type constructor names:
498  * ------------------------------------------------------------------------*/
499
500 #define TYCMIN       (MODMIN+NUM_MODULE)
501 #define isTycon(c)   (TYCMIN<=(c) && (c)<NAMEMIN)
502 #define mkTycon(n)   (TCMIN+(n))
503 #define tycon(n)     tabTycon[(n)-TYCMIN]
504
505 struct strTycon {
506     Text   text;
507     Int    line;
508     Module mod;                         /* module that defines it          */
509     Int    arity;
510     Kind   kind;                        /* kind (includes arity) of Tycon  */
511     Cell   what;                        /* DATATYPE/SYNONYM/RESTRICTSYN... */
512     Cell   defn;
513     Name   conToTag;                    /* used in derived code            */
514     Name   tagToCon;
515     Tycon  nextTyconHash;
516 };
517
518 extern struct strTycon DECTABLE(tabTycon);
519
520 extern Tycon newTycon     Args((Text));
521 extern Tycon findTycon    Args((Text));
522 extern Tycon addTycon     Args((Tycon));
523 extern Tycon findQualTycon Args((Cell));
524 extern Tycon addPrimTycon Args((Text,Kind,Int,Cell,Cell));
525
526 #define isSynonym(h)    (isTycon(h) && tycon(h).what==SYNONYM)
527 #define isQualType(t)   (isPair(t) && fst(t)==QUAL)
528 #define mkPolyType(n,t) pair(POLYTYPE,pair(n,t))
529 #define isPolyType(t)   (isPair(t) && fst(t)==POLYTYPE)
530 #define isPolyOrQualType(t) (isPair(t) && (fst(t)==POLYTYPE || fst(t)==QUAL))
531 #define polySigOf(t)    fst(snd(t))
532 #define monotypeOf(t)   snd(snd(t))
533
534 /* --------------------------------------------------------------------------
535  * Globally defined name values:
536  * ------------------------------------------------------------------------*/
537
538 #define NAMEMIN      (TYCMIN+NUM_TYCON)
539 #define isName(c)    (NAMEMIN<=(c) && (c)<INSTMIN)
540 #define mkName(n)    (NAMEMIN+(n))
541 #define name(n)      tabName[(n)-NAMEMIN]
542
543 struct strName {
544     Text   text;
545     Int    line;
546     Module mod;                         /* module that defines it          */
547     Syntax syntax;
548     Cell   parent; 
549     Int    arity;
550     Int    number;
551     Cell   type;
552     Cell   defn;
553     Cell   stgVar;        /* really StgVar   */
554     Text   callconv;      /* for foreign import/export */
555     const void*  primop;  /* really StgPrim* */
556     Name   nextNameHash;
557 };
558
559 extern int numNames Args(( Void ));
560
561 extern struct strName DECTABLE(tabName);
562
563 /* The number field in a name is used to distinguish various kinds of name:
564  *   mfunNo(i) = code for member function, offset i
565  *               members that are sole elements of dict use mfunNo(0)
566  *               members of dicts with more than one elem use mfunNo(n), n>=1
567  *   EXECNAME  = code for executable name (bytecodes or primitive)
568  *   SELNAME   = code for selector function
569  *   DFUNNAME  = code for dictionary builder or selector
570  *   cfunNo(i) = code for data constructor
571  *               datatypes with only one constructor uses cfunNo(0)
572  *               datatypes with multiple constructors use cfunNo(n), n>=1
573  */
574
575 #define EXECNAME        0
576 #define SELNAME         1
577 #define DFUNNAME        2
578 #define CFUNNAME        3
579
580 #define isSfun(n)       (name(n).number==SELNAME)
581 #define isDfun(n)       (name(n).number==DFUNNAME)
582
583 #define isCfun(n)       (name(n).number>=CFUNNAME)
584 #define cfunOf(n)       (name(n).number-CFUNNAME)
585 #define cfunNo(i)       ((i)+CFUNNAME)
586 #define hasCfun(cs)     (nonNull(cs) && isCfun(hd(cs)))
587
588 #define isMfun(n)       (name(n).number<0)
589 #define mfunOf(n)       ((-1)-name(n).number)
590 #define mfunNo(i)       ((-1)-(i))
591
592 extern Name   newName         Args((Text,Cell));
593 extern Name   findName        Args((Text));
594 extern Name   addName         Args((Name));
595 extern Name   findQualName    Args((Cell));
596 extern Name   addPrimCfun     Args((Text,Int,Int,Cell));
597 extern Name   addPrimCfunREP  Args((Text,Int,Int,Int));
598 extern Int    sfunPos         Args((Name,Name));
599 extern Name   nameFromStgVar  Args((Cell));
600 extern Name   jrsFindQualName Args((Text,Text));
601
602 /* --------------------------------------------------------------------------
603  * Type class values:
604  * ------------------------------------------------------------------------*/
605
606 #define INSTMIN      (NAMEMIN+NUM_NAME) /* instances                       */
607 #define isInst(c)    (INSTMIN<=(c) && (c)<CLASSMIN)
608 #define mkInst(n)    (INSTMIN+(n))
609 #define instOf(c)    ((Int)((c)-INSTMIN))
610 #define inst(in)     tabInst[(in)-INSTMIN]
611
612 struct strInst {
613     Class  c;                           /* class C                         */
614     Int    line;
615     Module mod;                         /* module that defines it          */
616     Kinds  kinds;                       /* Kinds of variables in head      */
617     Cell   head;                        /* :: Pred                         */
618     List   specifics;                   /* :: [Pred]                       */
619     Int    numSpecifics;                /* length(specifics)               */
620     List   implements;
621     Name   builder;                     /* Dictionary constructor function */
622 };
623
624 /* a predicate (an element :: Pred) is an application of a Class to one or
625  * more type expressions
626  */
627
628 #define CLASSMIN     (INSTMIN+NUM_INSTS)
629 #define isClass(c)   (CLASSMIN<=(c) && (c)<CHARMIN)
630 #define mkClass(n)   (CLASSMIN+(n))
631 #define cclass(n)    tabClass[(n)-CLASSMIN]
632
633 struct strClass {
634     Text   text;                        /* Name of class                   */
635     Int    line;                        /* Line where declaration begins   */
636     Module mod;                         /* module that declares it         */
637     Int    level;                       /* Level in class hierarchy        */
638     Int    arity;                       /* Number of arguments             */
639     Kinds  kinds;                       /* Kinds of constructors in class  */
640     List   fds;                         /* Functional Dependencies         */
641     List   xfds;                        /* Xpanded Functional Dependencies */
642     Cell   head;                        /* Head of class                   */
643     Name   dcon;                        /* Dictionary constructor function */
644     List   supers;                      /* :: [Pred]                       */
645     Int    numSupers;                   /* length(supers)                  */
646     List   dsels;                       /* Superclass dictionary selectors */
647     List   members;                     /* :: [Name]                       */
648     Int    numMembers;                  /* length(members)                 */
649     List   defaults;                    /* :: [Name]                       */
650     List   instances;                   /* :: [Inst]                       */
651 };
652
653 extern struct strClass    DECTABLE(tabClass);
654 extern struct strInst far *tabInst;
655
656 extern Class newClass      Args((Text));
657 extern Class classMax      Args((Void));
658 extern Class findClass     Args((Text));
659 extern Class addClass      Args((Class));
660 extern Class findQualClass Args((Cell));
661 extern Inst  newInst       Args((Void));
662 extern Inst  findFirstInst Args((Tycon));
663 extern Inst  findNextInst  Args((Tycon,Inst));
664
665 /* --------------------------------------------------------------------------
666  * Character values:
667  * ------------------------------------------------------------------------*/
668
669 #define CHARMIN      (CLASSMIN+NUM_CLASSES)
670 #define MAXCHARVAL   (NUM_CHARS-1)
671 #define isChar(c)    (CHARMIN<=(c) && (c)<INTMIN)
672 #define charOf(c)    ((Char)(c-CHARMIN))
673 #define mkChar(c)    ((Cell)(CHARMIN+(((unsigned)(c))%NUM_CHARS)))
674
675 /* --------------------------------------------------------------------------
676  * Small Integer values:
677  * ------------------------------------------------------------------------*/
678
679 #define INTMIN       (CHARMIN+NUM_CHARS)
680 #define INTMAX       (MAXPOSINT)
681 #define isSmall(c)   (INTMIN<=(c))
682 #define INTZERO      (INTMIN/2 + INTMAX/2)
683 #define MINSMALLINT  (INTMIN - INTZERO)
684 #define MAXSMALLINT  (INTMAX - INTZERO)
685 #define mkDigit(c)   ((Cell)((c)+INTMIN))
686 #define digitOf(c)   ((Int)((c)-INTMIN))
687
688 extern  Bool isInt    Args((Cell));
689 extern  Int  intOf    Args((Cell));
690 extern  Cell mkInt    Args((Int));
691
692 /* --------------------------------------------------------------------------
693  * Implementation of triples:
694  * ------------------------------------------------------------------------*/
695
696 #define triple(x,y,z) pair(x,pair(y,z))
697 #define fst3(c)      fst(c)
698 #define snd3(c)      fst(snd(c))
699 #define thd3(c)      snd(snd(c))
700
701 /* --------------------------------------------------------------------------
702  * Implementation of lists:
703  * ------------------------------------------------------------------------*/
704
705 #define NIL          0
706 #define isNull(c)    ((c)==NIL)
707 #define nonNull(c)   (c)
708 #define cons(x,xs)   pair(x,xs)
709 #define singleton(x)     cons(x,NIL)
710 #define doubleton(x,y)   cons(x,cons(y,NIL))
711 #define tripleton(x,y,z) cons(x,cons(y,cons(z,NIL)))
712 #define hd(c)        fst(c)
713 #define tl(c)        snd(c)
714
715 extern  Int          length       Args((List));
716 extern  List         appendOnto   Args((List,List));    /* destructive     */
717 extern  List         dupOnto      Args((List,List));
718 extern  List         dupList      Args((List));
719 extern  List         revOnto      Args((List, List));   /* destructive     */
720 #define rev(xs)      revOnto((xs),NIL)                  /* destructive     */
721 #define reverse(xs)  revOnto(dupList(xs),NIL)           /* non-destructive */
722 extern  Cell         cellIsMember Args((Cell,List));
723 extern  Cell         cellAssoc    Args((Cell,List));
724 extern  Cell         cellRevAssoc Args((Cell,List));
725 extern  Bool         eqList       Args((List,List));
726 extern  Cell         varIsMember  Args((Text,List));
727 extern  Name         nameIsMember Args((Text,List));
728 extern  Cell         intIsMember  Args((Int,List));
729 extern  List         replicate    Args((Int,Cell));
730 extern  List         diffList     Args((List,List));    /* destructive     */
731 extern  List         deleteCell   Args((List,Cell));    /* non-destructive */
732 extern  List         take         Args((Int,List));     /* destructive     */
733 extern  List         splitAt      Args((Int,List));     /* non-destructive */
734 extern  Cell         nth          Args((Int,List));
735 extern  List         removeCell   Args((Cell,List));    /* destructive     */
736 extern  List         dupListOnto  Args((List,List));    /* non-destructive */ 
737 extern  List         nubList      Args((List));         /* non-destructive */
738
739 /* The following macros provide `inline expansion' of some common ways of
740  * traversing, using and modifying lists:
741  *
742  * N.B. We use the names _f, _a, _xs, Zs, in an attempt to avoid clashes
743  *      with identifiers used elsewhere.
744  */
745
746 #define mapBasic(_init,_step)           {List Zs=(_init);\
747                                          for(;nonNull(Zs);Zs=tl(Zs))  \
748                                          _step;}
749 #define mapModify(_init,_step)          mapBasic(_init,hd(Zs)=_step)
750
751 #define mapProc(_f,_xs)                 mapBasic(_xs,_f(hd(Zs)))
752 #define map1Proc(_f,_a,_xs)             mapBasic(_xs,_f(_a,hd(Zs)))
753 #define map2Proc(_f,_a,_b,_xs)          mapBasic(_xs,_f(_a,_b,hd(Zs)))
754 #define map3Proc(_f,_a,_b,_c,_xs)       mapBasic(_xs,_f(_a,_b,_c,hd(Zs)))
755 #define map4Proc(_f,_a,_b,_c,_d,_xs)    mapBasic(_xs,_f(_a,_b,_c,_d,hd(Zs)))
756
757 #define mapOver(_f,_xs)                 mapModify(_xs,_f(hd(Zs)))
758 #define map1Over(_f,_a,_xs)             mapModify(_xs,_f(_a,hd(Zs)))
759 #define map2Over(_f,_a,_b,_xs)          mapModify(_xs,_f(_a,_b,hd(Zs)))
760 #define map3Over(_f,_a,_b,_c,_xs)       mapModify(_xs,_f(_a,_b,_c,hd(Zs)))
761 #define map4Over(_f,_a,_b,_c,_d,_xs)    mapModify(_xs,_f(_a,_b,_c,_d,hd(Zs)))
762
763 /* This is just what you want for functions with accumulating parameters */
764 #define mapAccum(_f,_acc,_xs)           mapBasic(_xs,_acc=_f(_acc,hd(Zs)))
765 #define map1Accum(_f,_acc,_a,_xs)       mapBasic(_xs,_acc=_f(_acc,_a,hd(Zs)))
766 #define map2Accum(_f,_acc,_a,_b,_xs)    mapBasic(_xs,_acc=_f(_acc,_a,_b,hd(Zs)))
767 #define map3Accum(_f,_acc,_a,_b,_c,_xs) mapBasic(_xs,_acc=_f(_acc,_a,_b,_c,hd(Zs)))
768
769 /* --------------------------------------------------------------------------
770  * Implementation of function application nodes:
771  * ------------------------------------------------------------------------*/
772
773 #define ap(f,x)      pair(f,x)
774 #define ap1(f,x)     ap(f,x)
775 #define ap2(f,x,y)   ap(ap(f,x),y)
776 #define ap3(f,x,y,z) ap(ap(ap(f,x),y),z)
777 #define fun(c)       fst(c)
778 #define arg(c)       snd(c)
779 #define isAp(c)      (isPair(c) && !isTag(fst(c)))
780 extern  Cell         getHead     Args((Cell));
781 extern  List         getArgs     Args((Cell));
782 extern  Int          argCount;
783 extern  Cell         nthArg      Args((Int,Cell));
784 extern  Int          numArgs     Args((Cell));
785 extern  Cell         applyToArgs Args((Cell,List));
786
787 /* --------------------------------------------------------------------------
788  * Stack implementation:
789  *
790  * NB: Use of macros makes order of evaluation hard to predict.
791  *     For example, "push(1+pop());" doesn't increment TOS.
792  * ------------------------------------------------------------------------*/
793
794 extern  Cell DECTABLE(cellStack);
795 extern  StackPtr sp;
796
797 #define clearStack() sp=(-1)
798 #define stackEmpty() (sp==(-1))
799 #define stack(p)     cellStack[p]
800 #define chkStack(n)  if (sp>=NUM_STACK-(n)) hugsStackOverflow()
801 #define push(c)      \
802   do {               \
803     chkStack(1);     \
804     onto(c);         \
805   } while (0)
806 #define onto(c)      stack(++sp)=(c);
807 #define pop()        stack(sp--)
808 #define drop()       sp--
809 #define top()        stack(sp)
810 #define pushed(n)    stack(sp-(n))
811 #define topfun(f)    top()=ap((f),top())
812 #define toparg(x)    top()=ap(top(),(x))
813
814 extern  Void hugsStackOverflow Args((Void));
815
816 #if SYMANTEC_C
817 #include <Memory.h>
818 #define STACK_HEADROOM 16384
819 #define STACK_CHECK if (StackSpace() <= STACK_HEADROOM) \
820                       internal("Macintosh function parameter stack overflow.");
821 #else
822 #define STACK_CHECK
823 #endif
824
825 /* --------------------------------------------------------------------------
826  * Script file control:
827  * The implementation of script file storage is hidden.
828  * ------------------------------------------------------------------------*/
829
830 extern Script      startNewScript   Args((String));
831 extern Bool        moduleThisScript Args((Module));
832 extern Module      moduleOfScript   Args((Script));
833 extern Bool        isPreludeScript  Args((Void));
834 extern Module      lastModule       Args((Void));
835 extern Script      scriptThisFile   Args((Text));
836 extern Script      scriptThisName   Args((Name));
837 extern Script      scriptThisTycon  Args((Tycon));
838 extern Script      scriptThisInst   Args((Inst));
839 extern Script      scriptThisClass  Args((Class));
840 extern String      fileOfModule     Args((Module));
841 extern Void        dropScriptsFrom  Args((Script));
842
843
844 /* --------------------------------------------------------------------------
845  * Plugins
846  * ------------------------------------------------------------------------*/
847
848 #if PLUGINS
849 /* This is an exact copy of the declaration found in GreenCard.h */
850
851 typedef int     HugsStackPtr;
852 typedef int     HugsStablePtr;
853 typedef Pointer HugsForeign;
854
855 typedef struct {
856
857   /* evaluate next argument */
858   int            (*getInt   )     Args(());  
859   unsigned int   (*getWord  )     Args(());
860   void*          (*getAddr  )     Args(());
861   float          (*getFloat )     Args(());
862   double         (*getDouble)     Args(());
863   char           (*getChar  )     Args(());
864   HugsForeign    (*getForeign)    Args(());
865   HugsStablePtr  (*getStablePtr)  Args(());
866
867   /* push part of result   */
868   void           (*putInt   )     Args((int));           
869   void           (*putWord  )     Args((unsigned int));
870   void           (*putAddr  )     Args((void*));
871   void           (*putFloat )     Args((double));
872   void           (*putDouble)     Args((double));
873   void           (*putChar  )     Args((char));
874   void           (*putForeign)    Args((HugsForeign, void (*)(HugsForeign)));
875   void           (*putStablePtr)  Args((HugsStablePtr));
876
877   /* return n values in IO monad or Id monad */
878   void           (*returnIO)      Args((HugsStackPtr, int));
879   void           (*returnId)      Args((HugsStackPtr, int));
880   int            (*runIO)         Args((int));
881
882   /* free a stable pointer */                            
883   void           (*freeStablePtr) Args((HugsStablePtr));
884
885   /* register the prim table */                          
886   void           (*registerPrims) Args((struct primInfo*));
887                            
888   /* garbage collect */
889   void           (*garbageCollect) Args(());
890
891 } HugsAPI2;
892
893 extern  HugsAPI2* hugsAPI2     Args((Void));
894 typedef Void (*InitModuleFun2) Args((HugsAPI2*));
895
896 typedef struct {
897   Name  nameTrue, nameFalse;
898   Name  nameNil,  nameCons;
899   Name  nameJust, nameNothing;
900   Name  nameLeft, nameRight;
901   Name  nameUnit;
902   Name  nameIORun;
903
904   Cell  (*makeInt)         Args((Int));
905                            
906   Cell  (*makeChar)        Args((Char));
907   Char  (*CharOf)          Args((Cell));
908                            
909   Cell  (*makeFloat)       Args((FloatPro));
910   Cell  (*makeTuple)       Args((Int));
911   Pair  (*pair)            Args((Cell,Cell));
912                            
913   Cell  (*mkMallocPtr)     Args((Void *, Void (*)(Void *)));
914   Void *(*derefMallocPtr)  Args((Cell));
915                            
916   Int   (*mkStablePtr)     Args((Cell));
917   Cell  (*derefStablePtr)  Args((Int));
918   Void  (*freeStablePtr)   Args((Int));
919                            
920   Void  (*eval)            Args((Cell));
921   Cell  (*evalWithNoError) Args((Cell));
922   Void  (*evalFails)       Args((StackPtr));
923   Int   *whnfArgs;         
924   Cell  *whnfHead;         
925   Int   *whnfInt;          
926   Float *whnfFloat;        
927                            
928   Void  (*garbageCollect)  Args(());
929   Void  (*stackOverflow)   Args(());
930   Void  (*internal)        Args((String)) HUGS_noreturn;
931
932   Void  (*registerPrims)   Args((struct primInfo*));
933   Name  (*addPrimCfun)     Args((Text,Int,Int,Cell));
934   Text  (*inventText)      Args(());
935
936   Cell *(*Fst)             Args((Cell));
937   Cell *(*Snd)             Args((Cell));
938
939   Cell  *cellStack;
940   StackPtr *sp;
941 } HugsAPI1;
942
943 extern  HugsAPI1* hugsAPI1     Args((Void));
944 typedef Void (*InitModuleFun1) Args((HugsAPI1*));
945 #endif /* PLUGINS */
946
947
948 /* --------------------------------------------------------------------------
949  * Misc:
950  * ------------------------------------------------------------------------*/
951
952 extern  Void   setLastExpr       Args((Cell));
953 extern  Cell   getLastExpr       Args((Void));
954 extern  List   addTyconsMatching Args((String,List));
955 extern  List   addNamesMatching  Args((String,List));
956
957 /*-------------------------------------------------------------------------*/