861bb82b6acdbd5720fed2900b2dcdaa2dc957f6
[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.7 $
13  * $Date: 1999/06/07 17:22:47 $
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 #define CPTRCELL     18           /* Native code pointer      snd :: Ptr   */
154 #endif
155 #if TREX
156 #define EXTCOPY      19           /* Copy of an Ext:          snd :: Text  */
157 #endif
158
159 //#define textOf(c)       ((Text)(snd(c)))         /* c ::  (VAR|CON)(ID|OP) */
160
161 #if 1
162 static Text textOf( Cell c )
163 {
164    Bool ok = 
165           (whatIs(c)==VARIDCELL
166            || whatIs(c)==CONIDCELL
167            || whatIs(c)==VAROPCELL
168            || whatIs(c)==CONOPCELL
169            || whatIs(c)==STRCELL
170            || whatIs(c)==DICTVAR
171           );
172    if (!ok) {
173 fprintf(stderr, "\ntextOf -- tag %d\n",whatIs(c) );
174       assert(ok);
175    }
176    return snd(c);
177 }
178 #endif
179
180 #define qmodOf(c)       (textOf(fst(snd(c))))    /* c ::  QUALIDENT        */
181 #define qtextOf(c)      (textOf(snd(snd(c))))    /* c ::  QUALIDENT        */
182 #define mkVar(t)        ap(VARIDCELL,t)
183 #define mkVarop(t)      ap(VAROPCELL,t)
184 #define mkCon(t)        ap(CONIDCELL,t)
185 #define mkConop(t)      ap(CONOPCELL,t)
186 #define mkQVar(m,t)     ap(QUALIDENT,pair(mkCon(m),mkVar(t)))
187 #define mkQCon(m,t)     ap(QUALIDENT,pair(mkCon(m),mkCon(t)))
188 #define mkQVarOp(m,t)   ap(QUALIDENT,pair(mkCon(m),mkVarop(t)))
189 #define mkQConOp(m,t)   ap(QUALIDENT,pair(mkCon(m),mkConop(t)))
190 #define intValOf(c)     (snd(c))
191 #define inventVar()     mkVar(inventText())
192 #define mkDictVar(t)    ap(DICTVAR,t)
193 #define inventDictVar() mkDictVar(inventDictText())
194 #define mkStr(t)        ap(STRCELL,t)
195 extern  Bool            isVar       Args((Cell));
196 extern  Bool            isCon       Args((Cell));
197 extern  Bool            isQVar      Args((Cell));
198 extern  Bool            isQCon      Args((Cell));
199 extern  Bool            isQualIdent Args((Cell));
200 extern  Bool            isIdent     Args((Cell));
201
202 extern  String           stringNegate Args((String));
203
204 #define isFloat(c)       (isPair(c) && fst(c)==FLOATCELL)
205 #define stringToFloat(s) pair(FLOATCELL,findText(s))
206 #define floatToString(f) textToStr(snd(f))
207 #define floatOf(f)       atof(floatToString(f))
208 #define mkFloat(f)       (f)  /* ToDo: is this right? */
209 #define floatNegate(f)   stringToFloat(stringNegate(floatToString(f)))
210
211 #define stringToBignum(s) pair(BIGCELL,findText(s))
212 #define bignumToString(b) textToStr(snd(b))
213
214
215 #if PTR_ON_HEAP
216 #define isPtr(c)        (isPair(c) && fst(c)==PTRCELL)
217 extern  Cell            mkPtr           Args((Ptr));
218 extern  Ptr             ptrOf           Args((Cell));
219 #define isCPtr(c)       (isPair(c) && fst(c)==CPTRCELL)
220 extern  Cell            mkCPtr          Args((Ptr));
221 extern  Ptr             cptrOf          Args((Cell));
222 #endif
223
224 /* --------------------------------------------------------------------------
225  * Constructor cell tags are used as the fst element of a pair to indicate
226  * a particular syntactic construct described by the snd element of the
227  * pair.
228  * Note that a cell c will not be treated as an application (AP/isAp) node
229  * if its first element is a constructor cell tag, whereas a cell whose fst
230  * element is a special cell will be treated as an application node.
231  * ------------------------------------------------------------------------*/
232
233 #define LETREC       20           /* LETREC     snd :: ([Decl],Exp)        */
234 #define COND         21           /* COND       snd :: (Exp,Exp,Exp)       */
235 #define LAMBDA       22           /* LAMBDA     snd :: Alt                 */
236 #define FINLIST      23           /* FINLIST    snd :: [Exp]               */
237 #define DOCOMP       24           /* DOCOMP     snd :: (Exp,[Qual])        */
238 #define BANG         25           /* BANG       snd :: Type                */
239 #define COMP         26           /* COMP       snd :: (Exp,[Qual])        */
240 #define ASPAT        27           /* ASPAT      snd :: (Var,Exp)           */
241 #define ESIGN        28           /* ESIGN      snd :: (Exp,Type)          */
242 #define RSIGN        29           /* RSIGN      snd :: (Rhs,Type)          */
243 #define CASE         30           /* CASE       snd :: (Exp,[Alt])         */
244 #define NUMCASE      31           /* NUMCASE    snd :: (Exp,Disc,Rhs)      */
245 #define FATBAR       32           /* FATBAR     snd :: (Exp,Exp)           */
246 #define LAZYPAT      33           /* LAZYPAT    snd :: Exp                 */
247 #define DERIVE       35           /* DERIVE     snd :: Cell                */
248 #if BREAK_FLOATS
249 #define FLOATCELL    36           /* FLOATCELL  snd :: (Int,Int)           */
250 #endif
251
252 #define BOOLQUAL     39           /* BOOLQUAL   snd :: Exp                 */
253 #define QWHERE       40           /* QWHERE     snd :: [Decl]              */
254 #define FROMQUAL     41           /* FROMQUAL   snd :: (Exp,Exp)           */
255 #define DOQUAL       42           /* DOQUAL     snd :: Exp                 */
256 #define MONADCOMP    43           /* MONADCOMP  snd :: ((m,m0),(Exp,[Qual])*/
257
258 #define GUARDED      44           /* GUARDED    snd :: [guarded exprs]     */
259
260 #define ARRAY        45           /* Array      snd :: (Bounds,[Values])   */
261 #define MUTVAR       46           /* Mutvar     snd :: Cell                */
262 #if INTERNAL_PRIMS
263 #define HUGSOBJECT   47           /* HUGSOBJECT snd :: Cell                */
264 #endif
265
266 #define POLYTYPE     50           /* POLYTYPE   snd :: (Kind,Type)         */
267 #define QUAL         51           /* QUAL       snd :: ([Classes],Type)    */
268 #define RANK2        52           /* RANK2      snd :: (Int,Type)          */
269 #define EXIST        53           /* EXIST      snd :: (Int,Type)          */
270 #define POLYREC      54           /* POLYREC    snd :: (Int,Type)          */
271 #define BIGLAM       55           /* BIGLAM     snd :: (vars,patterns)     */
272 #define CDICTS       56           /* CDICTS     snd :: ([Pred],Type)       */
273
274 #define LABC         60           /* LABC       snd :: (con,[(Vars,Type)]) */
275 #define CONFLDS      61           /* CONFLDS    snd :: (con,[Field])       */
276 #define UPDFLDS      62           /* UPDFLDS    snd :: (Exp,[con],[Field]) */
277 #if TREX
278 #define RECORD       63           /* RECORD     snd :: [Val]               */
279 #define EXTCASE      64           /* EXTCASE    snd :: (Exp,Disc,Rhs)      */
280 #define RECSEL       65           /* RECSEL     snd :: Ext                 */
281 #endif
282 #define IMPDEPS      68           /* IMPDEPS    snd :: [Binding]           */
283
284 #define QUALIDENT    70           /* Qualified identifier  snd :: (Id,Id)  */
285 #define HIDDEN       71           /* hiding import list    snd :: [Entity] */
286 #define MODULEENT    72           /* module in export list snd :: con      */
287
288 #define INFIX        80           /* INFIX      snd :: (see tidyInfix)     */
289 #define ONLY         81           /* ONLY       snd :: Exp                 */
290 #define NEG          82           /* NEG        snd :: Exp                 */
291
292 /* Used when parsing GHC interface files */
293 #define DICTAP       85           /* DICTTYPE   snd :: (QClassId,[Type])   */
294
295 #if SIZEOF_INTP != SIZEOF_INT
296 #define PTRCELL      90           /* C Heap Pointer snd :: (Int,Int)       */
297 #endif
298
299 #define STGVAR       92           /* STGVAR     snd :: (StgRhs,info)       */
300 #define STGAPP       93           /* STGAPP     snd :: (StgVar,[Arg])      */
301 #define STGPRIM      94           /* STGPRIM    snd :: (PrimOp,[Arg])      */
302 #define STGCON       95           /* STGCON     snd :: (StgCon,[Arg])      */
303 #define PRIMCASE     96           /* PRIMCASE   snd :: (Expr,[PrimAlt])    */
304 #define DEEFALT      97           /* DEEFALT    snd :: (Var,Expr)          */
305 #define CASEALT      98           /* CASEALT    snd :: (Con,[Var],Expr)    */
306 #define PRIMALT      99           /* PRIMALT    snd :: ([Var],Expr)        */
307 /* Last constructor tag must be less than SPECMIN */
308
309 /* --------------------------------------------------------------------------
310  * Special cell values:
311  * ------------------------------------------------------------------------*/
312
313 #define SPECMIN      101
314 #define isSpec(c)    (SPECMIN<=(c) && (c)<TUPMIN)/* Special cell values    */
315
316 #define NONE         101          /* Dummy stub                            */
317 #define STAR         102          /* Representing the kind of types        */
318 #if TREX
319 #define ROW          103          /* Representing the kind of rows         */
320 #endif
321 #define WILDCARD     104          /* Wildcard pattern                      */
322 #define SKOLEM       105          /* Skolem constant                       */
323
324 #define DOTDOT       106          /* ".." in import/export list            */
325
326 #define NAME         110          /* whatIs code for isName                */
327 #define TYCON        111          /* whatIs code for isTycon               */
328 #define CLASS        112          /* whatIs code for isClass               */
329 #define MODULE       113          /* whatIs code for isModule              */
330 #define INSTANCE     114          /* whatIs code for isInst                */
331 #define TUPLE        115          /* whatIs code for tuple constructor     */
332 #define OFFSET       116          /* whatis code for offset                */
333 #define AP           117          /* whatIs code for application node      */
334 #define CHARCELL     118          /* whatIs code for isChar                */
335 #if TREX
336 #define EXT          119          /* whatIs code for isExt                 */
337 #endif
338
339 #define SIGDECL      120          /* Signature declaration                 */
340 #define FIXDECL      121          /* Fixity declaration                    */
341 #define FUNBIND      122          /* Function binding                      */
342 #define PATBIND      123          /* Pattern binding                       */
343
344 #define DATATYPE     130          /* Datatype type constructor             */
345 #define NEWTYPE      131          /* Newtype type constructor              */
346 #define SYNONYM      132          /* Synonym type constructor              */
347 #define RESTRICTSYN  133          /* Synonym with restricted scope         */
348
349 #define NODEPENDS    135          /* Stop calculation of deps in type check*/
350 #define PREDEFINED   136          /* Predefined name, not yet filled       */
351
352 /* --------------------------------------------------------------------------
353  * Tuple data/type constructors:
354  * ------------------------------------------------------------------------*/
355
356 #define TUPMIN       201
357 #if TREX
358 #define isTuple(c)   (TUPMIN<=(c) && (c)<EXTMIN)
359 #else
360 #define isTuple(c)   (TUPMIN<=(c) && (c)<OFFMIN)
361 #endif
362 #define mkTuple(n)   (TUPMIN+(n))
363 #define tupleOf(n)   ((Int)((n)-TUPMIN))
364
365 #if TREX
366 #define EXTMIN       (TUPMIN+NUM_TUPLES)
367 #define isExt(c)     (EXTMIN<=(c) && (c)<OFFMIN)
368 #define extText(e)   tabExt[(e)-EXTMIN]
369 #define extField(c)  arg(fun(c))
370 #define extRow(c)    arg(c)
371
372 extern Text          DECTABLE(tabExt);
373 extern Ext           mkExt Args((Text));
374 #else
375 #define mkExt(t) NIL
376 #endif
377
378 /* --------------------------------------------------------------------------
379  * Offsets: (generic types/stack offsets)
380  * ------------------------------------------------------------------------*/
381
382 #if TREX
383 #define OFFMIN       (EXTMIN+NUM_EXT)
384 #else
385 #define OFFMIN       (TUPMIN+NUM_TUPLES)
386 #endif
387 #define isOffset(c)  (OFFMIN<=(c) && (c)<MODMIN)
388 #define offsetOf(c)  ((c)-OFFMIN)
389 #define mkOffset(o)  (OFFMIN+(o))
390
391 /* --------------------------------------------------------------------------
392  * Modules:
393  * ------------------------------------------------------------------------*/
394
395 #define MODMIN        (OFFMIN+NUM_OFFSETS)
396
397 #define isModule(c)   (MODMIN<=(c) && (c)<TYCMIN)
398 #define mkModule(n)   (MODMIN+(n))
399 #define module(n)     tabModule[(n)-MODMIN]
400
401 /* Under Haskell 1.3, the list of qualified imports is always a subset
402  * of the list of unqualified imports.  For simplicity and flexibility,
403  * we do not attempt to exploit this fact - when a module is imported
404  * unqualified, it is added to both the qualified and unqualified
405  * import lists.
406  * Similarily, Haskell 1.3 does not allow a constructor to be imported
407  * or exported without exporting the type it belongs to but the export
408  * list is just a flat list of Texts (before static analysis) or
409  * Tycons, Names and Classes (after static analysis).
410  */
411 struct Module {
412     Text  text;
413     /* Lists of top level objects (local defns + imports)                  */
414     List  tycons;
415     List  names;
416     List  classes;
417     List  exports; /* [ Entity | (Entity, NIL|DOTDOT) ] */
418     /* List of qualified imports.  Used both during compilation and when
419      * evaluating an expression in the context of the current module.
420      */
421     List  qualImports;
422     /* ptr to malloc'd lump of memory holding the obj file */
423     void* oImage;
424
425
426 };
427
428 extern Module currentModule;           /* Module currently being processed */
429 extern struct Module DECTABLE(tabModule);
430
431 extern Bool   isValidModule Args((Module));
432 extern Module newModule     Args((Text));
433 extern Module findModule    Args((Text));
434 extern Module findModid     Args((Cell));
435 extern Void   setCurrModule Args((Module));
436
437 #define isPrelude(m) (m==modulePrelude)
438
439 /* --------------------------------------------------------------------------
440  * Type constructor names:
441  * ------------------------------------------------------------------------*/
442
443 #define TYCMIN       (MODMIN+NUM_MODULE)
444 #define isTycon(c)   (TYCMIN<=(c) && (c)<NAMEMIN)
445 #define mkTycon(n)   (TCMIN+(n))
446 #define tycon(n)     tabTycon[(n)-TYCMIN]
447
448 struct strTycon {
449     Text   text;
450     Int    line;
451     Module mod;                         /* module that defines it          */
452     Int    arity;
453     Kind   kind;                        /* kind (includes arity) of Tycon  */
454     Cell   what;                        /* DATATYPE/SYNONYM/RESTRICTSYN... */
455     Cell   defn;
456     Name   conToTag;                    /* used in derived code            */
457     Name   tagToCon;
458     Tycon  nextTyconHash;
459 };
460
461 extern struct strTycon DECTABLE(tabTycon);
462
463 extern Tycon newTycon     Args((Text));
464 extern Tycon findTycon    Args((Text));
465 extern Tycon addTycon     Args((Tycon));
466 extern Tycon findQualTycon Args((Cell));
467 extern Tycon addPrimTycon Args((Text,Kind,Int,Cell,Cell));
468
469 #define isSynonym(h)    (isTycon(h) && tycon(h).what==SYNONYM)
470 #define mkPolyType(n,t) pair(POLYTYPE,pair(n,t))
471 #define isPolyType(t)   (isPair(t) && fst(t)==POLYTYPE)
472 #define polySigOf(t)    fst(snd(t))
473 #define monotypeOf(t)   snd(snd(t))
474
475 /* --------------------------------------------------------------------------
476  * Globally defined name values:
477  * ------------------------------------------------------------------------*/
478
479 #define NAMEMIN      (TYCMIN+NUM_TYCON)
480 #define isName(c)    (NAMEMIN<=(c) && (c)<INSTMIN)
481 #define mkName(n)    (NAMEMIN+(n))
482 #define name(n)      tabName[(n)-NAMEMIN]
483
484 struct strName {
485     Text   text;
486     Int    line;
487     Module mod;                         /* module that defines it          */
488     Syntax syntax;
489     Cell   parent; 
490     Int    arity;
491     Int    number;
492     Cell   type;
493     Cell   defn;
494     Cell   stgVar;        /* really StgVar   */
495     Int    stgSize;       /* == stgSize(stgVarBody(.stgVar)) */
496     Bool   inlineMe;      /* self-evident    */
497     Bool   simplified;    /* TRUE => already simplified */
498     Bool   isDBuilder;    /* TRUE => is a dictionary builder */
499     const void*  primop;  /* really StgPrim* */
500     List   ghc_names;     /* [(Text,Ptr)] */
501     Name   nextNameHash;
502 };
503
504 extern int numNames Args(( Void ));
505
506 extern struct strName DECTABLE(tabName);
507
508 /* The number field in a name is used to distinguish various kinds of name:
509  *   mfunNo(i) = code for member function, offset i
510  *               members that are sole elements of dict use mfunNo(0)
511  *               members of dicts with more than one elem use mfunNo(n), n>=1
512  *   EXECNAME  = code for executable name (bytecodes or primitive)
513  *   SELNAME   = code for selector function
514  *   DFUNNAME  = code for dictionary builder or selector
515  *   cfunNo(i) = code for data constructor
516  *               datatypes with only one constructor uses cfunNo(0)
517  *               datatypes with multiple constructors use cfunNo(n), n>=1
518  */
519
520 #define EXECNAME        0
521 #define SELNAME         1
522 #define DFUNNAME        2
523 #define CFUNNAME        3
524
525 #define isSfun(n)       (name(n).number==SELNAME)
526 #define isDfun(n)       (name(n).number==DFUNNAME)
527
528 #define isCfun(n)       (name(n).number>=CFUNNAME)
529 #define cfunOf(n)       (name(n).number-CFUNNAME)
530 #define cfunNo(i)       ((i)+CFUNNAME)
531 #define hasCfun(cs)     (nonNull(cs) && isCfun(hd(cs)))
532
533 #define isMfun(n)       (name(n).number<0)
534 #define mfunOf(n)       ((-1)-name(n).number)
535 #define mfunNo(i)       ((-1)-(i))
536
537 extern Name   newName         Args((Text,Cell));
538 extern Name   findName        Args((Text));
539 extern Name   addName         Args((Name));
540 extern Name   findQualName    Args((Cell));
541 extern Name   addPrimCfun     Args((Text,Int,Int,Cell));
542 extern Name   addPrimCfunREP  Args((Text,Int,Int,Int));
543 extern Int    sfunPos         Args((Name,Name));
544 extern Name   nameFromStgVar  Args((Cell));
545 extern Name   jrsFindQualName Args((Text,Text));
546
547 /* --------------------------------------------------------------------------
548  * Type class values:
549  * ------------------------------------------------------------------------*/
550
551 #define INSTMIN      (NAMEMIN+NUM_NAME) /* instances                       */
552 #define isInst(c)    (INSTMIN<=(c) && (c)<CLASSMIN)
553 #define mkInst(n)    (INSTMIN+(n))
554 #define instOf(c)    ((Int)((c)-INSTMIN))
555 #define inst(in)     tabInst[(in)-INSTMIN]
556
557 struct strInst {
558     Class  c;                           /* class C                         */
559     Int    line;
560     Module mod;                         /* module that defines it          */
561     Kinds  kinds;                       /* Kinds of variables in head      */
562     Cell   head;                        /* :: Pred                         */
563     List   specifics;                   /* :: [Pred]                       */
564     Int    numSpecifics;                /* length(specifics)               */
565     List   implements;
566     Name   builder;                     /* Dictionary constructor function */
567 };
568
569 /* a predicate (an element :: Pred) is an application of a Class to one or
570  * more type expressions
571  */
572
573 #define CLASSMIN     (INSTMIN+NUM_INSTS)
574 #define isClass(c)   (CLASSMIN<=(c) && (c)<CHARMIN)
575 #define mkClass(n)   (CLASSMIN+(n))
576 #define cclass(n)    tabClass[(n)-CLASSMIN]
577
578 struct strClass {
579     Text   text;                        /* Name of class                   */
580     Int    line;                        /* Line where declaration begins   */
581     Module mod;                         /* module that declares it         */
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
636 /* --------------------------------------------------------------------------
637  * Implementation of triples:
638  * ------------------------------------------------------------------------*/
639
640 #define triple(x,y,z) pair(x,pair(y,z))
641 #define fst3(c)      fst(c)
642 #define snd3(c)      fst(snd(c))
643 #define thd3(c)      snd(snd(c))
644
645 /* --------------------------------------------------------------------------
646  * Implementation of lists:
647  * ------------------------------------------------------------------------*/
648
649 #define NIL          0
650 #define isNull(c)    ((c)==NIL)
651 #define nonNull(c)   (c)
652 #define cons(x,xs)   pair(x,xs)
653 #define singleton(x)     cons(x,NIL)
654 #define doubleton(x,y)   cons(x,cons(y,NIL))
655 #define tripleton(x,y,z) cons(x,cons(y,cons(z,NIL)))
656 #define hd(c)        fst(c)
657 #define tl(c)        snd(c)
658
659 extern  Int          length       Args((List));
660 extern  List         appendOnto   Args((List,List));    /* destructive     */
661 extern  List         dupOnto      Args((List,List));
662 extern  List         dupList      Args((List));
663 extern  List         revOnto      Args((List, List));   /* destructive     */
664 #define rev(xs)      revOnto((xs),NIL)                  /* destructive     */
665 #define reverse(xs)  revOnto(dupList(xs),NIL)           /* non-destructive */
666 extern  Cell         cellIsMember Args((Cell,List));
667 extern  Cell         cellAssoc    Args((Cell,List));
668 extern  Cell         cellRevAssoc Args((Cell,List));
669 extern  Bool         eqList       Args((List,List));
670 extern  Cell         varIsMember  Args((Text,List));
671 extern  Name         nameIsMember Args((Text,List));
672 extern  Cell         intIsMember  Args((Int,List));
673 extern  List         replicate    Args((Int,Cell));
674 extern  List         diffList     Args((List,List));    /* destructive     */
675 extern  List         deleteCell   Args((List,Cell));    /* non-destructive */
676 extern  List         take         Args((Int,List));     /* destructive     */
677 extern  List         splitAt      Args((Int,List));     /* non-destructive */
678 extern  Cell         nth          Args((Int,List));
679 extern  List         removeCell   Args((Cell,List));    /* destructive     */
680 extern  List         dupListOnto  Args((List,List));    /* non-destructive */ 
681 extern  List         nubList      Args((List));         /* non-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 /* --------------------------------------------------------------------------
780  * Plugins
781  * ------------------------------------------------------------------------*/
782
783 #if PLUGINS
784 /* This is an exact copy of the declaration found in GreenCard.h */
785
786 typedef int     HugsStackPtr;
787 typedef int     HugsStablePtr;
788 typedef Pointer HugsForeign;
789
790 typedef struct {
791
792   /* evaluate next argument */
793   int            (*getInt   )     Args(());  
794   unsigned int   (*getWord  )     Args(());
795   void*          (*getAddr  )     Args(());
796   float          (*getFloat )     Args(());
797   double         (*getDouble)     Args(());
798   char           (*getChar  )     Args(());
799   HugsForeign    (*getForeign)    Args(());
800   HugsStablePtr  (*getStablePtr)  Args(());
801
802   /* push part of result   */
803   void           (*putInt   )     Args((int));           
804   void           (*putWord  )     Args((unsigned int));
805   void           (*putAddr  )     Args((void*));
806   void           (*putFloat )     Args((double));
807   void           (*putDouble)     Args((double));
808   void           (*putChar  )     Args((char));
809   void           (*putForeign)    Args((HugsForeign, void (*)(HugsForeign)));
810   void           (*putStablePtr)  Args((HugsStablePtr));
811
812   /* return n values in IO monad or Id monad */
813   void           (*returnIO)      Args((HugsStackPtr, int));
814   void           (*returnId)      Args((HugsStackPtr, int));
815   int            (*runIO)         Args((int));
816
817   /* free a stable pointer */                            
818   void           (*freeStablePtr) Args((HugsStablePtr));
819
820   /* register the prim table */                          
821   void           (*registerPrims) Args((struct primInfo*));
822                            
823   /* garbage collect */
824   void           (*garbageCollect) Args(());
825
826 } HugsAPI2;
827
828 extern  HugsAPI2* hugsAPI2     Args((Void));
829 typedef Void (*InitModuleFun2) Args((HugsAPI2*));
830
831 typedef struct {
832   Name  nameTrue, nameFalse;
833   Name  nameNil,  nameCons;
834   Name  nameJust, nameNothing;
835   Name  nameLeft, nameRight;
836   Name  nameUnit;
837   Name  nameIORun;
838
839   Cell  (*makeInt)         Args((Int));
840                            
841   Cell  (*makeChar)        Args((Char));
842   Char  (*CharOf)          Args((Cell));
843                            
844   Cell  (*makeFloat)       Args((FloatPro));
845   Cell  (*makeTuple)       Args((Int));
846   Pair  (*pair)            Args((Cell,Cell));
847                            
848   Cell  (*mkMallocPtr)     Args((Void *, Void (*)(Void *)));
849   Void *(*derefMallocPtr)  Args((Cell));
850                            
851   Int   (*mkStablePtr)     Args((Cell));
852   Cell  (*derefStablePtr)  Args((Int));
853   Void  (*freeStablePtr)   Args((Int));
854                            
855   Void  (*eval)            Args((Cell));
856   Cell  (*evalWithNoError) Args((Cell));
857   Void  (*evalFails)       Args((StackPtr));
858   Int   *whnfArgs;         
859   Cell  *whnfHead;         
860   Int   *whnfInt;          
861   Float *whnfFloat;        
862                            
863   Void  (*garbageCollect)  Args(());
864   Void  (*stackOverflow)   Args(());
865   Void  (*internal)        Args((String)) HUGS_noreturn;
866
867   Void  (*registerPrims)   Args((struct primInfo*));
868   Name  (*addPrimCfun)     Args((Text,Int,Int,Cell));
869   Text  (*inventText)      Args(());
870
871   Cell *(*Fst)             Args((Cell));
872   Cell *(*Snd)             Args((Cell));
873
874   Cell  *cellStack;
875   StackPtr *sp;
876 } HugsAPI1;
877
878 extern  HugsAPI1* hugsAPI1     Args((Void));
879 typedef Void (*InitModuleFun1) Args((HugsAPI1*));
880 #endif /* PLUGINS */
881
882
883 /* --------------------------------------------------------------------------
884  * Misc:
885  * ------------------------------------------------------------------------*/
886
887 extern  Void   setLastExpr       Args((Cell));
888 extern  Cell   getLastExpr       Args((Void));
889 extern  List   addTyconsMatching Args((String,List));
890 extern  List   addNamesMatching  Args((String,List));
891
892 /*-------------------------------------------------------------------------*/