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