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