2 /* --------------------------------------------------------------------------
3 * This is the Hugs compiler, handling translation of typechecked code to
4 * `kernel' language, elimination of pattern matching and translation to
5 * super combinators (lambda lifting).
7 * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
8 * Yale Haskell Group, and the Oregon Graduate Institute of Science and
9 * Technology, 1994-1999, All rights reserved. It is distributed as
10 * free software under the license in the file "License", which is
11 * included in the distribution.
13 * $RCSfile: compiler.c,v $
15 * $Date: 1999/11/11 17:42:31 $
16 * ------------------------------------------------------------------------*/
23 #include "Rts.h" /* for rts_eval and related stuff */
24 #include "RtsAPI.h" /* for rts_eval and related stuff */
25 #include "SchedAPI.h" /* for RevertCAFs */
29 Addr inputCode; /* Addr of compiled code for expr */
30 static Name currentName; /* Top level name being processed */
32 Bool debugCode = FALSE; /* TRUE => print G-code to screen */
37 /* --------------------------------------------------------------------------
38 * Local function prototypes:
39 * ------------------------------------------------------------------------*/
41 static Cell local translate Args((Cell));
42 static Void local transPair Args((Pair));
43 static Void local transTriple Args((Triple));
44 static Void local transAlt Args((Cell));
45 static Void local transCase Args((Cell));
46 static List local transBinds Args((List));
47 static Cell local transRhs Args((Cell));
48 static Cell local mkConsList Args((List));
49 static Cell local expandLetrec Args((Cell));
50 static Cell local transComp Args((Cell,List,Cell));
51 static Cell local transDo Args((Cell,Cell,List));
52 static Cell local transConFlds Args((Cell,List));
53 static Cell local transUpdFlds Args((Cell,List,List));
55 static Cell local refutePat Args((Cell));
56 static Cell local refutePatAp Args((Cell));
57 static Cell local matchPat Args((Cell));
58 static List local remPat Args((Cell,Cell,List));
59 static List local remPat1 Args((Cell,Cell,List));
61 static Cell local pmcTerm Args((Int,List,Cell));
62 static Cell local pmcPair Args((Int,List,Pair));
63 static Cell local pmcTriple Args((Int,List,Triple));
64 static Cell local pmcVar Args((List,Text));
65 static Void local pmcLetrec Args((Int,List,Pair));
66 static Cell local pmcVarDef Args((Int,List,List));
67 static Void local pmcFunDef Args((Int,List,Triple));
68 static List local altsMatch Args((Int,Int,List,List));
69 static Cell local match Args((Int,List));
70 static Cell local joinMas Args((Int,List));
71 static Bool local canFail Args((Cell));
72 static List local addConTable Args((Cell,Cell,List));
73 static Void local advance Args((Int,Int,Cell));
74 static Bool local emptyMatch Args((Cell));
75 static Cell local maDiscr Args((Cell));
76 static Bool local isNumDiscr Args((Cell));
77 static Bool local eqNumDiscr Args((Cell,Cell));
79 static Bool local isExtDiscr Args((Cell));
80 static Bool local eqExtDiscr Args((Cell,Cell));
83 static Void local compileGlobalFunction Args((Pair));
84 static Void local compileGenFunction Args((Name));
85 static Name local compileSelFunction Args((Pair));
86 static List local addStgVar Args((List,Pair));
89 /* --------------------------------------------------------------------------
90 * Translation: Convert input expressions into a less complex language
91 * of terms using only LETREC, AP, constants and vars.
92 * Also remove pattern definitions on lhs of eqns.
93 * ------------------------------------------------------------------------*/
95 static Cell local translate(e) /* Translate expression: */
98 case LETREC : snd(snd(e)) = translate(snd(snd(e)));
99 return expandLetrec(e);
101 case COND : transTriple(snd(e));
104 case AP : fst(e) = translate(fst(e));
106 if (fst(e)==nameId || fst(e)==nameInd)
107 return translate(snd(e));
108 if (isName(fst(e)) &&
111 return translate(snd(e));
113 snd(e) = translate(snd(e));
116 case NAME : if (e==nameOtherwise)
119 if (isName(name(e).defn))
121 if (isPair(name(e).defn))
122 return snd(name(e).defn);
127 case RECSEL : return nameRecSel;
139 case CHARCELL : return e;
141 case IPVAR : return nameId;
143 case FINLIST : mapOver(translate,snd(e));
144 return mkConsList(snd(e));
146 case DOCOMP : { Cell m = translate(fst(snd(e)));
147 Cell r = translate(fst(snd(snd(e))));
148 return transDo(m,r,snd(snd(snd(e))));
151 case MONADCOMP : { Cell m = translate(fst(snd(e)));
152 Cell r = translate(fst(snd(snd(e))));
153 Cell qs = snd(snd(snd(e)));
154 if (m == nameListMonad)
155 return transComp(r,qs,nameNil);
158 r = ap(ap(nameReturn,m),r);
159 return transDo(m,r,qs);
161 internal("translate: monad comps");
166 case CONFLDS : return transConFlds(fst(snd(e)),snd(snd(e)));
168 case UPDFLDS : return transUpdFlds(fst3(snd(e)),
172 case CASE : { Cell nv = inventVar();
173 mapProc(transCase,snd(snd(e)));
175 pair(singleton(pair(nv,snd(snd(e)))),
176 ap(nv,translate(fst(snd(e))))));
179 case LAMBDA : { Cell nv = inventVar();
188 default : fprintf(stderr, "stuff=%d\n",whatIs(e));internal("translate");
193 static Void local transPair(pr) /* Translate each component in a */
194 Pair pr; { /* pair of expressions. */
195 fst(pr) = translate(fst(pr));
196 snd(pr) = translate(snd(pr));
199 static Void local transTriple(tr) /* Translate each component in a */
200 Triple tr; { /* triple of expressions. */
201 fst3(tr) = translate(fst3(tr));
202 snd3(tr) = translate(snd3(tr));
203 thd3(tr) = translate(thd3(tr));
206 static Void local transAlt(e) /* Translate alt: */
207 Cell e; { /* ([Pat], Rhs) ==> ([Pat], Rhs') */
208 snd(e) = transRhs(snd(e));
211 static Void local transCase(c) /* Translate case: */
212 Cell c; { /* (Pat, Rhs) ==> ([Pat], Rhs') */
213 fst(c) = singleton(fst(c));
214 snd(c) = transRhs(snd(c));
217 static List local transBinds(bs) /* Translate list of bindings: */
218 List bs; { /* eliminating pattern matching on */
219 List newBinds = NIL; /* lhs of bindings. */
220 for (; nonNull(bs); bs=tl(bs)) {
222 Cell v = fst(hd(bs));
223 while (isAp(v) && fst(v) == nameInd)
228 if (isVar(fst(hd(bs)))) {
230 mapProc(transAlt,snd(hd(bs)));
231 newBinds = cons(hd(bs),newBinds);
234 newBinds = remPat(fst(snd(hd(bs))),
235 snd(snd(hd(bs)))=transRhs(snd(snd(hd(bs)))),
241 static Cell local transRhs(rhs) /* Translate rhs: removing line nos */
243 switch (whatIs(rhs)) {
244 case LETREC : snd(snd(rhs)) = transRhs(snd(snd(rhs)));
245 return expandLetrec(rhs);
247 case GUARDED : mapOver(snd,snd(rhs)); /* discard line number */
248 mapProc(transPair,snd(rhs));
251 default : return translate(snd(rhs)); /* discard line number */
255 static Cell local mkConsList(es) /* Construct expression for list es */
256 List es; { /* using nameNil and nameCons */
260 return ap(ap(nameCons,hd(es)),mkConsList(tl(es)));
263 static Cell local expandLetrec(root) /* translate LETREC with list of */
264 Cell root; { /* groups of bindings (from depend. */
265 Cell e = snd(snd(root)); /* analysis) to use nested LETRECs */
266 List bss = fst(snd(root));
269 if (isNull(bss)) /* should never happen, but just in */
270 return e; /* case: LETREC [] IN e ==> e */
272 mapOver(transBinds,bss); /* translate each group of bindings */
274 for (temp=root; nonNull(tl(bss)); bss=tl(bss)) {
275 fst(snd(temp)) = hd(bss);
276 snd(snd(temp)) = ap(LETREC,pair(NIL,e));
277 temp = snd(snd(temp));
279 fst(snd(temp)) = hd(bss);
284 /* --------------------------------------------------------------------------
285 * Translation of list comprehensions is based on the description in
286 * `The Implementation of Functional Programming Languages':
288 * [ e | qs ] ++ l => transComp e qs l
289 * transComp e [] l => e : l
290 * transComp e ((p<-xs):qs) l => LETREC _h [] = l
291 * _h (p:_xs) = transComp e qs (_h _xs)
292 * _h (_:_xs) = _h _xs --if p !failFree
294 * transComp e (b:qs) l => if b then transComp e qs l else l
295 * transComp e (decls:qs) l => LETREC decls IN transComp e qs l
296 * ------------------------------------------------------------------------*/
298 static Cell local transComp(e,qs,l) /* Translate [e | qs] ++ l */
307 case FROMQUAL : { Cell ld = NIL;
308 Cell hVar = inventVar();
309 Cell xsVar = inventVar();
311 if (!failFree(fst(snd(q))))
312 ld = cons(pair(singleton(
319 ld = cons(pair(singleton(
327 ld = cons(pair(singleton(nameNil),
332 pair(singleton(pair(hVar,
335 translate(snd(snd(q))))));
339 expandLetrec(ap(LETREC,
341 transComp(e,qs1,l))));
343 case BOOLQUAL : return ap(COND,
344 triple(translate(snd(q)),
350 return ap(ap(nameCons,e),l);
353 /* --------------------------------------------------------------------------
354 * Translation of monad comprehensions written using do-notation:
357 * do { p <- exp; qs } => LETREC _h p = do { qs }
358 * _h _ = fail m "match fails"
360 * do { LET decls; qs } => LETREC decls IN do { qs }
361 * do { IF guard; qs } => if guard then do { qs } else fail m "guard fails"
362 * do { e; qs } => LETREC _h _ = [ e | qs ] in bind m exp _h
365 * ------------------------------------------------------------------------*/
367 static Cell local transDo(m,e,qs) /* Translate do { qs ; e } */
376 case FROMQUAL : { Cell ld = NIL;
377 Cell hVar = inventVar();
379 if (!failFree(fst(snd(q)))) {
380 Cell str = mkStr(findText("match fails"));
381 ld = cons(pair(singleton(WILDCARD),
382 ap2(nameMFail,m,str)),
386 ld = cons(pair(singleton(fst(snd(q))),
391 pair(singleton(pair(hVar,ld)),
394 translate(snd(snd(q)))),
398 case DOQUAL : { Cell hVar = inventVar();
399 Cell ld = cons(pair(singleton(WILDCARD),
403 pair(singleton(pair(hVar,ld)),
411 expandLetrec(ap(LETREC,
415 case BOOLQUAL : return
417 triple(translate(snd(q)),
420 mkStr(findText("guard fails")))));
426 /* --------------------------------------------------------------------------
427 * Translation of named field construction and update:
429 * Construction is implemented using the following transformation:
431 * C{x1=e1, ..., xn=en} = C v1 ... vm
433 * vi = e1, if the ith component of C is labelled with x1
435 * = en, if the ith component of C is labelled with xn
436 * = undefined, otherwise
438 * Update is implemented using the following transformation:
440 * e{x1=e1, ..., xn=en}
441 * = let nv (C a1 ... am) v1 ... vn = C a1' .. am'
442 * nv (D b1 ... bk) v1 ... vn = D b1' .. bk
444 * nv _ v1 ... vn = error "failed update"
447 * nv, v1, ..., vn, a1, ..., am, b1, ..., bk, ... are new variables,
448 * C,D,... = { K | K is a constr fun s.t. {x1,...,xn} subset of sels(K)}
450 * ai' = v1, if the ith component of C is labelled with x1
452 * = vn, if the ith component of C is labelled with xn
456 * The error case may be omitted if C,D,... is an enumeration of all of the
457 * constructors for the datatype concerned. Strictly speaking, error case
458 * isn't needed at all -- the only benefit of including it is that the user
459 * will get a "failed update" message rather than a cryptic {v354 ...}.
460 * So, for now, we'll go with the second option!
462 * For the time being, code for each update operation is generated
463 * independently of any other updates. However, if updates are used
464 * frequently, then we might want to consider changing the implementation
465 * at a later stage to cache definitions of functions like nv above. This
466 * would create a shared library of update functions, indexed by a set of
467 * constructors {C,D,...}.
468 * ------------------------------------------------------------------------*/
470 static Cell local transConFlds(c,flds) /* Translate C{flds} */
474 Int m = name(c).arity;
477 e = ap(e,nameUndefined);
478 for (; nonNull(flds); flds=tl(flds)) {
480 for (i=m-sfunPos(fst(hd(flds)),c); i>0; i--)
482 arg(a) = translate(snd(hd(flds)));
487 static Cell local transUpdFlds(e,cs,flds)/* Translate e{flds} */
488 Cell e; /* (cs is corresp list of constrs) */
491 Cell nv = inventVar();
492 Cell body = ap(nv,translate(e));
497 for (; nonNull(fs); fs=tl(fs)) { /* body = nv e1 ... en */
498 Cell b = hd(fs); /* args = [v1, ..., vn] */
499 body = ap(body,translate(snd(b)));
500 args = cons(inventVar(),args);
503 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constructors to */
504 Cell c = hd(cs); /* build up list of alts. */
508 Int m = name(c).arity;
511 for (i=m; i>0; i--) { /* pat = C a1 ... am */
512 Cell a = inventVar(); /* rhs = C a1 ... am */
517 for (fs=flds; nonNull(fs); fs=tl(fs), as=tl(as)) {
518 Name s = fst(hd(fs)); /* Replace approp ai in rhs with */
519 Cell r = rhs; /* vars from [v1,...,vn] */
520 for (i=m-sfunPos(s,c); i>0; i--)
525 alts = cons(pair(cons(pat,args),rhs),alts);
527 return ap(LETREC,pair(singleton(pair(nv,alts)),body));
530 /* --------------------------------------------------------------------------
531 * Elimination of pattern bindings:
533 * The following code adopts the definition of failure free patterns as given
534 * in the Haskell 1.3 report; the term "irrefutable" is also used there for
535 * a subset of the failure free patterns described here, but has no useful
536 * role in this implementation. Basically speaking, the failure free patterns
537 * are: variable, wildcard, ~apat
538 * var@apat, if apat is failure free
539 * C apat1 ... apatn if C is a product constructor
540 * (i.e. an only constructor) and
541 * apat1,...,apatn are failure free
542 * Note that the last case automatically covers the case where C comes from
543 * a newtype construction.
544 * ------------------------------------------------------------------------*/
546 Bool failFree(pat) /* is pattern failure free? (do we need */
547 Cell pat; { /* a conformality check?) */
548 Cell c = getHead(pat);
551 case ASPAT : return failFree(snd(snd(pat)));
553 case NAME : if (!isCfun(c) || cfunOf(c)!=0)
555 /*intentional fall-thru*/
556 case TUPLE : for (; isAp(pat); pat=fun(pat))
557 if (!failFree(arg(pat)))
559 /*intentional fall-thru*/
564 case WILDCARD : return TRUE;
567 case EXT : return failFree(extField(pat)) &&
568 failFree(extRow(pat));
571 case CONFLDS : if (cfunOf(fst(snd(c)))==0) {
572 List fs = snd(snd(c));
573 for (; nonNull(fs); fs=tl(fs))
574 if (!failFree(snd(hd(fs))))
578 /*intentional fall-thru*/
579 default : return FALSE;
583 static Cell local refutePat(pat) /* find pattern to refute in conformality*/
584 Cell pat; { /* test with pat. */
585 /* e.g. refPat (x:y) == (_:_) */
586 /* refPat ~(x:y) == _ etc.. */
588 switch (whatIs(pat)) {
589 case ASPAT : return refutePat(snd(snd(pat)));
591 case FINLIST : { Cell ys = snd(pat);
593 for (; nonNull(ys); ys=tl(ys))
594 xs = ap(ap(nameCons,refutePat(hd(ys))),xs);
595 return revOnto(xs,nameNil);
598 case CONFLDS : { Cell ps = NIL;
599 Cell fs = snd(snd(pat));
600 for (; nonNull(fs); fs=tl(fs)) {
601 Cell p = refutePat(snd(hd(fs)));
602 ps = cons(pair(fst(hd(fs)),p),ps);
604 return pair(CONFLDS,pair(fst(snd(pat)),rev(ps)));
611 case LAZYPAT : return WILDCARD;
619 case NAME : return pat;
621 case AP : return refutePatAp(pat);
623 default : internal("refutePat");
624 return NIL; /*NOTREACHED*/
628 static Cell local refutePatAp(p) /* find pattern to refute in conformality*/
631 if (h==nameFromInt || h==nameFromInteger || h==nameFromDouble)
634 else if (whatIs(h)==ADDPAT)
635 return ap(fun(p),refutePat(arg(p)));
639 Cell pf = refutePat(extField(p));
640 Cell pr = refutePat(extRow(p));
641 return ap(ap(fun(fun(p)),pf),pr);
645 List as = getArgs(p);
646 mapOver(refutePat,as);
647 return applyToArgs(h,as);
651 static Cell local matchPat(pat) /* find pattern to match against */
652 Cell pat; { /* replaces parts of pattern that do not */
653 /* include variables with wildcards */
654 switch (whatIs(pat)) {
655 case ASPAT : { Cell p = matchPat(snd(snd(pat)));
656 return (p==WILDCARD) ? fst(snd(pat))
658 pair(fst(snd(pat)),p));
661 case FINLIST : { Cell ys = snd(pat);
663 for (; nonNull(ys); ys=tl(ys))
664 xs = cons(matchPat(hd(ys)),xs);
665 while (nonNull(xs) && hd(xs)==WILDCARD)
667 for (ys=nameNil; nonNull(xs); xs=tl(xs))
668 ys = ap(ap(nameCons,hd(xs)),ys);
672 case CONFLDS : { Cell ps = NIL;
673 Name c = fst(snd(pat));
674 Cell fs = snd(snd(pat));
676 for (; nonNull(fs); fs=tl(fs)) {
677 Cell p = matchPat(snd(hd(fs)));
678 ps = cons(pair(fst(hd(fs)),p),ps);
682 return avar ? pair(CONFLDS,pair(c,rev(ps)))
688 case DICTVAR : return pat;
690 case LAZYPAT : { Cell p = matchPat(snd(pat));
691 return (p==WILDCARD) ? WILDCARD : ap(LAZYPAT,p);
696 case CHARCELL : return WILDCARD;
700 case AP : { Cell h = getHead(pat);
701 if (h==nameFromInt ||
702 h==nameFromInteger || h==nameFromDouble)
705 else if (whatIs(h)==ADDPAT)
710 Cell pf = matchPat(extField(pat));
711 Cell pr = matchPat(extRow(pat));
712 return (pf==WILDCARD && pr==WILDCARD)
714 : ap(ap(fun(fun(pat)),pf),pr);
720 for (; isAp(pat); pat=fun(pat)) {
721 Cell p = matchPat(arg(pat));
726 return avar ? applyToArgs(pat,args)
731 default : internal("matchPat");
732 return NIL; /*NOTREACHED*/
736 #define addEqn(v,val,lds) cons(pair(v,singleton(pair(NIL,val))),lds)
738 static List local remPat(pat,expr,lds)
739 Cell pat; /* Produce list of definitions for eqn */
740 Cell expr; /* pat = expr, including a conformality */
741 List lds; { /* check if required. */
743 /* Conformality test (if required):
744 * pat = expr ==> nv = LETREC confCheck nv@pat = nv
746 * remPat1(pat,nv,.....);
749 if (!failFree(pat)) {
750 Cell confVar = inventVar();
751 Cell nv = inventVar();
752 Cell locfun = pair(confVar, /* confVar [([nv@refPat],nv)] */
753 singleton(pair(singleton(ap(ASPAT,
758 if (whatIs(expr)==GUARDED) { /* A spanner ... special case */
759 lds = addEqn(nv,expr,lds); /* for guarded pattern binding*/
764 if (whatIs(pat)==ASPAT) { /* avoid using new variable if*/
765 nv = fst(snd(pat)); /* a variable is already given*/
766 pat = snd(snd(pat)); /* by an as-pattern */
769 lds = addEqn(nv, /* nv = */
770 ap(LETREC,pair(singleton(locfun), /* LETREC [locfun] */
771 ap(confVar,expr))), /* IN confVar expr */
774 return remPat1(matchPat(pat),nv,lds);
777 return remPat1(matchPat(pat),expr,lds);
780 static List local remPat1(pat,expr,lds)
781 Cell pat; /* Add definitions for: pat = expr to */
782 Cell expr; /* list of local definitions in lds. */
784 Cell c = getHead(pat);
789 case CHARCELL : break;
791 case ASPAT : return remPat1(snd(snd(pat)), /* v@pat = expr */
793 addEqn(fst(snd(pat)),expr,lds));
795 case LAZYPAT : { Cell nv;
797 if (isVar(expr) || isName(expr))
801 lds = addEqn(nv,expr,lds);
804 return remPat(snd(pat),nv,lds);
808 case ADDPAT : return remPat1(arg(pat), /* n + k = expr */
811 mkInt(snd(fun(fun(pat))))),
816 case FINLIST : return remPat1(mkConsList(snd(pat)),expr,lds);
818 case CONFLDS : { Name h = fst(snd(pat));
819 Int m = name(h).arity;
821 List fs = snd(snd(pat));
825 for (; nonNull(fs); fs=tl(fs)) {
827 for (i=m-sfunPos(fst(hd(fs)),h); i>0; i--)
829 arg(r) = snd(hd(fs));
831 return remPat1(p,expr,lds);
834 case DICTVAR : /* shouldn't really occur */
835 assert(0); /* so let's test for it then! ADR */
837 case VAROPCELL : return addEqn(pat,expr,lds);
839 case NAME : if (c==nameFromInt || c==nameFromInteger
840 || c==nameFromDouble) {
842 arg(fun(pat)) = translate(arg(fun(pat)));
846 if (argCount==1 && isCfun(c) /* for newtype */
847 && cfunOf(c)==0 && name(c).defn==nameId)
848 return remPat1(arg(pat),expr,lds);
850 /* intentional fall-thru */
851 case TUPLE : { List ps = getArgs(pat);
857 if (isVar(expr) || isName(expr))
861 lds = addEqn(nv,expr,lds);
864 sel = ap(ap(nameSel,c),nv);
865 for (i=1; nonNull(ps); ++i, ps=tl(ps))
866 lds = remPat1(hd(ps),
874 case EXT : { Cell nv = inventVar();
876 = translate(arg(fun(fun(pat))));
882 lds = remPat1(extField(pat),ap(nameFst,nv),lds);
883 lds = remPat1(extRow(pat),ap(nameSnd,nv),lds);
888 default : internal("remPat1");
894 /* --------------------------------------------------------------------------
895 * Eliminate pattern matching in function definitions -- pattern matching
898 * The original Gofer/Hugs pattern matching compiler was based on Wadler's
899 * algorithms described in `Implementation of functional programming
900 * languages'. That should still provide a good starting point for anyone
901 * wanting to understand this part of the system. However, the original
902 * algorithm has been generalized and restructured in order to implement
903 * new features added in Haskell 1.3.
905 * During the translation, in preparation for later stages of compilation,
906 * all local and bound variables are replaced by suitable offsets, and
907 * locally defined function symbols are given new names (which will
908 * eventually be their names when lifted to make top level definitions).
909 * ------------------------------------------------------------------------*/
911 static Offset freeBegin; /* only variables with offset <= freeBegin are of */
912 static List freeVars; /* interest as `free' variables */
913 static List freeFuns; /* List of `free' local functions */
915 static Cell local pmcTerm(co,sc,e) /* apply pattern matching compiler */
916 Int co; /* co = current offset */
917 List sc; /* sc = scope */
918 Cell e; { /* e = expr to transform */
920 case GUARDED : map2Over(pmcPair,co,sc,snd(e));
923 case LETREC : pmcLetrec(co,sc,snd(e));
928 case DICTVAR : return pmcVar(sc,textOf(e));
930 case COND : return ap(COND,pmcTriple(co,sc,snd(e)));
932 case AP : return pmcPair(co,sc,e);
946 case STRCELL : break;
948 default : internal("pmcTerm");
954 static Cell local pmcPair(co,sc,pr) /* apply pattern matching compiler */
955 Int co; /* to a pair of exprs */
958 return pair(pmcTerm(co,sc,fst(pr)),
959 pmcTerm(co,sc,snd(pr)));
962 static Cell local pmcTriple(co,sc,tr) /* apply pattern matching compiler */
963 Int co; /* to a triple of exprs */
966 return triple(pmcTerm(co,sc,fst3(tr)),
967 pmcTerm(co,sc,snd3(tr)),
968 pmcTerm(co,sc,thd3(tr)));
971 static Cell local pmcVar(sc,t) /* find translation of variable */
972 List sc; /* in current scope */
977 for (xs=sc; nonNull(xs); xs=tl(xs)) {
979 if (t==textOf(fst(x))) {
980 if (isOffset(snd(x))) { /* local variable ... */
981 if (snd(x)<=freeBegin && !cellIsMember(snd(x),freeVars))
982 freeVars = cons(snd(x),freeVars);
985 else { /* local function ... */
986 if (!cellIsMember(snd(x),freeFuns))
987 freeFuns = cons(snd(x),freeFuns);
993 if (isNull(n=findName(t))) /* Lookup global name - the only way*/
994 n = newName(t,currentName); /* this (should be able to happen) */
995 /* is with new global var introduced*/
996 /* after type check; e.g. remPat1 */
1000 static Void local pmcLetrec(co,sc,e) /* apply pattern matching compiler */
1001 Int co; /* to LETREC, splitting decls into */
1002 List sc; /* two sections */
1004 List fs = NIL; /* local function definitions */
1005 List vs = NIL; /* local variable definitions */
1008 for (ds=fst(e); nonNull(ds); ds=tl(ds)) { /* Split decls into two */
1009 Cell v = fst(hd(ds));
1010 Int arity = length(fst(hd(snd(hd(ds)))));
1012 if (arity==0) { /* Variable declaration */
1013 vs = cons(snd(hd(ds)),vs);
1014 sc = cons(pair(v,mkOffset(++co)),sc);
1016 else { /* Function declaration */
1017 fs = cons(triple(inventVar(),mkInt(arity),snd(hd(ds))),fs);
1018 sc = cons(pair(v,hd(fs)),sc);
1021 vs = rev(vs); /* Put declaration lists back in */
1022 fs = rev(fs); /* original order */
1023 fst(e) = pair(vs,fs); /* Store declaration lists */
1024 map2Over(pmcVarDef,co,sc,vs); /* Translate variable definitions */
1025 map2Proc(pmcFunDef,co,sc,fs); /* Translate function definitions */
1026 snd(e) = pmcTerm(co,sc,snd(e)); /* Translate LETREC body */
1027 freeFuns = diffList(freeFuns,fs); /* Delete any `freeFuns' bound in fs*/
1030 static Cell local pmcVarDef(co,sc,vd) /* apply pattern matching compiler */
1031 Int co; /* to variable definition */
1033 List vd; { /* vd :: [ ([], rhs) ] */
1034 Cell d = snd(hd(vd));
1035 if (nonNull(tl(vd)) && canFail(d))
1036 return ap(FATBAR,pair(pmcTerm(co,sc,d),
1037 pmcVarDef(co,sc,tl(vd))));
1038 return pmcTerm(co,sc,d);
1041 static Void local pmcFunDef(co,sc,fd) /* apply pattern matching compiler */
1042 Int co; /* to function definition */
1044 Triple fd; { /* fd :: (Var, Arity, [Alt]) */
1045 Offset saveFreeBegin = freeBegin;
1046 List saveFreeVars = freeVars;
1047 List saveFreeFuns = freeFuns;
1048 Int arity = intOf(snd3(fd));
1049 Cell temp = altsMatch(co+1,arity,sc,thd3(fd));
1052 freeBegin = mkOffset(co);
1055 temp = match(co+arity,temp);
1056 thd3(fd) = triple(freeVars,freeFuns,temp);
1058 for (xs=freeVars; nonNull(xs); xs=tl(xs))
1059 if (hd(xs)<=saveFreeBegin && !cellIsMember(hd(xs),saveFreeVars))
1060 saveFreeVars = cons(hd(xs),saveFreeVars);
1062 for (xs=freeFuns; nonNull(xs); xs=tl(xs))
1063 if (!cellIsMember(hd(xs),saveFreeFuns))
1064 saveFreeFuns = cons(hd(xs),saveFreeFuns);
1066 freeBegin = saveFreeBegin;
1067 freeVars = saveFreeVars;
1068 freeFuns = saveFreeFuns;
1071 /* ---------------------------------------------------------------------------
1072 * Main part of pattern matching compiler: convert [Alt] to case constructs
1074 * This section of Hugs has been almost completely rewritten to be more
1075 * general, in particular, to allow pattern matching in orders other than the
1076 * strictly left-to-right approach of the previous version. This is needed
1077 * for the implementation of the so-called Haskell 1.3 `record' syntax.
1079 * At each stage, the different branches for the cases to be considered
1080 * are represented by a list of values of type:
1081 * Match ::= { maPats :: [Pat], patterns to match
1082 * maOffs :: [Offs], offsets of corresponding values
1083 * maSc :: Scope, mapping from vars to offsets
1084 * maRhs :: Rhs } right hand side
1085 * [Implementation uses nested pairs, ((pats,offs),(sc,rhs)).]
1087 * The Scope component has type:
1088 * Scope ::= [(Var,Expr)]
1089 * and provides a mapping from variable names to offsets used in the matching
1092 * Matches can be normalized by reducing them to a form in which the list
1093 * of patterns is empty (in which case the match itself is described as an
1094 * empty match), or in which the list is non-empty and the first pattern is
1095 * one that requires either a CASE or NUMCASE (or EXTCASE) to decompose.
1096 * ------------------------------------------------------------------------*/
1098 #define mkMatch(ps,os,sc,r) pair(pair(ps,os),pair(sc,r))
1099 #define maPats(ma) fst(fst(ma))
1100 #define maOffs(ma) snd(fst(ma))
1101 #define maSc(ma) fst(snd(ma))
1102 #define maRhs(ma) snd(snd(ma))
1103 #define extSc(v,o,ma) maSc(ma) = cons(pair(v,o),maSc(ma))
1105 static List local altsMatch(co,n,sc,as) /* Make a list of matches from list*/
1106 Int co; /* of Alts, with initial offsets */
1107 Int n; /* reverse (take n [co..]) */
1113 us = cons(mkOffset(co++),us);
1114 for (; nonNull(as); as=tl(as)) /* Each Alt is ([Pat], Rhs) */
1115 mas = cons(mkMatch(fst(hd(as)),us,sc,snd(hd(as))),mas);
1119 static Cell local match(co,mas) /* Generate case statement for Matches mas */
1120 Int co; /* at current offset co */
1121 List mas; { /* N.B. Assumes nonNull(mas). */
1122 Cell srhs = NIL; /* Rhs for selected matches */
1123 List smas = mas; /* List of selected matches */
1127 if (emptyMatch(hd(smas))) { /* The case for empty matches: */
1128 while (nonNull(mas) && emptyMatch(hd(mas))) {
1129 List temp = tl(mas);
1134 srhs = joinMas(co,rev(smas));
1136 else { /* Non-empty match */
1137 Int o = offsetOf(hd(maOffs(hd(smas))));
1138 Cell d = maDiscr(hd(smas));
1139 if (isNumDiscr(d)) { /* Numeric match */
1140 Int da = discrArity(d);
1141 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1142 while (nonNull(mas) && !emptyMatch(hd(mas))
1143 && o==offsetOf(hd(maOffs(hd(mas))))
1144 && isNumDiscr(d=maDiscr(hd(mas)))
1145 && eqNumDiscr(d,d1)) {
1146 List temp = tl(mas);
1152 map2Proc(advance,co,da,smas);
1153 srhs = ap(NUMCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1156 else if (isExtDiscr(d)) { /* Record match */
1157 Int da = discrArity(d);
1158 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1159 while (nonNull(mas) && !emptyMatch(hd(mas))
1160 && o==offsetOf(hd(maOffs(hd(mas))))
1161 && isExtDiscr(d=maDiscr(hd(mas)))
1162 && eqExtDiscr(d,d1)) {
1163 List temp = tl(mas);
1169 map2Proc(advance,co,da,smas);
1170 srhs = ap(EXTCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1173 else { /* Constructor match */
1174 List tab = addConTable(d,hd(smas),NIL);
1176 while (nonNull(mas) && !emptyMatch(hd(mas))
1177 && o==offsetOf(hd(maOffs(hd(mas))))
1178 && !isNumDiscr(d=maDiscr(hd(mas)))) {
1179 tab = addConTable(d,hd(mas),tab);
1182 for (tab=rev(tab); nonNull(tab); tab=tl(tab)) {
1184 smas = snd(hd(tab));
1186 map2Proc(advance,co,da,smas);
1187 srhs = cons(pair(d,match(co+da,smas)),srhs);
1189 srhs = ap(CASE,pair(mkOffset(o),srhs));
1192 return nonNull(mas) ? ap(FATBAR,pair(srhs,match(co,mas))) : srhs;
1195 static Cell local joinMas(co,mas) /* Combine list of matches into rhs*/
1196 Int co; /* using FATBARs as necessary */
1197 List mas; { /* Non-empty list of empty matches */
1199 Cell rhs = pmcTerm(co,maSc(ma),maRhs(ma));
1200 if (nonNull(tl(mas)) && canFail(rhs))
1201 return ap(FATBAR,pair(rhs,joinMas(co,tl(mas))));
1206 static Bool local canFail(rhs) /* Determine if expression (as rhs) */
1207 Cell rhs; { /* might ever be able to fail */
1208 switch (whatIs(rhs)) {
1209 case LETREC : return canFail(snd(snd(rhs)));
1210 case GUARDED : return TRUE; /* could get more sophisticated ..? */
1211 default : return FALSE;
1215 /* type Table a b = [(a, [b])]
1217 * addTable :: a -> b -> Table a b -> Table a b
1218 * addTable x y [] = [(x,[y])]
1219 * addTable x y (z@(n,sws):zs)
1220 * | n == x = (n,sws++[y]):zs
1221 * | otherwise = (n,sws):addTable x y zs
1224 static List local addConTable(x,y,tab) /* add element (x,y) to table */
1228 return singleton(pair(x,singleton(y)));
1229 else if (fst(hd(tab))==x)
1230 snd(hd(tab)) = appendOnto(snd(hd(tab)),singleton(y));
1232 tl(tab) = addConTable(x,y,tl(tab));
1237 static Void local advance(co,a,ma) /* Advance non-empty match by */
1238 Int co; /* processing head pattern */
1239 Int a; /* discriminator arity */
1241 Cell p = hd(maPats(ma));
1242 List ps = tl(maPats(ma));
1243 List us = tl(maOffs(ma));
1244 if (whatIs(p)==CONFLDS) { /* Special case for record syntax */
1245 Name c = fst(snd(p));
1246 List fs = snd(snd(p));
1249 for (; nonNull(fs); fs=tl(fs)) {
1250 vs = cons(mkOffset(co+a+1-sfunPos(fst(hd(fs)),c)),vs);
1251 qs = cons(snd(hd(fs)),qs);
1253 ps = revOnto(qs,ps);
1254 us = revOnto(vs,us);
1256 else /* Normally just spool off patterns*/
1257 for (; a>0; --a) { /* and corresponding offsets ... */
1258 us = cons(mkOffset(++co),us);
1259 ps = cons(arg(p),ps);
1267 /* --------------------------------------------------------------------------
1268 * Normalize and test for empty match:
1269 * ------------------------------------------------------------------------*/
1271 static Bool local emptyMatch(ma)/* Normalize and test to see if a given */
1272 Cell ma; { /* match, ma, is empty. */
1274 while (nonNull(maPats(ma))) {
1276 tidyHd: switch (whatIs(p=hd(maPats(ma)))) {
1277 case LAZYPAT : { Cell nv = inventVar();
1278 maRhs(ma) = ap(LETREC,
1279 pair(remPat(snd(p),nv,NIL),
1283 /* intentional fall-thru */
1286 case DICTVAR : extSc(p,hd(maOffs(ma)),ma);
1287 case WILDCARD : maPats(ma) = tl(maPats(ma));
1288 maOffs(ma) = tl(maOffs(ma));
1291 /* So-called "as-patterns"are really just pattern intersections:
1292 * (p1@p2:ps, o:os, sc, e) ==> (p1:p2:ps, o:o:os, sc, e)
1293 * (But the input grammar probably doesn't let us take
1294 * advantage of this, so we stick with the special case
1295 * when p1 is a variable.)
1297 case ASPAT : extSc(fst(snd(p)),hd(maOffs(ma)),ma);
1298 hd(maPats(ma)) = snd(snd(p));
1301 case FINLIST : hd(maPats(ma)) = mkConsList(snd(p));
1304 case STRCELL : { String s = textToStr(textOf(p));
1305 for (p=NIL; *s!='\0'; ++s) {
1306 if (*s!='\\' || *++s=='\\')
1307 p = ap(consChar(*s),p);
1309 p = ap(consChar('\0'),p);
1311 hd(maPats(ma)) = revOnto(p,nameNil);
1315 case AP : if (isName(fun(p)) && isCfun(fun(p))
1316 && cfunOf(fun(p))==0
1317 && name(fun(p)).defn==nameId) {
1318 hd(maPats(ma)) = arg(p);
1321 /* intentional fall-thru */
1327 default : internal("emptyMatch");
1333 /* --------------------------------------------------------------------------
1335 * ------------------------------------------------------------------------*/
1337 static Cell local maDiscr(ma) /* Get the discriminator for a non-empty */
1338 Cell ma; { /* match, ma. */
1339 Cell p = hd(maPats(ma));
1340 Cell h = getHead(p);
1341 switch (whatIs(h)) {
1342 case CONFLDS : return fst(snd(p));
1344 case ADDPAT : arg(fun(p)) = translate(arg(fun(p)));
1348 case EXT : h = fun(fun(p));
1349 arg(h) = translate(arg(h));
1352 case NAME : if (h==nameFromInt || h==nameFromInteger
1353 || h==nameFromDouble) {
1355 arg(fun(p)) = translate(arg(fun(p)));
1362 static Bool local isNumDiscr(d) /* TRUE => numeric discriminator */
1364 switch (whatIs(d)) {
1367 case CHARCELL : return FALSE;
1370 case AP : return !isExt(fun(d));
1372 case AP : return TRUE; /* must be a literal or (n+k) */
1375 internal("isNumDiscr");
1376 return 0;/*NOTREACHED*/
1379 Int discrArity(d) /* Find arity of discriminator */
1381 switch (whatIs(d)) {
1382 case NAME : return name(d).arity;
1383 case TUPLE : return tupleOf(d);
1384 case CHARCELL : return 0;
1386 case AP : switch (whatIs(fun(d))) {
1388 case ADDPAT : return 1;
1390 case EXT : return 2;
1395 case AP : return (whatIs(fun(d))==ADDPAT) ? 1 : 0;
1397 case AP : return 0; /* must be an Int or Float lit */
1401 internal("discrArity");
1402 return 0;/*NOTREACHED*/
1405 static Bool local eqNumDiscr(d1,d2) /* Determine whether two numeric */
1406 Cell d1, d2; { /* descriptors have same value */
1408 if (whatIs(fun(d1))==ADDPAT)
1409 return whatIs(fun(d2))==ADDPAT && snd(fun(d1))==snd(fun(d2));
1412 return isInt(arg(d2)) && intOf(arg(d1))==intOf(arg(d2));
1413 if (isFloat(arg(d1)))
1414 return isFloat(arg(d2)) && floatOf(arg(d1))==floatOf(arg(d2));
1415 internal("eqNumDiscr");
1416 return FALSE;/*NOTREACHED*/
1420 static Bool local isExtDiscr(d) /* Test of extension discriminator */
1422 return isAp(d) && isExt(fun(d));
1425 static Bool local eqExtDiscr(d1,d2) /* Determine whether two extension */
1426 Cell d1, d2; { /* discriminators have same label */
1427 return fun(d1)==fun(d2);
1431 /*-------------------------------------------------------------------------*/
1435 /* --------------------------------------------------------------------------
1437 * ------------------------------------------------------------------------*/
1439 static Void local stgCGBinds( List );
1441 static Void local stgCGBinds(binds)
1446 /* --------------------------------------------------------------------------
1447 * Main entry points to compiler:
1448 * ------------------------------------------------------------------------*/
1450 static List addGlobals( List binds )
1452 /* stgGlobals = list of top-level STG binds */
1453 for(;nonNull(stgGlobals);stgGlobals=tl(stgGlobals)) {
1454 StgVar bind = snd(hd(stgGlobals));
1455 if (nonNull(stgVarBody(bind))) {
1456 binds = cons(bind,binds);
1462 typedef void (*sighandler_t)(int);
1463 void eval_ctrlbrk ( int dunnowhat )
1466 /* reinstall the signal handler so that further interrupts which
1467 happen before the thread can return to the scheduler, lead back
1468 here rather than invoking the previous break handler. */
1469 signal(SIGINT, eval_ctrlbrk);
1472 Void evalExp() { /* compile and run input expression */
1473 /* ToDo: this name (and other names generated during pattern match?)
1474 * get inserted in the symbol table but never get removed.
1476 Name n = newName(inventText(),NIL);
1478 StgVar v = mkStgVar(NIL,NIL);
1481 e = pmcTerm(0,NIL,translate(inputExpr));
1484 stgCGBinds(addGlobals(singleton(v)));
1486 /* Run thread (and any other runnable threads) */
1488 /* Re-initialise the scheduler - ToDo: do I need this? */
1490 #ifdef CRUDE_PROFILING
1494 /* ToDo: don't really initScheduler every time. fix */
1496 HaskellObj result; /* ignored */
1497 sighandler_t old_ctrlbrk;
1498 SchedulerStatus status;
1499 Bool doRevertCAFs = FALSE;
1500 old_ctrlbrk = signal(SIGINT, eval_ctrlbrk);
1501 ASSERT(old_ctrlbrk != SIG_ERR);
1502 status = rts_eval_(closureOfVar(v),10000,&result);
1503 signal(SIGINT,old_ctrlbrk);
1508 case AllBlocked: /* I don't understand the distinction - ADR */
1509 printf("{Deadlock}");
1510 if (doRevertCAFs) RevertCAFs();
1513 printf("{Interrupted}");
1514 if (doRevertCAFs) RevertCAFs();
1517 printf("{Interrupted or Killed}");
1518 if (doRevertCAFs) RevertCAFs();
1521 if (doRevertCAFs) RevertCAFs();
1524 internal("evalExp: Unrecognised SchedulerStatus");
1529 #ifdef CRUDE_PROFILING
1536 static List local addStgVar( List binds, Pair bind )
1538 StgVar nv = mkStgVar(NIL,NIL);
1539 Text t = textOf(fst(bind));
1540 Name n = findName(t);
1542 if (isNull(n)) { /* Lookup global name - the only way*/
1543 n = newName(t,NIL); /* this (should be able to happen) */
1544 } /* is with new global var introduced*/
1545 /* after type check; e.g. remPat1 */
1546 name(n).stgVar = nv;
1547 return cons(nv,binds);
1551 Void compileDefns() { /* compile script definitions */
1552 Target t = length(valDefns) + length(genDefns) + length(selDefns);
1556 /* a nasty hack. But I don't know an easier way to make */
1557 /* these things appear. */
1558 if (lastModule() == modulePrelude) {
1559 implementCfun ( nameCons, NIL );
1560 implementCfun ( nameNil, NIL );
1561 implementCfun ( nameUnit, NIL );
1567 for(vs=genDefns; nonNull(vs); vs=tl(vs)) {
1569 StgVar nv = mkStgVar(NIL,NIL);
1571 name(n).stgVar = nv;
1572 binds = cons(nv,binds);
1574 for(vss=selDefns; nonNull(vss); vss=tl(vss)) {
1575 for(vs=hd(vss); nonNull(vs); vs=tl(vs)) {
1578 StgVar nv = mkStgVar(NIL,NIL);
1580 name(n).stgVar = nv;
1581 binds = cons(nv,binds);
1586 setGoal("Translating",t);
1587 /* do valDefns before everything else so that all stgVar's get added. */
1588 for (; nonNull(valDefns); valDefns=tl(valDefns)) {
1589 hd(valDefns) = transBinds(hd(valDefns));
1590 mapAccum(addStgVar,binds,hd(valDefns));
1591 mapProc(compileGlobalFunction,hd(valDefns));
1594 for (; nonNull(genDefns); genDefns=tl(genDefns)) {
1595 compileGenFunction(hd(genDefns));
1598 for (; nonNull(selDefns); selDefns=tl(selDefns)) {
1599 mapOver(compileSelFunction,hd(selDefns));
1603 binds = addGlobals(binds);
1605 #if USE_HUGS_OPTIMIZER
1608 setGoal("Simplifying",t);
1609 optimiseTopBinds(binds);
1613 setGoal("Generating code",t);
1619 static Void local compileGlobalFunction(bind)
1621 Name n = findName(textOf(fst(bind)));
1622 List defs = snd(bind);
1623 Int arity = length(fst(hd(defs)));
1626 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1629 static Void local compileGenFunction(n) /* Produce code for internally */
1630 Name n; { /* generated function */
1631 List defs = name(n).defn;
1632 Int arity = length(fst(hd(defs)));
1635 mapProc(transAlt,defs);
1636 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1640 static Name local compileSelFunction(p) /* Produce code for selector func */
1641 Pair p; { /* Should be merged with genDefns, */
1642 Name s = fst(p); /* but the name(_).defn field is */
1643 List defs = snd(p); /* already used for other purposes */
1644 Int arity = length(fst(hd(defs))); /* in selector functions. */
1647 mapProc(transAlt,defs);
1648 stgDefn(s,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1653 /* --------------------------------------------------------------------------
1655 * ------------------------------------------------------------------------*/
1661 case RESET : freeVars = NIL;
1663 freeBegin = mkOffset(0);
1670 case MARK : mark(freeVars);
1677 /*-------------------------------------------------------------------------*/