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/01/13 10:47:05 $
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));internal("translate");
196 static Void local transPair(pr) /* Translate each component in a */
197 Pair pr; { /* pair of expressions. */
198 fst(pr) = translate(fst(pr));
199 snd(pr) = translate(snd(pr));
202 static Void local transTriple(tr) /* Translate each component in a */
203 Triple tr; { /* triple of expressions. */
204 fst3(tr) = translate(fst3(tr));
205 snd3(tr) = translate(snd3(tr));
206 thd3(tr) = translate(thd3(tr));
209 static Void local transAlt(e) /* Translate alt: */
210 Cell e; { /* ([Pat], Rhs) ==> ([Pat], Rhs') */
211 snd(e) = transRhs(snd(e));
214 static Void local transCase(c) /* Translate case: */
215 Cell c; { /* (Pat, Rhs) ==> ([Pat], Rhs') */
216 fst(c) = singleton(fst(c));
217 snd(c) = transRhs(snd(c));
220 static List local transBinds(bs) /* Translate list of bindings: */
221 List bs; { /* eliminating pattern matching on */
222 List newBinds = NIL; /* lhs of bindings. */
223 for (; nonNull(bs); bs=tl(bs)) {
225 Cell v = fst(hd(bs));
226 while (isAp(v) && fst(v) == nameInd)
231 if (isVar(fst(hd(bs)))) {
233 mapProc(transAlt,snd(hd(bs)));
234 newBinds = cons(hd(bs),newBinds);
237 newBinds = remPat(fst(snd(hd(bs))),
238 snd(snd(hd(bs)))=transRhs(snd(snd(hd(bs)))),
244 static Cell local transRhs(rhs) /* Translate rhs: removing line nos */
246 switch (whatIs(rhs)) {
247 case LETREC : snd(snd(rhs)) = transRhs(snd(snd(rhs)));
248 return expandLetrec(rhs);
250 case GUARDED : mapOver(snd,snd(rhs)); /* discard line number */
251 mapProc(transPair,snd(rhs));
254 default : return translate(snd(rhs)); /* discard line number */
258 static Cell local mkConsList(es) /* Construct expression for list es */
259 List es; { /* using nameNil and nameCons */
263 return ap(ap(nameCons,hd(es)),mkConsList(tl(es)));
266 static Cell local expandLetrec(root) /* translate LETREC with list of */
267 Cell root; { /* groups of bindings (from depend. */
268 Cell e = snd(snd(root)); /* analysis) to use nested LETRECs */
269 List bss = fst(snd(root));
272 if (isNull(bss)) /* should never happen, but just in */
273 return e; /* case: LETREC [] IN e ==> e */
275 mapOver(transBinds,bss); /* translate each group of bindings */
277 for (temp=root; nonNull(tl(bss)); bss=tl(bss)) {
278 fst(snd(temp)) = hd(bss);
279 snd(snd(temp)) = ap(LETREC,pair(NIL,e));
280 temp = snd(snd(temp));
282 fst(snd(temp)) = hd(bss);
287 /* --------------------------------------------------------------------------
288 * Translation of list comprehensions is based on the description in
289 * `The Implementation of Functional Programming Languages':
291 * [ e | qs ] ++ l => transComp e qs l
292 * transComp e [] l => e : l
293 * transComp e ((p<-xs):qs) l => LETREC _h [] = l
294 * _h (p:_xs) = transComp e qs (_h _xs)
295 * _h (_:_xs) = _h _xs --if p !failFree
297 * transComp e (b:qs) l => if b then transComp e qs l else l
298 * transComp e (decls:qs) l => LETREC decls IN transComp e qs l
299 * ------------------------------------------------------------------------*/
301 static Cell local transComp(e,qs,l) /* Translate [e | qs] ++ l */
310 case FROMQUAL : { Cell ld = NIL;
311 Cell hVar = inventVar();
312 Cell xsVar = inventVar();
314 if (!failFree(fst(snd(q))))
315 ld = cons(pair(singleton(
322 ld = cons(pair(singleton(
330 ld = cons(pair(singleton(nameNil),
335 pair(singleton(pair(hVar,
338 translate(snd(snd(q))))));
342 expandLetrec(ap(LETREC,
344 transComp(e,qs1,l))));
346 case BOOLQUAL : return ap(COND,
347 triple(translate(snd(q)),
353 return ap(ap(nameCons,e),l);
356 /* --------------------------------------------------------------------------
357 * Translation of monad comprehensions written using do-notation:
360 * do { p <- exp; qs } => LETREC _h p = do { qs }
361 * _h _ = fail m "match fails"
363 * do { LET decls; qs } => LETREC decls IN do { qs }
364 * do { IF guard; qs } => if guard then do { qs } else fail m "guard fails"
365 * do { e; qs } => LETREC _h _ = [ e | qs ] in bind m exp _h
368 * ------------------------------------------------------------------------*/
370 static Cell local transDo(m,e,qs) /* Translate do { qs ; e } */
379 case FROMQUAL : { Cell ld = NIL;
380 Cell hVar = inventVar();
382 if (!failFree(fst(snd(q)))) {
383 Cell str = mkStr(findText("match fails"));
384 ld = cons(pair(singleton(WILDCARD),
385 ap2(nameMFail,m,str)),
389 ld = cons(pair(singleton(fst(snd(q))),
394 pair(singleton(pair(hVar,ld)),
397 translate(snd(snd(q)))),
401 case DOQUAL : { Cell hVar = inventVar();
402 Cell ld = cons(pair(singleton(WILDCARD),
406 pair(singleton(pair(hVar,ld)),
414 expandLetrec(ap(LETREC,
418 case BOOLQUAL : return
420 triple(translate(snd(q)),
423 mkStr(findText("guard fails")))));
429 /* --------------------------------------------------------------------------
430 * Translation of named field construction and update:
432 * Construction is implemented using the following transformation:
434 * C{x1=e1, ..., xn=en} = C v1 ... vm
436 * vi = e1, if the ith component of C is labelled with x1
438 * = en, if the ith component of C is labelled with xn
439 * = undefined, otherwise
441 * Update is implemented using the following transformation:
443 * e{x1=e1, ..., xn=en}
444 * = let nv (C a1 ... am) v1 ... vn = C a1' .. am'
445 * nv (D b1 ... bk) v1 ... vn = D b1' .. bk
447 * nv _ v1 ... vn = error "failed update"
450 * nv, v1, ..., vn, a1, ..., am, b1, ..., bk, ... are new variables,
451 * C,D,... = { K | K is a constr fun s.t. {x1,...,xn} subset of sels(K)}
453 * ai' = v1, if the ith component of C is labelled with x1
455 * = vn, if the ith component of C is labelled with xn
459 * The error case may be omitted if C,D,... is an enumeration of all of the
460 * constructors for the datatype concerned. Strictly speaking, error case
461 * isn't needed at all -- the only benefit of including it is that the user
462 * will get a "failed update" message rather than a cryptic {v354 ...}.
463 * So, for now, we'll go with the second option!
465 * For the time being, code for each update operation is generated
466 * independently of any other updates. However, if updates are used
467 * frequently, then we might want to consider changing the implementation
468 * at a later stage to cache definitions of functions like nv above. This
469 * would create a shared library of update functions, indexed by a set of
470 * constructors {C,D,...}.
471 * ------------------------------------------------------------------------*/
473 static Cell local transConFlds(c,flds) /* Translate C{flds} */
477 Int m = name(c).arity;
480 e = ap(e,nameUndefined);
481 for (; nonNull(flds); flds=tl(flds)) {
483 for (i=m-sfunPos(fst(hd(flds)),c); i>0; i--)
485 arg(a) = translate(snd(hd(flds)));
490 static Cell local transUpdFlds(e,cs,flds)/* Translate e{flds} */
491 Cell e; /* (cs is corresp list of constrs) */
494 Cell nv = inventVar();
495 Cell body = ap(nv,translate(e));
500 for (; nonNull(fs); fs=tl(fs)) { /* body = nv e1 ... en */
501 Cell b = hd(fs); /* args = [v1, ..., vn] */
502 body = ap(body,translate(snd(b)));
503 args = cons(inventVar(),args);
506 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constructors to */
507 Cell c = hd(cs); /* build up list of alts. */
511 Int m = name(c).arity;
514 for (i=m; i>0; i--) { /* pat = C a1 ... am */
515 Cell a = inventVar(); /* rhs = C a1 ... am */
520 for (fs=flds; nonNull(fs); fs=tl(fs), as=tl(as)) {
521 Name s = fst(hd(fs)); /* Replace approp ai in rhs with */
522 Cell r = rhs; /* vars from [v1,...,vn] */
523 for (i=m-sfunPos(s,c); i>0; i--)
528 alts = cons(pair(cons(pat,args),rhs),alts);
530 return ap(LETREC,pair(singleton(pair(nv,alts)),body));
533 /* --------------------------------------------------------------------------
534 * Elimination of pattern bindings:
536 * The following code adopts the definition of failure free patterns as given
537 * in the Haskell 1.3 report; the term "irrefutable" is also used there for
538 * a subset of the failure free patterns described here, but has no useful
539 * role in this implementation. Basically speaking, the failure free patterns
540 * are: variable, wildcard, ~apat
541 * var@apat, if apat is failure free
542 * C apat1 ... apatn if C is a product constructor
543 * (i.e. an only constructor) and
544 * apat1,...,apatn are failure free
545 * Note that the last case automatically covers the case where C comes from
546 * a newtype construction.
547 * ------------------------------------------------------------------------*/
549 Bool failFree(pat) /* is pattern failure free? (do we need */
550 Cell pat; { /* a conformality check?) */
551 Cell c = getHead(pat);
554 case ASPAT : return failFree(snd(snd(pat)));
556 case NAME : if (!isCfun(c) || cfunOf(c)!=0)
558 /*intentional fall-thru*/
559 case TUPLE : for (; isAp(pat); pat=fun(pat))
560 if (!failFree(arg(pat)))
562 /*intentional fall-thru*/
567 case WILDCARD : return TRUE;
570 case EXT : return failFree(extField(pat)) &&
571 failFree(extRow(pat));
574 case CONFLDS : if (cfunOf(fst(snd(c)))==0) {
575 List fs = snd(snd(c));
576 for (; nonNull(fs); fs=tl(fs))
577 if (!failFree(snd(hd(fs))))
581 /*intentional fall-thru*/
582 default : return FALSE;
586 static Cell local refutePat(pat) /* find pattern to refute in conformality*/
587 Cell pat; { /* test with pat. */
588 /* e.g. refPat (x:y) == (_:_) */
589 /* refPat ~(x:y) == _ etc.. */
591 switch (whatIs(pat)) {
592 case ASPAT : return refutePat(snd(snd(pat)));
594 case FINLIST : { Cell ys = snd(pat);
596 for (; nonNull(ys); ys=tl(ys))
597 xs = ap(ap(nameCons,refutePat(hd(ys))),xs);
598 return revOnto(xs,nameNil);
601 case CONFLDS : { Cell ps = NIL;
602 Cell fs = snd(snd(pat));
603 for (; nonNull(fs); fs=tl(fs)) {
604 Cell p = refutePat(snd(hd(fs)));
605 ps = cons(pair(fst(hd(fs)),p),ps);
607 return pair(CONFLDS,pair(fst(snd(pat)),rev(ps)));
614 case LAZYPAT : return WILDCARD;
622 case NAME : return pat;
624 case AP : return refutePatAp(pat);
626 default : internal("refutePat");
627 return NIL; /*NOTREACHED*/
631 static Cell local refutePatAp(p) /* find pattern to refute in conformality*/
634 if (h==nameFromInt || h==nameFromInteger || h==nameFromDouble)
637 else if (whatIs(h)==ADDPAT)
638 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)
708 else if (whatIs(h)==ADDPAT)
713 Cell pf = matchPat(extField(pat));
714 Cell pr = matchPat(extRow(pat));
715 return (pf==WILDCARD && pr==WILDCARD)
717 : ap(ap(fun(fun(pat)),pf),pr);
723 for (; isAp(pat); pat=fun(pat)) {
724 Cell p = matchPat(arg(pat));
729 return avar ? applyToArgs(pat,args)
734 default : internal("matchPat");
735 return NIL; /*NOTREACHED*/
739 #define addEqn(v,val,lds) cons(pair(v,singleton(pair(NIL,val))),lds)
741 static List local remPat(pat,expr,lds)
742 Cell pat; /* Produce list of definitions for eqn */
743 Cell expr; /* pat = expr, including a conformality */
744 List lds; { /* check if required. */
746 /* Conformality test (if required):
747 * pat = expr ==> nv = LETREC confCheck nv@pat = nv
749 * remPat1(pat,nv,.....);
752 if (!failFree(pat)) {
753 Cell confVar = inventVar();
754 Cell nv = inventVar();
755 Cell locfun = pair(confVar, /* confVar [([nv@refPat],nv)] */
756 singleton(pair(singleton(ap(ASPAT,
761 if (whatIs(expr)==GUARDED) { /* A spanner ... special case */
762 lds = addEqn(nv,expr,lds); /* for guarded pattern binding*/
767 if (whatIs(pat)==ASPAT) { /* avoid using new variable if*/
768 nv = fst(snd(pat)); /* a variable is already given*/
769 pat = snd(snd(pat)); /* by an as-pattern */
772 lds = addEqn(nv, /* nv = */
773 ap(LETREC,pair(singleton(locfun), /* LETREC [locfun] */
774 ap(confVar,expr))), /* IN confVar expr */
777 return remPat1(matchPat(pat),nv,lds);
780 return remPat1(matchPat(pat),expr,lds);
783 static List local remPat1(pat,expr,lds)
784 Cell pat; /* Add definitions for: pat = expr to */
785 Cell expr; /* list of local definitions in lds. */
787 Cell c = getHead(pat);
792 case CHARCELL : break;
794 case ASPAT : return remPat1(snd(snd(pat)), /* v@pat = expr */
796 addEqn(fst(snd(pat)),expr,lds));
798 case LAZYPAT : { Cell nv;
800 if (isVar(expr) || isName(expr))
804 lds = addEqn(nv,expr,lds);
807 return remPat(snd(pat),nv,lds);
811 case ADDPAT : return remPat1(arg(pat), /* n + k = expr */
814 mkInt(snd(fun(fun(pat))))),
819 case FINLIST : return remPat1(mkConsList(snd(pat)),expr,lds);
821 case CONFLDS : { Name h = fst(snd(pat));
822 Int m = name(h).arity;
824 List fs = snd(snd(pat));
828 for (; nonNull(fs); fs=tl(fs)) {
830 for (i=m-sfunPos(fst(hd(fs)),h); i>0; i--)
832 arg(r) = snd(hd(fs));
834 return remPat1(p,expr,lds);
837 case DICTVAR : /* shouldn't really occur */
838 assert(0); /* so let's test for it then! ADR */
840 case VAROPCELL : return addEqn(pat,expr,lds);
842 case NAME : if (c==nameFromInt || c==nameFromInteger
843 || c==nameFromDouble) {
845 arg(fun(pat)) = translate(arg(fun(pat)));
849 if (argCount==1 && isCfun(c) /* for newtype */
850 && cfunOf(c)==0 && name(c).defn==nameId)
851 return remPat1(arg(pat),expr,lds);
853 /* intentional fall-thru */
854 case TUPLE : { List ps = getArgs(pat);
860 if (isVar(expr) || isName(expr))
864 lds = addEqn(nv,expr,lds);
867 sel = ap(ap(nameSel,c),nv);
868 for (i=1; nonNull(ps); ++i, ps=tl(ps))
869 lds = remPat1(hd(ps),
877 case EXT : { Cell nv = inventVar();
879 = translate(arg(fun(fun(pat))));
885 lds = remPat1(extField(pat),ap(nameFst,nv),lds);
886 lds = remPat1(extRow(pat),ap(nameSnd,nv),lds);
891 default : internal("remPat1");
897 /* --------------------------------------------------------------------------
898 * Eliminate pattern matching in function definitions -- pattern matching
901 * The original Gofer/Hugs pattern matching compiler was based on Wadler's
902 * algorithms described in `Implementation of functional programming
903 * languages'. That should still provide a good starting point for anyone
904 * wanting to understand this part of the system. However, the original
905 * algorithm has been generalized and restructured in order to implement
906 * new features added in Haskell 1.3.
908 * During the translation, in preparation for later stages of compilation,
909 * all local and bound variables are replaced by suitable offsets, and
910 * locally defined function symbols are given new names (which will
911 * eventually be their names when lifted to make top level definitions).
912 * ------------------------------------------------------------------------*/
914 static Offset freeBegin; /* only variables with offset <= freeBegin are of */
915 static List freeVars; /* interest as `free' variables */
916 static List freeFuns; /* List of `free' local functions */
918 static Cell local pmcTerm(co,sc,e) /* apply pattern matching compiler */
919 Int co; /* co = current offset */
920 List sc; /* sc = scope */
921 Cell e; { /* e = expr to transform */
923 case GUARDED : map2Over(pmcPair,co,sc,snd(e));
926 case LETREC : pmcLetrec(co,sc,snd(e));
931 case DICTVAR : return pmcVar(sc,textOf(e));
933 case COND : return ap(COND,pmcTriple(co,sc,snd(e)));
935 case AP : return pmcPair(co,sc,e);
949 case STRCELL : break;
951 default : internal("pmcTerm");
957 static Cell local pmcPair(co,sc,pr) /* apply pattern matching compiler */
958 Int co; /* to a pair of exprs */
961 return pair(pmcTerm(co,sc,fst(pr)),
962 pmcTerm(co,sc,snd(pr)));
965 static Cell local pmcTriple(co,sc,tr) /* apply pattern matching compiler */
966 Int co; /* to a triple of exprs */
969 return triple(pmcTerm(co,sc,fst3(tr)),
970 pmcTerm(co,sc,snd3(tr)),
971 pmcTerm(co,sc,thd3(tr)));
974 static Cell local pmcVar(sc,t) /* find translation of variable */
975 List sc; /* in current scope */
980 for (xs=sc; nonNull(xs); xs=tl(xs)) {
982 if (t==textOf(fst(x))) {
983 if (isOffset(snd(x))) { /* local variable ... */
984 if (snd(x)<=freeBegin && !cellIsMember(snd(x),freeVars))
985 freeVars = cons(snd(x),freeVars);
988 else { /* local function ... */
989 if (!cellIsMember(snd(x),freeFuns))
990 freeFuns = cons(snd(x),freeFuns);
996 if (isNull(n=findName(t))) /* Lookup global name - the only way*/
997 n = newName(t,currentName); /* this (should be able to happen) */
998 /* is with new global var introduced*/
999 /* after type check; e.g. remPat1 */
1003 static Void local pmcLetrec(co,sc,e) /* apply pattern matching compiler */
1004 Int co; /* to LETREC, splitting decls into */
1005 List sc; /* two sections */
1007 List fs = NIL; /* local function definitions */
1008 List vs = NIL; /* local variable definitions */
1011 for (ds=fst(e); nonNull(ds); ds=tl(ds)) { /* Split decls into two */
1012 Cell v = fst(hd(ds));
1013 Int arity = length(fst(hd(snd(hd(ds)))));
1015 if (arity==0) { /* Variable declaration */
1016 vs = cons(snd(hd(ds)),vs);
1017 sc = cons(pair(v,mkOffset(++co)),sc);
1019 else { /* Function declaration */
1020 fs = cons(triple(inventVar(),mkInt(arity),snd(hd(ds))),fs);
1021 sc = cons(pair(v,hd(fs)),sc);
1024 vs = rev(vs); /* Put declaration lists back in */
1025 fs = rev(fs); /* original order */
1026 fst(e) = pair(vs,fs); /* Store declaration lists */
1027 map2Over(pmcVarDef,co,sc,vs); /* Translate variable definitions */
1028 map2Proc(pmcFunDef,co,sc,fs); /* Translate function definitions */
1029 snd(e) = pmcTerm(co,sc,snd(e)); /* Translate LETREC body */
1030 freeFuns = diffList(freeFuns,fs); /* Delete any `freeFuns' bound in fs*/
1033 static Cell local pmcVarDef(co,sc,vd) /* apply pattern matching compiler */
1034 Int co; /* to variable definition */
1036 List vd; { /* vd :: [ ([], rhs) ] */
1037 Cell d = snd(hd(vd));
1038 if (nonNull(tl(vd)) && canFail(d))
1039 return ap(FATBAR,pair(pmcTerm(co,sc,d),
1040 pmcVarDef(co,sc,tl(vd))));
1041 return pmcTerm(co,sc,d);
1044 static Void local pmcFunDef(co,sc,fd) /* apply pattern matching compiler */
1045 Int co; /* to function definition */
1047 Triple fd; { /* fd :: (Var, Arity, [Alt]) */
1048 Offset saveFreeBegin = freeBegin;
1049 List saveFreeVars = freeVars;
1050 List saveFreeFuns = freeFuns;
1051 Int arity = intOf(snd3(fd));
1052 Cell temp = altsMatch(co+1,arity,sc,thd3(fd));
1055 freeBegin = mkOffset(co);
1058 temp = match(co+arity,temp);
1059 thd3(fd) = triple(freeVars,freeFuns,temp);
1061 for (xs=freeVars; nonNull(xs); xs=tl(xs))
1062 if (hd(xs)<=saveFreeBegin && !cellIsMember(hd(xs),saveFreeVars))
1063 saveFreeVars = cons(hd(xs),saveFreeVars);
1065 for (xs=freeFuns; nonNull(xs); xs=tl(xs))
1066 if (!cellIsMember(hd(xs),saveFreeFuns))
1067 saveFreeFuns = cons(hd(xs),saveFreeFuns);
1069 freeBegin = saveFreeBegin;
1070 freeVars = saveFreeVars;
1071 freeFuns = saveFreeFuns;
1074 /* ---------------------------------------------------------------------------
1075 * Main part of pattern matching compiler: convert [Alt] to case constructs
1077 * This section of Hugs has been almost completely rewritten to be more
1078 * general, in particular, to allow pattern matching in orders other than the
1079 * strictly left-to-right approach of the previous version. This is needed
1080 * for the implementation of the so-called Haskell 1.3 `record' syntax.
1082 * At each stage, the different branches for the cases to be considered
1083 * are represented by a list of values of type:
1084 * Match ::= { maPats :: [Pat], patterns to match
1085 * maOffs :: [Offs], offsets of corresponding values
1086 * maSc :: Scope, mapping from vars to offsets
1087 * maRhs :: Rhs } right hand side
1088 * [Implementation uses nested pairs, ((pats,offs),(sc,rhs)).]
1090 * The Scope component has type:
1091 * Scope ::= [(Var,Expr)]
1092 * and provides a mapping from variable names to offsets used in the matching
1095 * Matches can be normalized by reducing them to a form in which the list
1096 * of patterns is empty (in which case the match itself is described as an
1097 * empty match), or in which the list is non-empty and the first pattern is
1098 * one that requires either a CASE or NUMCASE (or EXTCASE) to decompose.
1099 * ------------------------------------------------------------------------*/
1101 #define mkMatch(ps,os,sc,r) pair(pair(ps,os),pair(sc,r))
1102 #define maPats(ma) fst(fst(ma))
1103 #define maOffs(ma) snd(fst(ma))
1104 #define maSc(ma) fst(snd(ma))
1105 #define maRhs(ma) snd(snd(ma))
1106 #define extSc(v,o,ma) maSc(ma) = cons(pair(v,o),maSc(ma))
1108 static List local altsMatch(co,n,sc,as) /* Make a list of matches from list*/
1109 Int co; /* of Alts, with initial offsets */
1110 Int n; /* reverse (take n [co..]) */
1116 us = cons(mkOffset(co++),us);
1117 for (; nonNull(as); as=tl(as)) /* Each Alt is ([Pat], Rhs) */
1118 mas = cons(mkMatch(fst(hd(as)),us,sc,snd(hd(as))),mas);
1122 static Cell local match(co,mas) /* Generate case statement for Matches mas */
1123 Int co; /* at current offset co */
1124 List mas; { /* N.B. Assumes nonNull(mas). */
1125 Cell srhs = NIL; /* Rhs for selected matches */
1126 List smas = mas; /* List of selected matches */
1130 if (emptyMatch(hd(smas))) { /* The case for empty matches: */
1131 while (nonNull(mas) && emptyMatch(hd(mas))) {
1132 List temp = tl(mas);
1137 srhs = joinMas(co,rev(smas));
1139 else { /* Non-empty match */
1140 Int o = offsetOf(hd(maOffs(hd(smas))));
1141 Cell d = maDiscr(hd(smas));
1142 if (isNumDiscr(d)) { /* Numeric match */
1143 Int da = discrArity(d);
1144 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1145 while (nonNull(mas) && !emptyMatch(hd(mas))
1146 && o==offsetOf(hd(maOffs(hd(mas))))
1147 && isNumDiscr(d=maDiscr(hd(mas)))
1148 && eqNumDiscr(d,d1)) {
1149 List temp = tl(mas);
1155 map2Proc(advance,co,da,smas);
1156 srhs = ap(NUMCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1159 else if (isExtDiscr(d)) { /* Record match */
1160 Int da = discrArity(d);
1161 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1162 while (nonNull(mas) && !emptyMatch(hd(mas))
1163 && o==offsetOf(hd(maOffs(hd(mas))))
1164 && isExtDiscr(d=maDiscr(hd(mas)))
1165 && eqExtDiscr(d,d1)) {
1166 List temp = tl(mas);
1172 map2Proc(advance,co,da,smas);
1173 srhs = ap(EXTCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1176 else { /* Constructor match */
1177 List tab = addConTable(d,hd(smas),NIL);
1179 while (nonNull(mas) && !emptyMatch(hd(mas))
1180 && o==offsetOf(hd(maOffs(hd(mas))))
1181 && !isNumDiscr(d=maDiscr(hd(mas)))) {
1182 tab = addConTable(d,hd(mas),tab);
1185 for (tab=rev(tab); nonNull(tab); tab=tl(tab)) {
1187 smas = snd(hd(tab));
1189 map2Proc(advance,co,da,smas);
1190 srhs = cons(pair(d,match(co+da,smas)),srhs);
1192 srhs = ap(CASE,pair(mkOffset(o),srhs));
1195 return nonNull(mas) ? ap(FATBAR,pair(srhs,match(co,mas))) : srhs;
1198 static Cell local joinMas(co,mas) /* Combine list of matches into rhs*/
1199 Int co; /* using FATBARs as necessary */
1200 List mas; { /* Non-empty list of empty matches */
1202 Cell rhs = pmcTerm(co,maSc(ma),maRhs(ma));
1203 if (nonNull(tl(mas)) && canFail(rhs))
1204 return ap(FATBAR,pair(rhs,joinMas(co,tl(mas))));
1209 static Bool local canFail(rhs) /* Determine if expression (as rhs) */
1210 Cell rhs; { /* might ever be able to fail */
1211 switch (whatIs(rhs)) {
1212 case LETREC : return canFail(snd(snd(rhs)));
1213 case GUARDED : return TRUE; /* could get more sophisticated ..? */
1214 default : return FALSE;
1218 /* type Table a b = [(a, [b])]
1220 * addTable :: a -> b -> Table a b -> Table a b
1221 * addTable x y [] = [(x,[y])]
1222 * addTable x y (z@(n,sws):zs)
1223 * | n == x = (n,sws++[y]):zs
1224 * | otherwise = (n,sws):addTable x y zs
1227 static List local addConTable(x,y,tab) /* add element (x,y) to table */
1231 return singleton(pair(x,singleton(y)));
1232 else if (fst(hd(tab))==x)
1233 snd(hd(tab)) = appendOnto(snd(hd(tab)),singleton(y));
1235 tl(tab) = addConTable(x,y,tl(tab));
1240 static Void local advance(co,a,ma) /* Advance non-empty match by */
1241 Int co; /* processing head pattern */
1242 Int a; /* discriminator arity */
1244 Cell p = hd(maPats(ma));
1245 List ps = tl(maPats(ma));
1246 List us = tl(maOffs(ma));
1247 if (whatIs(p)==CONFLDS) { /* Special case for record syntax */
1248 Name c = fst(snd(p));
1249 List fs = snd(snd(p));
1252 for (; nonNull(fs); fs=tl(fs)) {
1253 vs = cons(mkOffset(co+a+1-sfunPos(fst(hd(fs)),c)),vs);
1254 qs = cons(snd(hd(fs)),qs);
1256 ps = revOnto(qs,ps);
1257 us = revOnto(vs,us);
1259 else /* Normally just spool off patterns*/
1260 for (; a>0; --a) { /* and corresponding offsets ... */
1261 us = cons(mkOffset(++co),us);
1262 ps = cons(arg(p),ps);
1270 /* --------------------------------------------------------------------------
1271 * Normalize and test for empty match:
1272 * ------------------------------------------------------------------------*/
1274 static Bool local emptyMatch(ma)/* Normalize and test to see if a given */
1275 Cell ma; { /* match, ma, is empty. */
1277 while (nonNull(maPats(ma))) {
1279 tidyHd: switch (whatIs(p=hd(maPats(ma)))) {
1280 case LAZYPAT : { Cell nv = inventVar();
1281 maRhs(ma) = ap(LETREC,
1282 pair(remPat(snd(p),nv,NIL),
1286 /* intentional fall-thru */
1289 case DICTVAR : extSc(p,hd(maOffs(ma)),ma);
1290 case WILDCARD : maPats(ma) = tl(maPats(ma));
1291 maOffs(ma) = tl(maOffs(ma));
1294 /* So-called "as-patterns"are really just pattern intersections:
1295 * (p1@p2:ps, o:os, sc, e) ==> (p1:p2:ps, o:o:os, sc, e)
1296 * (But the input grammar probably doesn't let us take
1297 * advantage of this, so we stick with the special case
1298 * when p1 is a variable.)
1300 case ASPAT : extSc(fst(snd(p)),hd(maOffs(ma)),ma);
1301 hd(maPats(ma)) = snd(snd(p));
1304 case FINLIST : hd(maPats(ma)) = mkConsList(snd(p));
1307 case STRCELL : { String s = textToStr(textOf(p));
1308 for (p=NIL; *s!='\0'; ++s) {
1309 if (*s!='\\' || *++s=='\\')
1310 p = ap(consChar(*s),p);
1312 p = ap(consChar('\0'),p);
1314 hd(maPats(ma)) = revOnto(p,nameNil);
1318 case AP : if (isName(fun(p)) && isCfun(fun(p))
1319 && cfunOf(fun(p))==0
1320 && name(fun(p)).defn==nameId) {
1321 hd(maPats(ma)) = arg(p);
1324 /* intentional fall-thru */
1330 default : internal("emptyMatch");
1336 /* --------------------------------------------------------------------------
1338 * ------------------------------------------------------------------------*/
1340 static Cell local maDiscr(ma) /* Get the discriminator for a non-empty */
1341 Cell ma; { /* match, ma. */
1342 Cell p = hd(maPats(ma));
1343 Cell h = getHead(p);
1344 switch (whatIs(h)) {
1345 case CONFLDS : return fst(snd(p));
1347 case ADDPAT : arg(fun(p)) = translate(arg(fun(p)));
1351 case EXT : h = fun(fun(p));
1352 arg(h) = translate(arg(h));
1355 case NAME : if (h==nameFromInt || h==nameFromInteger
1356 || h==nameFromDouble) {
1358 arg(fun(p)) = translate(arg(fun(p)));
1365 static Bool local isNumDiscr(d) /* TRUE => numeric discriminator */
1367 switch (whatIs(d)) {
1370 case CHARCELL : return FALSE;
1373 case AP : return !isExt(fun(d));
1375 case AP : return TRUE; /* must be a literal or (n+k) */
1378 internal("isNumDiscr");
1379 return 0;/*NOTREACHED*/
1382 Int discrArity(d) /* Find arity of discriminator */
1384 switch (whatIs(d)) {
1385 case NAME : return name(d).arity;
1386 case TUPLE : return tupleOf(d);
1387 case CHARCELL : return 0;
1389 case AP : switch (whatIs(fun(d))) {
1391 case ADDPAT : return 1;
1393 case EXT : return 2;
1398 case AP : return (whatIs(fun(d))==ADDPAT) ? 1 : 0;
1400 case AP : return 0; /* must be an Int or Float lit */
1404 internal("discrArity");
1405 return 0;/*NOTREACHED*/
1408 static Bool local eqNumDiscr(d1,d2) /* Determine whether two numeric */
1409 Cell d1, d2; { /* descriptors have same value */
1411 if (whatIs(fun(d1))==ADDPAT)
1412 return whatIs(fun(d2))==ADDPAT && snd(fun(d1))==snd(fun(d2));
1415 return isInt(arg(d2)) && intOf(arg(d1))==intOf(arg(d2));
1416 if (isFloat(arg(d1)))
1417 return isFloat(arg(d2)) && floatOf(arg(d1))==floatOf(arg(d2));
1418 internal("eqNumDiscr");
1419 return FALSE;/*NOTREACHED*/
1423 static Bool local isExtDiscr(d) /* Test of extension discriminator */
1425 return isAp(d) && isExt(fun(d));
1428 static Bool local eqExtDiscr(d1,d2) /* Determine whether two extension */
1429 Cell d1, d2; { /* discriminators have same label */
1430 return fun(d1)==fun(d2);
1434 /*-------------------------------------------------------------------------*/
1438 /* --------------------------------------------------------------------------
1440 * ------------------------------------------------------------------------*/
1442 static Void local stgCGBinds( List );
1444 static Void local stgCGBinds(binds)
1449 /* --------------------------------------------------------------------------
1450 * Main entry points to compiler:
1451 * ------------------------------------------------------------------------*/
1453 static List addGlobals( List binds )
1455 /* stgGlobals = list of top-level STG binds */
1456 for(;nonNull(stgGlobals);stgGlobals=tl(stgGlobals)) {
1457 StgVar bind = snd(hd(stgGlobals));
1458 if (nonNull(stgVarBody(bind))) {
1459 binds = cons(bind,binds);
1465 typedef void (*sighandler_t)(int);
1466 void eval_ctrlbrk ( int dunnowhat )
1469 /* reinstall the signal handler so that further interrupts which
1470 happen before the thread can return to the scheduler, lead back
1471 here rather than invoking the previous break handler. */
1472 signal(SIGINT, eval_ctrlbrk);
1475 Void evalExp() { /* compile and run input expression */
1476 /* ToDo: this name (and other names generated during pattern match?)
1477 * get inserted in the symbol table but never get removed.
1479 Name n = newName(inventText(),NIL);
1481 StgVar v = mkStgVar(NIL,NIL);
1484 e = pmcTerm(0,NIL,translate(inputExpr));
1487 stgCGBinds(addGlobals(singleton(v)));
1489 /* Run thread (and any other runnable threads) */
1491 /* Re-initialise the scheduler - ToDo: do I need this? */
1492 /* JRS, 991118: on SM's advice, don't call initScheduler every time.
1493 This causes an assertion failure in GC.c(revert_dead_cafs)
1494 unless doRevertCAFs below is permanently TRUE.
1496 /* initScheduler(); */
1497 #ifdef CRUDE_PROFILING
1502 HaskellObj result; /* ignored */
1503 sighandler_t old_ctrlbrk;
1504 SchedulerStatus status;
1505 Bool doRevertCAFs = TRUE; /* do not change -- comment above */
1506 old_ctrlbrk = signal(SIGINT, eval_ctrlbrk);
1507 ASSERT(old_ctrlbrk != SIG_ERR);
1508 status = rts_eval_(closureOfVar(v),10000,&result);
1509 signal(SIGINT,old_ctrlbrk);
1514 printf("{Deadlock or Blackhole}");
1515 if (doRevertCAFs) RevertCAFs();
1518 printf("{Interrupted}");
1519 if (doRevertCAFs) RevertCAFs();
1522 printf("{Interrupted or Killed}");
1523 if (doRevertCAFs) RevertCAFs();
1526 if (doRevertCAFs) RevertCAFs();
1529 internal("evalExp: Unrecognised SchedulerStatus");
1535 #ifdef CRUDE_PROFILING
1542 static List local addStgVar( List binds, Pair bind )
1544 StgVar nv = mkStgVar(NIL,NIL);
1545 Text t = textOf(fst(bind));
1546 Name n = findName(t);
1548 if (isNull(n)) { /* Lookup global name - the only way*/
1549 n = newName(t,NIL); /* this (should be able to happen) */
1550 } /* is with new global var introduced*/
1551 /* after type check; e.g. remPat1 */
1552 name(n).stgVar = nv;
1553 return cons(nv,binds);
1557 Void compileDefns() { /* compile script definitions */
1558 Target t = length(valDefns) + length(genDefns) + length(selDefns);
1565 for(vs=genDefns; nonNull(vs); vs=tl(vs)) {
1567 StgVar nv = mkStgVar(NIL,NIL);
1569 name(n).stgVar = nv;
1570 binds = cons(nv,binds);
1572 for(vss=selDefns; nonNull(vss); vss=tl(vss)) {
1573 for(vs=hd(vss); nonNull(vs); vs=tl(vs)) {
1576 StgVar nv = mkStgVar(NIL,NIL);
1578 name(n).stgVar = nv;
1579 binds = cons(nv,binds);
1584 setGoal("Translating",t);
1585 /* do valDefns before everything else so that all stgVar's get added. */
1586 for (; nonNull(valDefns); valDefns=tl(valDefns)) {
1587 hd(valDefns) = transBinds(hd(valDefns));
1588 mapAccum(addStgVar,binds,hd(valDefns));
1589 mapProc(compileGlobalFunction,hd(valDefns));
1592 for (; nonNull(genDefns); genDefns=tl(genDefns)) {
1593 compileGenFunction(hd(genDefns));
1596 for (; nonNull(selDefns); selDefns=tl(selDefns)) {
1597 mapOver(compileSelFunction,hd(selDefns));
1601 binds = addGlobals(binds);
1603 setGoal("Generating code",t);
1609 static Void local compileGlobalFunction(bind)
1611 Name n = findName(textOf(fst(bind)));
1612 List defs = snd(bind);
1613 Int arity = length(fst(hd(defs)));
1616 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1619 static Void local compileGenFunction(n) /* Produce code for internally */
1620 Name n; { /* generated function */
1621 List defs = name(n).defn;
1622 Int arity = length(fst(hd(defs)));
1625 mapProc(transAlt,defs);
1626 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1630 static Name local compileSelFunction(p) /* Produce code for selector func */
1631 Pair p; { /* Should be merged with genDefns, */
1632 Name s = fst(p); /* but the name(_).defn field is */
1633 List defs = snd(p); /* already used for other purposes */
1634 Int arity = length(fst(hd(defs))); /* in selector functions. */
1637 mapProc(transAlt,defs);
1638 stgDefn(s,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1643 /* --------------------------------------------------------------------------
1645 * ------------------------------------------------------------------------*/
1651 case RESET : freeVars = NIL;
1653 freeBegin = mkOffset(0);
1656 case MARK : mark(freeVars);
1660 case POSTPREL: break;
1664 /*-------------------------------------------------------------------------*/