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