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: 2000/03/10 14:53:00 $
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 printf ( "translate: " );print(e,100);printf("\n");
101 case LETREC : snd(snd(e)) = translate(snd(snd(e)));
102 return expandLetrec(e);
104 case COND : transTriple(snd(e));
107 case AP : fst(e) = translate(fst(e));
109 if (fst(e)==nameId || fst(e)==nameInd)
110 return translate(snd(e));
111 if (isName(fst(e)) &&
114 return translate(snd(e));
116 snd(e) = translate(snd(e));
119 case NAME : if (e==nameOtherwise)
122 if (isName(name(e).defn))
124 if (isPair(name(e).defn))
125 return snd(name(e).defn);
130 case RECSEL : return nameRecSel;
142 case CHARCELL : return e;
144 case IPVAR : return nameId;
146 case FINLIST : mapOver(translate,snd(e));
147 return mkConsList(snd(e));
149 case DOCOMP : { Cell m = translate(fst(snd(e)));
150 Cell r = translate(fst(snd(snd(e))));
151 return transDo(m,r,snd(snd(snd(e))));
154 case MONADCOMP : { Cell m = translate(fst(snd(e)));
155 Cell r = translate(fst(snd(snd(e))));
156 Cell qs = snd(snd(snd(e)));
157 if (m == nameListMonad)
158 return transComp(r,qs,nameNil);
161 r = ap(ap(nameReturn,m),r);
162 return transDo(m,r,qs);
164 internal("translate: monad comps");
169 case CONFLDS : return transConFlds(fst(snd(e)),snd(snd(e)));
171 case UPDFLDS : return transUpdFlds(fst3(snd(e)),
175 case CASE : { Cell nv = inventVar();
176 mapProc(transCase,snd(snd(e)));
178 pair(singleton(pair(nv,snd(snd(e)))),
179 ap(nv,translate(fst(snd(e))))));
182 case LAMBDA : { Cell nv = inventVar();
191 default : fprintf(stderr, "stuff=%d\n",whatIs(e));
192 internal("translate");
197 static Void local transPair(pr) /* Translate each component in a */
198 Pair pr; { /* pair of expressions. */
199 fst(pr) = translate(fst(pr));
200 snd(pr) = translate(snd(pr));
203 static Void local transTriple(tr) /* Translate each component in a */
204 Triple tr; { /* triple of expressions. */
205 fst3(tr) = translate(fst3(tr));
206 snd3(tr) = translate(snd3(tr));
207 thd3(tr) = translate(thd3(tr));
210 static Void local transAlt(e) /* Translate alt: */
211 Cell e; { /* ([Pat], Rhs) ==> ([Pat], Rhs') */
213 printf ( "transAlt: " );print(snd(e),100);printf("\n");
215 snd(e) = transRhs(snd(e));
218 static Void local transCase(c) /* Translate case: */
219 Cell c; { /* (Pat, Rhs) ==> ([Pat], Rhs') */
220 fst(c) = singleton(fst(c));
221 snd(c) = transRhs(snd(c));
224 static List local transBinds(bs) /* Translate list of bindings: */
225 List bs; { /* eliminating pattern matching on */
226 List newBinds = NIL; /* lhs of bindings. */
227 for (; nonNull(bs); bs=tl(bs)) {
229 Cell v = fst(hd(bs));
230 while (isAp(v) && fst(v) == nameInd)
235 if (isVar(fst(hd(bs)))) {
237 mapProc(transAlt,snd(hd(bs)));
238 newBinds = cons(hd(bs),newBinds);
241 newBinds = remPat(fst(snd(hd(bs))),
242 snd(snd(hd(bs)))=transRhs(snd(snd(hd(bs)))),
248 static Cell local transRhs(rhs) /* Translate rhs: removing line nos */
250 switch (whatIs(rhs)) {
251 case LETREC : snd(snd(rhs)) = transRhs(snd(snd(rhs)));
252 return expandLetrec(rhs);
254 case GUARDED : mapOver(snd,snd(rhs)); /* discard line number */
255 mapProc(transPair,snd(rhs));
258 default : return translate(snd(rhs)); /* discard line number */
262 static Cell local mkConsList(es) /* Construct expression for list es */
263 List es; { /* using nameNil and nameCons */
267 return ap(ap(nameCons,hd(es)),mkConsList(tl(es)));
270 static Cell local expandLetrec(root) /* translate LETREC with list of */
271 Cell root; { /* groups of bindings (from depend. */
272 Cell e = snd(snd(root)); /* analysis) to use nested LETRECs */
273 List bss = fst(snd(root));
276 if (isNull(bss)) /* should never happen, but just in */
277 return e; /* case: LETREC [] IN e ==> e */
279 mapOver(transBinds,bss); /* translate each group of bindings */
281 for (temp=root; nonNull(tl(bss)); bss=tl(bss)) {
282 fst(snd(temp)) = hd(bss);
283 snd(snd(temp)) = ap(LETREC,pair(NIL,e));
284 temp = snd(snd(temp));
286 fst(snd(temp)) = hd(bss);
291 /* --------------------------------------------------------------------------
292 * Translation of list comprehensions is based on the description in
293 * `The Implementation of Functional Programming Languages':
295 * [ e | qs ] ++ l => transComp e qs l
296 * transComp e [] l => e : l
297 * transComp e ((p<-xs):qs) l => LETREC _h [] = l
298 * _h (p:_xs) = transComp e qs (_h _xs)
299 * _h (_:_xs) = _h _xs --if p !failFree
301 * transComp e (b:qs) l => if b then transComp e qs l else l
302 * transComp e (decls:qs) l => LETREC decls IN transComp e qs l
303 * ------------------------------------------------------------------------*/
305 static Cell local transComp(e,qs,l) /* Translate [e | qs] ++ l */
314 case FROMQUAL : { Cell ld = NIL;
315 Cell hVar = inventVar();
316 Cell xsVar = inventVar();
318 if (!failFree(fst(snd(q))))
319 ld = cons(pair(singleton(
326 ld = cons(pair(singleton(
334 ld = cons(pair(singleton(nameNil),
339 pair(singleton(pair(hVar,
342 translate(snd(snd(q))))));
346 expandLetrec(ap(LETREC,
348 transComp(e,qs1,l))));
350 case BOOLQUAL : return ap(COND,
351 triple(translate(snd(q)),
357 return ap(ap(nameCons,e),l);
360 /* --------------------------------------------------------------------------
361 * Translation of monad comprehensions written using do-notation:
364 * do { p <- exp; qs } => LETREC _h p = do { qs }
365 * _h _ = fail m "match fails"
367 * do { LET decls; qs } => LETREC decls IN do { qs }
368 * do { IF guard; qs } => if guard then do { qs } else fail m "guard fails"
369 * do { e; qs } => LETREC _h _ = [ e | qs ] in bind m exp _h
372 * ------------------------------------------------------------------------*/
374 static Cell local transDo(m,e,qs) /* Translate do { qs ; e } */
383 case FROMQUAL : { Cell ld = NIL;
384 Cell hVar = inventVar();
386 if (!failFree(fst(snd(q)))) {
387 Cell str = mkStr(findText("match fails"));
388 ld = cons(pair(singleton(WILDCARD),
389 ap2(nameMFail,m,str)),
393 ld = cons(pair(singleton(fst(snd(q))),
398 pair(singleton(pair(hVar,ld)),
401 translate(snd(snd(q)))),
405 case DOQUAL : { Cell hVar = inventVar();
406 Cell ld = cons(pair(singleton(WILDCARD),
410 pair(singleton(pair(hVar,ld)),
418 expandLetrec(ap(LETREC,
422 case BOOLQUAL : return
424 triple(translate(snd(q)),
427 mkStr(findText("guard fails")))));
433 /* --------------------------------------------------------------------------
434 * Translation of named field construction and update:
436 * Construction is implemented using the following transformation:
438 * C{x1=e1, ..., xn=en} = C v1 ... vm
440 * vi = e1, if the ith component of C is labelled with x1
442 * = en, if the ith component of C is labelled with xn
443 * = undefined, otherwise
445 * Update is implemented using the following transformation:
447 * e{x1=e1, ..., xn=en}
448 * = let nv (C a1 ... am) v1 ... vn = C a1' .. am'
449 * nv (D b1 ... bk) v1 ... vn = D b1' .. bk
451 * nv _ v1 ... vn = error "failed update"
454 * nv, v1, ..., vn, a1, ..., am, b1, ..., bk, ... are new variables,
455 * C,D,... = { K | K is a constr fun s.t. {x1,...,xn} subset of sels(K)}
457 * ai' = v1, if the ith component of C is labelled with x1
459 * = vn, if the ith component of C is labelled with xn
463 * The error case may be omitted if C,D,... is an enumeration of all of the
464 * constructors for the datatype concerned. Strictly speaking, error case
465 * isn't needed at all -- the only benefit of including it is that the user
466 * will get a "failed update" message rather than a cryptic {v354 ...}.
467 * So, for now, we'll go with the second option!
469 * For the time being, code for each update operation is generated
470 * independently of any other updates. However, if updates are used
471 * frequently, then we might want to consider changing the implementation
472 * at a later stage to cache definitions of functions like nv above. This
473 * would create a shared library of update functions, indexed by a set of
474 * constructors {C,D,...}.
475 * ------------------------------------------------------------------------*/
477 static Cell local transConFlds(c,flds) /* Translate C{flds} */
481 Int m = name(c).arity;
484 e = ap(e,nameUndefined);
485 for (; nonNull(flds); flds=tl(flds)) {
487 for (i=m-sfunPos(fst(hd(flds)),c); i>0; i--)
489 arg(a) = translate(snd(hd(flds)));
494 static Cell local transUpdFlds(e,cs,flds)/* Translate e{flds} */
495 Cell e; /* (cs is corresp list of constrs) */
498 Cell nv = inventVar();
499 Cell body = ap(nv,translate(e));
504 for (; nonNull(fs); fs=tl(fs)) { /* body = nv e1 ... en */
505 Cell b = hd(fs); /* args = [v1, ..., vn] */
506 body = ap(body,translate(snd(b)));
507 args = cons(inventVar(),args);
510 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constructors to */
511 Cell c = hd(cs); /* build up list of alts. */
515 Int m = name(c).arity;
518 for (i=m; i>0; i--) { /* pat = C a1 ... am */
519 Cell a = inventVar(); /* rhs = C a1 ... am */
524 for (fs=flds; nonNull(fs); fs=tl(fs), as=tl(as)) {
525 Name s = fst(hd(fs)); /* Replace approp ai in rhs with */
526 Cell r = rhs; /* vars from [v1,...,vn] */
527 for (i=m-sfunPos(s,c); i>0; i--)
532 alts = cons(pair(cons(pat,args),rhs),alts);
534 return ap(LETREC,pair(singleton(pair(nv,alts)),body));
537 /* --------------------------------------------------------------------------
538 * Elimination of pattern bindings:
540 * The following code adopts the definition of failure free patterns as given
541 * in the Haskell 1.3 report; the term "irrefutable" is also used there for
542 * a subset of the failure free patterns described here, but has no useful
543 * role in this implementation. Basically speaking, the failure free patterns
544 * are: variable, wildcard, ~apat
545 * var@apat, if apat is failure free
546 * C apat1 ... apatn if C is a product constructor
547 * (i.e. an only constructor) and
548 * apat1,...,apatn are failure free
549 * Note that the last case automatically covers the case where C comes from
550 * a newtype construction.
551 * ------------------------------------------------------------------------*/
553 Bool failFree(pat) /* is pattern failure free? (do we need */
554 Cell pat; { /* a conformality check?) */
555 Cell c = getHead(pat);
558 case ASPAT : return failFree(snd(snd(pat)));
560 case NAME : if (!isCfun(c) || cfunOf(c)!=0)
562 /*intentional fall-thru*/
563 case TUPLE : for (; isAp(pat); pat=fun(pat))
564 if (!failFree(arg(pat)))
566 /*intentional fall-thru*/
571 case WILDCARD : return TRUE;
574 case EXT : return failFree(extField(pat)) &&
575 failFree(extRow(pat));
578 case CONFLDS : if (cfunOf(fst(snd(c)))==0) {
579 List fs = snd(snd(c));
580 for (; nonNull(fs); fs=tl(fs))
581 if (!failFree(snd(hd(fs))))
585 /*intentional fall-thru*/
586 default : return FALSE;
590 static Cell local refutePat(pat) /* find pattern to refute in conformality*/
591 Cell pat; { /* test with pat. */
592 /* e.g. refPat (x:y) == (_:_) */
593 /* refPat ~(x:y) == _ etc.. */
595 switch (whatIs(pat)) {
596 case ASPAT : return refutePat(snd(snd(pat)));
598 case FINLIST : { Cell ys = snd(pat);
600 for (; nonNull(ys); ys=tl(ys))
601 xs = ap(ap(nameCons,refutePat(hd(ys))),xs);
602 return revOnto(xs,nameNil);
605 case CONFLDS : { Cell ps = NIL;
606 Cell fs = snd(snd(pat));
607 for (; nonNull(fs); fs=tl(fs)) {
608 Cell p = refutePat(snd(hd(fs)));
609 ps = cons(pair(fst(hd(fs)),p),ps);
611 return pair(CONFLDS,pair(fst(snd(pat)),rev(ps)));
618 case LAZYPAT : return WILDCARD;
624 case NAME : return pat;
626 case AP : return refutePatAp(pat);
628 default : internal("refutePat");
629 return NIL; /*NOTREACHED*/
633 static Cell local refutePatAp(p) /* find pattern to refute in conformality*/
636 if (h==nameFromInt || h==nameFromInteger || h==nameFromDouble)
638 else if (whatIs(h)==ADDPAT)
639 return ap(fun(p),refutePat(arg(p)));
642 Cell pf = refutePat(extField(p));
643 Cell pr = refutePat(extRow(p));
644 return ap(ap(fun(fun(p)),pf),pr);
648 List as = getArgs(p);
649 mapOver(refutePat,as);
650 return applyToArgs(h,as);
654 static Cell local matchPat(pat) /* find pattern to match against */
655 Cell pat; { /* replaces parts of pattern that do not */
656 /* include variables with wildcards */
657 switch (whatIs(pat)) {
658 case ASPAT : { Cell p = matchPat(snd(snd(pat)));
659 return (p==WILDCARD) ? fst(snd(pat))
661 pair(fst(snd(pat)),p));
664 case FINLIST : { Cell ys = snd(pat);
666 for (; nonNull(ys); ys=tl(ys))
667 xs = cons(matchPat(hd(ys)),xs);
668 while (nonNull(xs) && hd(xs)==WILDCARD)
670 for (ys=nameNil; nonNull(xs); xs=tl(xs))
671 ys = ap(ap(nameCons,hd(xs)),ys);
675 case CONFLDS : { Cell ps = NIL;
676 Name c = fst(snd(pat));
677 Cell fs = snd(snd(pat));
679 for (; nonNull(fs); fs=tl(fs)) {
680 Cell p = matchPat(snd(hd(fs)));
681 ps = cons(pair(fst(hd(fs)),p),ps);
685 return avar ? pair(CONFLDS,pair(c,rev(ps)))
691 case DICTVAR : return pat;
693 case LAZYPAT : { Cell p = matchPat(snd(pat));
694 return (p==WILDCARD) ? WILDCARD : ap(LAZYPAT,p);
699 case CHARCELL : return WILDCARD;
703 case AP : { Cell h = getHead(pat);
704 if (h==nameFromInt ||
705 h==nameFromInteger || h==nameFromDouble)
707 else if (whatIs(h)==ADDPAT)
711 Cell pf = matchPat(extField(pat));
712 Cell pr = matchPat(extRow(pat));
713 return (pf==WILDCARD && pr==WILDCARD)
715 : ap(ap(fun(fun(pat)),pf),pr);
721 for (; isAp(pat); pat=fun(pat)) {
722 Cell p = matchPat(arg(pat));
727 return avar ? applyToArgs(pat,args)
732 default : internal("matchPat");
733 return NIL; /*NOTREACHED*/
737 #define addEqn(v,val,lds) cons(pair(v,singleton(pair(NIL,val))),lds)
739 static List local remPat(pat,expr,lds)
740 Cell pat; /* Produce list of definitions for eqn */
741 Cell expr; /* pat = expr, including a conformality */
742 List lds; { /* check if required. */
744 /* Conformality test (if required):
745 * pat = expr ==> nv = LETREC confCheck nv@pat = nv
747 * remPat1(pat,nv,.....);
750 if (!failFree(pat)) {
751 Cell confVar = inventVar();
752 Cell nv = inventVar();
753 Cell locfun = pair(confVar, /* confVar [([nv@refPat],nv)] */
754 singleton(pair(singleton(ap(ASPAT,
759 if (whatIs(expr)==GUARDED) { /* A spanner ... special case */
760 lds = addEqn(nv,expr,lds); /* for guarded pattern binding*/
765 if (whatIs(pat)==ASPAT) { /* avoid using new variable if*/
766 nv = fst(snd(pat)); /* a variable is already given*/
767 pat = snd(snd(pat)); /* by an as-pattern */
770 lds = addEqn(nv, /* nv = */
771 ap(LETREC,pair(singleton(locfun), /* LETREC [locfun] */
772 ap(confVar,expr))), /* IN confVar expr */
775 return remPat1(matchPat(pat),nv,lds);
778 return remPat1(matchPat(pat),expr,lds);
781 static List local remPat1(pat,expr,lds)
782 Cell pat; /* Add definitions for: pat = expr to */
783 Cell expr; /* list of local definitions in lds. */
785 Cell c = getHead(pat);
790 case CHARCELL : break;
792 case ASPAT : return remPat1(snd(snd(pat)), /* v@pat = expr */
794 addEqn(fst(snd(pat)),expr,lds));
796 case LAZYPAT : { Cell nv;
798 if (isVar(expr) || isName(expr))
802 lds = addEqn(nv,expr,lds);
805 return remPat(snd(pat),nv,lds);
808 case ADDPAT : return remPat1(arg(pat), /* n + k = expr */
811 mkInt(snd(fun(fun(pat))))),
815 case FINLIST : return remPat1(mkConsList(snd(pat)),expr,lds);
817 case CONFLDS : { Name h = fst(snd(pat));
818 Int m = name(h).arity;
820 List fs = snd(snd(pat));
824 for (; nonNull(fs); fs=tl(fs)) {
826 for (i=m-sfunPos(fst(hd(fs)),h); i>0; i--)
828 arg(r) = snd(hd(fs));
830 return remPat1(p,expr,lds);
833 case DICTVAR : /* shouldn't really occur */
834 assert(0); /* so let's test for it then! ADR */
836 case VAROPCELL : return addEqn(pat,expr,lds);
838 case NAME : if (c==nameFromInt || c==nameFromInteger
839 || c==nameFromDouble) {
841 arg(fun(pat)) = translate(arg(fun(pat)));
845 if (argCount==1 && isCfun(c) /* for newtype */
846 && cfunOf(c)==0 && name(c).defn==nameId)
847 return remPat1(arg(pat),expr,lds);
849 /* intentional fall-thru */
850 case TUPLE : { List ps = getArgs(pat);
856 if (isVar(expr) || isName(expr))
860 lds = addEqn(nv,expr,lds);
863 sel = ap(ap(nameSel,c),nv);
864 for (i=1; nonNull(ps); ++i, ps=tl(ps))
865 lds = remPat1(hd(ps),
873 case EXT : { Cell nv = inventVar();
875 = translate(arg(fun(fun(pat))));
881 lds = remPat1(extField(pat),ap(nameFst,nv),lds);
882 lds = remPat1(extRow(pat),ap(nameSnd,nv),lds);
887 default : internal("remPat1");
893 /* --------------------------------------------------------------------------
894 * Eliminate pattern matching in function definitions -- pattern matching
897 * The original Gofer/Hugs pattern matching compiler was based on Wadler's
898 * algorithms described in `Implementation of functional programming
899 * languages'. That should still provide a good starting point for anyone
900 * wanting to understand this part of the system. However, the original
901 * algorithm has been generalized and restructured in order to implement
902 * new features added in Haskell 1.3.
904 * During the translation, in preparation for later stages of compilation,
905 * all local and bound variables are replaced by suitable offsets, and
906 * locally defined function symbols are given new names (which will
907 * eventually be their names when lifted to make top level definitions).
908 * ------------------------------------------------------------------------*/
910 static Offset freeBegin; /* only variables with offset <= freeBegin are of */
911 static List freeVars; /* interest as `free' variables */
912 static List freeFuns; /* List of `free' local functions */
914 static Cell local pmcTerm(co,sc,e) /* apply pattern matching compiler */
915 Int co; /* co = current offset */
916 List sc; /* sc = scope */
917 Cell e; { /* e = expr to transform */
919 case GUARDED : map2Over(pmcPair,co,sc,snd(e));
922 case LETREC : pmcLetrec(co,sc,snd(e));
927 case DICTVAR : return pmcVar(sc,textOf(e));
929 case COND : return ap(COND,pmcTriple(co,sc,snd(e)));
931 case AP : return pmcPair(co,sc,e);
943 case STRCELL : break;
945 default : internal("pmcTerm");
951 static Cell local pmcPair(co,sc,pr) /* apply pattern matching compiler */
952 Int co; /* to a pair of exprs */
955 return pair(pmcTerm(co,sc,fst(pr)),
956 pmcTerm(co,sc,snd(pr)));
959 static Cell local pmcTriple(co,sc,tr) /* apply pattern matching compiler */
960 Int co; /* to a triple of exprs */
963 return triple(pmcTerm(co,sc,fst3(tr)),
964 pmcTerm(co,sc,snd3(tr)),
965 pmcTerm(co,sc,thd3(tr)));
968 static Cell local pmcVar(sc,t) /* find translation of variable */
969 List sc; /* in current scope */
974 for (xs=sc; nonNull(xs); xs=tl(xs)) {
976 if (t==textOf(fst(x))) {
977 if (isOffset(snd(x))) { /* local variable ... */
978 if (snd(x)<=freeBegin && !cellIsMember(snd(x),freeVars))
979 freeVars = cons(snd(x),freeVars);
982 else { /* local function ... */
983 if (!cellIsMember(snd(x),freeFuns))
984 freeFuns = cons(snd(x),freeFuns);
990 if (isNull(n=findName(t))) /* Lookup global name - the only way*/
991 n = newName(t,currentName); /* this (should be able to happen) */
992 /* is with new global var introduced*/
993 /* after type check; e.g. remPat1 */
997 static Void local pmcLetrec(co,sc,e) /* apply pattern matching compiler */
998 Int co; /* to LETREC, splitting decls into */
999 List sc; /* two sections */
1001 List fs = NIL; /* local function definitions */
1002 List vs = NIL; /* local variable definitions */
1005 for (ds=fst(e); nonNull(ds); ds=tl(ds)) { /* Split decls into two */
1006 Cell v = fst(hd(ds));
1007 Int arity = length(fst(hd(snd(hd(ds)))));
1009 if (arity==0) { /* Variable declaration */
1010 vs = cons(snd(hd(ds)),vs);
1011 sc = cons(pair(v,mkOffset(++co)),sc);
1013 else { /* Function declaration */
1014 fs = cons(triple(inventVar(),mkInt(arity),snd(hd(ds))),fs);
1015 sc = cons(pair(v,hd(fs)),sc);
1018 vs = rev(vs); /* Put declaration lists back in */
1019 fs = rev(fs); /* original order */
1020 fst(e) = pair(vs,fs); /* Store declaration lists */
1021 map2Over(pmcVarDef,co,sc,vs); /* Translate variable definitions */
1022 map2Proc(pmcFunDef,co,sc,fs); /* Translate function definitions */
1023 snd(e) = pmcTerm(co,sc,snd(e)); /* Translate LETREC body */
1024 freeFuns = diffList(freeFuns,fs); /* Delete any `freeFuns' bound in fs*/
1027 static Cell local pmcVarDef(co,sc,vd) /* apply pattern matching compiler */
1028 Int co; /* to variable definition */
1030 List vd; { /* vd :: [ ([], rhs) ] */
1031 Cell d = snd(hd(vd));
1032 if (nonNull(tl(vd)) && canFail(d))
1033 return ap(FATBAR,pair(pmcTerm(co,sc,d),
1034 pmcVarDef(co,sc,tl(vd))));
1035 return pmcTerm(co,sc,d);
1038 static Void local pmcFunDef(co,sc,fd) /* apply pattern matching compiler */
1039 Int co; /* to function definition */
1041 Triple fd; { /* fd :: (Var, Arity, [Alt]) */
1042 Offset saveFreeBegin = freeBegin;
1043 List saveFreeVars = freeVars;
1044 List saveFreeFuns = freeFuns;
1045 Int arity = intOf(snd3(fd));
1046 Cell temp = altsMatch(co+1,arity,sc,thd3(fd));
1049 freeBegin = mkOffset(co);
1052 temp = match(co+arity,temp);
1053 thd3(fd) = triple(freeVars,freeFuns,temp);
1055 for (xs=freeVars; nonNull(xs); xs=tl(xs))
1056 if (hd(xs)<=saveFreeBegin && !cellIsMember(hd(xs),saveFreeVars))
1057 saveFreeVars = cons(hd(xs),saveFreeVars);
1059 for (xs=freeFuns; nonNull(xs); xs=tl(xs))
1060 if (!cellIsMember(hd(xs),saveFreeFuns))
1061 saveFreeFuns = cons(hd(xs),saveFreeFuns);
1063 freeBegin = saveFreeBegin;
1064 freeVars = saveFreeVars;
1065 freeFuns = saveFreeFuns;
1068 /* ---------------------------------------------------------------------------
1069 * Main part of pattern matching compiler: convert [Alt] to case constructs
1071 * This section of Hugs has been almost completely rewritten to be more
1072 * general, in particular, to allow pattern matching in orders other than the
1073 * strictly left-to-right approach of the previous version. This is needed
1074 * for the implementation of the so-called Haskell 1.3 `record' syntax.
1076 * At each stage, the different branches for the cases to be considered
1077 * are represented by a list of values of type:
1078 * Match ::= { maPats :: [Pat], patterns to match
1079 * maOffs :: [Offs], offsets of corresponding values
1080 * maSc :: Scope, mapping from vars to offsets
1081 * maRhs :: Rhs } right hand side
1082 * [Implementation uses nested pairs, ((pats,offs),(sc,rhs)).]
1084 * The Scope component has type:
1085 * Scope ::= [(Var,Expr)]
1086 * and provides a mapping from variable names to offsets used in the matching
1089 * Matches can be normalized by reducing them to a form in which the list
1090 * of patterns is empty (in which case the match itself is described as an
1091 * empty match), or in which the list is non-empty and the first pattern is
1092 * one that requires either a CASE or NUMCASE (or EXTCASE) to decompose.
1093 * ------------------------------------------------------------------------*/
1095 #define mkMatch(ps,os,sc,r) pair(pair(ps,os),pair(sc,r))
1096 #define maPats(ma) fst(fst(ma))
1097 #define maOffs(ma) snd(fst(ma))
1098 #define maSc(ma) fst(snd(ma))
1099 #define maRhs(ma) snd(snd(ma))
1100 #define extSc(v,o,ma) maSc(ma) = cons(pair(v,o),maSc(ma))
1102 static List local altsMatch(co,n,sc,as) /* Make a list of matches from list*/
1103 Int co; /* of Alts, with initial offsets */
1104 Int n; /* reverse (take n [co..]) */
1110 us = cons(mkOffset(co++),us);
1111 for (; nonNull(as); as=tl(as)) /* Each Alt is ([Pat], Rhs) */
1112 mas = cons(mkMatch(fst(hd(as)),us,sc,snd(hd(as))),mas);
1116 static Cell local match(co,mas) /* Generate case statement for Matches mas */
1117 Int co; /* at current offset co */
1118 List mas; { /* N.B. Assumes nonNull(mas). */
1119 Cell srhs = NIL; /* Rhs for selected matches */
1120 List smas = mas; /* List of selected matches */
1124 if (emptyMatch(hd(smas))) { /* The case for empty matches: */
1125 while (nonNull(mas) && emptyMatch(hd(mas))) {
1126 List temp = tl(mas);
1131 srhs = joinMas(co,rev(smas));
1133 else { /* Non-empty match */
1134 Int o = offsetOf(hd(maOffs(hd(smas))));
1135 Cell d = maDiscr(hd(smas));
1136 if (isNumDiscr(d)) { /* Numeric match */
1137 Int da = discrArity(d);
1138 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1139 while (nonNull(mas) && !emptyMatch(hd(mas))
1140 && o==offsetOf(hd(maOffs(hd(mas))))
1141 && isNumDiscr(d=maDiscr(hd(mas)))
1142 && eqNumDiscr(d,d1)) {
1143 List temp = tl(mas);
1149 map2Proc(advance,co,da,smas);
1150 srhs = ap(NUMCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1153 else if (isExtDiscr(d)) { /* Record match */
1154 Int da = discrArity(d);
1155 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1156 while (nonNull(mas) && !emptyMatch(hd(mas))
1157 && o==offsetOf(hd(maOffs(hd(mas))))
1158 && isExtDiscr(d=maDiscr(hd(mas)))
1159 && eqExtDiscr(d,d1)) {
1160 List temp = tl(mas);
1166 map2Proc(advance,co,da,smas);
1167 srhs = ap(EXTCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1170 else { /* Constructor match */
1171 List tab = addConTable(d,hd(smas),NIL);
1173 while (nonNull(mas) && !emptyMatch(hd(mas))
1174 && o==offsetOf(hd(maOffs(hd(mas))))
1175 && !isNumDiscr(d=maDiscr(hd(mas)))) {
1176 tab = addConTable(d,hd(mas),tab);
1179 for (tab=rev(tab); nonNull(tab); tab=tl(tab)) {
1181 smas = snd(hd(tab));
1183 map2Proc(advance,co,da,smas);
1184 srhs = cons(pair(d,match(co+da,smas)),srhs);
1186 srhs = ap(CASE,pair(mkOffset(o),srhs));
1189 return nonNull(mas) ? ap(FATBAR,pair(srhs,match(co,mas))) : srhs;
1192 static Cell local joinMas(co,mas) /* Combine list of matches into rhs*/
1193 Int co; /* using FATBARs as necessary */
1194 List mas; { /* Non-empty list of empty matches */
1196 Cell rhs = pmcTerm(co,maSc(ma),maRhs(ma));
1197 if (nonNull(tl(mas)) && canFail(rhs))
1198 return ap(FATBAR,pair(rhs,joinMas(co,tl(mas))));
1203 static Bool local canFail(rhs) /* Determine if expression (as rhs) */
1204 Cell rhs; { /* might ever be able to fail */
1205 switch (whatIs(rhs)) {
1206 case LETREC : return canFail(snd(snd(rhs)));
1207 case GUARDED : return TRUE; /* could get more sophisticated ..? */
1208 default : return FALSE;
1212 /* type Table a b = [(a, [b])]
1214 * addTable :: a -> b -> Table a b -> Table a b
1215 * addTable x y [] = [(x,[y])]
1216 * addTable x y (z@(n,sws):zs)
1217 * | n == x = (n,sws++[y]):zs
1218 * | otherwise = (n,sws):addTable x y zs
1221 static List local addConTable(x,y,tab) /* add element (x,y) to table */
1225 return singleton(pair(x,singleton(y)));
1226 else if (fst(hd(tab))==x)
1227 snd(hd(tab)) = appendOnto(snd(hd(tab)),singleton(y));
1229 tl(tab) = addConTable(x,y,tl(tab));
1234 static Void local advance(co,a,ma) /* Advance non-empty match by */
1235 Int co; /* processing head pattern */
1236 Int a; /* discriminator arity */
1238 Cell p = hd(maPats(ma));
1239 List ps = tl(maPats(ma));
1240 List us = tl(maOffs(ma));
1241 if (whatIs(p)==CONFLDS) { /* Special case for record syntax */
1242 Name c = fst(snd(p));
1243 List fs = snd(snd(p));
1246 for (; nonNull(fs); fs=tl(fs)) {
1247 vs = cons(mkOffset(co+a+1-sfunPos(fst(hd(fs)),c)),vs);
1248 qs = cons(snd(hd(fs)),qs);
1250 ps = revOnto(qs,ps);
1251 us = revOnto(vs,us);
1253 else /* Normally just spool off patterns*/
1254 for (; a>0; --a) { /* and corresponding offsets ... */
1255 us = cons(mkOffset(++co),us);
1256 ps = cons(arg(p),ps);
1264 /* --------------------------------------------------------------------------
1265 * Normalize and test for empty match:
1266 * ------------------------------------------------------------------------*/
1268 static Bool local emptyMatch(ma)/* Normalize and test to see if a given */
1269 Cell ma; { /* match, ma, is empty. */
1271 while (nonNull(maPats(ma))) {
1273 tidyHd: switch (whatIs(p=hd(maPats(ma)))) {
1274 case LAZYPAT : { Cell nv = inventVar();
1275 maRhs(ma) = ap(LETREC,
1276 pair(remPat(snd(p),nv,NIL),
1280 /* intentional fall-thru */
1283 case DICTVAR : extSc(p,hd(maOffs(ma)),ma);
1284 case WILDCARD : maPats(ma) = tl(maPats(ma));
1285 maOffs(ma) = tl(maOffs(ma));
1288 /* So-called "as-patterns"are really just pattern intersections:
1289 * (p1@p2:ps, o:os, sc, e) ==> (p1:p2:ps, o:o:os, sc, e)
1290 * (But the input grammar probably doesn't let us take
1291 * advantage of this, so we stick with the special case
1292 * when p1 is a variable.)
1294 case ASPAT : extSc(fst(snd(p)),hd(maOffs(ma)),ma);
1295 hd(maPats(ma)) = snd(snd(p));
1298 case FINLIST : hd(maPats(ma)) = mkConsList(snd(p));
1301 case STRCELL : { String s = textToStr(textOf(p));
1302 for (p=NIL; *s!='\0'; ++s) {
1303 if (*s!='\\' || *++s=='\\')
1304 p = ap(consChar(*s),p);
1306 p = ap(consChar('\0'),p);
1308 hd(maPats(ma)) = revOnto(p,nameNil);
1312 case AP : if (isName(fun(p)) && isCfun(fun(p))
1313 && cfunOf(fun(p))==0
1314 && name(fun(p)).defn==nameId) {
1315 hd(maPats(ma)) = arg(p);
1318 /* intentional fall-thru */
1324 default : internal("emptyMatch");
1330 /* --------------------------------------------------------------------------
1332 * ------------------------------------------------------------------------*/
1334 static Cell local maDiscr(ma) /* Get the discriminator for a non-empty */
1335 Cell ma; { /* match, ma. */
1336 Cell p = hd(maPats(ma));
1337 Cell h = getHead(p);
1338 switch (whatIs(h)) {
1339 case CONFLDS : return fst(snd(p));
1340 case ADDPAT : arg(fun(p)) = translate(arg(fun(p)));
1343 case EXT : h = fun(fun(p));
1344 arg(h) = translate(arg(h));
1347 case NAME : if (h==nameFromInt || h==nameFromInteger
1348 || h==nameFromDouble) {
1350 arg(fun(p)) = translate(arg(fun(p)));
1357 static Bool local isNumDiscr(d) /* TRUE => numeric discriminator */
1359 switch (whatIs(d)) {
1362 case CHARCELL : return FALSE;
1365 case AP : return !isExt(fun(d));
1367 case AP : return TRUE; /* must be a literal or (n+k) */
1370 internal("isNumDiscr");
1371 return 0;/*NOTREACHED*/
1374 Int discrArity(d) /* Find arity of discriminator */
1376 switch (whatIs(d)) {
1377 case NAME : return name(d).arity;
1378 case TUPLE : return tupleOf(d);
1379 case CHARCELL : return 0;
1381 case AP : switch (whatIs(fun(d))) {
1382 case ADDPAT : return 1;
1383 case EXT : return 2;
1387 case AP : return (whatIs(fun(d))==ADDPAT) ? 1 : 0;
1390 internal("discrArity");
1391 return 0;/*NOTREACHED*/
1394 static Bool local eqNumDiscr(d1,d2) /* Determine whether two numeric */
1395 Cell d1, d2; { /* descriptors have same value */
1396 if (whatIs(fun(d1))==ADDPAT)
1397 return whatIs(fun(d2))==ADDPAT && snd(fun(d1))==snd(fun(d2));
1399 return isInt(arg(d2)) && intOf(arg(d1))==intOf(arg(d2));
1400 if (isFloat(arg(d1)))
1401 return isFloat(arg(d2)) && floatOf(arg(d1))==floatOf(arg(d2));
1402 internal("eqNumDiscr");
1403 return FALSE;/*NOTREACHED*/
1407 static Bool local isExtDiscr(d) /* Test of extension discriminator */
1409 return isAp(d) && isExt(fun(d));
1412 static Bool local eqExtDiscr(d1,d2) /* Determine whether two extension */
1413 Cell d1, d2; { /* discriminators have same label */
1414 return fun(d1)==fun(d2);
1418 /*-------------------------------------------------------------------------*/
1422 /* --------------------------------------------------------------------------
1424 * ------------------------------------------------------------------------*/
1426 static Void local stgCGBinds( List );
1428 static Void local stgCGBinds(binds)
1433 /* --------------------------------------------------------------------------
1434 * Main entry points to compiler:
1435 * ------------------------------------------------------------------------*/
1437 static List addGlobals( List binds )
1439 /* stgGlobals = list of top-level STG binds */
1440 for(;nonNull(stgGlobals);stgGlobals=tl(stgGlobals)) {
1441 StgVar bind = snd(hd(stgGlobals));
1442 if (nonNull(stgVarBody(bind))) {
1443 binds = cons(bind,binds);
1449 typedef void (*sighandler_t)(int);
1450 void eval_ctrlbrk ( int dunnowhat )
1453 /* reinstall the signal handler so that further interrupts which
1454 happen before the thread can return to the scheduler, lead back
1455 here rather than invoking the previous break handler. */
1456 signal(SIGINT, eval_ctrlbrk);
1459 Void evalExp() { /* compile and run input expression */
1460 /* ToDo: this name (and other names generated during pattern match?)
1461 * get inserted in the symbol table but never get removed.
1463 Name n = newName(inventText(),NIL);
1465 StgVar v = mkStgVar(NIL,NIL);
1468 e = pmcTerm(0,NIL,translate(inputExpr));
1471 stgCGBinds(addGlobals(singleton(v)));
1473 /* Run thread (and any other runnable threads) */
1475 /* Re-initialise the scheduler - ToDo: do I need this? */
1476 /* JRS, 991118: on SM's advice, don't call initScheduler every time.
1477 This causes an assertion failure in GC.c(revert_dead_cafs)
1478 unless doRevertCAFs below is permanently TRUE.
1480 /* initScheduler(); */
1481 #ifdef CRUDE_PROFILING
1486 HaskellObj result; /* ignored */
1487 sighandler_t old_ctrlbrk;
1488 SchedulerStatus status;
1489 Bool doRevertCAFs = TRUE; /* do not change -- comment above */
1490 old_ctrlbrk = signal(SIGINT, eval_ctrlbrk);
1491 ASSERT(old_ctrlbrk != SIG_ERR);
1492 status = rts_eval_(closureOfVar(v),10000,&result);
1493 signal(SIGINT,old_ctrlbrk);
1498 printf("{Deadlock or Blackhole}");
1499 if (doRevertCAFs) RevertCAFs();
1502 printf("{Interrupted}");
1503 if (doRevertCAFs) RevertCAFs();
1506 printf("{Interrupted or Killed}");
1507 if (doRevertCAFs) RevertCAFs();
1510 if (doRevertCAFs) RevertCAFs();
1513 internal("evalExp: Unrecognised SchedulerStatus");
1519 #ifdef CRUDE_PROFILING
1526 static List local addStgVar( List binds, Pair bind )
1528 StgVar nv = mkStgVar(NIL,NIL);
1529 Text t = textOf(fst(bind));
1530 Name n = findName(t);
1532 if (isNull(n)) { /* Lookup global name - the only way*/
1533 n = newName(t,NIL); /* this (should be able to happen) */
1534 } /* is with new global var introduced*/
1535 /* after type check; e.g. remPat1 */
1536 name(n).stgVar = nv;
1537 return cons(nv,binds);
1541 Void compileDefns() { /* compile script definitions */
1542 Target t = length(valDefns) + length(genDefns) + length(selDefns);
1549 for(vs=genDefns; nonNull(vs); vs=tl(vs)) {
1551 StgVar nv = mkStgVar(NIL,NIL);
1553 name(n).stgVar = nv;
1554 binds = cons(nv,binds);
1556 for(vss=selDefns; nonNull(vss); vss=tl(vss)) {
1557 for(vs=hd(vss); nonNull(vs); vs=tl(vs)) {
1560 StgVar nv = mkStgVar(NIL,NIL);
1562 name(n).stgVar = nv;
1563 binds = cons(nv,binds);
1568 setGoal("Translating",t);
1569 /* do valDefns before everything else so that all stgVar's get added. */
1570 for (; nonNull(valDefns); valDefns=tl(valDefns)) {
1571 hd(valDefns) = transBinds(hd(valDefns));
1572 mapAccum(addStgVar,binds,hd(valDefns));
1573 mapProc(compileGlobalFunction,hd(valDefns));
1576 for (; nonNull(genDefns); genDefns=tl(genDefns)) {
1577 compileGenFunction(hd(genDefns));
1580 for (; nonNull(selDefns); selDefns=tl(selDefns)) {
1581 mapOver(compileSelFunction,hd(selDefns));
1585 binds = addGlobals(binds);
1587 setGoal("Generating code",t);
1593 static Void local compileGlobalFunction(bind)
1595 Name n = findName(textOf(fst(bind)));
1596 List defs = snd(bind);
1597 Int arity = length(fst(hd(defs)));
1600 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1603 static Void local compileGenFunction(n) /* Produce code for internally */
1604 Name n; { /* generated function */
1605 List defs = name(n).defn;
1606 Int arity = length(fst(hd(defs)));
1608 printf ( "compGenFn: " );print(defs,100);printf("\n");
1612 mapProc(transAlt,defs);
1613 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1617 static Name local compileSelFunction(p) /* Produce code for selector func */
1618 Pair p; { /* Should be merged with genDefns, */
1619 Name s = fst(p); /* but the name(_).defn field is */
1620 List defs = snd(p); /* already used for other purposes */
1621 Int arity = length(fst(hd(defs))); /* in selector functions. */
1624 mapProc(transAlt,defs);
1625 stgDefn(s,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1630 /* --------------------------------------------------------------------------
1632 * ------------------------------------------------------------------------*/
1638 case RESET : freeVars = NIL;
1640 freeBegin = mkOffset(0);
1643 case MARK : mark(freeVars);
1647 case POSTPREL: break;
1651 /*-------------------------------------------------------------------------*/