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 20:03:36 $
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 */
28 /* --------------------------------------------------------------------------
29 * Local function prototypes:
30 * ------------------------------------------------------------------------*/
32 static Cell local translate Args((Cell));
33 static Void local transPair Args((Pair));
34 static Void local transTriple Args((Triple));
35 static Void local transAlt Args((Cell));
36 static Void local transCase Args((Cell));
37 static List local transBinds Args((List));
38 static Cell local transRhs Args((Cell));
39 static Cell local mkConsList Args((List));
40 static Cell local expandLetrec Args((Cell));
41 static Cell local transComp Args((Cell,List,Cell));
42 static Cell local transDo Args((Cell,Cell,List));
43 static Cell local transConFlds Args((Cell,List));
44 static Cell local transUpdFlds Args((Cell,List,List));
46 static Cell local refutePat Args((Cell));
47 static Cell local refutePatAp Args((Cell));
48 static Cell local matchPat Args((Cell));
49 static List local remPat Args((Cell,Cell,List));
50 static List local remPat1 Args((Cell,Cell,List));
52 static Cell local pmcTerm Args((Int,List,Cell));
53 static Cell local pmcPair Args((Int,List,Pair));
54 static Cell local pmcTriple Args((Int,List,Triple));
55 static Cell local pmcVar Args((List,Text));
56 static Void local pmcLetrec Args((Int,List,Pair));
57 static Cell local pmcVarDef Args((Int,List,List));
58 static Void local pmcFunDef Args((Int,List,Triple));
59 static List local altsMatch Args((Int,Int,List,List));
60 static Cell local match Args((Int,List));
61 static Cell local joinMas Args((Int,List));
62 static Bool local canFail Args((Cell));
63 static List local addConTable Args((Cell,Cell,List));
64 static Void local advance Args((Int,Int,Cell));
65 static Bool local emptyMatch Args((Cell));
66 static Cell local maDiscr Args((Cell));
67 static Bool local isNumDiscr Args((Cell));
68 static Bool local eqNumDiscr Args((Cell,Cell));
70 static Bool local isExtDiscr Args((Cell));
71 static Bool local eqExtDiscr Args((Cell,Cell));
74 static Void local compileGlobalFunction Args((Pair));
75 static Void local compileGenFunction Args((Name));
76 static Name local compileSelFunction Args((Pair));
77 static List local addStgVar Args((List,Pair));
79 static Name currentName; /* Top level name being processed */
81 /* --------------------------------------------------------------------------
82 * Translation: Convert input expressions into a less complex language
83 * of terms using only LETREC, AP, constants and vars.
84 * Also remove pattern definitions on lhs of eqns.
85 * ------------------------------------------------------------------------*/
87 static Cell local translate(e) /* Translate expression: */
90 printf ( "translate: " );print(e,100);printf("\n");
93 case LETREC : snd(snd(e)) = translate(snd(snd(e)));
94 return expandLetrec(e);
96 case COND : transTriple(snd(e));
99 case AP : fst(e) = translate(fst(e));
101 if (fst(e)==nameId || fst(e)==nameInd)
102 return translate(snd(e));
103 if (isName(fst(e)) &&
106 return translate(snd(e));
108 snd(e) = translate(snd(e));
111 case NAME : if (e==nameOtherwise)
114 if (isName(name(e).defn))
116 if (isPair(name(e).defn))
117 return snd(name(e).defn);
122 case RECSEL : return nameRecSel;
134 case CHARCELL : return e;
136 case IPVAR : return nameId;
138 case FINLIST : mapOver(translate,snd(e));
139 return mkConsList(snd(e));
141 case DOCOMP : { Cell m = translate(fst(snd(e)));
142 Cell r = translate(fst(snd(snd(e))));
143 return transDo(m,r,snd(snd(snd(e))));
146 case MONADCOMP : { Cell m = translate(fst(snd(e)));
147 Cell r = translate(fst(snd(snd(e))));
148 Cell qs = snd(snd(snd(e)));
149 if (m == nameListMonad)
150 return transComp(r,qs,nameNil);
153 r = ap(ap(nameReturn,m),r);
154 return transDo(m,r,qs);
156 internal("translate: monad comps");
161 case CONFLDS : return transConFlds(fst(snd(e)),snd(snd(e)));
163 case UPDFLDS : return transUpdFlds(fst3(snd(e)),
167 case CASE : { Cell nv = inventVar();
168 mapProc(transCase,snd(snd(e)));
170 pair(singleton(pair(nv,snd(snd(e)))),
171 ap(nv,translate(fst(snd(e))))));
174 case LAMBDA : { Cell nv = inventVar();
183 default : fprintf(stderr, "stuff=%d\n",whatIs(e));
184 internal("translate");
189 static Void local transPair(pr) /* Translate each component in a */
190 Pair pr; { /* pair of expressions. */
191 fst(pr) = translate(fst(pr));
192 snd(pr) = translate(snd(pr));
195 static Void local transTriple(tr) /* Translate each component in a */
196 Triple tr; { /* triple of expressions. */
197 fst3(tr) = translate(fst3(tr));
198 snd3(tr) = translate(snd3(tr));
199 thd3(tr) = translate(thd3(tr));
202 static Void local transAlt(e) /* Translate alt: */
203 Cell e; { /* ([Pat], Rhs) ==> ([Pat], Rhs') */
205 printf ( "transAlt: " );print(snd(e),100);printf("\n");
207 snd(e) = transRhs(snd(e));
210 static Void local transCase(c) /* Translate case: */
211 Cell c; { /* (Pat, Rhs) ==> ([Pat], Rhs') */
212 fst(c) = singleton(fst(c));
213 snd(c) = transRhs(snd(c));
216 static List local transBinds(bs) /* Translate list of bindings: */
217 List bs; { /* eliminating pattern matching on */
218 List newBinds = NIL; /* lhs of bindings. */
219 for (; nonNull(bs); bs=tl(bs)) {
221 Cell v = fst(hd(bs));
222 while (isAp(v) && fst(v) == nameInd)
227 if (isVar(fst(hd(bs)))) {
229 mapProc(transAlt,snd(hd(bs)));
230 newBinds = cons(hd(bs),newBinds);
233 newBinds = remPat(fst(snd(hd(bs))),
234 snd(snd(hd(bs)))=transRhs(snd(snd(hd(bs)))),
240 static Cell local transRhs(rhs) /* Translate rhs: removing line nos */
242 switch (whatIs(rhs)) {
243 case LETREC : snd(snd(rhs)) = transRhs(snd(snd(rhs)));
244 return expandLetrec(rhs);
246 case GUARDED : mapOver(snd,snd(rhs)); /* discard line number */
247 mapProc(transPair,snd(rhs));
250 default : return translate(snd(rhs)); /* discard line number */
254 static Cell local mkConsList(es) /* Construct expression for list es */
255 List es; { /* using nameNil and nameCons */
259 return ap(ap(nameCons,hd(es)),mkConsList(tl(es)));
262 static Cell local expandLetrec(root) /* translate LETREC with list of */
263 Cell root; { /* groups of bindings (from depend. */
264 Cell e = snd(snd(root)); /* analysis) to use nested LETRECs */
265 List bss = fst(snd(root));
268 if (isNull(bss)) /* should never happen, but just in */
269 return e; /* case: LETREC [] IN e ==> e */
271 mapOver(transBinds,bss); /* translate each group of bindings */
273 for (temp=root; nonNull(tl(bss)); bss=tl(bss)) {
274 fst(snd(temp)) = hd(bss);
275 snd(snd(temp)) = ap(LETREC,pair(NIL,e));
276 temp = snd(snd(temp));
278 fst(snd(temp)) = hd(bss);
283 /* --------------------------------------------------------------------------
284 * Translation of list comprehensions is based on the description in
285 * `The Implementation of Functional Programming Languages':
287 * [ e | qs ] ++ l => transComp e qs l
288 * transComp e [] l => e : l
289 * transComp e ((p<-xs):qs) l => LETREC _h [] = l
290 * _h (p:_xs) = transComp e qs (_h _xs)
291 * _h (_:_xs) = _h _xs --if p !failFree
293 * transComp e (b:qs) l => if b then transComp e qs l else l
294 * transComp e (decls:qs) l => LETREC decls IN transComp e qs l
295 * ------------------------------------------------------------------------*/
297 static Cell local transComp(e,qs,l) /* Translate [e | qs] ++ l */
306 case FROMQUAL : { Cell ld = NIL;
307 Cell hVar = inventVar();
308 Cell xsVar = inventVar();
310 if (!failFree(fst(snd(q))))
311 ld = cons(pair(singleton(
318 ld = cons(pair(singleton(
326 ld = cons(pair(singleton(nameNil),
331 pair(singleton(pair(hVar,
334 translate(snd(snd(q))))));
338 expandLetrec(ap(LETREC,
340 transComp(e,qs1,l))));
342 case BOOLQUAL : return ap(COND,
343 triple(translate(snd(q)),
349 return ap(ap(nameCons,e),l);
352 /* --------------------------------------------------------------------------
353 * Translation of monad comprehensions written using do-notation:
356 * do { p <- exp; qs } => LETREC _h p = do { qs }
357 * _h _ = fail m "match fails"
359 * do { LET decls; qs } => LETREC decls IN do { qs }
360 * do { IF guard; qs } => if guard then do { qs } else fail m "guard fails"
361 * do { e; qs } => LETREC _h _ = [ e | qs ] in bind m exp _h
364 * ------------------------------------------------------------------------*/
366 static Cell local transDo(m,e,qs) /* Translate do { qs ; e } */
375 case FROMQUAL : { Cell ld = NIL;
376 Cell hVar = inventVar();
378 if (!failFree(fst(snd(q)))) {
379 Cell str = mkStr(findText("match fails"));
380 ld = cons(pair(singleton(WILDCARD),
381 ap2(nameMFail,m,str)),
385 ld = cons(pair(singleton(fst(snd(q))),
390 pair(singleton(pair(hVar,ld)),
393 translate(snd(snd(q)))),
397 case DOQUAL : { Cell hVar = inventVar();
398 Cell ld = cons(pair(singleton(WILDCARD),
402 pair(singleton(pair(hVar,ld)),
410 expandLetrec(ap(LETREC,
414 case BOOLQUAL : return
416 triple(translate(snd(q)),
419 mkStr(findText("guard fails")))));
425 /* --------------------------------------------------------------------------
426 * Translation of named field construction and update:
428 * Construction is implemented using the following transformation:
430 * C{x1=e1, ..., xn=en} = C v1 ... vm
432 * vi = e1, if the ith component of C is labelled with x1
434 * = en, if the ith component of C is labelled with xn
435 * = undefined, otherwise
437 * Update is implemented using the following transformation:
439 * e{x1=e1, ..., xn=en}
440 * = let nv (C a1 ... am) v1 ... vn = C a1' .. am'
441 * nv (D b1 ... bk) v1 ... vn = D b1' .. bk
443 * nv _ v1 ... vn = error "failed update"
446 * nv, v1, ..., vn, a1, ..., am, b1, ..., bk, ... are new variables,
447 * C,D,... = { K | K is a constr fun s.t. {x1,...,xn} subset of sels(K)}
449 * ai' = v1, if the ith component of C is labelled with x1
451 * = vn, if the ith component of C is labelled with xn
455 * The error case may be omitted if C,D,... is an enumeration of all of the
456 * constructors for the datatype concerned. Strictly speaking, error case
457 * isn't needed at all -- the only benefit of including it is that the user
458 * will get a "failed update" message rather than a cryptic {v354 ...}.
459 * So, for now, we'll go with the second option!
461 * For the time being, code for each update operation is generated
462 * independently of any other updates. However, if updates are used
463 * frequently, then we might want to consider changing the implementation
464 * at a later stage to cache definitions of functions like nv above. This
465 * would create a shared library of update functions, indexed by a set of
466 * constructors {C,D,...}.
467 * ------------------------------------------------------------------------*/
469 static Cell local transConFlds(c,flds) /* Translate C{flds} */
473 Int m = name(c).arity;
476 e = ap(e,nameUndefined);
477 for (; nonNull(flds); flds=tl(flds)) {
479 for (i=m-sfunPos(fst(hd(flds)),c); i>0; i--)
481 arg(a) = translate(snd(hd(flds)));
486 static Cell local transUpdFlds(e,cs,flds)/* Translate e{flds} */
487 Cell e; /* (cs is corresp list of constrs) */
490 Cell nv = inventVar();
491 Cell body = ap(nv,translate(e));
496 for (; nonNull(fs); fs=tl(fs)) { /* body = nv e1 ... en */
497 Cell b = hd(fs); /* args = [v1, ..., vn] */
498 body = ap(body,translate(snd(b)));
499 args = cons(inventVar(),args);
502 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constructors to */
503 Cell c = hd(cs); /* build up list of alts. */
507 Int m = name(c).arity;
510 for (i=m; i>0; i--) { /* pat = C a1 ... am */
511 Cell a = inventVar(); /* rhs = C a1 ... am */
516 for (fs=flds; nonNull(fs); fs=tl(fs), as=tl(as)) {
517 Name s = fst(hd(fs)); /* Replace approp ai in rhs with */
518 Cell r = rhs; /* vars from [v1,...,vn] */
519 for (i=m-sfunPos(s,c); i>0; i--)
524 alts = cons(pair(cons(pat,args),rhs),alts);
526 return ap(LETREC,pair(singleton(pair(nv,alts)),body));
529 /* --------------------------------------------------------------------------
530 * Elimination of pattern bindings:
532 * The following code adopts the definition of failure free patterns as given
533 * in the Haskell 1.3 report; the term "irrefutable" is also used there for
534 * a subset of the failure free patterns described here, but has no useful
535 * role in this implementation. Basically speaking, the failure free patterns
536 * are: variable, wildcard, ~apat
537 * var@apat, if apat is failure free
538 * C apat1 ... apatn if C is a product constructor
539 * (i.e. an only constructor) and
540 * apat1,...,apatn are failure free
541 * Note that the last case automatically covers the case where C comes from
542 * a newtype construction.
543 * ------------------------------------------------------------------------*/
545 Bool failFree(pat) /* is pattern failure free? (do we need */
546 Cell pat; { /* a conformality check?) */
547 Cell c = getHead(pat);
550 case ASPAT : return failFree(snd(snd(pat)));
552 case NAME : if (!isCfun(c) || cfunOf(c)!=0)
554 /*intentional fall-thru*/
555 case TUPLE : for (; isAp(pat); pat=fun(pat))
556 if (!failFree(arg(pat)))
558 /*intentional fall-thru*/
563 case WILDCARD : return TRUE;
566 case EXT : return failFree(extField(pat)) &&
567 failFree(extRow(pat));
570 case CONFLDS : if (cfunOf(fst(snd(c)))==0) {
571 List fs = snd(snd(c));
572 for (; nonNull(fs); fs=tl(fs))
573 if (!failFree(snd(hd(fs))))
577 /*intentional fall-thru*/
578 default : return FALSE;
582 static Cell local refutePat(pat) /* find pattern to refute in conformality*/
583 Cell pat; { /* test with pat. */
584 /* e.g. refPat (x:y) == (_:_) */
585 /* refPat ~(x:y) == _ etc.. */
587 switch (whatIs(pat)) {
588 case ASPAT : return refutePat(snd(snd(pat)));
590 case FINLIST : { Cell ys = snd(pat);
592 for (; nonNull(ys); ys=tl(ys))
593 xs = ap(ap(nameCons,refutePat(hd(ys))),xs);
594 return revOnto(xs,nameNil);
597 case CONFLDS : { Cell ps = NIL;
598 Cell fs = snd(snd(pat));
599 for (; nonNull(fs); fs=tl(fs)) {
600 Cell p = refutePat(snd(hd(fs)));
601 ps = cons(pair(fst(hd(fs)),p),ps);
603 return pair(CONFLDS,pair(fst(snd(pat)),rev(ps)));
610 case LAZYPAT : return WILDCARD;
616 case NAME : return pat;
618 case AP : return refutePatAp(pat);
620 default : internal("refutePat");
621 return NIL; /*NOTREACHED*/
625 static Cell local refutePatAp(p) /* find pattern to refute in conformality*/
628 if (h==nameFromInt || h==nameFromInteger || h==nameFromDouble)
630 else if (whatIs(h)==ADDPAT)
631 return ap(fun(p),refutePat(arg(p)));
634 Cell pf = refutePat(extField(p));
635 Cell pr = refutePat(extRow(p));
636 return ap(ap(fun(fun(p)),pf),pr);
640 List as = getArgs(p);
641 mapOver(refutePat,as);
642 return applyToArgs(h,as);
646 static Cell local matchPat(pat) /* find pattern to match against */
647 Cell pat; { /* replaces parts of pattern that do not */
648 /* include variables with wildcards */
649 switch (whatIs(pat)) {
650 case ASPAT : { Cell p = matchPat(snd(snd(pat)));
651 return (p==WILDCARD) ? fst(snd(pat))
653 pair(fst(snd(pat)),p));
656 case FINLIST : { Cell ys = snd(pat);
658 for (; nonNull(ys); ys=tl(ys))
659 xs = cons(matchPat(hd(ys)),xs);
660 while (nonNull(xs) && hd(xs)==WILDCARD)
662 for (ys=nameNil; nonNull(xs); xs=tl(xs))
663 ys = ap(ap(nameCons,hd(xs)),ys);
667 case CONFLDS : { Cell ps = NIL;
668 Name c = fst(snd(pat));
669 Cell fs = snd(snd(pat));
671 for (; nonNull(fs); fs=tl(fs)) {
672 Cell p = matchPat(snd(hd(fs)));
673 ps = cons(pair(fst(hd(fs)),p),ps);
677 return avar ? pair(CONFLDS,pair(c,rev(ps)))
683 case DICTVAR : return pat;
685 case LAZYPAT : { Cell p = matchPat(snd(pat));
686 return (p==WILDCARD) ? WILDCARD : ap(LAZYPAT,p);
691 case CHARCELL : return WILDCARD;
695 case AP : { Cell h = getHead(pat);
696 if (h==nameFromInt ||
697 h==nameFromInteger || h==nameFromDouble)
699 else if (whatIs(h)==ADDPAT)
703 Cell pf = matchPat(extField(pat));
704 Cell pr = matchPat(extRow(pat));
705 return (pf==WILDCARD && pr==WILDCARD)
707 : ap(ap(fun(fun(pat)),pf),pr);
713 for (; isAp(pat); pat=fun(pat)) {
714 Cell p = matchPat(arg(pat));
719 return avar ? applyToArgs(pat,args)
724 default : internal("matchPat");
725 return NIL; /*NOTREACHED*/
729 #define addEqn(v,val,lds) cons(pair(v,singleton(pair(NIL,val))),lds)
731 static List local remPat(pat,expr,lds)
732 Cell pat; /* Produce list of definitions for eqn */
733 Cell expr; /* pat = expr, including a conformality */
734 List lds; { /* check if required. */
736 /* Conformality test (if required):
737 * pat = expr ==> nv = LETREC confCheck nv@pat = nv
739 * remPat1(pat,nv,.....);
742 if (!failFree(pat)) {
743 Cell confVar = inventVar();
744 Cell nv = inventVar();
745 Cell locfun = pair(confVar, /* confVar [([nv@refPat],nv)] */
746 singleton(pair(singleton(ap(ASPAT,
751 if (whatIs(expr)==GUARDED) { /* A spanner ... special case */
752 lds = addEqn(nv,expr,lds); /* for guarded pattern binding*/
757 if (whatIs(pat)==ASPAT) { /* avoid using new variable if*/
758 nv = fst(snd(pat)); /* a variable is already given*/
759 pat = snd(snd(pat)); /* by an as-pattern */
762 lds = addEqn(nv, /* nv = */
763 ap(LETREC,pair(singleton(locfun), /* LETREC [locfun] */
764 ap(confVar,expr))), /* IN confVar expr */
767 return remPat1(matchPat(pat),nv,lds);
770 return remPat1(matchPat(pat),expr,lds);
773 static List local remPat1(pat,expr,lds)
774 Cell pat; /* Add definitions for: pat = expr to */
775 Cell expr; /* list of local definitions in lds. */
777 Cell c = getHead(pat);
782 case CHARCELL : break;
784 case ASPAT : return remPat1(snd(snd(pat)), /* v@pat = expr */
786 addEqn(fst(snd(pat)),expr,lds));
788 case LAZYPAT : { Cell nv;
790 if (isVar(expr) || isName(expr))
794 lds = addEqn(nv,expr,lds);
797 return remPat(snd(pat),nv,lds);
800 case ADDPAT : return remPat1(arg(pat), /* n + k = expr */
803 mkInt(snd(fun(fun(pat))))),
807 case FINLIST : return remPat1(mkConsList(snd(pat)),expr,lds);
809 case CONFLDS : { Name h = fst(snd(pat));
810 Int m = name(h).arity;
812 List fs = snd(snd(pat));
816 for (; nonNull(fs); fs=tl(fs)) {
818 for (i=m-sfunPos(fst(hd(fs)),h); i>0; i--)
820 arg(r) = snd(hd(fs));
822 return remPat1(p,expr,lds);
825 case DICTVAR : /* shouldn't really occur */
826 assert(0); /* so let's test for it then! ADR */
828 case VAROPCELL : return addEqn(pat,expr,lds);
830 case NAME : if (c==nameFromInt || c==nameFromInteger
831 || c==nameFromDouble) {
833 arg(fun(pat)) = translate(arg(fun(pat)));
837 if (argCount==1 && isCfun(c) /* for newtype */
838 && cfunOf(c)==0 && name(c).defn==nameId)
839 return remPat1(arg(pat),expr,lds);
841 /* intentional fall-thru */
842 case TUPLE : { List ps = getArgs(pat);
848 if (isVar(expr) || isName(expr))
852 lds = addEqn(nv,expr,lds);
855 sel = ap(ap(nameSel,c),nv);
856 for (i=1; nonNull(ps); ++i, ps=tl(ps))
857 lds = remPat1(hd(ps),
865 case EXT : { Cell nv = inventVar();
867 = translate(arg(fun(fun(pat))));
873 lds = remPat1(extField(pat),ap(nameFst,nv),lds);
874 lds = remPat1(extRow(pat),ap(nameSnd,nv),lds);
879 default : internal("remPat1");
885 /* --------------------------------------------------------------------------
886 * Eliminate pattern matching in function definitions -- pattern matching
889 * The original Gofer/Hugs pattern matching compiler was based on Wadler's
890 * algorithms described in `Implementation of functional programming
891 * languages'. That should still provide a good starting point for anyone
892 * wanting to understand this part of the system. However, the original
893 * algorithm has been generalized and restructured in order to implement
894 * new features added in Haskell 1.3.
896 * During the translation, in preparation for later stages of compilation,
897 * all local and bound variables are replaced by suitable offsets, and
898 * locally defined function symbols are given new names (which will
899 * eventually be their names when lifted to make top level definitions).
900 * ------------------------------------------------------------------------*/
902 static Offset freeBegin; /* only variables with offset <= freeBegin are of */
903 static List freeVars; /* interest as `free' variables */
904 static List freeFuns; /* List of `free' local functions */
906 static Cell local pmcTerm(co,sc,e) /* apply pattern matching compiler */
907 Int co; /* co = current offset */
908 List sc; /* sc = scope */
909 Cell e; { /* e = expr to transform */
911 case GUARDED : map2Over(pmcPair,co,sc,snd(e));
914 case LETREC : pmcLetrec(co,sc,snd(e));
919 case DICTVAR : return pmcVar(sc,textOf(e));
921 case COND : return ap(COND,pmcTriple(co,sc,snd(e)));
923 case AP : return pmcPair(co,sc,e);
935 case STRCELL : break;
937 default : internal("pmcTerm");
943 static Cell local pmcPair(co,sc,pr) /* apply pattern matching compiler */
944 Int co; /* to a pair of exprs */
947 return pair(pmcTerm(co,sc,fst(pr)),
948 pmcTerm(co,sc,snd(pr)));
951 static Cell local pmcTriple(co,sc,tr) /* apply pattern matching compiler */
952 Int co; /* to a triple of exprs */
955 return triple(pmcTerm(co,sc,fst3(tr)),
956 pmcTerm(co,sc,snd3(tr)),
957 pmcTerm(co,sc,thd3(tr)));
960 static Cell local pmcVar(sc,t) /* find translation of variable */
961 List sc; /* in current scope */
966 for (xs=sc; nonNull(xs); xs=tl(xs)) {
968 if (t==textOf(fst(x))) {
969 if (isOffset(snd(x))) { /* local variable ... */
970 if (snd(x)<=freeBegin && !cellIsMember(snd(x),freeVars))
971 freeVars = cons(snd(x),freeVars);
974 else { /* local function ... */
975 if (!cellIsMember(snd(x),freeFuns))
976 freeFuns = cons(snd(x),freeFuns);
982 if (isNull(n=findName(t))) /* Lookup global name - the only way*/
983 n = newName(t,currentName); /* this (should be able to happen) */
984 /* is with new global var introduced*/
985 /* after type check; e.g. remPat1 */
989 static Void local pmcLetrec(co,sc,e) /* apply pattern matching compiler */
990 Int co; /* to LETREC, splitting decls into */
991 List sc; /* two sections */
993 List fs = NIL; /* local function definitions */
994 List vs = NIL; /* local variable definitions */
997 for (ds=fst(e); nonNull(ds); ds=tl(ds)) { /* Split decls into two */
998 Cell v = fst(hd(ds));
999 Int arity = length(fst(hd(snd(hd(ds)))));
1001 if (arity==0) { /* Variable declaration */
1002 vs = cons(snd(hd(ds)),vs);
1003 sc = cons(pair(v,mkOffset(++co)),sc);
1005 else { /* Function declaration */
1006 fs = cons(triple(inventVar(),mkInt(arity),snd(hd(ds))),fs);
1007 sc = cons(pair(v,hd(fs)),sc);
1010 vs = rev(vs); /* Put declaration lists back in */
1011 fs = rev(fs); /* original order */
1012 fst(e) = pair(vs,fs); /* Store declaration lists */
1013 map2Over(pmcVarDef,co,sc,vs); /* Translate variable definitions */
1014 map2Proc(pmcFunDef,co,sc,fs); /* Translate function definitions */
1015 snd(e) = pmcTerm(co,sc,snd(e)); /* Translate LETREC body */
1016 freeFuns = diffList(freeFuns,fs); /* Delete any `freeFuns' bound in fs*/
1019 static Cell local pmcVarDef(co,sc,vd) /* apply pattern matching compiler */
1020 Int co; /* to variable definition */
1022 List vd; { /* vd :: [ ([], rhs) ] */
1023 Cell d = snd(hd(vd));
1024 if (nonNull(tl(vd)) && canFail(d))
1025 return ap(FATBAR,pair(pmcTerm(co,sc,d),
1026 pmcVarDef(co,sc,tl(vd))));
1027 return pmcTerm(co,sc,d);
1030 static Void local pmcFunDef(co,sc,fd) /* apply pattern matching compiler */
1031 Int co; /* to function definition */
1033 Triple fd; { /* fd :: (Var, Arity, [Alt]) */
1034 Offset saveFreeBegin = freeBegin;
1035 List saveFreeVars = freeVars;
1036 List saveFreeFuns = freeFuns;
1037 Int arity = intOf(snd3(fd));
1038 Cell temp = altsMatch(co+1,arity,sc,thd3(fd));
1041 freeBegin = mkOffset(co);
1044 temp = match(co+arity,temp);
1045 thd3(fd) = triple(freeVars,freeFuns,temp);
1047 for (xs=freeVars; nonNull(xs); xs=tl(xs))
1048 if (hd(xs)<=saveFreeBegin && !cellIsMember(hd(xs),saveFreeVars))
1049 saveFreeVars = cons(hd(xs),saveFreeVars);
1051 for (xs=freeFuns; nonNull(xs); xs=tl(xs))
1052 if (!cellIsMember(hd(xs),saveFreeFuns))
1053 saveFreeFuns = cons(hd(xs),saveFreeFuns);
1055 freeBegin = saveFreeBegin;
1056 freeVars = saveFreeVars;
1057 freeFuns = saveFreeFuns;
1060 /* ---------------------------------------------------------------------------
1061 * Main part of pattern matching compiler: convert [Alt] to case constructs
1063 * This section of Hugs has been almost completely rewritten to be more
1064 * general, in particular, to allow pattern matching in orders other than the
1065 * strictly left-to-right approach of the previous version. This is needed
1066 * for the implementation of the so-called Haskell 1.3 `record' syntax.
1068 * At each stage, the different branches for the cases to be considered
1069 * are represented by a list of values of type:
1070 * Match ::= { maPats :: [Pat], patterns to match
1071 * maOffs :: [Offs], offsets of corresponding values
1072 * maSc :: Scope, mapping from vars to offsets
1073 * maRhs :: Rhs } right hand side
1074 * [Implementation uses nested pairs, ((pats,offs),(sc,rhs)).]
1076 * The Scope component has type:
1077 * Scope ::= [(Var,Expr)]
1078 * and provides a mapping from variable names to offsets used in the matching
1081 * Matches can be normalized by reducing them to a form in which the list
1082 * of patterns is empty (in which case the match itself is described as an
1083 * empty match), or in which the list is non-empty and the first pattern is
1084 * one that requires either a CASE or NUMCASE (or EXTCASE) to decompose.
1085 * ------------------------------------------------------------------------*/
1087 #define mkMatch(ps,os,sc,r) pair(pair(ps,os),pair(sc,r))
1088 #define maPats(ma) fst(fst(ma))
1089 #define maOffs(ma) snd(fst(ma))
1090 #define maSc(ma) fst(snd(ma))
1091 #define maRhs(ma) snd(snd(ma))
1092 #define extSc(v,o,ma) maSc(ma) = cons(pair(v,o),maSc(ma))
1094 static List local altsMatch(co,n,sc,as) /* Make a list of matches from list*/
1095 Int co; /* of Alts, with initial offsets */
1096 Int n; /* reverse (take n [co..]) */
1102 us = cons(mkOffset(co++),us);
1103 for (; nonNull(as); as=tl(as)) /* Each Alt is ([Pat], Rhs) */
1104 mas = cons(mkMatch(fst(hd(as)),us,sc,snd(hd(as))),mas);
1108 static Cell local match(co,mas) /* Generate case statement for Matches mas */
1109 Int co; /* at current offset co */
1110 List mas; { /* N.B. Assumes nonNull(mas). */
1111 Cell srhs = NIL; /* Rhs for selected matches */
1112 List smas = mas; /* List of selected matches */
1116 if (emptyMatch(hd(smas))) { /* The case for empty matches: */
1117 while (nonNull(mas) && emptyMatch(hd(mas))) {
1118 List temp = tl(mas);
1123 srhs = joinMas(co,rev(smas));
1125 else { /* Non-empty match */
1126 Int o = offsetOf(hd(maOffs(hd(smas))));
1127 Cell d = maDiscr(hd(smas));
1128 if (isNumDiscr(d)) { /* Numeric match */
1129 Int da = discrArity(d);
1130 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1131 while (nonNull(mas) && !emptyMatch(hd(mas))
1132 && o==offsetOf(hd(maOffs(hd(mas))))
1133 && isNumDiscr(d=maDiscr(hd(mas)))
1134 && eqNumDiscr(d,d1)) {
1135 List temp = tl(mas);
1141 map2Proc(advance,co,da,smas);
1142 srhs = ap(NUMCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1145 else if (isExtDiscr(d)) { /* Record match */
1146 Int da = discrArity(d);
1147 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1148 while (nonNull(mas) && !emptyMatch(hd(mas))
1149 && o==offsetOf(hd(maOffs(hd(mas))))
1150 && isExtDiscr(d=maDiscr(hd(mas)))
1151 && eqExtDiscr(d,d1)) {
1152 List temp = tl(mas);
1158 map2Proc(advance,co,da,smas);
1159 srhs = ap(EXTCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1162 else { /* Constructor match */
1163 List tab = addConTable(d,hd(smas),NIL);
1165 while (nonNull(mas) && !emptyMatch(hd(mas))
1166 && o==offsetOf(hd(maOffs(hd(mas))))
1167 && !isNumDiscr(d=maDiscr(hd(mas)))) {
1168 tab = addConTable(d,hd(mas),tab);
1171 for (tab=rev(tab); nonNull(tab); tab=tl(tab)) {
1173 smas = snd(hd(tab));
1175 map2Proc(advance,co,da,smas);
1176 srhs = cons(pair(d,match(co+da,smas)),srhs);
1178 srhs = ap(CASE,pair(mkOffset(o),srhs));
1181 return nonNull(mas) ? ap(FATBAR,pair(srhs,match(co,mas))) : srhs;
1184 static Cell local joinMas(co,mas) /* Combine list of matches into rhs*/
1185 Int co; /* using FATBARs as necessary */
1186 List mas; { /* Non-empty list of empty matches */
1188 Cell rhs = pmcTerm(co,maSc(ma),maRhs(ma));
1189 if (nonNull(tl(mas)) && canFail(rhs))
1190 return ap(FATBAR,pair(rhs,joinMas(co,tl(mas))));
1195 static Bool local canFail(rhs) /* Determine if expression (as rhs) */
1196 Cell rhs; { /* might ever be able to fail */
1197 switch (whatIs(rhs)) {
1198 case LETREC : return canFail(snd(snd(rhs)));
1199 case GUARDED : return TRUE; /* could get more sophisticated ..? */
1200 default : return FALSE;
1204 /* type Table a b = [(a, [b])]
1206 * addTable :: a -> b -> Table a b -> Table a b
1207 * addTable x y [] = [(x,[y])]
1208 * addTable x y (z@(n,sws):zs)
1209 * | n == x = (n,sws++[y]):zs
1210 * | otherwise = (n,sws):addTable x y zs
1213 static List local addConTable(x,y,tab) /* add element (x,y) to table */
1217 return singleton(pair(x,singleton(y)));
1218 else if (fst(hd(tab))==x)
1219 snd(hd(tab)) = appendOnto(snd(hd(tab)),singleton(y));
1221 tl(tab) = addConTable(x,y,tl(tab));
1226 static Void local advance(co,a,ma) /* Advance non-empty match by */
1227 Int co; /* processing head pattern */
1228 Int a; /* discriminator arity */
1230 Cell p = hd(maPats(ma));
1231 List ps = tl(maPats(ma));
1232 List us = tl(maOffs(ma));
1233 if (whatIs(p)==CONFLDS) { /* Special case for record syntax */
1234 Name c = fst(snd(p));
1235 List fs = snd(snd(p));
1238 for (; nonNull(fs); fs=tl(fs)) {
1239 vs = cons(mkOffset(co+a+1-sfunPos(fst(hd(fs)),c)),vs);
1240 qs = cons(snd(hd(fs)),qs);
1242 ps = revOnto(qs,ps);
1243 us = revOnto(vs,us);
1245 else /* Normally just spool off patterns*/
1246 for (; a>0; --a) { /* and corresponding offsets ... */
1247 us = cons(mkOffset(++co),us);
1248 ps = cons(arg(p),ps);
1256 /* --------------------------------------------------------------------------
1257 * Normalize and test for empty match:
1258 * ------------------------------------------------------------------------*/
1260 static Bool local emptyMatch(ma)/* Normalize and test to see if a given */
1261 Cell ma; { /* match, ma, is empty. */
1263 while (nonNull(maPats(ma))) {
1265 tidyHd: switch (whatIs(p=hd(maPats(ma)))) {
1266 case LAZYPAT : { Cell nv = inventVar();
1267 maRhs(ma) = ap(LETREC,
1268 pair(remPat(snd(p),nv,NIL),
1272 /* intentional fall-thru */
1275 case DICTVAR : extSc(p,hd(maOffs(ma)),ma);
1276 case WILDCARD : maPats(ma) = tl(maPats(ma));
1277 maOffs(ma) = tl(maOffs(ma));
1280 /* So-called "as-patterns"are really just pattern intersections:
1281 * (p1@p2:ps, o:os, sc, e) ==> (p1:p2:ps, o:o:os, sc, e)
1282 * (But the input grammar probably doesn't let us take
1283 * advantage of this, so we stick with the special case
1284 * when p1 is a variable.)
1286 case ASPAT : extSc(fst(snd(p)),hd(maOffs(ma)),ma);
1287 hd(maPats(ma)) = snd(snd(p));
1290 case FINLIST : hd(maPats(ma)) = mkConsList(snd(p));
1293 case STRCELL : { String s = textToStr(textOf(p));
1294 for (p=NIL; *s!='\0'; ++s) {
1295 if (*s!='\\' || *++s=='\\')
1296 p = ap(consChar(*s),p);
1298 p = ap(consChar('\0'),p);
1300 hd(maPats(ma)) = revOnto(p,nameNil);
1304 case AP : if (isName(fun(p)) && isCfun(fun(p))
1305 && cfunOf(fun(p))==0
1306 && name(fun(p)).defn==nameId) {
1307 hd(maPats(ma)) = arg(p);
1310 /* intentional fall-thru */
1316 default : internal("emptyMatch");
1322 /* --------------------------------------------------------------------------
1324 * ------------------------------------------------------------------------*/
1326 static Cell local maDiscr(ma) /* Get the discriminator for a non-empty */
1327 Cell ma; { /* match, ma. */
1328 Cell p = hd(maPats(ma));
1329 Cell h = getHead(p);
1330 switch (whatIs(h)) {
1331 case CONFLDS : return fst(snd(p));
1332 case ADDPAT : arg(fun(p)) = translate(arg(fun(p)));
1335 case EXT : h = fun(fun(p));
1336 arg(h) = translate(arg(h));
1339 case NAME : if (h==nameFromInt || h==nameFromInteger
1340 || h==nameFromDouble) {
1342 arg(fun(p)) = translate(arg(fun(p)));
1349 static Bool local isNumDiscr(d) /* TRUE => numeric discriminator */
1351 switch (whatIs(d)) {
1354 case CHARCELL : return FALSE;
1357 case AP : return !isExt(fun(d));
1359 case AP : return TRUE; /* must be a literal or (n+k) */
1362 internal("isNumDiscr");
1363 return 0;/*NOTREACHED*/
1366 Int discrArity(d) /* Find arity of discriminator */
1368 switch (whatIs(d)) {
1369 case NAME : return name(d).arity;
1370 case TUPLE : return tupleOf(d);
1371 case CHARCELL : return 0;
1373 case AP : switch (whatIs(fun(d))) {
1374 case ADDPAT : return 1;
1375 case EXT : return 2;
1379 case AP : return (whatIs(fun(d))==ADDPAT) ? 1 : 0;
1382 internal("discrArity");
1383 return 0;/*NOTREACHED*/
1386 static Bool local eqNumDiscr(d1,d2) /* Determine whether two numeric */
1387 Cell d1, d2; { /* descriptors have same value */
1388 if (whatIs(fun(d1))==ADDPAT)
1389 return whatIs(fun(d2))==ADDPAT && snd(fun(d1))==snd(fun(d2));
1391 return isInt(arg(d2)) && intOf(arg(d1))==intOf(arg(d2));
1392 if (isFloat(arg(d1)))
1393 return isFloat(arg(d2)) && floatOf(arg(d1))==floatOf(arg(d2));
1394 internal("eqNumDiscr");
1395 return FALSE;/*NOTREACHED*/
1399 static Bool local isExtDiscr(d) /* Test of extension discriminator */
1401 return isAp(d) && isExt(fun(d));
1404 static Bool local eqExtDiscr(d1,d2) /* Determine whether two extension */
1405 Cell d1, d2; { /* discriminators have same label */
1406 return fun(d1)==fun(d2);
1410 /*-------------------------------------------------------------------------*/
1414 /* --------------------------------------------------------------------------
1416 * ------------------------------------------------------------------------*/
1418 static Void local stgCGBinds( List );
1420 static Void local stgCGBinds(binds)
1425 /* --------------------------------------------------------------------------
1426 * Main entry points to compiler:
1427 * ------------------------------------------------------------------------*/
1429 static List addGlobals( List binds )
1431 /* stgGlobals = list of top-level STG binds */
1432 for(;nonNull(stgGlobals);stgGlobals=tl(stgGlobals)) {
1433 StgVar bind = snd(hd(stgGlobals));
1434 if (nonNull(stgVarBody(bind))) {
1435 binds = cons(bind,binds);
1441 typedef void (*sighandler_t)(int);
1442 void eval_ctrlbrk ( int dunnowhat )
1445 /* reinstall the signal handler so that further interrupts which
1446 happen before the thread can return to the scheduler, lead back
1447 here rather than invoking the previous break handler. */
1448 signal(SIGINT, eval_ctrlbrk);
1451 Void evalExp() { /* compile and run input expression */
1452 /* ToDo: this name (and other names generated during pattern match?)
1453 * get inserted in the symbol table but never get removed.
1455 Name n = newName(inventText(),NIL);
1457 StgVar v = mkStgVar(NIL,NIL);
1460 e = pmcTerm(0,NIL,translate(inputExpr));
1463 stgCGBinds(addGlobals(singleton(v)));
1465 /* Run thread (and any other runnable threads) */
1467 /* Re-initialise the scheduler - ToDo: do I need this? */
1468 /* JRS, 991118: on SM's advice, don't call initScheduler every time.
1469 This causes an assertion failure in GC.c(revert_dead_cafs)
1470 unless doRevertCAFs below is permanently TRUE.
1472 /* initScheduler(); */
1473 #ifdef CRUDE_PROFILING
1478 HaskellObj result; /* ignored */
1479 sighandler_t old_ctrlbrk;
1480 SchedulerStatus status;
1481 Bool doRevertCAFs = TRUE; /* do not change -- comment above */
1482 old_ctrlbrk = signal(SIGINT, eval_ctrlbrk);
1483 ASSERT(old_ctrlbrk != SIG_ERR);
1484 status = rts_eval_(closureOfVar(v),10000,&result);
1485 signal(SIGINT,old_ctrlbrk);
1490 printf("{Deadlock or Blackhole}");
1491 if (doRevertCAFs) RevertCAFs();
1494 printf("{Interrupted}");
1495 if (doRevertCAFs) RevertCAFs();
1498 printf("{Interrupted or Killed}");
1499 if (doRevertCAFs) RevertCAFs();
1502 if (doRevertCAFs) RevertCAFs();
1505 internal("evalExp: Unrecognised SchedulerStatus");
1511 #ifdef CRUDE_PROFILING
1518 static List local addStgVar( List binds, Pair bind )
1520 StgVar nv = mkStgVar(NIL,NIL);
1521 Text t = textOf(fst(bind));
1522 Name n = findName(t);
1524 if (isNull(n)) { /* Lookup global name - the only way*/
1525 n = newName(t,NIL); /* this (should be able to happen) */
1526 } /* is with new global var introduced*/
1527 /* after type check; e.g. remPat1 */
1528 name(n).stgVar = nv;
1529 return cons(nv,binds);
1533 Void compileDefns() { /* compile script definitions */
1534 Target t = length(valDefns) + length(genDefns) + length(selDefns);
1541 for(vs=genDefns; nonNull(vs); vs=tl(vs)) {
1543 StgVar nv = mkStgVar(NIL,NIL);
1545 name(n).stgVar = nv;
1546 binds = cons(nv,binds);
1548 for(vss=selDefns; nonNull(vss); vss=tl(vss)) {
1549 for(vs=hd(vss); nonNull(vs); vs=tl(vs)) {
1552 StgVar nv = mkStgVar(NIL,NIL);
1554 name(n).stgVar = nv;
1555 binds = cons(nv,binds);
1560 setGoal("Translating",t);
1561 /* do valDefns before everything else so that all stgVar's get added. */
1562 for (; nonNull(valDefns); valDefns=tl(valDefns)) {
1563 hd(valDefns) = transBinds(hd(valDefns));
1564 mapAccum(addStgVar,binds,hd(valDefns));
1565 mapProc(compileGlobalFunction,hd(valDefns));
1568 for (; nonNull(genDefns); genDefns=tl(genDefns)) {
1569 compileGenFunction(hd(genDefns));
1572 for (; nonNull(selDefns); selDefns=tl(selDefns)) {
1573 mapOver(compileSelFunction,hd(selDefns));
1577 binds = addGlobals(binds);
1579 setGoal("Generating code",t);
1585 static Void local compileGlobalFunction(bind)
1587 Name n = findName(textOf(fst(bind)));
1588 List defs = snd(bind);
1589 Int arity = length(fst(hd(defs)));
1592 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1595 static Void local compileGenFunction(n) /* Produce code for internally */
1596 Name n; { /* generated function */
1597 List defs = name(n).defn;
1598 Int arity = length(fst(hd(defs)));
1600 printf ( "compGenFn: " );print(defs,100);printf("\n");
1604 mapProc(transAlt,defs);
1605 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1609 static Name local compileSelFunction(p) /* Produce code for selector func */
1610 Pair p; { /* Should be merged with genDefns, */
1611 Name s = fst(p); /* but the name(_).defn field is */
1612 List defs = snd(p); /* already used for other purposes */
1613 Int arity = length(fst(hd(defs))); /* in selector functions. */
1616 mapProc(transAlt,defs);
1617 stgDefn(s,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1622 /* --------------------------------------------------------------------------
1624 * ------------------------------------------------------------------------*/
1630 case RESET : freeVars = NIL;
1632 freeBegin = mkOffset(0);
1635 case MARK : mark(freeVars);
1639 case POSTPREL: break;
1643 /*-------------------------------------------------------------------------*/