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/11/01 04:17:37 $
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);
349 for (i=0; i<n; ++i, vs=tl(vs)) { /* build three patterns for values */
350 ls = ap(ls,hd(vs)); /* of the datatype concerned */
351 us = ap(us,hd(vs=tl(vs)));
352 is = ap(is,hd(vs=tl(vs)));
353 js = ap(js,hd(vs)); /* ... and one expression */
355 pr = ap2(mkTuple(2),ls,us); /* Build (ls,us) */
356 pats = cons(pr,cons(is,NIL)); /* Build [(ls,us),is] */
358 return cons(prodRange(line,singleton(pr),ls,us,js),
359 cons(prodIndex(line,pats,ls,us,is),
360 cons(prodInRange(line,pats,ls,us,is),
364 static Cell local prodRange(line,pats,ls,us,is)
365 Int line; /* Make definition of range for a */
366 List pats; /* product type */
368 /* range :: (a,a) -> [a]
369 * range (X a b c, X p q r)
370 * = [ X x y z | x <- range (a,p), y <- range (b,q), z <- range (c,r) ]
374 for (; isAp(ls); ls=fun(ls), us=fun(us), is=fun(is)) {
375 e = cons(ap(FROMQUAL,pair(arg(is),
376 ap(nameRange,ap2(mkTuple(2),
380 e = ap(COMP,pair(is1,e));
381 e = singleton(pair(pats,pair(mkInt(line),e)));
382 return mkBind("range",e);
385 static Cell local prodIndex(line,pats,ls,us,is)
386 Int line; /* Make definition of index for a */
387 List pats; /* product type */
389 /* index :: (a,a) -> a -> Bool
390 * index (X a b c, X p q r) (X x y z)
391 * = index (c,r) z + rangeSize (c,r) * (
392 * index (b,q) y + rangeSize (b,q) * (
397 for (; isAp(ls); ls=fun(ls), us=fun(us), is=fun(is)) {
398 xs = cons(ap2(nameIndex,ap2(mkTuple(2),arg(ls),arg(us)),arg(is)),xs);
400 for (e=hd(xs); nonNull(xs=tl(xs));) {
402 e = ap2(namePlus,x,ap2(nameMult,ap(nameRangeSize,arg(fun(x))),e));
404 e = singleton(pair(pats,pair(mkInt(line),e)));
405 return mkBind("index",e);
408 static Cell local prodInRange(line,pats,ls,us,is)
409 Int line; /* Make definition of inRange for a*/
410 List pats; /* product type */
412 /* inRange :: (a,a) -> a -> Bool
413 * inRange (X a b c, X p q r) (X x y z)
414 * = inRange (a,p) x && inRange (b,q) y && inRange (c,r) z
416 Cell e = ap2(nameInRange,ap2(mkTuple(2),arg(ls),arg(us)),arg(is));
417 while (ls=fun(ls), us=fun(us), is=fun(is), isAp(ls)) {
419 ap2(nameInRange,ap2(mkTuple(2),arg(ls),arg(us)),arg(is)),
422 e = singleton(pair(pats,pair(mkInt(line),e)));
423 return mkBind("inRange",e);
427 /* --------------------------------------------------------------------------
429 * ------------------------------------------------------------------------*/
431 List deriveShow(t) /* Construct definition of text conversion */
434 if (isTycon(t)) { /* deal with type constrs */
435 List cs = tycon(t).defn;
436 for (; hasCfun(cs); cs=tl(cs)) {
437 alts = cons(mkAltShow(tycon(t).line,hd(cs),userArity(hd(cs))),
441 } else { /* special case for tuples */
442 alts = singleton(mkAltShow(0,t,tupleOf(t)));
444 return singleton(mkBind("showsPrec",alts));
447 static Cell local mkAltShow(line,h,a) /* make alt for showsPrec eqn */
451 List vs = getDiVars(a+1);
456 for (vs=tl(vs); i<a; i++) {
457 pat = ap(pat,hd(vs));
460 pats = cons(d,cons(pat,NIL));
461 return pair(pats,pair(mkInt(line),showsPrecRhs(d,pat,a)));
464 #define shows0 ap(nameShowsPrec,mkInt(0))
465 #define shows10 ap(nameShowsPrec,mkInt(10))
466 #define showsOP ap(nameComp,consChar('('))
467 #define showsOB ap(nameComp,consChar('{'))
468 #define showsCM ap(nameComp,consChar(','))
469 #define showsSP ap(nameComp,consChar(' '))
470 #define showsBQ ap(nameComp,consChar('`'))
471 #define showsCP consChar(')')
472 #define showsCB consChar('}')
474 static Cell local showsPrecRhs(d,pat,a) /* build a rhs for showsPrec for a */
475 Cell d, pat; /* given pattern, pat */
477 Cell h = getHead(pat);
478 List cfs = cfunSfuns;
481 /* To display a tuple:
482 * showsPrec d (a,b,c,d) = showChar '(' . showsPrec 0 a .
483 * showChar ',' . showsPrec 0 b .
484 * showChar ',' . showsPrec 0 c .
485 * showChar ',' . showsPrec 0 d .
491 rhs = ap(showsCM,ap2(nameComp,ap(shows0,arg(pat)),rhs));
494 return ap(showsOP,ap2(nameComp,ap(shows0,arg(pat)),rhs));
497 for (; nonNull(cfs) && h!=fst(hd(cfs)); cfs=tl(cfs)) {
500 /* To display a value using record syntax:
501 * showsPrec d C{x=e, y=f, z=g} = showString "C" . showChar '{' .
502 * showField "x" e . showChar ',' .
503 * showField "y" f . showChar ',' .
504 * showField "z" g . showChar '}'
506 * = showString lab . showChar '=' . shows val
509 List vs = dupOnto(snd(hd(cfs)),NIL);
514 mkStr(textOf(hd(vs))),
520 rhs = ap(showsCM,rhs);
526 rhs = ap2(nameComp,ap(nameApp,mkStr(name(h).text)),ap(showsOB,rhs));
530 /* To display a nullary constructor:
531 * showsPrec d Foo = showString "Foo"
533 return ap(nameApp,mkStr(name(h).text));
535 Syntax s = syntaxOf(h);
536 if (a==2 && assocOf(s)!=APPLIC) {
537 /* For a binary constructor with prec p:
538 * showsPrec d (a :* b) = showParen (d > p)
539 * (showsPrec lp a . showChar ' ' .
540 * showsString s . showChar ' ' .
544 Int lp = (assocOf(s)==LEFT_ASS) ? p : (p+1);
545 Int rp = (assocOf(s)==RIGHT_ASS) ? p : (p+1);
546 Cell rhs = ap(showsSP,ap2(nameShowsPrec,mkInt(rp),arg(pat)));
547 if (defaultSyntax(name(h).text)==APPLIC) {
550 ap(nameApp,mkStr(fixLitText(name(h).text))),
554 ap(nameApp,mkStr(fixLitText(name(h).text))),rhs);
558 ap2(nameShowsPrec,mkInt(lp),arg(fun(pat))),
560 rhs = ap2(nameShowParen,ap2(nameLe,mkInt(p+1),d),rhs);
564 /* To display a non-nullary constructor with applicative syntax:
565 * showsPrec d (Foo x y) = showParen (d>=10)
566 * (showString "Foo" .
567 * showChar ' ' . showsPrec 10 x .
568 * showChar ' ' . showsPrec 10 y)
570 Cell rhs = ap(showsSP,ap(shows10,arg(pat)));
571 for (pat=fun(pat); isAp(pat); pat=fun(pat)) {
572 rhs = ap(showsSP,ap2(nameComp,ap(shows10,arg(pat)),rhs));
574 rhs = ap2(nameComp,ap(nameApp,mkStr(name(h).text)),rhs);
575 rhs = ap2(nameShowParen,ap2(nameLe,mkInt(10),d),rhs);
590 /* --------------------------------------------------------------------------
592 * ------------------------------------------------------------------------*/
594 #define Tuple2(f,s) ap2(mkTuple(2),f,s)
595 #define Lex(r) ap(nameLex,r)
596 #define ZFexp(h,q) ap(FROMQUAL, pair(h,q))
597 #define ReadsPrec(n,e) ap2(nameReadsPrec,n,e)
598 #define Lambda(v,e) ap(LAMBDA,pair(v, pair(mkInt(0),e)))
599 #define ReadParen(a,b,c) ap(ap2(nameReadParen,a,b),c)
600 #define ReadField(f,s) ap2(nameReadField,f,s)
601 #define GT(l,r) ap2(nameGt,l,r)
602 #define Append(a,b) ap2(nameApp,a,b)
604 /* Construct the readsPrec function of the form:
606 * readsPrec d r = (readParen (d>p1) (\r -> [ (C1 ...,s) | ... ]) r ++
607 * (readParen (d>p2) (\r -> [ (C2 ...,s) | ... ]) r ++
609 * (readParen (d>pn) (\r -> [ (Cn ...,s) | ... ]) r) ... ))
611 List deriveRead(t) /* construct definition of text reader */
615 Cell d = inventVar();
616 Cell r = inventVar();
617 List pat = cons(d,cons(r,NIL));
621 List cs = tycon(t).defn;
623 for (; hasCfun(cs); cs=tl(cs)) {
624 exps = cons(mkReadCon(hd(cs),d,r),exps);
626 /* reverse concatenate list of subexpressions */
628 for (exps=tl(exps); nonNull(exps); exps=tl(exps)) {
629 exp = ap2(nameApp,hd(exps),exp);
631 line = tycon(t).line;
634 exp = ap(mkReadTuple(t),r);
636 /* printExp(stdout,exp); putc('\n',stdout); */
637 alt = pair(pat,pair(mkInt(line),exp));
638 return singleton(mkBind("readsPrec",singleton(alt)));
641 /* Generate an expression of the form:
643 * readParen (d > p) <derived expression> r
645 * for a (non-tuple) constructor "con" of precedence "p".
648 static Cell local mkReadCon(con, d, r) /* generate reader for a constructor */
654 Syntax s = syntaxOf(con);
655 List cfs = cfunSfuns;
656 for (; nonNull(cfs) && con!=fst(hd(cfs)); cfs=tl(cfs)) {
659 exp = mkReadRecord(con,snd(hd(cfs)));
660 return ReadParen(nameFalse, exp, r);
663 if (userArity(con)==2 && assocOf(s)!=APPLIC) {
664 exp = mkReadInfix(con);
667 exp = mkReadPrefix(con);
670 return ReadParen(userArity(con)==0 ? nameFalse : GT(d,mkInt(p)), exp, r);
673 /* Given an n-ary prefix constructor, generate a single lambda
674 * expression, such that
676 * data T ... = Constr a1 a2 .. an | ....
680 * \ r -> [ (Constr t1 t2 ... tn, sn) | ("Constr",s0) <- lex r,
681 * (t1,s1) <- readsPrec 10 s0,
682 * (t2,s2) <- readsPrec 10 s1,
684 * (tn,sn) <- readsPrec 10 sn-1 ]
687 static Cell local mkReadPrefix(con) /* readsPrec for prefix constructor */
689 Int arity = userArity(con);
690 Cell cn = mkStr(name(con).text);
691 Cell r = inventVar();
692 Cell prev_s = inventVar();
697 /* build (reversed) list of qualifiers and constructor */
698 quals = cons(ZFexp(Tuple2(cn,prev_s),Lex(r)),quals);
699 for(i=0; i<arity; i++) {
700 Cell t = inventVar();
701 Cell s = inventVar();
702 quals = cons(ZFexp(Tuple2(t,s),ReadsPrec(mkInt(10),prev_s)), quals);
707 /* \r -> [ (exp, prev_s) | quals ] */
708 return Lambda(singleton(r),ap(COMP,pair(Tuple2(exp, prev_s), rev(quals))));
711 /* Given a binary infix constructor of precedence p
713 * ... | T1 `con` T2 | ...
715 * generate the lambda expression
717 * \ r -> [ (u `con` v, s2) | (u,s0) <- readsPrec lp r,
718 * ("con",s1) <- lex s0,
719 * (v,s2) <- readsPrec rp s1 ]
721 * where lp and rp are either p or p+1 depending on associativity
723 static Cell local mkReadInfix( con )
726 Syntax s = syntaxOf(con);
728 Int lp = assocOf(s)==LEFT_ASS ? p : (p+1);
729 Int rp = assocOf(s)==RIGHT_ASS ? p : (p+1);
730 Cell cn = mkStr(name(con).text);
731 Cell r = inventVar();
732 Cell s0 = inventVar();
733 Cell s1 = inventVar();
734 Cell s2 = inventVar();
735 Cell u = inventVar();
736 Cell v = inventVar();
739 quals = cons(ZFexp(Tuple2(u, s0), ReadsPrec(mkInt(lp),r)), quals);
740 quals = cons(ZFexp(Tuple2(cn,s1), Lex(s0)), quals);
741 quals = cons(ZFexp(Tuple2(v, s2), ReadsPrec(mkInt(rp),s1)), quals);
743 return Lambda(singleton(r),
744 ap(COMP,pair(Tuple2(ap2(con,u,v),s2),rev(quals))));
747 /* Given the n-ary tuple constructor return a lambda expression:
749 * \ r -> [ ((t1,t2,...tn),s(2n+1)) | ("(",s0) <- lex r,
750 * (t1, s1) <- readsPrec 0 s0,
752 * (",",s(2n-1)) <- lex s(2n-2),
753 * (tn, s(2n)) <- readsPrec 0 s(2n-1),
754 * (")",s(2n+1)) <- lex s(2n) ]
756 static Cell local mkReadTuple( tup ) /* readsPrec for n-tuple */
758 Int arity = tupleOf(tup);
759 Cell lp = mkStr(findText("("));
760 Cell rp = mkStr(findText(")"));
761 Cell co = mkStr(findText(","));
763 Cell r = inventVar();
765 Cell s = inventVar();
770 /* build (reversed) list of qualifiers and constructor */
771 for(i=0; i<arity; i++) {
772 Cell t = inventVar();
773 Cell si = inventVar();
774 Cell sj = inventVar();
775 quals = cons(ZFexp(Tuple2(sep,si),Lex(prev_s)),quals);
776 quals = cons(ZFexp(Tuple2(t,sj),ReadsPrec(mkInt(0),si)), quals);
781 quals = cons(ZFexp(Tuple2(rp,s),Lex(prev_s)),quals);
783 /* \ r -> [ (exp,s) | quals ] */
784 return Lambda(singleton(r),ap(COMP,pair(Tuple2(exp,s),rev(quals))));
787 /* Given a record constructor
789 * ... | C { f1 :: T1, ... fn :: Tn } | ...
791 * generate the expression:
793 * \ r -> [(C t1 t2 ... tn,s(2n+1)) | ("C", s0) <- lex r,
794 * ("{", s1) <- lex s0,
795 * (t1, s2) <- readField "f1" s1,
797 * (",", s(2n-1)) <- lex s(2n),
798 * (tn, s(2n)) <- readField "fn" s(2n+1),
799 * ("}", s(2n+1)) <- lex s(2n+2) ]
803 * readField :: Read a => String -> ReadS a
804 * readField m s0 = [ r | (t, s1) <- lex s0, t == m,
805 * ("=",s2) <- lex s1,
806 * r <- readsPrec 10 s2 ]
808 static Cell local mkReadRecord(con, fs) /* readsPrec for record constructor */
811 Cell cn = mkStr(name(con).text);
812 Cell lb = mkStr(findText("{"));
813 Cell rb = mkStr(findText("}"));
814 Cell co = mkStr(findText(","));
816 Cell r = inventVar();
817 Cell s0 = inventVar();
819 Cell s = inventVar();
823 /* build (reversed) list of qualifiers and constructor */
824 quals = cons(ZFexp(Tuple2(cn,s0),Lex(r)), quals);
825 for(; nonNull(fs); fs=tl(fs)) {
826 Cell f = mkStr(textOf(hd(fs)));
827 Cell t = inventVar();
828 Cell si = inventVar();
829 Cell sj = inventVar();
830 quals = cons(ZFexp(Tuple2(sep,si),Lex(prev_s)), quals);
831 quals = cons(ZFexp(Tuple2(t, sj),ReadField(f,si)), quals);
836 quals = cons(ZFexp(Tuple2(rb,s),Lex(prev_s)),quals);
838 /* \ r -> [ (exp,s) | quals ] */
839 return Lambda(singleton(r),ap(COMP,pair(Tuple2(exp,s),rev(quals))));
852 /* --------------------------------------------------------------------------
854 * ------------------------------------------------------------------------*/
856 List deriveBounded(t) /* construct definition of bounds */
859 Cell last = tycon(t).defn;
860 Cell first = hd(last);
861 while (hasCfun(tl(last))) {
864 return cons(mkBind("minBound",mkVarAlts(tycon(t).line,first)),
865 cons(mkBind("maxBound",mkVarAlts(tycon(t).line,hd(last))),
867 } else if (isTuple(t)) { /* Definitions for product types */
868 return mkBndBinds(0,t,tupleOf(t));
869 } else if (isTycon(t) && cfunOf(hd(tycon(t).defn))==0) {
870 return mkBndBinds(tycon(t).line,
872 userArity(hd(tycon(t).defn)));
874 ERRMSG(tycon(t).line)
875 "Can only derive instances of Bounded for enumeration and product types"
880 static List local mkBndBinds(line,h,n) /* build bindings for derived */
881 Int line; /* Bounded on a product type */
887 minB = ap(minB,nameMinBnd);
888 maxB = ap(maxB,nameMaxBnd);
890 return cons(mkBind("minBound",mkVarAlts(line,minB)),
891 cons(mkBind("maxBound",mkVarAlts(line,maxB)),
896 /* --------------------------------------------------------------------------
897 * Helpers: conToTag and tagToCon
898 * ------------------------------------------------------------------------*/
900 /* \ v -> case v of { ...; Ci _ _ -> i; ... } */
901 Void implementConToTag(t)
903 if (isNull(tycon(t).conToTag)) {
904 List cs = tycon(t).defn;
905 Name nm = newName(inventText(),NIL);
906 StgVar v = mkStgVar(NIL,NIL);
907 List alts = NIL; /* can't fail */
909 assert(isTycon(t) && (tycon(t).what==DATATYPE
910 || tycon(t).what==NEWTYPE));
911 for (; hasCfun(cs); cs=tl(cs)) {
913 Int num = cfunOf(c) == 0 ? 0 : cfunOf(c)-1;
914 StgVar r = mkStgVar(mkStgCon(nameMkI,singleton(mkInt(num))),
916 StgExpr tag = mkStgLet(singleton(r),r);
919 for(i=0; i < name(c).arity; ++i) {
920 vs = cons(mkStgVar(NIL,NIL),vs);
922 alts = cons(mkStgCaseAlt(c,vs,tag),alts);
925 name(nm).line = tycon(t).line;
926 name(nm).type = conToTagType(t);
928 name(nm).stgVar = mkStgVar(mkStgLambda(singleton(v),mkStgCase(v,alts)),
930 name(nm).stgSize = stgSize(stgVarBody(name(nm).stgVar));
931 tycon(t).conToTag = nm;
932 /* hack to make it print out */
933 stgGlobals = cons(pair(nm,name(nm).stgVar),stgGlobals);
937 /* \ v -> case v of { ...; i -> Ci; ... } */
938 Void implementTagToCon(t)
940 if (isNull(tycon(t).tagToCon)) {
954 assert(nameUnpackString);
956 assert(isTycon(t) && (tycon(t).what==DATATYPE
957 || tycon(t).what==NEWTYPE));
959 tyconname = textToStr(tycon(t).text);
960 if (strlen(tyconname) > 100)
961 internal("implementTagToCon: tycon name too long");
964 "out-of-range arg for `toEnum' "
965 "in derived `instance Enum %s'",
969 nm = newName(inventText(),NIL);
970 v1 = mkStgVar(NIL,NIL);
971 v2 = mkStgPrimVar(NIL,mkStgRep(INT_REP),NIL);
973 txt0 = mkStr(findText(etxt));
974 bind1 = mkStgVar(mkStgCon(nameMkA,singleton(txt0)),NIL);
975 bind2 = mkStgVar(mkStgApp(nameUnpackString,singleton(bind1)),NIL);
976 bind3 = mkStgVar(mkStgApp(nameError,singleton(bind2)),NIL);
981 mkStgPrimVar(NIL,mkStgRep(INT_REP),NIL)
983 makeStgLet ( tripleton(bind1,bind2,bind3), bind3 )
987 for (; hasCfun(cs); cs=tl(cs)) {
989 Int num = cfunOf(c) == 0 ? 0 : cfunOf(c)-1;
990 StgVar pat = mkStgPrimVar(mkInt(num),mkStgRep(INT_REP),NIL);
991 assert(name(c).arity==0);
992 alts = cons(mkStgPrimAlt(singleton(pat),c),alts);
995 name(nm).line = tycon(t).line;
996 name(nm).type = tagToConType(t);
998 name(nm).stgVar = mkStgVar(
1007 mkStgPrimCase(v2,alts))))),
1010 name(nm).stgSize = stgSize(stgVarBody(name(nm).stgVar));
1011 tycon(t).tagToCon = nm;
1012 /* hack to make it print out */
1013 stgGlobals = cons(pair(nm,name(nm).stgVar),stgGlobals);
1018 /* --------------------------------------------------------------------------
1019 * Derivation control:
1020 * ------------------------------------------------------------------------*/
1022 Void deriveControl(what)
1026 /* deliberate fall through */
1040 /*-------------------------------------------------------------------------*/