1efe760b337d927feb37ee0b99c4f8ff08795a58
[ghc-hetmet.git] / ghc / interpreter / derive.c
1
2 /* --------------------------------------------------------------------------
3  * Deriving
4  *
5  * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
6  * Yale Haskell Group, and the Oregon Graduate Institute of Science and
7  * Technology, 1994-1999, All rights reserved.  It is distributed as
8  * free software under the license in the file "License", which is
9  * included in the distribution.
10  *
11  * $RCSfile: derive.c,v $
12  * $Revision: 1.7 $
13  * $Date: 1999/10/15 21:41:04 $
14  * ------------------------------------------------------------------------*/
15
16 #include "prelude.h"
17 #include "storage.h"
18 #include "backend.h"
19 #include "connect.h"
20 #include "errors.h"
21 #include "Assembler.h"
22 #include "link.h"
23
24 List cfunSfuns;                        /* List of (Cfun,[SelectorVar])    */
25
26 /* --------------------------------------------------------------------------
27  * local function prototypes:
28  * ------------------------------------------------------------------------*/
29
30 static List  local getDiVars            Args((Int));
31 static Cell  local mkBind               Args((String,List));
32 static Cell  local mkVarAlts            Args((Int,Cell));
33 static List  local makeDPats2           Args((Cell,Int));
34 static Bool  local isEnumType           Args((Tycon));
35 static Pair   local mkAltEq             Args((Int,List));
36 static Pair   local mkAltOrd            Args((Int,List));
37 static Cell   local prodRange           Args((Int,List,Cell,Cell,Cell));
38 static Cell   local prodIndex           Args((Int,List,Cell,Cell,Cell));
39 static Cell   local prodInRange         Args((Int,List,Cell,Cell,Cell));
40 static List   local mkIxBinds           Args((Int,Cell,Int));
41 static Cell   local mkAltShow           Args((Int,Cell,Int));
42 static Cell   local showsPrecRhs        Args((Cell,Cell,Int));
43 static Cell   local mkReadCon           Args((Name,Cell,Cell));
44 static Cell   local mkReadPrefix        Args((Cell));
45 static Cell   local mkReadInfix         Args((Cell));
46 static Cell   local mkReadTuple         Args((Cell));
47 static Cell   local mkReadRecord        Args((Cell,List));
48 static List   local mkBndBinds          Args((Int,Cell,Int));
49
50
51 /* --------------------------------------------------------------------------
52  * Deriving Utilities
53  * ------------------------------------------------------------------------*/
54
55 List diVars = NIL;                      /* Acts as a cache of invented vars*/
56 Int  diNum  = 0;
57
58 static List local getDiVars(n)          /* get list of at least n vars for */
59 Int n; {                                /* derived instance generation     */
60     for (; diNum<n; diNum++) {
61         diVars = cons(inventVar(),diVars);
62     }
63     return diVars;
64 }
65
66 static Cell local mkBind(s,alts)        /* make a binding for a variable   */
67 String s;
68 List   alts; {
69     return pair(mkVar(findText(s)),pair(NIL,alts));
70 }
71
72 static Cell local mkVarAlts(line,r)     /* make alts for binding a var to  */
73 Int  line;                              /* a simple expression             */
74 Cell r; {
75     return singleton(pair(NIL,pair(mkInt(line),r)));
76 }
77
78 static List local makeDPats2(h,n)       /* generate pattern list           */
79 Cell h;                                 /* by putting two new patterns with*/
80 Int  n; {                               /* head h and new var components   */
81     List us = getDiVars(2*n);
82     List vs = NIL;
83     Cell p;
84     Int  i;
85
86     for (i=0, p=h; i<n; ++i) {          /* make first version of pattern   */
87         p  = ap(p,hd(us));
88         us = tl(us);
89     }
90     vs = cons(p,vs);
91
92     for (i=0, p=h; i<n; ++i) {          /* make second version of pattern  */
93         p  = ap(p,hd(us));
94         us = tl(us);
95     }
96     return cons(p,vs);
97 }
98
99 static Bool local isEnumType(t) /* Determine whether t is an enumeration   */
100 Tycon t; {                      /* type (i.e. all constructors arity == 0) */
101     if (isTycon(t) && (tycon(t).what==DATATYPE || tycon(t).what==NEWTYPE)) {
102         List cs = tycon(t).defn;
103         for (; hasCfun(cs); cs=tl(cs)) {
104             if (name(hd(cs)).arity!=0) {
105                 return FALSE;
106             }
107         }
108         /* ToDo: correct?  addCfunTable(t); */
109         return TRUE;
110     }
111     return FALSE;
112 }
113
114
115 /* --------------------------------------------------------------------------
116  * Given a datatype:   data T a b = A a b | B Int | C  deriving (Eq, Ord)
117  * The derived definitions of equality and ordering are given by:
118  *
119  *   A a b == A x y  =  a==x && b==y
120  *   B a   == B x    =  a==x
121  *   C     == C      =  True
122  *   _     == _      =  False
123  *
124  *   compare (A a b) (A x y) =  primCompAux a x (compare b y)
125  *   compare (B a)   (B x)   =  compare a x
126  *   compare C       C       =  EQ
127  *   compare a       x       =  cmpConstr a x
128  *
129  * In each case, the last line is only needed if there are multiple
130  * constructors in the datatype definition.
131  * ------------------------------------------------------------------------*/
132
133 static Pair  local mkAltEq              Args((Int,List));
134
135 List deriveEq(t)                        /* generate binding for derived == */
136 Type t; {                               /* for some TUPLE or DATATYPE t    */
137     List alts = NIL;
138     if (isTycon(t)) {                   /* deal with type constrs          */
139         List cs = tycon(t).defn;
140         for (; hasCfun(cs); cs=tl(cs)) {
141             alts = cons(mkAltEq(tycon(t).line,
142                                 makeDPats2(hd(cs),userArity(hd(cs)))),
143                         alts);
144         }
145         if (cfunOf(hd(tycon(t).defn))!=0) {
146             alts = cons(pair(cons(WILDCARD,cons(WILDCARD,NIL)),
147                              pair(mkInt(tycon(t).line),nameFalse)),alts);
148         }
149         alts = rev(alts);
150     } else {                            /* special case for tuples         */
151         alts = singleton(mkAltEq(0,makeDPats2(t,tupleOf(t))));
152     }
153     return singleton(mkBind("==",alts));
154 }
155
156 static Pair local mkAltEq(line,pats)    /* make alt for an equation for == */
157 Int  line;                              /* using patterns in pats for lhs  */
158 List pats; {                            /* arguments                       */
159     Cell p = hd(pats);
160     Cell q = hd(tl(pats));
161     Cell e = nameTrue;
162
163     if (isAp(p)) {
164         e = ap2(nameEq,arg(p),arg(q));
165         for (p=fun(p), q=fun(q); isAp(p); p=fun(p), q=fun(q)) {
166             e = ap2(nameAnd,ap2(nameEq,arg(p),arg(q)),e);
167         }
168     }
169     return pair(pats,pair(mkInt(line),e));
170 }
171
172
173 static Pair  local mkAltOrd             Args((Int,List));
174
175 List deriveOrd(t)                       /* make binding for derived compare*/
176 Type t; {                               /* for some TUPLE or DATATYPE t    */
177     List alts = NIL;
178     if (isEnumType(t)) {                /* special case for enumerations   */
179         Cell u = inventVar();
180         Cell w = inventVar();
181         Cell rhs = NIL;
182         if (cfunOf(hd(tycon(t).defn))!=0) {
183             implementConToTag(t);
184             rhs = ap2(nameCompare,
185                       ap(tycon(t).conToTag,u),
186                       ap(tycon(t).conToTag,w));
187         } else {
188             rhs = nameEQ;
189         }
190         alts = singleton(pair(doubleton(u,w),pair(mkInt(tycon(t).line),rhs)));
191     } else if (isTycon(t)) {            /* deal with type constrs          */
192         List cs = tycon(t).defn;
193         for (; hasCfun(cs); cs=tl(cs)) {
194             alts = cons(mkAltOrd(tycon(t).line,
195                                  makeDPats2(hd(cs),userArity(hd(cs)))),
196                         alts);
197         }
198         if (cfunOf(hd(tycon(t).defn))!=0) {
199             Cell u = inventVar();
200             Cell w = inventVar();
201             implementConToTag(t);
202             alts   = cons(pair(doubleton(u,w),
203                                pair(mkInt(tycon(t).line),
204                                     ap2(nameCompare,
205                                         ap(tycon(t).conToTag,u),
206                                         ap(tycon(t).conToTag,w)))),
207                           alts);
208         }
209         alts = rev(alts);
210     } else {                            /* special case for tuples         */
211         alts = singleton(mkAltOrd(0,makeDPats2(t,tupleOf(t))));
212     }
213     return singleton(mkBind("compare",alts));
214 }
215
216 static Pair local mkAltOrd(line,pats)   /* make alt for eqn for compare    */
217 Int  line;                              /* using patterns in pats for lhs  */
218 List pats; {                            /* arguments                       */
219     Cell p = hd(pats);
220     Cell q = hd(tl(pats));
221     Cell e = nameEQ;
222
223     if (isAp(p)) {
224         e = ap2(nameCompare,arg(p),arg(q));
225         for (p=fun(p), q=fun(q); isAp(p); p=fun(p), q=fun(q)) {
226             e = ap3(nameCompAux,arg(p),arg(q),e);
227         }
228     }
229
230     return pair(pats,pair(mkInt(line),e));
231 }
232
233
234 /* --------------------------------------------------------------------------
235  * Deriving Ix and Enum:
236  * ------------------------------------------------------------------------*/
237
238 List deriveEnum(t)              /* Construct definition of enumeration     */
239 Tycon t; {
240     Int  l     = tycon(t).line;
241     Cell x     = inventVar();
242     Cell y     = inventVar();
243     Cell first = hd(tycon(t).defn);
244     Cell last  = tycon(t).defn;
245
246     if (!isEnumType(t)) {
247         ERRMSG(l) "Can only derive instances of Enum for enumeration types"
248         EEND;
249     }
250     while (hasCfun(tl(last))) {
251         last = tl(last);
252     }
253     last = hd(last);
254     implementConToTag(t);
255     implementTagToCon(t);
256     return cons(mkBind("toEnum",      mkVarAlts(l,tycon(t).tagToCon)),
257            cons(mkBind("fromEnum",    mkVarAlts(l,tycon(t).conToTag)),
258            cons(mkBind("enumFrom",    singleton(pair(singleton(x),  
259                                         pair(mkInt(l),
260                                         ap2(nameFromTo,x,last))))),
261            /* default instance of enumFromTo is good */
262            cons(mkBind("enumFromThen",singleton(pair(doubleton(x,y),
263                                         pair(mkInt(l),
264                                         ap3(nameFromThenTo,x,y,
265                                         ap(COND,triple(ap2(nameLe,x,y),
266                                         last,first))))))),
267            /* default instance of enumFromThenTo is good */
268            NIL))));
269 }
270
271
272 static List  local mkIxBindsEnum        Args((Tycon));
273 static List  local mkIxBinds            Args((Int,Cell,Int));
274 static Cell  local prodRange            Args((Int,List,Cell,Cell,Cell));
275 static Cell  local prodIndex            Args((Int,List,Cell,Cell,Cell));
276 static Cell  local prodInRange          Args((Int,List,Cell,Cell,Cell));
277
278 List deriveIx(t)                /* Construct definition of indexing        */
279 Tycon t; {
280     if (isEnumType(t)) {        /* Definitions for enumerations            */
281         implementConToTag(t);
282         implementTagToCon(t);
283         return mkIxBindsEnum(t);
284     } else if (isTuple(t)) {    /* Definitions for product types           */
285         return mkIxBinds(0,t,tupleOf(t));
286     } else if (isTycon(t) && cfunOf(hd(tycon(t).defn))==0) {
287         return mkIxBinds(tycon(t).line,
288                          hd(tycon(t).defn),
289                          userArity(hd(tycon(t).defn)));
290     }
291     ERRMSG(tycon(t).line)
292         "Can only derive instances of Ix for enumeration or product types"
293     EEND;
294     return NIL;/* NOTREACHED*/
295 }
296
297 /* instance  Ix T  where
298  *     range (c1,c2)       =  map tagToCon [conToTag c1 .. conToTag c2]
299  *     index b@(c1,c2) ci
300  *         | inRange b ci  =  conToTag ci - conToTag c1
301  *         | otherwise     =  error "Ix.index.T: Index out of range."
302  *     inRange (c1,c2) ci  =  conToTag c1 <= i && i <= conToTag c2
303  *                            where i = conToTag ci
304  */
305 static List local mkIxBindsEnum(t)
306 Tycon t; {
307     Int l = tycon(t).line;
308     Name tagToCon = tycon(t).tagToCon;
309     Name conToTag = tycon(t).conToTag;
310     Cell b  = inventVar();
311     Cell c1 = inventVar();
312     Cell c2 = inventVar();
313     Cell ci = inventVar();
314     return cons(mkBind("range",  singleton(pair(singleton(ap2(mkTuple(2),
315                                  c1,c2)), pair(mkInt(l),ap2(nameMap,tagToCon,
316                                  ap2(nameFromTo,ap(conToTag,c1),
317                                  ap(conToTag,c2))))))),
318            cons(mkBind("index",  singleton(pair(doubleton(ap(ASPAT,pair(b,
319                                  ap2(mkTuple(2),c1,c2))),ci), 
320                                  pair(mkInt(l),ap(COND,
321                                  triple(ap2(nameInRange,b,ci),
322                                  ap2(nameMinus,ap(conToTag,ci),
323                                  ap(conToTag,c1)),
324                                  ap(nameError,mkStr(findText(
325                                  "Ix.index: Index out of range"))))))))),
326            cons(mkBind("inRange",singleton(pair(doubleton(ap2(mkTuple(2),
327                                  c1,c2),ci), pair(mkInt(l),ap2(nameAnd,
328                                  ap2(nameLe,ap(conToTag,c1),ap(conToTag,ci)),
329                                  ap2(nameLe,ap(conToTag,ci),
330                                  ap(conToTag,c2))))))), 
331                                         /* ToDo: share conToTag ci         */
332            NIL)));
333 }
334
335 static List local mkIxBinds(line,h,n)   /* build bindings for derived Ix on*/
336 Int  line;                              /* a product type                  */
337 Cell h;
338 Int  n; {
339     List vs   = getDiVars(3*n);
340     Cell ls   = h;
341     Cell us   = h;
342     Cell is   = h;
343     Cell pr   = NIL;
344     Cell pats = NIL;
345     Int  i;
346
347     for (i=0; i<n; ++i, vs=tl(vs)) {    /* build three patterns for values */
348         ls = ap(ls,hd(vs));             /* of the datatype concerned       */
349         us = ap(us,hd(vs=tl(vs)));
350         is = ap(is,hd(vs=tl(vs)));
351     }
352     pr   = ap2(mkTuple(2),ls,us);       /* Build (ls,us)                   */
353     pats = cons(pr,cons(is,NIL));       /* Build [(ls,us),is]              */
354
355     return cons(prodRange(line,singleton(pr),ls,us,is),
356            cons(prodIndex(line,pats,ls,us,is),
357            cons(prodInRange(line,pats,ls,us,is),
358            NIL)));
359 }
360
361 static Cell local prodRange(line,pats,ls,us,is)
362 Int  line;                              /* Make definition of range for a  */
363 List pats;                              /* product type                    */
364 Cell ls, us, is; {
365     /* range :: (a,a) -> [a]
366      * range (X a b c, X p q r)
367      *   = [ X x y z | x <- range (a,p), y <- range (b,q), z <- range (c,r) ]
368      */
369     Cell is1 = is;
370     List e   = NIL;
371     for (; isAp(ls); ls=fun(ls), us=fun(us), is=fun(is)) {
372         e = cons(ap(FROMQUAL,pair(arg(is),
373                                   ap(nameRange,ap2(mkTuple(2),
374                                                    arg(ls),
375                                                    arg(us))))),e);
376     }
377     e = ap(COMP,pair(is1,e));
378     e = singleton(pair(pats,pair(mkInt(line),e)));
379     return mkBind("range",e);
380 }
381
382 static Cell local prodIndex(line,pats,ls,us,is)
383 Int  line;                              /* Make definition of index for a  */
384 List pats;                              /* product type                    */
385 Cell ls, us, is; {
386     /* index :: (a,a) -> a -> Bool
387      * index (X a b c, X p q r) (X x y z)
388      *  = index (c,r) z + rangeSize (c,r) * (
389      *     index (b,q) y + rangeSize (b,q) * (
390      *      index (a,x) x))
391      */
392     List xs = NIL;
393     Cell e  = NIL;
394     for (; isAp(ls); ls=fun(ls), us=fun(us), is=fun(is)) {
395         xs = cons(ap2(nameIndex,ap2(mkTuple(2),arg(ls),arg(us)),arg(is)),xs);
396     }
397     for (e=hd(xs); nonNull(xs=tl(xs));) {
398         Cell x = hd(xs);
399         e = ap2(namePlus,x,ap2(nameMult,ap(nameRangeSize,arg(fun(x))),e));
400     }
401     e = singleton(pair(pats,pair(mkInt(line),e)));
402     return mkBind("index",e);
403 }
404
405 static Cell local prodInRange(line,pats,ls,us,is)
406 Int  line;                              /* Make definition of inRange for a*/
407 List pats;                              /* product type                    */
408 Cell ls, us, is; {
409     /* inRange :: (a,a) -> a -> Bool
410      * inRange (X a b c, X p q r) (X x y z)
411      *          = inRange (a,p) x && inRange (b,q) y && inRange (c,r) z
412      */
413     Cell e = ap2(nameInRange,ap2(mkTuple(2),arg(ls),arg(us)),arg(is));
414     while (ls=fun(ls), us=fun(us), is=fun(is), isAp(ls)) {
415         e = ap2(nameAnd,
416                 ap2(nameInRange,ap2(mkTuple(2),arg(ls),arg(us)),arg(is)),
417                 e);
418     }
419     e = singleton(pair(pats,pair(mkInt(line),e)));
420     return mkBind("inRange",e);
421 }
422
423
424 /* --------------------------------------------------------------------------
425  * Deriving Show:
426  * ------------------------------------------------------------------------*/
427
428 List deriveShow(t)              /* Construct definition of text conversion */
429 Tycon t; {
430     List alts = NIL;
431     if (isTycon(t)) {                   /* deal with type constrs          */
432         List cs = tycon(t).defn;
433         for (; hasCfun(cs); cs=tl(cs)) {
434             alts = cons(mkAltShow(tycon(t).line,hd(cs),userArity(hd(cs))),
435                         alts);
436         }
437         alts = rev(alts);
438     } else {                            /* special case for tuples         */
439         alts = singleton(mkAltShow(0,t,tupleOf(t)));
440     }
441     return singleton(mkBind("showsPrec",alts));
442 }
443
444 static Cell local mkAltShow(line,h,a)   /* make alt for showsPrec eqn      */
445 Int  line;
446 Cell h;
447 Int  a; {
448     List vs   = getDiVars(a+1);
449     Cell d    = hd(vs);
450     Cell pat  = h;
451     List pats = NIL;
452     Int  i    = 0;
453     for (vs=tl(vs); i<a; i++) {
454         pat = ap(pat,hd(vs));
455         vs  = tl(vs);
456     }
457     pats = cons(d,cons(pat,NIL));
458     return pair(pats,pair(mkInt(line),showsPrecRhs(d,pat,a)));
459 }
460
461 #define shows0   ap(nameShowsPrec,mkInt(0))
462 #define shows10  ap(nameShowsPrec,mkInt(10))
463 #define showsOP  ap(nameComp,consChar('('))
464 #define showsOB  ap(nameComp,consChar('{'))
465 #define showsCM  ap(nameComp,consChar(','))
466 #define showsSP  ap(nameComp,consChar(' '))
467 #define showsBQ  ap(nameComp,consChar('`'))
468 #define showsCP  consChar(')')
469 #define showsCB  consChar('}')
470
471 static Cell local showsPrecRhs(d,pat,a) /* build a rhs for showsPrec for a */
472 Cell d, pat;                            /* given pattern, pat              */
473 Int  a; {
474     Cell h   = getHead(pat);
475     List cfs = cfunSfuns;
476
477     if (isTuple(h)) {
478         /* To display a tuple:
479          *    showsPrec d (a,b,c,d) = showChar '(' . showsPrec 0 a .
480          *                            showChar ',' . showsPrec 0 b .
481          *                            showChar ',' . showsPrec 0 c .
482          *                            showChar ',' . showsPrec 0 d .
483          *                            showChar ')'
484          */
485         Int  i   = tupleOf(h);
486         Cell rhs = showsCP;
487         for (; i>1; --i) {
488             rhs = ap(showsCM,ap2(nameComp,ap(shows0,arg(pat)),rhs));
489             pat = fun(pat);
490         }
491         return ap(showsOP,ap2(nameComp,ap(shows0,arg(pat)),rhs));
492     }
493
494     for (; nonNull(cfs) && h!=fst(hd(cfs)); cfs=tl(cfs)) {
495     }
496     if (nonNull(cfs)) {
497         /* To display a value using record syntax:
498          *    showsPrec d C{x=e, y=f, z=g} = showString "C"  . showChar '{' .
499          *                                   showField "x" e . showChar ',' .
500          *                                   showField "y" f . showChar ',' .
501          *                                   showField "z" g . showChar '}'
502          *    showField lab val
503          *      = showString lab . showChar '=' . shows val
504          */
505         Cell rhs     = showsCB;
506         List vs      = dupOnto(snd(hd(cfs)),NIL);
507         if (isAp(pat)) {
508             for (;;) {
509                 rhs = ap2(nameComp,
510                           ap2(nameShowField,
511                               mkStr(textOf(hd(vs))),
512                               arg(pat)),
513                           rhs);
514                 pat = fun(pat);
515                 vs  = tl(vs);
516                 if (isAp(pat)) {
517                     rhs = ap(showsCM,rhs);
518                 } else {
519                     break;
520                 }
521             }
522         }
523         rhs = ap2(nameComp,ap(nameApp,mkStr(name(h).text)),ap(showsOB,rhs));
524         return rhs;
525     }
526     else if (a==0) {
527         /* To display a nullary constructor:
528          *    showsPrec d Foo = showString "Foo"
529          */
530         return ap(nameApp,mkStr(name(h).text));
531     } else {
532         Syntax s = syntaxOf(h);
533         if (a==2 && assocOf(s)!=APPLIC) {
534             /* For a binary constructor with prec p:
535              * showsPrec d (a :* b) = showParen (d > p)
536              *                          (showsPrec lp a . showChar ' ' .
537              *                           showsString s  . showChar ' ' .
538              *                           showsPrec rp b)
539              */
540             Int  p   = precOf(s);
541             Int  lp  = (assocOf(s)==LEFT_ASS)  ? p : (p+1);
542             Int  rp  = (assocOf(s)==RIGHT_ASS) ? p : (p+1);
543             Cell rhs = ap(showsSP,ap2(nameShowsPrec,mkInt(rp),arg(pat)));
544             if (defaultSyntax(name(h).text)==APPLIC) {
545                 rhs = ap(showsBQ,
546                          ap2(nameComp,
547                              ap(nameApp,mkStr(name(h).text)),
548                              ap(showsBQ,rhs)));
549             } else {
550                 rhs = ap2(nameComp,ap(nameApp,mkStr(name(h).text)),rhs);
551             }
552
553             rhs = ap2(nameComp,
554                       ap2(nameShowsPrec,mkInt(lp),arg(fun(pat))),
555                       ap(showsSP,rhs));
556             rhs = ap2(nameShowParen,ap2(nameLe,mkInt(p+1),d),rhs);
557             return rhs;
558         }
559         else {
560             /* To display a non-nullary constructor with applicative syntax:
561              *    showsPrec d (Foo x y) = showParen (d>=10)
562              *                             (showString "Foo" .
563              *                              showChar ' ' . showsPrec 10 x .
564              *                              showChar ' ' . showsPrec 10 y)
565              */
566             Cell rhs = ap(showsSP,ap(shows10,arg(pat)));
567             for (pat=fun(pat); isAp(pat); pat=fun(pat)) {
568                 rhs = ap(showsSP,ap2(nameComp,ap(shows10,arg(pat)),rhs));
569             }
570             rhs = ap2(nameComp,ap(nameApp,mkStr(name(h).text)),rhs);
571             rhs = ap2(nameShowParen,ap2(nameLe,mkInt(10),d),rhs);
572             return rhs;
573         }
574     }
575 }
576 #undef  shows10
577 #undef  shows0
578 #undef  showsOP
579 #undef  showsOB
580 #undef  showsCM
581 #undef  showsSP
582 #undef  showsBQ
583 #undef  showsCP
584 #undef  showsCB
585
586 /* --------------------------------------------------------------------------
587  * Deriving Read:
588  * ------------------------------------------------------------------------*/
589
590 #define Tuple2(f,s)      ap2(mkTuple(2),f,s)
591 #define Lex(r)           ap(nameLex,r)  
592 #define ZFexp(h,q)       ap(FROMQUAL, pair(h,q))
593 #define ReadsPrec(n,e)   ap2(nameReadsPrec,n,e)
594 #define Lambda(v,e)      ap(LAMBDA,pair(v, pair(mkInt(0),e)))
595 #define ReadParen(a,b,c) ap(ap2(nameReadParen,a,b),c)
596 #define ReadField(f,s)   ap2(nameReadField,f,s)
597 #define GT(l,r)          ap2(nameGt,l,r)
598 #define Append(a,b)      ap2(nameApp,a,b)      
599
600 /*  Construct the readsPrec function of the form:
601  *
602  *    readsPrec d r = (readParen (d>p1) (\r -> [ (C1 ...,s) | ... ]) r ++
603  *                    (readParen (d>p2) (\r -> [ (C2 ...,s) | ... ]) r ++
604  *                    ...
605  *                    (readParen (d>pn) (\r -> [ (Cn ...,s) | ... ]) r) ... ))
606  */
607 List deriveRead(t)              /* construct definition of text reader     */
608 Cell t; {
609     Cell alt  = NIL;
610     Cell exp  = NIL;
611     Cell d    = inventVar();
612     Cell r    = inventVar();
613     List pat  = cons(d,cons(r,NIL));
614     Int  line = 0;
615
616     if (isTycon(t)) {
617         List cs = tycon(t).defn;
618         List exps = NIL;
619         for (; hasCfun(cs); cs=tl(cs)) {
620             exps = cons(mkReadCon(hd(cs),d,r),exps);
621         }
622         /* reverse concatenate list of subexpressions */
623         exp = hd(exps);
624         for (exps=tl(exps); nonNull(exps); exps=tl(exps)) {
625             exp = ap2(nameApp,hd(exps),exp);
626         }
627         line = tycon(t).line;
628     }
629     else { /* Tuples */
630         exp = ap(mkReadTuple(t),r);
631     }
632     /* printExp(stdout,exp); putc('\n',stdout); */
633     alt  = pair(pat,pair(mkInt(line),exp)); 
634     return singleton(mkBind("readsPrec",singleton(alt)));
635 }
636
637 /* Generate an expression of the form:
638  *
639  *   readParen (d > p) <derived expression> r
640  *
641  * for a (non-tuple) constructor "con" of precedence "p".
642  */
643
644 static Cell local mkReadCon(con, d, r) /* generate reader for a constructor */
645 Name con;
646 Cell d;
647 Cell r; {
648     Cell exp = NIL;
649     Int  p   = 0;
650     Syntax s = syntaxOf(con);
651     List cfs = cfunSfuns;
652     for (; nonNull(cfs) && con!=fst(hd(cfs)); cfs=tl(cfs)) {
653     }
654     if (nonNull(cfs)) {
655         exp = mkReadRecord(con,snd(hd(cfs)));
656         return ReadParen(nameFalse, exp, r);
657     }
658
659     if (userArity(con)==2 && assocOf(s)!=APPLIC) {
660         exp = mkReadInfix(con);
661         p   = precOf(s);
662     } else {
663         exp = mkReadPrefix(con);
664         p   = 9;
665     }
666     return ReadParen(userArity(con)==0 ? nameFalse : GT(d,mkInt(p)), exp, r);
667 }
668
669 /* Given an n-ary prefix constructor, generate a single lambda
670  * expression, such that
671  *
672  *   data T ... = Constr a1 a2 .. an | ....
673  *
674  * derives 
675  *
676  *   \ r -> [ (Constr t1 t2 ... tn, sn) | ("Constr",s0) <- lex r,
677  *                                        (t1,s1) <- readsPrec 10 s0,
678  *                                        (t2,s2) <- readsPrec 10 s1,
679  *                                        ...,
680  *                                        (tn,sn) <- readsPrec 10 sn-1 ]
681  *
682  */
683 static Cell local mkReadPrefix(con)    /* readsPrec for prefix constructor */
684 Cell con; {
685     Int  arity  = userArity(con);
686     Cell cn     = mkStr(name(con).text);
687     Cell r      = inventVar();
688     Cell prev_s = inventVar();
689     Cell exp    = con;
690     List quals  = NIL;
691     Int  i;
692
693     /* build (reversed) list of qualifiers and constructor */
694     quals = cons(ZFexp(Tuple2(cn,prev_s),Lex(r)),quals);
695     for(i=0; i<arity; i++) { 
696         Cell t = inventVar();
697         Cell s = inventVar();
698         quals  = cons(ZFexp(Tuple2(t,s),ReadsPrec(mkInt(10),prev_s)), quals);
699         exp    = ap(exp,t);
700         prev_s = s;
701     }
702
703     /* \r -> [ (exp, prev_s) | quals ] */
704     return Lambda(singleton(r),ap(COMP,pair(Tuple2(exp, prev_s), rev(quals))));
705 }
706
707 /* Given a binary infix constructor of precedence p
708  *
709  *   ... | T1 `con` T2 | ...
710  * 
711  * generate the lambda expression
712  *
713  *   \ r -> [ (u `con` v, s2) | (u,s0)     <- readsPrec lp r,
714  *                              ("con",s1) <- lex s0,
715  *                              (v,s2)     <- readsPrec rp s1 ]
716  *
717  * where lp and rp are either p or p+1 depending on associativity
718  */
719 static Cell local mkReadInfix( con )
720 Cell con;
721 {
722     Syntax s  = syntaxOf(con);
723     Int    p  = precOf(s); 
724     Int    lp = assocOf(s)==LEFT_ASS  ? p : (p+1);
725     Int    rp = assocOf(s)==RIGHT_ASS ? p : (p+1);
726     Cell   cn = mkStr(name(con).text);  
727     Cell   r  = inventVar();
728     Cell   s0 = inventVar();
729     Cell   s1 = inventVar();
730     Cell   s2 = inventVar();
731     Cell   u  = inventVar();
732     Cell   v  = inventVar();
733     List quals = NIL;
734
735     quals = cons(ZFexp(Tuple2(u, s0), ReadsPrec(mkInt(lp),r)),  quals);
736     quals = cons(ZFexp(Tuple2(cn,s1), Lex(s0)),                 quals);
737     quals = cons(ZFexp(Tuple2(v, s2), ReadsPrec(mkInt(rp),s1)), quals);
738
739     return Lambda(singleton(r), 
740                   ap(COMP,pair(Tuple2(ap2(con,u,v),s2),rev(quals))));
741 }
742
743 /* Given the n-ary tuple constructor return a lambda expression:
744  *
745  *   \ r -> [ ((t1,t2,...tn),s(2n+1)) | ("(",s0)      <- lex r,
746  *                                      (t1, s1)      <- readsPrec 0 s0,
747  *                                      ...
748  *                                      (",",s(2n-1)) <- lex s(2n-2),
749  *                                      (tn, s(2n))   <- readsPrec 0 s(2n-1),
750  *                                      (")",s(2n+1)) <- lex s(2n) ]
751  */
752 static Cell local mkReadTuple( tup ) /* readsPrec for n-tuple */
753 Cell tup; {
754     Int  arity  = tupleOf(tup);
755     Cell lp     = mkStr(findText("("));
756     Cell rp     = mkStr(findText(")"));
757     Cell co     = mkStr(findText(","));
758     Cell sep    = lp;
759     Cell r      = inventVar();
760     Cell prev_s = r;
761     Cell s      = inventVar();
762     Cell exp    = tup;
763     List quals  = NIL;
764     Int  i;
765
766     /* build (reversed) list of qualifiers and constructor */
767     for(i=0; i<arity; i++) { 
768         Cell t  = inventVar();
769         Cell si = inventVar();
770         Cell sj = inventVar();
771         quals  = cons(ZFexp(Tuple2(sep,si),Lex(prev_s)),quals); 
772         quals  = cons(ZFexp(Tuple2(t,sj),ReadsPrec(mkInt(0),si)), quals);
773         exp    = ap(exp,t);
774         prev_s = sj;
775         sep    = co;
776     }
777     quals = cons(ZFexp(Tuple2(rp,s),Lex(prev_s)),quals);
778
779     /* \ r -> [ (exp,s) | quals ] */
780     return Lambda(singleton(r),ap(COMP,pair(Tuple2(exp,s),rev(quals))));
781 }
782
783 /* Given a record constructor 
784  *
785  *   ... | C { f1 :: T1, ... fn :: Tn } | ...
786  *
787  * generate the expression:
788  *
789  *   \ r -> [(C t1 t2 ... tn,s(2n+1)) | ("C", s0)    <- lex r,
790  *                                      ("{", s1)    <- lex s0,
791  *                                      (t1,  s2)    <- readField "f1" s1,
792  *                                      ...
793  *                                      (",", s(2n-1)) <- lex s(2n),
794  *                                      (tn,  s(2n)) <- readField "fn" s(2n+1),
795  *                                      ("}", s(2n+1)) <- lex s(2n+2) ]
796  *
797  * where
798  *
799  *   readField    :: Read a => String -> ReadS a
800  *   readField m s0 = [ r | (t,  s1) <- lex s0, t == m,
801  *                          ("=",s2) <- lex s1,
802  *                          r        <- readsPrec 10 s2 ]
803  */
804 static Cell local mkReadRecord(con, fs) /* readsPrec for record constructor */
805 Cell con; 
806 List fs; {
807     Cell cn     = mkStr(name(con).text);  
808     Cell lb     = mkStr(findText("{"));
809     Cell rb     = mkStr(findText("}"));
810     Cell co     = mkStr(findText(","));
811     Cell sep    = lb;
812     Cell r      = inventVar();
813     Cell s0     = inventVar();
814     Cell prev_s = s0;
815     Cell s      = inventVar();
816     Cell exp    = con;
817     List quals  = NIL;
818
819     /* build (reversed) list of qualifiers and constructor */
820     quals  = cons(ZFexp(Tuple2(cn,s0),Lex(r)), quals); 
821     for(; nonNull(fs); fs=tl(fs)) { 
822         Cell f  = mkStr(textOf(hd(fs))); 
823         Cell t  = inventVar();
824         Cell si = inventVar();
825         Cell sj = inventVar();
826         quals  = cons(ZFexp(Tuple2(sep,si),Lex(prev_s)),     quals); 
827         quals  = cons(ZFexp(Tuple2(t,  sj),ReadField(f,si)), quals);
828         exp    = ap(exp,t);
829         prev_s = sj;
830         sep    = co;
831     }
832     quals = cons(ZFexp(Tuple2(rb,s),Lex(prev_s)),quals);
833
834     /* \ r -> [ (exp,s) | quals ] */
835     return Lambda(singleton(r),ap(COMP,pair(Tuple2(exp,s),rev(quals))));
836 }
837
838 #undef Tuple2
839 #undef Lex
840 #undef ZFexp
841 #undef ReadsPrec
842 #undef Lambda
843 #undef ReadParen
844 #undef ReadField
845 #undef GT
846 #undef Append
847
848 /* --------------------------------------------------------------------------
849  * Deriving Bounded:
850  * ------------------------------------------------------------------------*/
851
852 List deriveBounded(t)             /* construct definition of bounds        */
853 Tycon t; {
854     if (isEnumType(t)) {
855         Cell last  = tycon(t).defn;
856         Cell first = hd(last);
857         while (hasCfun(tl(last))) {
858             last = tl(last);
859         }
860         return cons(mkBind("minBound",mkVarAlts(tycon(t).line,first)),
861                 cons(mkBind("maxBound",mkVarAlts(tycon(t).line,hd(last))),
862                  NIL));
863     } else if (isTuple(t)) {    /* Definitions for product types           */
864         return mkBndBinds(0,t,tupleOf(t));
865     } else if (isTycon(t) && cfunOf(hd(tycon(t).defn))==0) {
866         return mkBndBinds(tycon(t).line,
867                           hd(tycon(t).defn),
868                           userArity(hd(tycon(t).defn)));
869     }
870     ERRMSG(tycon(t).line)
871      "Can only derive instances of Bounded for enumeration and product types"
872     EEND;
873     return NIL;
874 }
875
876 static List local mkBndBinds(line,h,n)  /* build bindings for derived      */
877 Int  line;                              /* Bounded on a product type       */
878 Cell h;
879 Int  n; {
880     Cell minB = h;
881     Cell maxB = h;
882     while (n-- > 0) {
883         minB = ap(minB,nameMinBnd);
884         maxB = ap(maxB,nameMaxBnd);
885     }
886     return cons(mkBind("minBound",mkVarAlts(line,minB)),
887             cons(mkBind("maxBound",mkVarAlts(line,maxB)),
888              NIL));
889 }
890
891
892 /* --------------------------------------------------------------------------
893  * Helpers: conToTag and tagToCon
894  * ------------------------------------------------------------------------*/
895
896 /* \ v -> case v of { ...; Ci _ _ -> i; ... } */
897 Void implementConToTag(t)
898 Tycon t; {                    
899     if (isNull(tycon(t).conToTag)) {
900         List   cs  = tycon(t).defn;
901         Name   nm  = newName(inventText(),NIL);
902         StgVar v   = mkStgVar(NIL,NIL);
903         List alts  = NIL; /* can't fail */
904
905         assert(isTycon(t) && (tycon(t).what==DATATYPE 
906                               || tycon(t).what==NEWTYPE));
907         for (; hasCfun(cs); cs=tl(cs)) {
908             Name    c   = hd(cs);
909             Int     num = cfunOf(c) == 0 ? 0 : cfunOf(c)-1;
910             StgVar  r   = mkStgVar(mkStgCon(nameMkI,singleton(mkInt(num))),
911                                    NIL);
912             StgExpr tag = mkStgLet(singleton(r),r);
913             List    vs  = NIL;
914             Int i;
915             for(i=0; i < name(c).arity; ++i) {
916                 vs = cons(mkStgVar(NIL,NIL),vs);
917             }
918             alts = cons(mkStgCaseAlt(c,vs,tag),alts);
919         }
920
921         name(nm).line   = tycon(t).line;
922         name(nm).type   = conToTagType(t);
923         name(nm).arity  = 1;
924         name(nm).stgVar = mkStgVar(mkStgLambda(singleton(v),mkStgCase(v,alts)),
925                                    NIL);
926         name(nm).stgSize = stgSize(stgVarBody(name(nm).stgVar));
927         tycon(t).conToTag = nm;
928         /* hack to make it print out */
929         stgGlobals = cons(pair(nm,name(nm).stgVar),stgGlobals); 
930     }
931 }
932
933 /* \ v -> case v of { ...; i -> Ci; ... } */
934 Void implementTagToCon(t)
935 Tycon t; {
936     if (isNull(tycon(t).tagToCon)) {
937         String tyconname;
938         List   cs;
939         Name   nm;
940         StgVar v1;
941         StgVar v2;
942         Cell   txt0;
943         StgVar bind1;
944         StgVar bind2;
945         StgVar bind3;
946         List   alts;
947         char   etxt[200];
948
949         assert(nameMkA);
950         assert(nameUnpackString);
951         assert(nameError);
952         assert(isTycon(t) && (tycon(t).what==DATATYPE 
953                               || tycon(t).what==NEWTYPE));
954
955         tyconname  = textToStr(tycon(t).text);
956         if (strlen(tyconname) > 100) 
957            internal("implementTagToCon: tycon name too long");
958
959         sprintf(etxt, 
960                 "out-of-range arg for `toEnum' "
961                 "in derived `instance Enum %s'", 
962                 tyconname);
963         
964         cs  = tycon(t).defn;
965         nm  = newName(inventText(),NIL);
966         v1  = mkStgVar(NIL,NIL);
967         v2  = mkStgPrimVar(NIL,mkStgRep(INT_REP),NIL);
968
969         txt0  = mkStr(findText(etxt));
970         bind1 = mkStgVar(mkStgCon(nameMkA,singleton(txt0)),NIL);
971         bind2 = mkStgVar(mkStgApp(nameUnpackString,singleton(bind1)),NIL);
972         bind3 = mkStgVar(mkStgApp(nameError,singleton(bind2)),NIL);
973
974         alts  = singleton(
975                    mkStgPrimAlt(
976                       singleton(
977                          mkStgPrimVar(NIL,mkStgRep(INT_REP),NIL)
978                       ),
979                       makeStgLet ( tripleton(bind1,bind2,bind3), bind3 )
980                    )
981                 );
982
983         for (; hasCfun(cs); cs=tl(cs)) {
984             Name   c   = hd(cs);
985             Int    num = cfunOf(c) == 0 ? 0 : cfunOf(c)-1;
986             StgVar pat = mkStgPrimVar(mkInt(num),mkStgRep(INT_REP),NIL);
987             assert(name(c).arity==0);
988             alts = cons(mkStgPrimAlt(singleton(pat),c),alts);
989         }
990
991         name(nm).line   = tycon(t).line;
992         name(nm).type   = tagToConType(t);
993         name(nm).arity  = 1;
994         name(nm).stgVar = mkStgVar(
995                             mkStgLambda(
996                               singleton(v1),
997                               mkStgCase(
998                                 v1,
999                                 singleton(
1000                                   mkStgCaseAlt(
1001                                     nameMkI,
1002                                     singleton(v2),
1003                                     mkStgPrimCase(v2,alts))))),
1004                             NIL
1005                           );
1006         name(nm).stgSize = stgSize(stgVarBody(name(nm).stgVar));
1007         tycon(t).tagToCon = nm;
1008         /* hack to make it print out */
1009         stgGlobals = cons(pair(nm,name(nm).stgVar),stgGlobals); 
1010     }
1011 }
1012
1013
1014 /* --------------------------------------------------------------------------
1015  * Derivation control:
1016  * ------------------------------------------------------------------------*/
1017
1018 Void deriveControl(what)
1019 Int what; {
1020     switch (what) {
1021         case INSTALL :
1022                 /* deliberate fall through */
1023         case RESET   : 
1024                 diVars      = NIL;
1025                 diNum       = 0;
1026                 cfunSfuns   = NIL;
1027                 break;
1028
1029         case MARK    : 
1030                 mark(diVars);
1031                 mark(cfunSfuns);
1032                 break;
1033     }
1034 }
1035
1036 /*-------------------------------------------------------------------------*/