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 * Hugs 98 is Copyright (c) Mark P Jones, Alastair Reid and the Yale
8 * Haskell Group 1994-99, and is distributed as Open Source software
9 * under the Artistic License; see the file "Artistic" that is included
10 * in the distribution for details.
12 * $RCSfile: compiler.c,v $
14 * $Date: 1999/02/03 17:08:26 $
15 * ------------------------------------------------------------------------*/
22 #include "Rts.h" /* for rts_eval and related stuff */
23 #include "RtsAPI.h" /* for rts_eval and related stuff */
27 /*#define DEBUG_SHOWSC*/ /* Must also be set in output.c */
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 Cell local lift Args((Int,List,Cell));
84 static Void local liftPair Args((Int,List,Pair));
85 static Void local liftTriple Args((Int,List,Triple));
86 static Void local liftAlt Args((Int,List,Cell));
87 static Void local liftNumcase Args((Int,List,Triple));
88 static Cell local liftVar Args((List,Cell));
89 static Cell local liftLetrec Args((Int,List,Cell));
90 static Void local liftFundef Args((Int,List,Triple));
91 static Void local solve Args((List));
93 static Cell local preComp Args((Cell));
94 static Cell local preCompPair Args((Pair));
95 static Cell local preCompTriple Args((Triple));
96 static Void local preCompCase Args((Pair));
97 static Cell local preCompOffset Args((Int));
99 static Void local compileGlobalFunction Args((Pair));
100 static Void local compileGenFunction Args((Name));
101 static Name local compileSelFunction Args((Pair));
102 static Void local newGlobalFunction Args((Name,Int,List,Int,Cell));
104 /* --------------------------------------------------------------------------
105 * Translation: Convert input expressions into a less complex language
106 * of terms using only LETREC, AP, constants and vars.
107 * Also remove pattern definitions on lhs of eqns.
108 * ------------------------------------------------------------------------*/
110 static Cell local translate(e) /* Translate expression: */
113 case LETREC : snd(snd(e)) = translate(snd(snd(e)));
114 return expandLetrec(e);
116 case COND : transTriple(snd(e));
119 case AP : fst(e) = translate(fst(e));
121 if (fst(e)==nameId || fst(e)==nameInd)
122 return translate(snd(e));
124 if (fst(e)==nameStrict)
129 if (isName(fst(e)) &&
132 return translate(snd(e));
134 snd(e) = translate(snd(e));
140 case NEGNUM : return e;
142 case NAME : if (e==nameOtherwise)
145 if (isName(name(e).defn))
147 if (isPair(name(e).defn))
148 return snd(name(e).defn);
153 case RECSEL : return nameRecSel;
164 case CHARCELL : return e;
166 case FINLIST : mapOver(translate,snd(e));
167 return mkConsList(snd(e));
169 case DOCOMP : { Cell m = translate(fst(snd(e)));
170 Cell r = translate(fst(snd(snd(e))));
171 return transDo(m,r,snd(snd(snd(e))));
174 case MONADCOMP : { Cell m = translate(fst(snd(e)));
175 Cell r = translate(fst(snd(snd(e))));
176 Cell qs = snd(snd(snd(e)));
177 if (m == nameListMonad)
178 return transComp(r,qs,nameNil);
181 r = ap(ap(nameReturn,m),r);
182 return transDo(m,r,qs);
184 internal("translate: monad comps");
189 case CONFLDS : return transConFlds(fst(snd(e)),snd(snd(e)));
191 case UPDFLDS : return transUpdFlds(fst3(snd(e)),
195 case CASE : { Cell nv = inventVar();
196 mapProc(transCase,snd(snd(e)));
198 pair(singleton(pair(nv,snd(snd(e)))),
199 ap(nv,translate(fst(snd(e))))));
202 case LAMBDA : { Cell nv = inventVar();
211 default : internal("translate");
216 static Void local transPair(pr) /* Translate each component in a */
217 Pair pr; { /* pair of expressions. */
218 fst(pr) = translate(fst(pr));
219 snd(pr) = translate(snd(pr));
222 static Void local transTriple(tr) /* Translate each component in a */
223 Triple tr; { /* triple of expressions. */
224 fst3(tr) = translate(fst3(tr));
225 snd3(tr) = translate(snd3(tr));
226 thd3(tr) = translate(thd3(tr));
229 static Void local transAlt(e) /* Translate alt: */
230 Cell e; { /* ([Pat], Rhs) ==> ([Pat], Rhs') */
231 snd(e) = transRhs(snd(e));
234 static Void local transCase(c) /* Translate case: */
235 Cell c; { /* (Pat, Rhs) ==> ([Pat], Rhs') */
236 fst(c) = singleton(fst(c));
237 snd(c) = transRhs(snd(c));
240 static List local transBinds(bs) /* Translate list of bindings: */
241 List bs; { /* eliminating pattern matching on */
242 List newBinds = NIL; /* lhs of bindings. */
243 for (; nonNull(bs); bs=tl(bs)) {
244 if (isVar(fst(hd(bs)))) {
245 mapProc(transAlt,snd(hd(bs)));
246 newBinds = cons(hd(bs),newBinds);
249 newBinds = remPat(fst(snd(hd(bs))),
250 snd(snd(hd(bs)))=transRhs(snd(snd(hd(bs)))),
256 static Cell local transRhs(rhs) /* Translate rhs: removing line nos */
258 switch (whatIs(rhs)) {
259 case LETREC : snd(snd(rhs)) = transRhs(snd(snd(rhs)));
260 return expandLetrec(rhs);
262 case GUARDED : mapOver(snd,snd(rhs)); /* discard line number */
263 mapProc(transPair,snd(rhs));
266 default : return translate(snd(rhs)); /* discard line number */
270 static Cell local mkConsList(es) /* Construct expression for list es */
271 List es; { /* using nameNil and nameCons */
275 return ap(ap(nameCons,hd(es)),mkConsList(tl(es)));
278 static Cell local expandLetrec(root) /* translate LETREC with list of */
279 Cell root; { /* groups of bindings (from depend. */
280 Cell e = snd(snd(root)); /* analysis) to use nested LETRECs */
281 List bss = fst(snd(root));
284 if (isNull(bss)) /* should never happen, but just in */
285 return e; /* case: LETREC [] IN e ==> e */
287 mapOver(transBinds,bss); /* translate each group of bindings */
289 for (temp=root; nonNull(tl(bss)); bss=tl(bss)) {
290 fst(snd(temp)) = hd(bss);
291 snd(snd(temp)) = ap(LETREC,pair(NIL,e));
292 temp = snd(snd(temp));
294 fst(snd(temp)) = hd(bss);
299 /* --------------------------------------------------------------------------
300 * Translation of list comprehensions is based on the description in
301 * `The Implementation of Functional Programming Languages':
303 * [ e | qs ] ++ l => transComp e qs l
304 * transComp e [] l => e : l
305 * transComp e ((p<-xs):qs) l => LETREC _h [] = l
306 * _h (p:_xs) = transComp e qs (_h _xs)
307 * _h (_:_xs) = _h _xs --if p !failFree
309 * transComp e (b:qs) l => if b then transComp e qs l else l
310 * transComp e (decls:qs) l => LETREC decls IN transComp e qs l
311 * ------------------------------------------------------------------------*/
313 static Cell local transComp(e,qs,l) /* Translate [e | qs] ++ l */
322 case FROMQUAL : { Cell ld = NIL;
323 Cell hVar = inventVar();
324 Cell xsVar = inventVar();
326 if (!failFree(fst(snd(q))))
327 ld = cons(pair(singleton(
334 ld = cons(pair(singleton(
342 ld = cons(pair(singleton(nameNil),
347 pair(singleton(pair(hVar,
350 translate(snd(snd(q))))));
354 expandLetrec(ap(LETREC,
356 transComp(e,qs1,l))));
358 case BOOLQUAL : return ap(COND,
359 triple(translate(snd(q)),
365 return ap(ap(nameCons,e),l);
368 /* --------------------------------------------------------------------------
369 * Translation of monad comprehensions written using do-notation:
372 * do { p <- exp; qs } => LETREC _h p = do { qs }
373 * _h _ = fail m "match fails"
375 * do { LET decls; qs } => LETREC decls IN do { qs }
376 * do { IF guard; qs } => if guard then do { qs } else fail m "guard fails"
377 * do { e; qs } => LETREC _h _ = [ e | qs ] in bind m exp _h
380 * ------------------------------------------------------------------------*/
382 static Cell local transDo(m,e,qs) /* Translate do { qs ; e } */
391 case FROMQUAL : { Cell ld = NIL;
392 Cell hVar = inventVar();
394 if (!failFree(fst(snd(q)))) {
395 Cell str = mkStr(findText("match fails"));
396 ld = cons(pair(singleton(WILDCARD),
397 ap2(nameMFail,m,str)),
401 ld = cons(pair(singleton(fst(snd(q))),
406 pair(singleton(pair(hVar,ld)),
409 translate(snd(snd(q)))),
413 case DOQUAL : { Cell hVar = inventVar();
414 Cell ld = cons(pair(singleton(WILDCARD),
418 pair(singleton(pair(hVar,ld)),
426 expandLetrec(ap(LETREC,
430 case BOOLQUAL : return
432 triple(translate(snd(q)),
435 mkStr(findText("guard fails")))));
441 /* --------------------------------------------------------------------------
442 * Translation of named field construction and update:
444 * Construction is implemented using the following transformation:
446 * C{x1=e1, ..., xn=en} = C v1 ... vm
448 * vi = e1, if the ith component of C is labelled with x1
450 * = en, if the ith component of C is labelled with xn
451 * = undefined, otherwise
453 * Update is implemented using the following transformation:
455 * e{x1=e1, ..., xn=en}
456 * = let nv (C a1 ... am) v1 ... vn = C a1' .. am'
457 * nv (D b1 ... bk) v1 ... vn = D b1' .. bk
459 * nv _ v1 ... vn = error "failed update"
462 * nv, v1, ..., vn, a1, ..., am, b1, ..., bk, ... are new variables,
463 * C,D,... = { K | K is a constr fun s.t. {x1,...,xn} subset of sels(K)}
465 * ai' = v1, if the ith component of C is labelled with x1
467 * = vn, if the ith component of C is labelled with xn
471 * The error case may be omitted if C,D,... is an enumeration of all of the
472 * constructors for the datatype concerned. Strictly speaking, error case
473 * isn't needed at all -- the only benefit of including it is that the user
474 * will get a "failed update" message rather than a cryptic {v354 ...}.
475 * So, for now, we'll go with the second option!
477 * For the time being, code for each update operation is generated
478 * independently of any other updates. However, if updates are used
479 * frequently, then we might want to consider changing the implementation
480 * at a later stage to cache definitions of functions like nv above. This
481 * would create a shared library of update functions, indexed by a set of
482 * constructors {C,D,...}.
483 * ------------------------------------------------------------------------*/
485 static Cell local transConFlds(c,flds) /* Translate C{flds} */
489 Int m = name(c).arity;
492 e = ap(e,nameUndefined);
493 for (; nonNull(flds); flds=tl(flds)) {
495 for (i=m-sfunPos(fst(hd(flds)),c); i>0; i--)
497 arg(a) = translate(snd(hd(flds)));
502 static Cell local transUpdFlds(e,cs,flds)/* Translate e{flds} */
503 Cell e; /* (cs is corresp list of constrs) */
506 Cell nv = inventVar();
507 Cell body = ap(nv,translate(e));
512 for (; nonNull(fs); fs=tl(fs)) { /* body = nv e1 ... en */
513 Cell b = hd(fs); /* args = [v1, ..., vn] */
514 body = ap(body,translate(snd(b)));
515 args = cons(inventVar(),args);
518 for (; nonNull(cs); cs=tl(cs)) { /* Loop through constructors to */
519 Cell c = hd(cs); /* build up list of alts. */
523 Int m = name(c).arity;
526 for (i=m; i>0; i--) { /* pat = C a1 ... am */
527 Cell a = inventVar(); /* rhs = C a1 ... am */
532 for (fs=flds; nonNull(fs); fs=tl(fs), as=tl(as)) {
533 Name s = fst(hd(fs)); /* Replace approp ai in rhs with */
534 Cell r = rhs; /* vars from [v1,...,vn] */
535 for (i=m-sfunPos(s,c); i>0; i--)
540 alts = cons(pair(cons(pat,args),rhs),alts);
542 return ap(LETREC,pair(singleton(pair(nv,alts)),body));
545 /* --------------------------------------------------------------------------
546 * Elimination of pattern bindings:
548 * The following code adopts the definition of failure free patterns as given
549 * in the Haskell 1.3 report; the term "irrefutable" is also used there for
550 * a subset of the failure free patterns described here, but has no useful
551 * role in this implementation. Basically speaking, the failure free patterns
552 * are: variable, wildcard, ~apat
553 * var@apat, if apat is failure free
554 * C apat1 ... apatn if C is a product constructor
555 * (i.e. an only constructor) and
556 * apat1,...,apatn are failure free
557 * Note that the last case automatically covers the case where C comes from
558 * a newtype construction.
559 * ------------------------------------------------------------------------*/
561 Bool failFree(pat) /* is pattern failure free? (do we need */
562 Cell pat; { /* a conformality check?) */
563 Cell c = getHead(pat);
566 case ASPAT : return failFree(snd(snd(pat)));
568 case NAME : if (!isCfun(c) || cfunOf(c)!=0)
570 /*intentional fall-thru*/
571 case TUPLE : for (; isAp(pat); pat=fun(pat))
572 if (!failFree(arg(pat)))
574 /*intentional fall-thru*/
579 case WILDCARD : return TRUE;
582 case EXT : return failFree(extField(pat)) &&
583 failFree(extRow(pat));
586 case CONFLDS : if (cfunOf(fst(snd(c)))==0) {
587 List fs = snd(snd(c));
588 for (; nonNull(fs); fs=tl(fs))
589 if (!failFree(snd(hd(fs))))
593 /*intentional fall-thru*/
594 default : return FALSE;
598 static Cell local refutePat(pat) /* find pattern to refute in conformality*/
599 Cell pat; { /* test with pat. */
600 /* e.g. refPat (x:y) == (_:_) */
601 /* refPat ~(x:y) == _ etc.. */
603 switch (whatIs(pat)) {
604 case ASPAT : return refutePat(snd(snd(pat)));
606 case FINLIST : { Cell ys = snd(pat);
608 for (; nonNull(ys); ys=tl(ys))
609 xs = ap(ap(nameCons,refutePat(hd(ys))),xs);
610 return revOnto(xs,nameNil);
613 case CONFLDS : { Cell ps = NIL;
614 Cell fs = snd(snd(pat));
615 for (; nonNull(fs); fs=tl(fs)) {
616 Cell p = refutePat(snd(hd(fs)));
617 ps = cons(pair(fst(hd(fs)),p),ps);
619 return pair(CONFLDS,pair(fst(snd(pat)),rev(ps)));
626 case LAZYPAT : return WILDCARD;
634 case NAME : return pat;
636 case AP : return refutePatAp(pat);
638 default : internal("refutePat");
639 return NIL; /*NOTREACHED*/
643 static Cell local refutePatAp(p) /* find pattern to refute in conformality*/
646 if (h==nameFromInt || h==nameFromInteger || h==nameFromDouble)
649 else if (whatIs(h)==ADDPAT)
650 return ap(fun(p),refutePat(arg(p)));
654 Cell pf = refutePat(extField(p));
655 Cell pr = refutePat(extRow(p));
656 return ap(ap(fun(fun(p)),pf),pr);
660 List as = getArgs(p);
661 mapOver(refutePat,as);
662 return applyToArgs(h,as);
666 static Cell local matchPat(pat) /* find pattern to match against */
667 Cell pat; { /* replaces parts of pattern that do not */
668 /* include variables with wildcards */
669 switch (whatIs(pat)) {
670 case ASPAT : { Cell p = matchPat(snd(snd(pat)));
671 return (p==WILDCARD) ? fst(snd(pat))
673 pair(fst(snd(pat)),p));
676 case FINLIST : { Cell ys = snd(pat);
678 for (; nonNull(ys); ys=tl(ys))
679 xs = cons(matchPat(hd(ys)),xs);
680 while (nonNull(xs) && hd(xs)==WILDCARD)
682 for (ys=nameNil; nonNull(xs); xs=tl(xs))
683 ys = ap(ap(nameCons,hd(xs)),ys);
687 case CONFLDS : { Cell ps = NIL;
688 Name c = fst(snd(pat));
689 Cell fs = snd(snd(pat));
691 for (; nonNull(fs); fs=tl(fs)) {
692 Cell p = matchPat(snd(hd(fs)));
693 ps = cons(pair(fst(hd(fs)),p),ps);
697 return avar ? pair(CONFLDS,pair(c,rev(ps)))
703 case DICTVAR : return pat;
705 case LAZYPAT : { Cell p = matchPat(snd(pat));
706 return (p==WILDCARD) ? WILDCARD : ap(LAZYPAT,p);
711 case CHARCELL : return WILDCARD;
715 case AP : { Cell h = getHead(pat);
716 if (h==nameFromInt ||
717 h==nameFromInteger || h==nameFromDouble)
720 else if (whatIs(h)==ADDPAT)
725 Cell pf = matchPat(extField(pat));
726 Cell pr = matchPat(extRow(pat));
727 return (pf==WILDCARD && pr==WILDCARD)
729 : ap(ap(fun(fun(pat)),pf),pr);
735 for (; isAp(pat); pat=fun(pat)) {
736 Cell p = matchPat(arg(pat));
741 return avar ? applyToArgs(pat,args)
746 default : internal("matchPat");
747 return NIL; /*NOTREACHED*/
751 #define addEqn(v,val,lds) cons(pair(v,singleton(pair(NIL,val))),lds)
753 static List local remPat(pat,expr,lds)
754 Cell pat; /* Produce list of definitions for eqn */
755 Cell expr; /* pat = expr, including a conformality */
756 List lds; { /* check if required. */
758 /* Conformality test (if required):
759 * pat = expr ==> nv = LETREC confCheck nv@pat = nv
761 * remPat1(pat,nv,.....);
764 if (!failFree(pat)) {
765 Cell confVar = inventVar();
766 Cell nv = inventVar();
767 Cell locfun = pair(confVar, /* confVar [([nv@refPat],nv)] */
768 singleton(pair(singleton(ap(ASPAT,
773 if (whatIs(expr)==GUARDED) { /* A spanner ... special case */
774 lds = addEqn(nv,expr,lds); /* for guarded pattern binding*/
779 if (whatIs(pat)==ASPAT) { /* avoid using new variable if*/
780 nv = fst(snd(pat)); /* a variable is already given*/
781 pat = snd(snd(pat)); /* by an as-pattern */
784 lds = addEqn(nv, /* nv = */
785 ap(LETREC,pair(singleton(locfun), /* LETREC [locfun] */
786 ap(confVar,expr))), /* IN confVar expr */
789 return remPat1(matchPat(pat),nv,lds);
792 return remPat1(matchPat(pat),expr,lds);
795 static List local remPat1(pat,expr,lds)
796 Cell pat; /* Add definitions for: pat = expr to */
797 Cell expr; /* list of local definitions in lds. */
799 Cell c = getHead(pat);
804 case CHARCELL : break;
806 case ASPAT : return remPat1(snd(snd(pat)), /* v@pat = expr */
808 addEqn(fst(snd(pat)),expr,lds));
810 case LAZYPAT : { Cell nv;
812 if (isVar(expr) || isName(expr))
816 lds = addEqn(nv,expr,lds);
819 return remPat(snd(pat),nv,lds);
823 case ADDPAT : return remPat1(arg(pat), /* n + k = expr */
826 mkInt(snd(fun(fun(pat))))),
831 case FINLIST : return remPat1(mkConsList(snd(pat)),expr,lds);
833 case CONFLDS : { Name h = fst(snd(pat));
834 Int m = name(h).arity;
836 List fs = snd(snd(pat));
840 for (; nonNull(fs); fs=tl(fs)) {
842 for (i=m-sfunPos(fst(hd(fs)),h); i>0; i--)
844 arg(r) = snd(hd(fs));
846 return remPat1(p,expr,lds);
849 case DICTVAR : /* shouldn't really occur */
850 assert(0); /* so let's test for it then! ADR */
852 case VAROPCELL : return addEqn(pat,expr,lds);
854 case NAME : if (c==nameFromInt || c==nameFromInteger
855 || c==nameFromDouble) {
857 arg(fun(pat)) = translate(arg(fun(pat)));
861 if (argCount==1 && isCfun(c) /* for newtype */
862 && cfunOf(c)==0 && name(c).defn==nameId)
863 return remPat1(arg(pat),expr,lds);
865 /* intentional fall-thru */
866 case TUPLE : { List ps = getArgs(pat);
872 if (isVar(expr) || isName(expr))
876 lds = addEqn(nv,expr,lds);
879 sel = ap(ap(nameSel,c),nv);
880 for (i=1; nonNull(ps); ++i, ps=tl(ps))
881 lds = remPat1(hd(ps),
889 case EXT : { Cell nv = inventVar();
891 = translate(arg(fun(fun(pat))));
897 lds = remPat1(extField(pat),ap(nameFst,nv),lds);
898 lds = remPat1(extRow(pat),ap(nameSnd,nv),lds);
903 default : internal("remPat1");
909 /* --------------------------------------------------------------------------
910 * Eliminate pattern matching in function definitions -- pattern matching
913 * The original Gofer/Hugs pattern matching compiler was based on Wadler's
914 * algorithms described in `Implementation of functional programming
915 * languages'. That should still provide a good starting point for anyone
916 * wanting to understand this part of the system. However, the original
917 * algorithm has been generalized and restructured in order to implement
918 * new features added in Haskell 1.3.
920 * During the translation, in preparation for later stages of compilation,
921 * all local and bound variables are replaced by suitable offsets, and
922 * locally defined function symbols are given new names (which will
923 * eventually be their names when lifted to make top level definitions).
924 * ------------------------------------------------------------------------*/
926 static Offset freeBegin; /* only variables with offset <= freeBegin are of */
927 static List freeVars; /* interest as `free' variables */
928 static List freeFuns; /* List of `free' local functions */
930 static Cell local pmcTerm(co,sc,e) /* apply pattern matching compiler */
931 Int co; /* co = current offset */
932 List sc; /* sc = scope */
933 Cell e; { /* e = expr to transform */
935 case GUARDED : map2Over(pmcPair,co,sc,snd(e));
938 case LETREC : pmcLetrec(co,sc,snd(e));
943 case DICTVAR : return pmcVar(sc,textOf(e));
945 case COND : return ap(COND,pmcTriple(co,sc,snd(e)));
947 case AP : return pmcPair(co,sc,e);
965 case STRCELL : break;
967 default : internal("pmcTerm");
973 static Cell local pmcPair(co,sc,pr) /* apply pattern matching compiler */
974 Int co; /* to a pair of exprs */
977 return pair(pmcTerm(co,sc,fst(pr)),
978 pmcTerm(co,sc,snd(pr)));
981 static Cell local pmcTriple(co,sc,tr) /* apply pattern matching compiler */
982 Int co; /* to a triple of exprs */
985 return triple(pmcTerm(co,sc,fst3(tr)),
986 pmcTerm(co,sc,snd3(tr)),
987 pmcTerm(co,sc,thd3(tr)));
990 static Cell local pmcVar(sc,t) /* find translation of variable */
991 List sc; /* in current scope */
996 for (xs=sc; nonNull(xs); xs=tl(xs)) {
998 if (t==textOf(fst(x))) {
999 if (isOffset(snd(x))) { /* local variable ... */
1000 if (snd(x)<=freeBegin && !cellIsMember(snd(x),freeVars))
1001 freeVars = cons(snd(x),freeVars);
1004 else { /* local function ... */
1005 if (!cellIsMember(snd(x),freeFuns))
1006 freeFuns = cons(snd(x),freeFuns);
1007 return fst3(snd(x));
1012 if (isNull(n=findName(t))) /* Lookup global name - the only way*/
1013 n = newName(t,currentName); /* this (should be able to happen) */
1014 /* is with new global var introduced*/
1015 /* after type check; e.g. remPat1 */
1019 static Void local pmcLetrec(co,sc,e) /* apply pattern matching compiler */
1020 Int co; /* to LETREC, splitting decls into */
1021 List sc; /* two sections */
1023 List fs = NIL; /* local function definitions */
1024 List vs = NIL; /* local variable definitions */
1027 for (ds=fst(e); nonNull(ds); ds=tl(ds)) { /* Split decls into two */
1028 Cell v = fst(hd(ds));
1029 Int arity = length(fst(hd(snd(hd(ds)))));
1031 if (arity==0) { /* Variable declaration */
1032 vs = cons(snd(hd(ds)),vs);
1033 sc = cons(pair(v,mkOffset(++co)),sc);
1035 else { /* Function declaration */
1036 fs = cons(triple(inventVar(),mkInt(arity),snd(hd(ds))),fs);
1037 sc = cons(pair(v,hd(fs)),sc);
1040 vs = rev(vs); /* Put declaration lists back in */
1041 fs = rev(fs); /* original order */
1042 fst(e) = pair(vs,fs); /* Store declaration lists */
1043 map2Over(pmcVarDef,co,sc,vs); /* Translate variable definitions */
1044 map2Proc(pmcFunDef,co,sc,fs); /* Translate function definitions */
1045 snd(e) = pmcTerm(co,sc,snd(e)); /* Translate LETREC body */
1046 freeFuns = diffList(freeFuns,fs); /* Delete any `freeFuns' bound in fs*/
1049 static Cell local pmcVarDef(co,sc,vd) /* apply pattern matching compiler */
1050 Int co; /* to variable definition */
1052 List vd; { /* vd :: [ ([], rhs) ] */
1053 Cell d = snd(hd(vd));
1054 if (nonNull(tl(vd)) && canFail(d))
1055 return ap(FATBAR,pair(pmcTerm(co,sc,d),
1056 pmcVarDef(co,sc,tl(vd))));
1057 return pmcTerm(co,sc,d);
1060 static Void local pmcFunDef(co,sc,fd) /* apply pattern matching compiler */
1061 Int co; /* to function definition */
1063 Triple fd; { /* fd :: (Var, Arity, [Alt]) */
1064 Offset saveFreeBegin = freeBegin;
1065 List saveFreeVars = freeVars;
1066 List saveFreeFuns = freeFuns;
1067 Int arity = intOf(snd3(fd));
1068 Cell temp = altsMatch(co+1,arity,sc,thd3(fd));
1071 freeBegin = mkOffset(co);
1074 temp = match(co+arity,temp);
1075 thd3(fd) = triple(freeVars,freeFuns,temp);
1077 for (xs=freeVars; nonNull(xs); xs=tl(xs))
1078 if (hd(xs)<=saveFreeBegin && !cellIsMember(hd(xs),saveFreeVars))
1079 saveFreeVars = cons(hd(xs),saveFreeVars);
1081 for (xs=freeFuns; nonNull(xs); xs=tl(xs))
1082 if (!cellIsMember(hd(xs),saveFreeFuns))
1083 saveFreeFuns = cons(hd(xs),saveFreeFuns);
1085 freeBegin = saveFreeBegin;
1086 freeVars = saveFreeVars;
1087 freeFuns = saveFreeFuns;
1090 /* ---------------------------------------------------------------------------
1091 * Main part of pattern matching compiler: convert [Alt] to case constructs
1093 * This section of Hugs has been almost completely rewritten to be more
1094 * general, in particular, to allow pattern matching in orders other than the
1095 * strictly left-to-right approach of the previous version. This is needed
1096 * for the implementation of the so-called Haskell 1.3 `record' syntax.
1098 * At each stage, the different branches for the cases to be considered
1099 * are represented by a list of values of type:
1100 * Match ::= { maPats :: [Pat], patterns to match
1101 * maOffs :: [Offs], offsets of corresponding values
1102 * maSc :: Scope, mapping from vars to offsets
1103 * maRhs :: Rhs } right hand side
1104 * [Implementation uses nested pairs, ((pats,offs),(sc,rhs)).]
1106 * The Scope component has type:
1107 * Scope ::= [(Var,Expr)]
1108 * and provides a mapping from variable names to offsets used in the matching
1111 * Matches can be normalized by reducing them to a form in which the list
1112 * of patterns is empty (in which case the match itself is described as an
1113 * empty match), or in which the list is non-empty and the first pattern is
1114 * one that requires either a CASE or NUMCASE (or EXTCASE) to decompose.
1115 * ------------------------------------------------------------------------*/
1117 #define mkMatch(ps,os,sc,r) pair(pair(ps,os),pair(sc,r))
1118 #define maPats(ma) fst(fst(ma))
1119 #define maOffs(ma) snd(fst(ma))
1120 #define maSc(ma) fst(snd(ma))
1121 #define maRhs(ma) snd(snd(ma))
1122 #define extSc(v,o,ma) maSc(ma) = cons(pair(v,o),maSc(ma))
1124 static List local altsMatch(co,n,sc,as) /* Make a list of matches from list*/
1125 Int co; /* of Alts, with initial offsets */
1126 Int n; /* reverse (take n [co..]) */
1132 us = cons(mkOffset(co++),us);
1133 for (; nonNull(as); as=tl(as)) /* Each Alt is ([Pat], Rhs) */
1134 mas = cons(mkMatch(fst(hd(as)),us,sc,snd(hd(as))),mas);
1138 static Cell local match(co,mas) /* Generate case statement for Matches mas */
1139 Int co; /* at current offset co */
1140 List mas; { /* N.B. Assumes nonNull(mas). */
1141 Cell srhs = NIL; /* Rhs for selected matches */
1142 List smas = mas; /* List of selected matches */
1146 if (emptyMatch(hd(smas))) { /* The case for empty matches: */
1147 while (nonNull(mas) && emptyMatch(hd(mas))) {
1148 List temp = tl(mas);
1153 srhs = joinMas(co,rev(smas));
1155 else { /* Non-empty match */
1156 Int o = offsetOf(hd(maOffs(hd(smas))));
1157 Cell d = maDiscr(hd(smas));
1158 if (isNumDiscr(d)) { /* Numeric match */
1159 Int da = discrArity(d);
1160 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1161 while (nonNull(mas) && !emptyMatch(hd(mas))
1162 && o==offsetOf(hd(maOffs(hd(mas))))
1163 && isNumDiscr(d=maDiscr(hd(mas)))
1164 && eqNumDiscr(d,d1)) {
1165 List temp = tl(mas);
1171 map2Proc(advance,co,da,smas);
1172 srhs = ap(NUMCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1175 else if (isExtDiscr(d)) { /* Record match */
1176 Int da = discrArity(d);
1177 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1178 while (nonNull(mas) && !emptyMatch(hd(mas))
1179 && o==offsetOf(hd(maOffs(hd(mas))))
1180 && isExtDiscr(d=maDiscr(hd(mas)))
1181 && eqExtDiscr(d,d1)) {
1182 List temp = tl(mas);
1188 map2Proc(advance,co,da,smas);
1189 srhs = ap(EXTCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1192 else { /* Constructor match */
1193 List tab = addConTable(d,hd(smas),NIL);
1195 while (nonNull(mas) && !emptyMatch(hd(mas))
1196 && o==offsetOf(hd(maOffs(hd(mas))))
1197 && !isNumDiscr(d=maDiscr(hd(mas)))) {
1198 tab = addConTable(d,hd(mas),tab);
1201 for (tab=rev(tab); nonNull(tab); tab=tl(tab)) {
1203 smas = snd(hd(tab));
1205 map2Proc(advance,co,da,smas);
1206 srhs = cons(pair(d,match(co+da,smas)),srhs);
1208 srhs = ap(CASE,pair(mkOffset(o),srhs));
1211 return nonNull(mas) ? ap(FATBAR,pair(srhs,match(co,mas))) : srhs;
1214 static Cell local joinMas(co,mas) /* Combine list of matches into rhs*/
1215 Int co; /* using FATBARs as necessary */
1216 List mas; { /* Non-empty list of empty matches */
1218 Cell rhs = pmcTerm(co,maSc(ma),maRhs(ma));
1219 if (nonNull(tl(mas)) && canFail(rhs))
1220 return ap(FATBAR,pair(rhs,joinMas(co,tl(mas))));
1225 static Bool local canFail(rhs) /* Determine if expression (as rhs) */
1226 Cell rhs; { /* might ever be able to fail */
1227 switch (whatIs(rhs)) {
1228 case LETREC : return canFail(snd(snd(rhs)));
1229 case GUARDED : return TRUE; /* could get more sophisticated ..? */
1230 default : return FALSE;
1234 /* type Table a b = [(a, [b])]
1236 * addTable :: a -> b -> Table a b -> Table a b
1237 * addTable x y [] = [(x,[y])]
1238 * addTable x y (z@(n,sws):zs)
1239 * | n == x = (n,sws++[y]):zs
1240 * | otherwise = (n,sws):addTable x y zs
1243 static List local addConTable(x,y,tab) /* add element (x,y) to table */
1247 return singleton(pair(x,singleton(y)));
1248 else if (fst(hd(tab))==x)
1249 snd(hd(tab)) = appendOnto(snd(hd(tab)),singleton(y));
1251 tl(tab) = addConTable(x,y,tl(tab));
1256 static Void local advance(co,a,ma) /* Advance non-empty match by */
1257 Int co; /* processing head pattern */
1258 Int a; /* discriminator arity */
1260 Cell p = hd(maPats(ma));
1261 List ps = tl(maPats(ma));
1262 List us = tl(maOffs(ma));
1263 if (whatIs(p)==CONFLDS) { /* Special case for record syntax */
1264 Name c = fst(snd(p));
1265 List fs = snd(snd(p));
1268 for (; nonNull(fs); fs=tl(fs)) {
1269 vs = cons(mkOffset(co+a+1-sfunPos(fst(hd(fs)),c)),vs);
1270 qs = cons(snd(hd(fs)),qs);
1272 ps = revOnto(qs,ps);
1273 us = revOnto(vs,us);
1275 else /* Normally just spool off patterns*/
1276 for (; a>0; --a) { /* and corresponding offsets ... */
1277 us = cons(mkOffset(++co),us);
1278 ps = cons(arg(p),ps);
1286 /* --------------------------------------------------------------------------
1287 * Normalize and test for empty match:
1288 * ------------------------------------------------------------------------*/
1290 static Bool local emptyMatch(ma)/* Normalize and test to see if a given */
1291 Cell ma; { /* match, ma, is empty. */
1293 while (nonNull(maPats(ma))) {
1295 tidyHd: switch (whatIs(p=hd(maPats(ma)))) {
1296 case LAZYPAT : { Cell nv = inventVar();
1297 maRhs(ma) = ap(LETREC,
1298 pair(remPat(snd(p),nv,NIL),
1302 /* intentional fall-thru */
1305 case DICTVAR : extSc(p,hd(maOffs(ma)),ma);
1306 case WILDCARD : maPats(ma) = tl(maPats(ma));
1307 maOffs(ma) = tl(maOffs(ma));
1310 /* So-called "as-patterns"are really just pattern intersections:
1311 * (p1@p2:ps, o:os, sc, e) ==> (p1:p2:ps, o:o:os, sc, e)
1312 * (But the input grammar probably doesn't let us take
1313 * advantage of this, so we stick with the special case
1314 * when p1 is a variable.)
1316 case ASPAT : extSc(fst(snd(p)),hd(maOffs(ma)),ma);
1317 hd(maPats(ma)) = snd(snd(p));
1320 case FINLIST : hd(maPats(ma)) = mkConsList(snd(p));
1323 case STRCELL : { String s = textToStr(textOf(p));
1324 for (p=NIL; *s!='\0'; ++s)
1325 if (*s!='\\' || *++s=='\\')
1326 p = ap(consChar(*s),p);
1328 p = ap(consChar('\0'),p);
1329 hd(maPats(ma)) = revOnto(p,nameNil);
1333 case AP : if (isName(fun(p)) && isCfun(fun(p))
1334 && cfunOf(fun(p))==0
1335 && name(fun(p)).defn==nameId) {
1336 hd(maPats(ma)) = arg(p);
1339 /* intentional fall-thru */
1345 default : internal("emptyMatch");
1351 /* --------------------------------------------------------------------------
1353 * ------------------------------------------------------------------------*/
1355 static Cell local maDiscr(ma) /* Get the discriminator for a non-empty */
1356 Cell ma; { /* match, ma. */
1357 Cell p = hd(maPats(ma));
1358 Cell h = getHead(p);
1359 switch (whatIs(h)) {
1360 case CONFLDS : return fst(snd(p));
1362 case ADDPAT : arg(fun(p)) = translate(arg(fun(p)));
1366 case EXT : h = fun(fun(p));
1367 arg(h) = translate(arg(h));
1370 case NAME : if (h==nameFromInt || h==nameFromInteger
1371 || h==nameFromDouble) {
1373 arg(fun(p)) = translate(arg(fun(p)));
1380 static Bool local isNumDiscr(d) /* TRUE => numeric discriminator */
1382 switch (whatIs(d)) {
1385 case CHARCELL : return FALSE;
1388 case AP : return !isExt(fun(d));
1390 case AP : return TRUE; /* must be a literal or (n+k) */
1393 internal("isNumDiscr");
1394 return 0;/*NOTREACHED*/
1397 Int discrArity(d) /* Find arity of discriminator */
1399 switch (whatIs(d)) {
1400 case NAME : return name(d).arity;
1401 case TUPLE : return tupleOf(d);
1402 case CHARCELL : return 0;
1404 case AP : switch (whatIs(fun(d))) {
1406 case ADDPAT : return 1;
1408 case EXT : return 2;
1413 case AP : return (whatIs(fun(d))==ADDPAT) ? 1 : 0;
1415 case AP : return 0; /* must be an Int or Float lit */
1419 internal("discrArity");
1420 return 0;/*NOTREACHED*/
1423 static Bool local eqNumDiscr(d1,d2) /* Determine whether two numeric */
1424 Cell d1, d2; { /* descriptors have same value */
1426 if (whatIs(fun(d1))==ADDPAT)
1427 return whatIs(fun(d2))==ADDPAT && snd(fun(d1))==snd(fun(d2));
1430 return isInt(arg(d2)) && intOf(arg(d1))==intOf(arg(d2));
1431 if (isFloat(arg(d1)))
1432 return isFloat(arg(d2)) && floatOf(arg(d1))==floatOf(arg(d2));
1434 if (isBignum(arg(d1)))
1435 return isBignum(arg(d2)) && bigCmp(arg(d1),arg(d2))==0;
1437 internal("eqNumDiscr");
1438 return FALSE;/*NOTREACHED*/
1442 static Bool local isExtDiscr(d) /* Test of extension discriminator */
1444 return isAp(d) && isExt(fun(d));
1447 static Bool local eqExtDiscr(d1,d2) /* Determine whether two extension */
1448 Cell d1, d2; { /* discriminators have same label */
1449 return fun(d1)==fun(d2);
1453 /*-------------------------------------------------------------------------*/
1457 /* --------------------------------------------------------------------------
1459 * ------------------------------------------------------------------------*/
1461 static Void local stgCGBinds( List );
1463 static Void local stgCGBinds(binds)
1468 /* --------------------------------------------------------------------------
1469 * Main entry points to compiler:
1470 * ------------------------------------------------------------------------*/
1472 static List addGlobals( List binds )
1474 /* stgGlobals = pieces of code generated for selectors, tuples, etc */
1475 for(;nonNull(stgGlobals);stgGlobals=tl(stgGlobals)) {
1476 StgVar bind = snd(hd(stgGlobals));
1477 if (nonNull(stgVarBody(bind))) {
1478 binds = cons(bind,binds);
1485 Void evalExp() { /* compile and run input expression */
1486 /* ToDo: this name (and other names generated during pattern match?)
1487 * get inserted in the symbol table but never get removed.
1489 Name n = newName(inventText(),NIL);
1490 StgVar v = mkStgVar(NIL,NIL);
1493 stgDefn(n,0,pmcTerm(0,NIL,translate(inputExpr)));
1495 stgCGBinds(addGlobals(singleton(v)));
1498 /* Run thread (and any other runnable threads) */
1500 /* Re-initialise the scheduler - ToDo: do I need this? */
1502 /* ToDo: don't really initScheduler every time. fix */
1504 HaskellObj result; /* ignored */
1505 SchedulerStatus status = rts_eval_(closureOfVar(v),10000,&result);
1508 case AllBlocked: /* I don't understand the distinction - ADR */
1509 printf("{Deadlock}");
1513 printf("{Interrupted}");
1524 internal("evalExp: Unrecognised SchedulerStatus");
1531 static List local addStgVar( List binds, Pair bind ); /* todo */
1533 static List local addStgVar( List binds, Pair bind )
1535 StgVar nv = mkStgVar(NIL,NIL);
1536 Text t = textOf(fst(bind));
1537 Name n = findName(t);
1539 if (isNull(n)) { /* Lookup global name - the only way*/
1540 n = newName(t,NIL); /* this (should be able to happen) */
1541 } /* is with new global var introduced*/
1542 /* after type check; e.g. remPat1 */
1543 name(n).stgVar = nv;
1544 return cons(nv,binds);
1548 Void compileDefns() { /* compile script definitions */
1549 Target t = length(valDefns) + length(genDefns) + length(selDefns);
1556 for(vs=genDefns; nonNull(vs); vs=tl(vs)) {
1558 StgVar nv = mkStgVar(NIL,NIL);
1560 name(n).stgVar = nv;
1561 binds = cons(nv,binds);
1563 for(vss=selDefns; nonNull(vss); vss=tl(vss)) {
1564 for(vs=hd(vss); nonNull(vs); vs=tl(vs)) {
1567 StgVar nv = mkStgVar(NIL,NIL);
1569 name(n).stgVar = nv;
1570 binds = cons(nv,binds);
1575 setGoal("Compiling",t);
1576 /* do valDefns before everything else so that all stgVar's get added. */
1577 for (; nonNull(valDefns); valDefns=tl(valDefns)) {
1578 hd(valDefns) = transBinds(hd(valDefns));
1579 mapAccum(addStgVar,binds,hd(valDefns));
1580 mapProc(compileGlobalFunction,hd(valDefns));
1583 for (; nonNull(genDefns); genDefns=tl(genDefns)) {
1584 compileGenFunction(hd(genDefns));
1587 for (; nonNull(selDefns); selDefns=tl(selDefns)) {
1588 mapOver(compileSelFunction,hd(selDefns));
1592 /* binds=revOnto(binds,NIL); *//* ToDo: maintain compilation order?? */
1593 binds = addGlobals(binds);
1594 #if USE_HUGS_OPTIMIZER
1595 mapProc(optimiseBind,binds);
1602 static Void local compileGlobalFunction(bind)
1604 Name n = findName(textOf(fst(bind)));
1605 List defs = snd(bind);
1606 Int arity = length(fst(hd(defs)));
1609 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1612 static Void local compileGenFunction(n) /* Produce code for internally */
1613 Name n; { /* generated function */
1614 List defs = name(n).defn;
1615 Int arity = length(fst(hd(defs)));
1619 mapProc(transAlt,defs);
1620 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1624 static Name local compileSelFunction(p) /* Produce code for selector func */
1625 Pair p; { /* Should be merged with genDefns, */
1626 Name s = fst(p); /* but the name(_).defn field is */
1627 List defs = snd(p); /* already used for other purposes */
1628 Int arity = length(fst(hd(defs))); /* in selector functions. */
1631 mapProc(transAlt,defs);
1632 stgDefn(s,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1638 I think this is 98-specific.
1639 static Void local newGlobalFunction(n,arity,fvs,co,e)
1646 extern Void printSc Args((FILE*, Text, Int, Cell));
1649 numExtraVars = length(extraVars);
1652 name(n).arity = arity+numExtraVars;
1656 printSc(stdout,name(n).text,name(n).arity,e);
1659 name(n).code = codeGen(n,name(n).arity,e);
1663 /* --------------------------------------------------------------------------
1665 * ------------------------------------------------------------------------*/
1671 case RESET : freeVars = NIL;
1673 freeBegin = mkOffset(0);
1680 case MARK : mark(freeVars);
1687 /*-------------------------------------------------------------------------*/