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