2 /* --------------------------------------------------------------------------
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.
11 * $RCSfile: derive.c,v $
13 * $Date: 1999/10/15 21:41:04 $
14 * ------------------------------------------------------------------------*/
21 #include "Assembler.h"
24 List cfunSfuns; /* List of (Cfun,[SelectorVar]) */
26 /* --------------------------------------------------------------------------
27 * local function prototypes:
28 * ------------------------------------------------------------------------*/
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));
51 /* --------------------------------------------------------------------------
53 * ------------------------------------------------------------------------*/
55 List diVars = NIL; /* Acts as a cache of invented vars*/
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);
66 static Cell local mkBind(s,alts) /* make a binding for a variable */
69 return pair(mkVar(findText(s)),pair(NIL,alts));
72 static Cell local mkVarAlts(line,r) /* make alts for binding a var to */
73 Int line; /* a simple expression */
75 return singleton(pair(NIL,pair(mkInt(line),r)));
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);
86 for (i=0, p=h; i<n; ++i) { /* make first version of pattern */
92 for (i=0, p=h; i<n; ++i) { /* make second version of pattern */
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) {
108 /* ToDo: correct? addCfunTable(t); */
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:
119 * A a b == A x y = a==x && b==y
124 * compare (A a b) (A x y) = primCompAux a x (compare b y)
125 * compare (B a) (B x) = compare a x
127 * compare a x = cmpConstr a x
129 * In each case, the last line is only needed if there are multiple
130 * constructors in the datatype definition.
131 * ------------------------------------------------------------------------*/
133 static Pair local mkAltEq Args((Int,List));
135 List deriveEq(t) /* generate binding for derived == */
136 Type t; { /* for some TUPLE or DATATYPE t */
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)))),
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);
150 } else { /* special case for tuples */
151 alts = singleton(mkAltEq(0,makeDPats2(t,tupleOf(t))));
153 return singleton(mkBind("==",alts));
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 */
160 Cell q = hd(tl(pats));
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);
169 return pair(pats,pair(mkInt(line),e));
173 static Pair local mkAltOrd Args((Int,List));
175 List deriveOrd(t) /* make binding for derived compare*/
176 Type t; { /* for some TUPLE or DATATYPE t */
178 if (isEnumType(t)) { /* special case for enumerations */
179 Cell u = inventVar();
180 Cell w = inventVar();
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));
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)))),
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),
205 ap(tycon(t).conToTag,u),
206 ap(tycon(t).conToTag,w)))),
210 } else { /* special case for tuples */
211 alts = singleton(mkAltOrd(0,makeDPats2(t,tupleOf(t))));
213 return singleton(mkBind("compare",alts));
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 */
220 Cell q = hd(tl(pats));
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);
230 return pair(pats,pair(mkInt(line),e));
234 /* --------------------------------------------------------------------------
235 * Deriving Ix and Enum:
236 * ------------------------------------------------------------------------*/
238 List deriveEnum(t) /* Construct definition of enumeration */
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;
246 if (!isEnumType(t)) {
247 ERRMSG(l) "Can only derive instances of Enum for enumeration types"
250 while (hasCfun(tl(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),
260 ap2(nameFromTo,x,last))))),
261 /* default instance of enumFromTo is good */
262 cons(mkBind("enumFromThen",singleton(pair(doubleton(x,y),
264 ap3(nameFromThenTo,x,y,
265 ap(COND,triple(ap2(nameLe,x,y),
267 /* default instance of enumFromThenTo is good */
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));
278 List deriveIx(t) /* Construct definition of indexing */
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,
289 userArity(hd(tycon(t).defn)));
291 ERRMSG(tycon(t).line)
292 "Can only derive instances of Ix for enumeration or product types"
294 return NIL;/* NOTREACHED*/
297 /* instance Ix T where
298 * range (c1,c2) = map tagToCon [conToTag c1 .. conToTag c2]
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
305 static List local mkIxBindsEnum(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),
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 */
335 static List local mkIxBinds(line,h,n) /* build bindings for derived Ix on*/
336 Int line; /* a product type */
339 List vs = getDiVars(3*n);
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)));
352 pr = ap2(mkTuple(2),ls,us); /* Build (ls,us) */
353 pats = cons(pr,cons(is,NIL)); /* Build [(ls,us),is] */
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),
361 static Cell local prodRange(line,pats,ls,us,is)
362 Int line; /* Make definition of range for a */
363 List pats; /* product type */
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) ]
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),
377 e = ap(COMP,pair(is1,e));
378 e = singleton(pair(pats,pair(mkInt(line),e)));
379 return mkBind("range",e);
382 static Cell local prodIndex(line,pats,ls,us,is)
383 Int line; /* Make definition of index for a */
384 List pats; /* product type */
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) * (
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);
397 for (e=hd(xs); nonNull(xs=tl(xs));) {
399 e = ap2(namePlus,x,ap2(nameMult,ap(nameRangeSize,arg(fun(x))),e));
401 e = singleton(pair(pats,pair(mkInt(line),e)));
402 return mkBind("index",e);
405 static Cell local prodInRange(line,pats,ls,us,is)
406 Int line; /* Make definition of inRange for a*/
407 List pats; /* product type */
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
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)) {
416 ap2(nameInRange,ap2(mkTuple(2),arg(ls),arg(us)),arg(is)),
419 e = singleton(pair(pats,pair(mkInt(line),e)));
420 return mkBind("inRange",e);
424 /* --------------------------------------------------------------------------
426 * ------------------------------------------------------------------------*/
428 List deriveShow(t) /* Construct definition of text conversion */
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))),
438 } else { /* special case for tuples */
439 alts = singleton(mkAltShow(0,t,tupleOf(t)));
441 return singleton(mkBind("showsPrec",alts));
444 static Cell local mkAltShow(line,h,a) /* make alt for showsPrec eqn */
448 List vs = getDiVars(a+1);
453 for (vs=tl(vs); i<a; i++) {
454 pat = ap(pat,hd(vs));
457 pats = cons(d,cons(pat,NIL));
458 return pair(pats,pair(mkInt(line),showsPrecRhs(d,pat,a)));
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('}')
471 static Cell local showsPrecRhs(d,pat,a) /* build a rhs for showsPrec for a */
472 Cell d, pat; /* given pattern, pat */
474 Cell h = getHead(pat);
475 List cfs = cfunSfuns;
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 .
488 rhs = ap(showsCM,ap2(nameComp,ap(shows0,arg(pat)),rhs));
491 return ap(showsOP,ap2(nameComp,ap(shows0,arg(pat)),rhs));
494 for (; nonNull(cfs) && h!=fst(hd(cfs)); cfs=tl(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 '}'
503 * = showString lab . showChar '=' . shows val
506 List vs = dupOnto(snd(hd(cfs)),NIL);
511 mkStr(textOf(hd(vs))),
517 rhs = ap(showsCM,rhs);
523 rhs = ap2(nameComp,ap(nameApp,mkStr(name(h).text)),ap(showsOB,rhs));
527 /* To display a nullary constructor:
528 * showsPrec d Foo = showString "Foo"
530 return ap(nameApp,mkStr(name(h).text));
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 ' ' .
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) {
547 ap(nameApp,mkStr(name(h).text)),
550 rhs = ap2(nameComp,ap(nameApp,mkStr(name(h).text)),rhs);
554 ap2(nameShowsPrec,mkInt(lp),arg(fun(pat))),
556 rhs = ap2(nameShowParen,ap2(nameLe,mkInt(p+1),d),rhs);
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)
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));
570 rhs = ap2(nameComp,ap(nameApp,mkStr(name(h).text)),rhs);
571 rhs = ap2(nameShowParen,ap2(nameLe,mkInt(10),d),rhs);
586 /* --------------------------------------------------------------------------
588 * ------------------------------------------------------------------------*/
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)
600 /* Construct the readsPrec function of the form:
602 * readsPrec d r = (readParen (d>p1) (\r -> [ (C1 ...,s) | ... ]) r ++
603 * (readParen (d>p2) (\r -> [ (C2 ...,s) | ... ]) r ++
605 * (readParen (d>pn) (\r -> [ (Cn ...,s) | ... ]) r) ... ))
607 List deriveRead(t) /* construct definition of text reader */
611 Cell d = inventVar();
612 Cell r = inventVar();
613 List pat = cons(d,cons(r,NIL));
617 List cs = tycon(t).defn;
619 for (; hasCfun(cs); cs=tl(cs)) {
620 exps = cons(mkReadCon(hd(cs),d,r),exps);
622 /* reverse concatenate list of subexpressions */
624 for (exps=tl(exps); nonNull(exps); exps=tl(exps)) {
625 exp = ap2(nameApp,hd(exps),exp);
627 line = tycon(t).line;
630 exp = ap(mkReadTuple(t),r);
632 /* printExp(stdout,exp); putc('\n',stdout); */
633 alt = pair(pat,pair(mkInt(line),exp));
634 return singleton(mkBind("readsPrec",singleton(alt)));
637 /* Generate an expression of the form:
639 * readParen (d > p) <derived expression> r
641 * for a (non-tuple) constructor "con" of precedence "p".
644 static Cell local mkReadCon(con, d, r) /* generate reader for a constructor */
650 Syntax s = syntaxOf(con);
651 List cfs = cfunSfuns;
652 for (; nonNull(cfs) && con!=fst(hd(cfs)); cfs=tl(cfs)) {
655 exp = mkReadRecord(con,snd(hd(cfs)));
656 return ReadParen(nameFalse, exp, r);
659 if (userArity(con)==2 && assocOf(s)!=APPLIC) {
660 exp = mkReadInfix(con);
663 exp = mkReadPrefix(con);
666 return ReadParen(userArity(con)==0 ? nameFalse : GT(d,mkInt(p)), exp, r);
669 /* Given an n-ary prefix constructor, generate a single lambda
670 * expression, such that
672 * data T ... = Constr a1 a2 .. an | ....
676 * \ r -> [ (Constr t1 t2 ... tn, sn) | ("Constr",s0) <- lex r,
677 * (t1,s1) <- readsPrec 10 s0,
678 * (t2,s2) <- readsPrec 10 s1,
680 * (tn,sn) <- readsPrec 10 sn-1 ]
683 static Cell local mkReadPrefix(con) /* readsPrec for prefix constructor */
685 Int arity = userArity(con);
686 Cell cn = mkStr(name(con).text);
687 Cell r = inventVar();
688 Cell prev_s = inventVar();
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);
703 /* \r -> [ (exp, prev_s) | quals ] */
704 return Lambda(singleton(r),ap(COMP,pair(Tuple2(exp, prev_s), rev(quals))));
707 /* Given a binary infix constructor of precedence p
709 * ... | T1 `con` T2 | ...
711 * generate the lambda expression
713 * \ r -> [ (u `con` v, s2) | (u,s0) <- readsPrec lp r,
714 * ("con",s1) <- lex s0,
715 * (v,s2) <- readsPrec rp s1 ]
717 * where lp and rp are either p or p+1 depending on associativity
719 static Cell local mkReadInfix( con )
722 Syntax s = syntaxOf(con);
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();
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);
739 return Lambda(singleton(r),
740 ap(COMP,pair(Tuple2(ap2(con,u,v),s2),rev(quals))));
743 /* Given the n-ary tuple constructor return a lambda expression:
745 * \ r -> [ ((t1,t2,...tn),s(2n+1)) | ("(",s0) <- lex r,
746 * (t1, s1) <- readsPrec 0 s0,
748 * (",",s(2n-1)) <- lex s(2n-2),
749 * (tn, s(2n)) <- readsPrec 0 s(2n-1),
750 * (")",s(2n+1)) <- lex s(2n) ]
752 static Cell local mkReadTuple( tup ) /* readsPrec for n-tuple */
754 Int arity = tupleOf(tup);
755 Cell lp = mkStr(findText("("));
756 Cell rp = mkStr(findText(")"));
757 Cell co = mkStr(findText(","));
759 Cell r = inventVar();
761 Cell s = inventVar();
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);
777 quals = cons(ZFexp(Tuple2(rp,s),Lex(prev_s)),quals);
779 /* \ r -> [ (exp,s) | quals ] */
780 return Lambda(singleton(r),ap(COMP,pair(Tuple2(exp,s),rev(quals))));
783 /* Given a record constructor
785 * ... | C { f1 :: T1, ... fn :: Tn } | ...
787 * generate the expression:
789 * \ r -> [(C t1 t2 ... tn,s(2n+1)) | ("C", s0) <- lex r,
790 * ("{", s1) <- lex s0,
791 * (t1, s2) <- readField "f1" s1,
793 * (",", s(2n-1)) <- lex s(2n),
794 * (tn, s(2n)) <- readField "fn" s(2n+1),
795 * ("}", s(2n+1)) <- lex s(2n+2) ]
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 ]
804 static Cell local mkReadRecord(con, fs) /* readsPrec for record constructor */
807 Cell cn = mkStr(name(con).text);
808 Cell lb = mkStr(findText("{"));
809 Cell rb = mkStr(findText("}"));
810 Cell co = mkStr(findText(","));
812 Cell r = inventVar();
813 Cell s0 = inventVar();
815 Cell s = inventVar();
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);
832 quals = cons(ZFexp(Tuple2(rb,s),Lex(prev_s)),quals);
834 /* \ r -> [ (exp,s) | quals ] */
835 return Lambda(singleton(r),ap(COMP,pair(Tuple2(exp,s),rev(quals))));
848 /* --------------------------------------------------------------------------
850 * ------------------------------------------------------------------------*/
852 List deriveBounded(t) /* construct definition of bounds */
855 Cell last = tycon(t).defn;
856 Cell first = hd(last);
857 while (hasCfun(tl(last))) {
860 return cons(mkBind("minBound",mkVarAlts(tycon(t).line,first)),
861 cons(mkBind("maxBound",mkVarAlts(tycon(t).line,hd(last))),
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,
868 userArity(hd(tycon(t).defn)));
870 ERRMSG(tycon(t).line)
871 "Can only derive instances of Bounded for enumeration and product types"
876 static List local mkBndBinds(line,h,n) /* build bindings for derived */
877 Int line; /* Bounded on a product type */
883 minB = ap(minB,nameMinBnd);
884 maxB = ap(maxB,nameMaxBnd);
886 return cons(mkBind("minBound",mkVarAlts(line,minB)),
887 cons(mkBind("maxBound",mkVarAlts(line,maxB)),
892 /* --------------------------------------------------------------------------
893 * Helpers: conToTag and tagToCon
894 * ------------------------------------------------------------------------*/
896 /* \ v -> case v of { ...; Ci _ _ -> i; ... } */
897 Void implementConToTag(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 */
905 assert(isTycon(t) && (tycon(t).what==DATATYPE
906 || tycon(t).what==NEWTYPE));
907 for (; hasCfun(cs); cs=tl(cs)) {
909 Int num = cfunOf(c) == 0 ? 0 : cfunOf(c)-1;
910 StgVar r = mkStgVar(mkStgCon(nameMkI,singleton(mkInt(num))),
912 StgExpr tag = mkStgLet(singleton(r),r);
915 for(i=0; i < name(c).arity; ++i) {
916 vs = cons(mkStgVar(NIL,NIL),vs);
918 alts = cons(mkStgCaseAlt(c,vs,tag),alts);
921 name(nm).line = tycon(t).line;
922 name(nm).type = conToTagType(t);
924 name(nm).stgVar = mkStgVar(mkStgLambda(singleton(v),mkStgCase(v,alts)),
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);
933 /* \ v -> case v of { ...; i -> Ci; ... } */
934 Void implementTagToCon(t)
936 if (isNull(tycon(t).tagToCon)) {
950 assert(nameUnpackString);
952 assert(isTycon(t) && (tycon(t).what==DATATYPE
953 || tycon(t).what==NEWTYPE));
955 tyconname = textToStr(tycon(t).text);
956 if (strlen(tyconname) > 100)
957 internal("implementTagToCon: tycon name too long");
960 "out-of-range arg for `toEnum' "
961 "in derived `instance Enum %s'",
965 nm = newName(inventText(),NIL);
966 v1 = mkStgVar(NIL,NIL);
967 v2 = mkStgPrimVar(NIL,mkStgRep(INT_REP),NIL);
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);
977 mkStgPrimVar(NIL,mkStgRep(INT_REP),NIL)
979 makeStgLet ( tripleton(bind1,bind2,bind3), bind3 )
983 for (; hasCfun(cs); cs=tl(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);
991 name(nm).line = tycon(t).line;
992 name(nm).type = tagToConType(t);
994 name(nm).stgVar = mkStgVar(
1003 mkStgPrimCase(v2,alts))))),
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);
1014 /* --------------------------------------------------------------------------
1015 * Derivation control:
1016 * ------------------------------------------------------------------------*/
1018 Void deriveControl(what)
1022 /* deliberate fall through */
1036 /*-------------------------------------------------------------------------*/