2 /* --------------------------------------------------------------------------
3 * This is the Hugs compiler, handling translation of typechecked code to
4 * `kernel' language, elimination of pattern matching and translation to
5 * super combinators (lambda lifting).
7 * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
8 * Yale Haskell Group, and the Oregon Graduate Institute of Science and
9 * Technology, 1994-1999, All rights reserved. It is distributed as
10 * free software under the license in the file "License", which is
11 * included in the distribution.
13 * $RCSfile: compiler.c,v $
15 * $Date: 1999/10/20 02:15:58 $
16 * ------------------------------------------------------------------------*/
23 #include "Rts.h" /* for rts_eval and related stuff */
24 #include "RtsAPI.h" /* for rts_eval and related stuff */
28 Addr inputCode; /* Addr of compiled code for expr */
29 static Name currentName; /* Top level name being processed */
31 Bool debugCode = FALSE; /* TRUE => print G-code to screen */
36 /* --------------------------------------------------------------------------
37 * Local function prototypes:
38 * ------------------------------------------------------------------------*/
40 static Cell local translate Args((Cell));
41 static Void local transPair Args((Pair));
42 static Void local transTriple Args((Triple));
43 static Void local transAlt Args((Cell));
44 static Void local transCase Args((Cell));
45 static List local transBinds Args((List));
46 static Cell local transRhs Args((Cell));
47 static Cell local mkConsList Args((List));
48 static Cell local expandLetrec Args((Cell));
49 static Cell local transComp Args((Cell,List,Cell));
50 static Cell local transDo Args((Cell,Cell,List));
51 static Cell local transConFlds Args((Cell,List));
52 static Cell local transUpdFlds Args((Cell,List,List));
54 static Cell local refutePat Args((Cell));
55 static Cell local refutePatAp Args((Cell));
56 static Cell local matchPat Args((Cell));
57 static List local remPat Args((Cell,Cell,List));
58 static List local remPat1 Args((Cell,Cell,List));
60 static Cell local pmcTerm Args((Int,List,Cell));
61 static Cell local pmcPair Args((Int,List,Pair));
62 static Cell local pmcTriple Args((Int,List,Triple));
63 static Cell local pmcVar Args((List,Text));
64 static Void local pmcLetrec Args((Int,List,Pair));
65 static Cell local pmcVarDef Args((Int,List,List));
66 static Void local pmcFunDef Args((Int,List,Triple));
67 static List local altsMatch Args((Int,Int,List,List));
68 static Cell local match Args((Int,List));
69 static Cell local joinMas Args((Int,List));
70 static Bool local canFail Args((Cell));
71 static List local addConTable Args((Cell,Cell,List));
72 static Void local advance Args((Int,Int,Cell));
73 static Bool local emptyMatch Args((Cell));
74 static Cell local maDiscr Args((Cell));
75 static Bool local isNumDiscr Args((Cell));
76 static Bool local eqNumDiscr Args((Cell,Cell));
78 static Bool local isExtDiscr Args((Cell));
79 static Bool local eqExtDiscr Args((Cell,Cell));
82 static Void local compileGlobalFunction Args((Pair));
83 static Void local compileGenFunction Args((Name));
84 static Name local compileSelFunction Args((Pair));
85 static List local addStgVar Args((List,Pair));
88 /* --------------------------------------------------------------------------
89 * Translation: Convert input expressions into a less complex language
90 * of terms using only LETREC, AP, constants and vars.
91 * Also remove pattern definitions on lhs of eqns.
92 * ------------------------------------------------------------------------*/
94 static Cell local translate(e) /* Translate expression: */
97 case LETREC : snd(snd(e)) = translate(snd(snd(e)));
98 return expandLetrec(e);
100 case COND : transTriple(snd(e));
103 case AP : fst(e) = translate(fst(e));
105 if (fst(e)==nameId || fst(e)==nameInd)
106 return translate(snd(e));
107 if (isName(fst(e)) &&
110 return translate(snd(e));
112 snd(e) = translate(snd(e));
115 case NAME : if (e==nameOtherwise)
118 if (isName(name(e).defn))
120 if (isPair(name(e).defn))
121 return snd(name(e).defn);
126 case RECSEL : return nameRecSel;
138 case CHARCELL : return e;
140 case IPVAR : return nameId;
142 case FINLIST : mapOver(translate,snd(e));
143 return mkConsList(snd(e));
145 case DOCOMP : { Cell m = translate(fst(snd(e)));
146 Cell r = translate(fst(snd(snd(e))));
147 return transDo(m,r,snd(snd(snd(e))));
150 case MONADCOMP : { Cell m = translate(fst(snd(e)));
151 Cell r = translate(fst(snd(snd(e))));
152 Cell qs = snd(snd(snd(e)));
153 if (m == nameListMonad)
154 return transComp(r,qs,nameNil);
157 r = ap(ap(nameReturn,m),r);
158 return transDo(m,r,qs);
160 internal("translate: monad comps");
165 case CONFLDS : return transConFlds(fst(snd(e)),snd(snd(e)));
167 case UPDFLDS : return transUpdFlds(fst3(snd(e)),
171 case CASE : { Cell nv = inventVar();
172 mapProc(transCase,snd(snd(e)));
174 pair(singleton(pair(nv,snd(snd(e)))),
175 ap(nv,translate(fst(snd(e))))));
178 case LAMBDA : { Cell nv = inventVar();
187 default : fprintf(stderr, "stuff=%d\n",whatIs(e));internal("translate");
192 static Void local transPair(pr) /* Translate each component in a */
193 Pair pr; { /* pair of expressions. */
194 fst(pr) = translate(fst(pr));
195 snd(pr) = translate(snd(pr));
198 static Void local transTriple(tr) /* Translate each component in a */
199 Triple tr; { /* triple of expressions. */
200 fst3(tr) = translate(fst3(tr));
201 snd3(tr) = translate(snd3(tr));
202 thd3(tr) = translate(thd3(tr));
205 static Void local transAlt(e) /* Translate alt: */
206 Cell e; { /* ([Pat], Rhs) ==> ([Pat], Rhs') */
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;
618 case NAME : return pat;
620 case AP : return refutePatAp(pat);
622 default : internal("refutePat");
623 return NIL; /*NOTREACHED*/
627 static Cell local refutePatAp(p) /* find pattern to refute in conformality*/
630 if (h==nameFromInt || h==nameFromInteger || h==nameFromDouble)
633 else if (whatIs(h)==ADDPAT)
634 return ap(fun(p),refutePat(arg(p)));
638 Cell pf = refutePat(extField(p));
639 Cell pr = refutePat(extRow(p));
640 return ap(ap(fun(fun(p)),pf),pr);
644 List as = getArgs(p);
645 mapOver(refutePat,as);
646 return applyToArgs(h,as);
650 static Cell local matchPat(pat) /* find pattern to match against */
651 Cell pat; { /* replaces parts of pattern that do not */
652 /* include variables with wildcards */
653 switch (whatIs(pat)) {
654 case ASPAT : { Cell p = matchPat(snd(snd(pat)));
655 return (p==WILDCARD) ? fst(snd(pat))
657 pair(fst(snd(pat)),p));
660 case FINLIST : { Cell ys = snd(pat);
662 for (; nonNull(ys); ys=tl(ys))
663 xs = cons(matchPat(hd(ys)),xs);
664 while (nonNull(xs) && hd(xs)==WILDCARD)
666 for (ys=nameNil; nonNull(xs); xs=tl(xs))
667 ys = ap(ap(nameCons,hd(xs)),ys);
671 case CONFLDS : { Cell ps = NIL;
672 Name c = fst(snd(pat));
673 Cell fs = snd(snd(pat));
675 for (; nonNull(fs); fs=tl(fs)) {
676 Cell p = matchPat(snd(hd(fs)));
677 ps = cons(pair(fst(hd(fs)),p),ps);
681 return avar ? pair(CONFLDS,pair(c,rev(ps)))
687 case DICTVAR : return pat;
689 case LAZYPAT : { Cell p = matchPat(snd(pat));
690 return (p==WILDCARD) ? WILDCARD : ap(LAZYPAT,p);
695 case CHARCELL : return WILDCARD;
699 case AP : { Cell h = getHead(pat);
700 if (h==nameFromInt ||
701 h==nameFromInteger || h==nameFromDouble)
704 else if (whatIs(h)==ADDPAT)
709 Cell pf = matchPat(extField(pat));
710 Cell pr = matchPat(extRow(pat));
711 return (pf==WILDCARD && pr==WILDCARD)
713 : ap(ap(fun(fun(pat)),pf),pr);
719 for (; isAp(pat); pat=fun(pat)) {
720 Cell p = matchPat(arg(pat));
725 return avar ? applyToArgs(pat,args)
730 default : internal("matchPat");
731 return NIL; /*NOTREACHED*/
735 #define addEqn(v,val,lds) cons(pair(v,singleton(pair(NIL,val))),lds)
737 static List local remPat(pat,expr,lds)
738 Cell pat; /* Produce list of definitions for eqn */
739 Cell expr; /* pat = expr, including a conformality */
740 List lds; { /* check if required. */
742 /* Conformality test (if required):
743 * pat = expr ==> nv = LETREC confCheck nv@pat = nv
745 * remPat1(pat,nv,.....);
748 if (!failFree(pat)) {
749 Cell confVar = inventVar();
750 Cell nv = inventVar();
751 Cell locfun = pair(confVar, /* confVar [([nv@refPat],nv)] */
752 singleton(pair(singleton(ap(ASPAT,
757 if (whatIs(expr)==GUARDED) { /* A spanner ... special case */
758 lds = addEqn(nv,expr,lds); /* for guarded pattern binding*/
763 if (whatIs(pat)==ASPAT) { /* avoid using new variable if*/
764 nv = fst(snd(pat)); /* a variable is already given*/
765 pat = snd(snd(pat)); /* by an as-pattern */
768 lds = addEqn(nv, /* nv = */
769 ap(LETREC,pair(singleton(locfun), /* LETREC [locfun] */
770 ap(confVar,expr))), /* IN confVar expr */
773 return remPat1(matchPat(pat),nv,lds);
776 return remPat1(matchPat(pat),expr,lds);
779 static List local remPat1(pat,expr,lds)
780 Cell pat; /* Add definitions for: pat = expr to */
781 Cell expr; /* list of local definitions in lds. */
783 Cell c = getHead(pat);
788 case CHARCELL : break;
790 case ASPAT : return remPat1(snd(snd(pat)), /* v@pat = expr */
792 addEqn(fst(snd(pat)),expr,lds));
794 case LAZYPAT : { Cell nv;
796 if (isVar(expr) || isName(expr))
800 lds = addEqn(nv,expr,lds);
803 return remPat(snd(pat),nv,lds);
807 case ADDPAT : return remPat1(arg(pat), /* n + k = expr */
810 mkInt(snd(fun(fun(pat))))),
815 case FINLIST : return remPat1(mkConsList(snd(pat)),expr,lds);
817 case CONFLDS : { Name h = fst(snd(pat));
818 Int m = name(h).arity;
820 List fs = snd(snd(pat));
824 for (; nonNull(fs); fs=tl(fs)) {
826 for (i=m-sfunPos(fst(hd(fs)),h); i>0; i--)
828 arg(r) = snd(hd(fs));
830 return remPat1(p,expr,lds);
833 case DICTVAR : /* shouldn't really occur */
834 assert(0); /* so let's test for it then! ADR */
836 case VAROPCELL : return addEqn(pat,expr,lds);
838 case NAME : if (c==nameFromInt || c==nameFromInteger
839 || c==nameFromDouble) {
841 arg(fun(pat)) = translate(arg(fun(pat)));
845 if (argCount==1 && isCfun(c) /* for newtype */
846 && cfunOf(c)==0 && name(c).defn==nameId)
847 return remPat1(arg(pat),expr,lds);
849 /* intentional fall-thru */
850 case TUPLE : { List ps = getArgs(pat);
856 if (isVar(expr) || isName(expr))
860 lds = addEqn(nv,expr,lds);
863 sel = ap(ap(nameSel,c),nv);
864 for (i=1; nonNull(ps); ++i, ps=tl(ps))
865 lds = remPat1(hd(ps),
873 case EXT : { Cell nv = inventVar();
875 = translate(arg(fun(fun(pat))));
881 lds = remPat1(extField(pat),ap(nameFst,nv),lds);
882 lds = remPat1(extRow(pat),ap(nameSnd,nv),lds);
887 default : internal("remPat1");
893 /* --------------------------------------------------------------------------
894 * Eliminate pattern matching in function definitions -- pattern matching
897 * The original Gofer/Hugs pattern matching compiler was based on Wadler's
898 * algorithms described in `Implementation of functional programming
899 * languages'. That should still provide a good starting point for anyone
900 * wanting to understand this part of the system. However, the original
901 * algorithm has been generalized and restructured in order to implement
902 * new features added in Haskell 1.3.
904 * During the translation, in preparation for later stages of compilation,
905 * all local and bound variables are replaced by suitable offsets, and
906 * locally defined function symbols are given new names (which will
907 * eventually be their names when lifted to make top level definitions).
908 * ------------------------------------------------------------------------*/
910 static Offset freeBegin; /* only variables with offset <= freeBegin are of */
911 static List freeVars; /* interest as `free' variables */
912 static List freeFuns; /* List of `free' local functions */
914 static Cell local pmcTerm(co,sc,e) /* apply pattern matching compiler */
915 Int co; /* co = current offset */
916 List sc; /* sc = scope */
917 Cell e; { /* e = expr to transform */
919 case GUARDED : map2Over(pmcPair,co,sc,snd(e));
922 case LETREC : pmcLetrec(co,sc,snd(e));
927 case DICTVAR : return pmcVar(sc,textOf(e));
929 case COND : return ap(COND,pmcTriple(co,sc,snd(e)));
931 case AP : return pmcPair(co,sc,e);
945 case STRCELL : break;
947 default : internal("pmcTerm");
953 static Cell local pmcPair(co,sc,pr) /* apply pattern matching compiler */
954 Int co; /* to a pair of exprs */
957 return pair(pmcTerm(co,sc,fst(pr)),
958 pmcTerm(co,sc,snd(pr)));
961 static Cell local pmcTriple(co,sc,tr) /* apply pattern matching compiler */
962 Int co; /* to a triple of exprs */
965 return triple(pmcTerm(co,sc,fst3(tr)),
966 pmcTerm(co,sc,snd3(tr)),
967 pmcTerm(co,sc,thd3(tr)));
970 static Cell local pmcVar(sc,t) /* find translation of variable */
971 List sc; /* in current scope */
976 for (xs=sc; nonNull(xs); xs=tl(xs)) {
978 if (t==textOf(fst(x))) {
979 if (isOffset(snd(x))) { /* local variable ... */
980 if (snd(x)<=freeBegin && !cellIsMember(snd(x),freeVars))
981 freeVars = cons(snd(x),freeVars);
984 else { /* local function ... */
985 if (!cellIsMember(snd(x),freeFuns))
986 freeFuns = cons(snd(x),freeFuns);
992 if (isNull(n=findName(t))) /* Lookup global name - the only way*/
993 n = newName(t,currentName); /* this (should be able to happen) */
994 /* is with new global var introduced*/
995 /* after type check; e.g. remPat1 */
999 static Void local pmcLetrec(co,sc,e) /* apply pattern matching compiler */
1000 Int co; /* to LETREC, splitting decls into */
1001 List sc; /* two sections */
1003 List fs = NIL; /* local function definitions */
1004 List vs = NIL; /* local variable definitions */
1007 for (ds=fst(e); nonNull(ds); ds=tl(ds)) { /* Split decls into two */
1008 Cell v = fst(hd(ds));
1009 Int arity = length(fst(hd(snd(hd(ds)))));
1011 if (arity==0) { /* Variable declaration */
1012 vs = cons(snd(hd(ds)),vs);
1013 sc = cons(pair(v,mkOffset(++co)),sc);
1015 else { /* Function declaration */
1016 fs = cons(triple(inventVar(),mkInt(arity),snd(hd(ds))),fs);
1017 sc = cons(pair(v,hd(fs)),sc);
1020 vs = rev(vs); /* Put declaration lists back in */
1021 fs = rev(fs); /* original order */
1022 fst(e) = pair(vs,fs); /* Store declaration lists */
1023 map2Over(pmcVarDef,co,sc,vs); /* Translate variable definitions */
1024 map2Proc(pmcFunDef,co,sc,fs); /* Translate function definitions */
1025 snd(e) = pmcTerm(co,sc,snd(e)); /* Translate LETREC body */
1026 freeFuns = diffList(freeFuns,fs); /* Delete any `freeFuns' bound in fs*/
1029 static Cell local pmcVarDef(co,sc,vd) /* apply pattern matching compiler */
1030 Int co; /* to variable definition */
1032 List vd; { /* vd :: [ ([], rhs) ] */
1033 Cell d = snd(hd(vd));
1034 if (nonNull(tl(vd)) && canFail(d))
1035 return ap(FATBAR,pair(pmcTerm(co,sc,d),
1036 pmcVarDef(co,sc,tl(vd))));
1037 return pmcTerm(co,sc,d);
1040 static Void local pmcFunDef(co,sc,fd) /* apply pattern matching compiler */
1041 Int co; /* to function definition */
1043 Triple fd; { /* fd :: (Var, Arity, [Alt]) */
1044 Offset saveFreeBegin = freeBegin;
1045 List saveFreeVars = freeVars;
1046 List saveFreeFuns = freeFuns;
1047 Int arity = intOf(snd3(fd));
1048 Cell temp = altsMatch(co+1,arity,sc,thd3(fd));
1051 freeBegin = mkOffset(co);
1054 temp = match(co+arity,temp);
1055 thd3(fd) = triple(freeVars,freeFuns,temp);
1057 for (xs=freeVars; nonNull(xs); xs=tl(xs))
1058 if (hd(xs)<=saveFreeBegin && !cellIsMember(hd(xs),saveFreeVars))
1059 saveFreeVars = cons(hd(xs),saveFreeVars);
1061 for (xs=freeFuns; nonNull(xs); xs=tl(xs))
1062 if (!cellIsMember(hd(xs),saveFreeFuns))
1063 saveFreeFuns = cons(hd(xs),saveFreeFuns);
1065 freeBegin = saveFreeBegin;
1066 freeVars = saveFreeVars;
1067 freeFuns = saveFreeFuns;
1070 /* ---------------------------------------------------------------------------
1071 * Main part of pattern matching compiler: convert [Alt] to case constructs
1073 * This section of Hugs has been almost completely rewritten to be more
1074 * general, in particular, to allow pattern matching in orders other than the
1075 * strictly left-to-right approach of the previous version. This is needed
1076 * for the implementation of the so-called Haskell 1.3 `record' syntax.
1078 * At each stage, the different branches for the cases to be considered
1079 * are represented by a list of values of type:
1080 * Match ::= { maPats :: [Pat], patterns to match
1081 * maOffs :: [Offs], offsets of corresponding values
1082 * maSc :: Scope, mapping from vars to offsets
1083 * maRhs :: Rhs } right hand side
1084 * [Implementation uses nested pairs, ((pats,offs),(sc,rhs)).]
1086 * The Scope component has type:
1087 * Scope ::= [(Var,Expr)]
1088 * and provides a mapping from variable names to offsets used in the matching
1091 * Matches can be normalized by reducing them to a form in which the list
1092 * of patterns is empty (in which case the match itself is described as an
1093 * empty match), or in which the list is non-empty and the first pattern is
1094 * one that requires either a CASE or NUMCASE (or EXTCASE) to decompose.
1095 * ------------------------------------------------------------------------*/
1097 #define mkMatch(ps,os,sc,r) pair(pair(ps,os),pair(sc,r))
1098 #define maPats(ma) fst(fst(ma))
1099 #define maOffs(ma) snd(fst(ma))
1100 #define maSc(ma) fst(snd(ma))
1101 #define maRhs(ma) snd(snd(ma))
1102 #define extSc(v,o,ma) maSc(ma) = cons(pair(v,o),maSc(ma))
1104 static List local altsMatch(co,n,sc,as) /* Make a list of matches from list*/
1105 Int co; /* of Alts, with initial offsets */
1106 Int n; /* reverse (take n [co..]) */
1112 us = cons(mkOffset(co++),us);
1113 for (; nonNull(as); as=tl(as)) /* Each Alt is ([Pat], Rhs) */
1114 mas = cons(mkMatch(fst(hd(as)),us,sc,snd(hd(as))),mas);
1118 static Cell local match(co,mas) /* Generate case statement for Matches mas */
1119 Int co; /* at current offset co */
1120 List mas; { /* N.B. Assumes nonNull(mas). */
1121 Cell srhs = NIL; /* Rhs for selected matches */
1122 List smas = mas; /* List of selected matches */
1126 if (emptyMatch(hd(smas))) { /* The case for empty matches: */
1127 while (nonNull(mas) && emptyMatch(hd(mas))) {
1128 List temp = tl(mas);
1133 srhs = joinMas(co,rev(smas));
1135 else { /* Non-empty match */
1136 Int o = offsetOf(hd(maOffs(hd(smas))));
1137 Cell d = maDiscr(hd(smas));
1138 if (isNumDiscr(d)) { /* Numeric match */
1139 Int da = discrArity(d);
1140 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1141 while (nonNull(mas) && !emptyMatch(hd(mas))
1142 && o==offsetOf(hd(maOffs(hd(mas))))
1143 && isNumDiscr(d=maDiscr(hd(mas)))
1144 && eqNumDiscr(d,d1)) {
1145 List temp = tl(mas);
1151 map2Proc(advance,co,da,smas);
1152 srhs = ap(NUMCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1155 else if (isExtDiscr(d)) { /* Record match */
1156 Int da = discrArity(d);
1157 Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1158 while (nonNull(mas) && !emptyMatch(hd(mas))
1159 && o==offsetOf(hd(maOffs(hd(mas))))
1160 && isExtDiscr(d=maDiscr(hd(mas)))
1161 && eqExtDiscr(d,d1)) {
1162 List temp = tl(mas);
1168 map2Proc(advance,co,da,smas);
1169 srhs = ap(EXTCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1172 else { /* Constructor match */
1173 List tab = addConTable(d,hd(smas),NIL);
1175 while (nonNull(mas) && !emptyMatch(hd(mas))
1176 && o==offsetOf(hd(maOffs(hd(mas))))
1177 && !isNumDiscr(d=maDiscr(hd(mas)))) {
1178 tab = addConTable(d,hd(mas),tab);
1181 for (tab=rev(tab); nonNull(tab); tab=tl(tab)) {
1183 smas = snd(hd(tab));
1185 map2Proc(advance,co,da,smas);
1186 srhs = cons(pair(d,match(co+da,smas)),srhs);
1188 srhs = ap(CASE,pair(mkOffset(o),srhs));
1191 return nonNull(mas) ? ap(FATBAR,pair(srhs,match(co,mas))) : srhs;
1194 static Cell local joinMas(co,mas) /* Combine list of matches into rhs*/
1195 Int co; /* using FATBARs as necessary */
1196 List mas; { /* Non-empty list of empty matches */
1198 Cell rhs = pmcTerm(co,maSc(ma),maRhs(ma));
1199 if (nonNull(tl(mas)) && canFail(rhs))
1200 return ap(FATBAR,pair(rhs,joinMas(co,tl(mas))));
1205 static Bool local canFail(rhs) /* Determine if expression (as rhs) */
1206 Cell rhs; { /* might ever be able to fail */
1207 switch (whatIs(rhs)) {
1208 case LETREC : return canFail(snd(snd(rhs)));
1209 case GUARDED : return TRUE; /* could get more sophisticated ..? */
1210 default : return FALSE;
1214 /* type Table a b = [(a, [b])]
1216 * addTable :: a -> b -> Table a b -> Table a b
1217 * addTable x y [] = [(x,[y])]
1218 * addTable x y (z@(n,sws):zs)
1219 * | n == x = (n,sws++[y]):zs
1220 * | otherwise = (n,sws):addTable x y zs
1223 static List local addConTable(x,y,tab) /* add element (x,y) to table */
1227 return singleton(pair(x,singleton(y)));
1228 else if (fst(hd(tab))==x)
1229 snd(hd(tab)) = appendOnto(snd(hd(tab)),singleton(y));
1231 tl(tab) = addConTable(x,y,tl(tab));
1236 static Void local advance(co,a,ma) /* Advance non-empty match by */
1237 Int co; /* processing head pattern */
1238 Int a; /* discriminator arity */
1240 Cell p = hd(maPats(ma));
1241 List ps = tl(maPats(ma));
1242 List us = tl(maOffs(ma));
1243 if (whatIs(p)==CONFLDS) { /* Special case for record syntax */
1244 Name c = fst(snd(p));
1245 List fs = snd(snd(p));
1248 for (; nonNull(fs); fs=tl(fs)) {
1249 vs = cons(mkOffset(co+a+1-sfunPos(fst(hd(fs)),c)),vs);
1250 qs = cons(snd(hd(fs)),qs);
1252 ps = revOnto(qs,ps);
1253 us = revOnto(vs,us);
1255 else /* Normally just spool off patterns*/
1256 for (; a>0; --a) { /* and corresponding offsets ... */
1257 us = cons(mkOffset(++co),us);
1258 ps = cons(arg(p),ps);
1266 /* --------------------------------------------------------------------------
1267 * Normalize and test for empty match:
1268 * ------------------------------------------------------------------------*/
1270 static Bool local emptyMatch(ma)/* Normalize and test to see if a given */
1271 Cell ma; { /* match, ma, is empty. */
1273 while (nonNull(maPats(ma))) {
1275 tidyHd: switch (whatIs(p=hd(maPats(ma)))) {
1276 case LAZYPAT : { Cell nv = inventVar();
1277 maRhs(ma) = ap(LETREC,
1278 pair(remPat(snd(p),nv,NIL),
1282 /* intentional fall-thru */
1285 case DICTVAR : extSc(p,hd(maOffs(ma)),ma);
1286 case WILDCARD : maPats(ma) = tl(maPats(ma));
1287 maOffs(ma) = tl(maOffs(ma));
1290 /* So-called "as-patterns"are really just pattern intersections:
1291 * (p1@p2:ps, o:os, sc, e) ==> (p1:p2:ps, o:o:os, sc, e)
1292 * (But the input grammar probably doesn't let us take
1293 * advantage of this, so we stick with the special case
1294 * when p1 is a variable.)
1296 case ASPAT : extSc(fst(snd(p)),hd(maOffs(ma)),ma);
1297 hd(maPats(ma)) = snd(snd(p));
1300 case FINLIST : hd(maPats(ma)) = mkConsList(snd(p));
1303 case STRCELL : { String s = textToStr(textOf(p));
1304 for (p=NIL; *s!='\0'; ++s) {
1305 if (*s!='\\' || *++s=='\\')
1306 p = ap(consChar(*s),p);
1308 p = ap(consChar('\0'),p);
1310 hd(maPats(ma)) = revOnto(p,nameNil);
1314 case AP : if (isName(fun(p)) && isCfun(fun(p))
1315 && cfunOf(fun(p))==0
1316 && name(fun(p)).defn==nameId) {
1317 hd(maPats(ma)) = arg(p);
1320 /* intentional fall-thru */
1326 default : internal("emptyMatch");
1332 /* --------------------------------------------------------------------------
1334 * ------------------------------------------------------------------------*/
1336 static Cell local maDiscr(ma) /* Get the discriminator for a non-empty */
1337 Cell ma; { /* match, ma. */
1338 Cell p = hd(maPats(ma));
1339 Cell h = getHead(p);
1340 switch (whatIs(h)) {
1341 case CONFLDS : return fst(snd(p));
1343 case ADDPAT : arg(fun(p)) = translate(arg(fun(p)));
1347 case EXT : h = fun(fun(p));
1348 arg(h) = translate(arg(h));
1351 case NAME : if (h==nameFromInt || h==nameFromInteger
1352 || h==nameFromDouble) {
1354 arg(fun(p)) = translate(arg(fun(p)));
1361 static Bool local isNumDiscr(d) /* TRUE => numeric discriminator */
1363 switch (whatIs(d)) {
1366 case CHARCELL : return FALSE;
1369 case AP : return !isExt(fun(d));
1371 case AP : return TRUE; /* must be a literal or (n+k) */
1374 internal("isNumDiscr");
1375 return 0;/*NOTREACHED*/
1378 Int discrArity(d) /* Find arity of discriminator */
1380 switch (whatIs(d)) {
1381 case NAME : return name(d).arity;
1382 case TUPLE : return tupleOf(d);
1383 case CHARCELL : return 0;
1385 case AP : switch (whatIs(fun(d))) {
1387 case ADDPAT : return 1;
1389 case EXT : return 2;
1394 case AP : return (whatIs(fun(d))==ADDPAT) ? 1 : 0;
1396 case AP : return 0; /* must be an Int or Float lit */
1400 internal("discrArity");
1401 return 0;/*NOTREACHED*/
1404 static Bool local eqNumDiscr(d1,d2) /* Determine whether two numeric */
1405 Cell d1, d2; { /* descriptors have same value */
1407 if (whatIs(fun(d1))==ADDPAT)
1408 return whatIs(fun(d2))==ADDPAT && snd(fun(d1))==snd(fun(d2));
1411 return isInt(arg(d2)) && intOf(arg(d1))==intOf(arg(d2));
1412 if (isFloat(arg(d1)))
1413 return isFloat(arg(d2)) && floatOf(arg(d1))==floatOf(arg(d2));
1414 internal("eqNumDiscr");
1415 return FALSE;/*NOTREACHED*/
1419 static Bool local isExtDiscr(d) /* Test of extension discriminator */
1421 return isAp(d) && isExt(fun(d));
1424 static Bool local eqExtDiscr(d1,d2) /* Determine whether two extension */
1425 Cell d1, d2; { /* discriminators have same label */
1426 return fun(d1)==fun(d2);
1430 /*-------------------------------------------------------------------------*/
1434 /* --------------------------------------------------------------------------
1436 * ------------------------------------------------------------------------*/
1438 static Void local stgCGBinds( List );
1440 static Void local stgCGBinds(binds)
1445 /* --------------------------------------------------------------------------
1446 * Main entry points to compiler:
1447 * ------------------------------------------------------------------------*/
1449 static List addGlobals( List binds )
1451 /* stgGlobals = list of top-level STG binds */
1452 for(;nonNull(stgGlobals);stgGlobals=tl(stgGlobals)) {
1453 StgVar bind = snd(hd(stgGlobals));
1454 if (nonNull(stgVarBody(bind))) {
1455 binds = cons(bind,binds);
1461 typedef void (*sighandler_t)(int);
1462 void eval_ctrlbrk ( int dunnowhat )
1465 /* reinstall the signal handler so that further interrupts which
1466 happen before the thread can return to the scheduler, lead back
1467 here rather than invoking the previous break handler. */
1468 signal(SIGINT, eval_ctrlbrk);
1471 Void evalExp() { /* compile and run input expression */
1472 /* ToDo: this name (and other names generated during pattern match?)
1473 * get inserted in the symbol table but never get removed.
1475 Name n = newName(inventText(),NIL);
1477 StgVar v = mkStgVar(NIL,NIL);
1480 e = pmcTerm(0,NIL,translate(inputExpr));
1483 stgCGBinds(addGlobals(singleton(v)));
1485 /* Run thread (and any other runnable threads) */
1487 /* Re-initialise the scheduler - ToDo: do I need this? */
1489 #ifdef CRUDE_PROFILING
1493 /* ToDo: don't really initScheduler every time. fix */
1495 HaskellObj result; /* ignored */
1496 sighandler_t old_ctrlbrk;
1497 SchedulerStatus status;
1498 old_ctrlbrk = signal(SIGINT, eval_ctrlbrk);
1499 assert(old_ctrlbrk != SIG_ERR);
1500 status = rts_eval_(closureOfVar(v),10000,&result);
1501 signal(SIGINT,old_ctrlbrk);
1504 case AllBlocked: /* I don't understand the distinction - ADR */
1505 printf("{Deadlock}");
1509 printf("{Interrupted}");
1517 //fflush(stderr);fflush(stdout);
1518 //fprintf(stderr, "\n\nFinal top-of-stack is\n" );
1519 //printObj ( *(MainRegTable.rSp) );
1523 internal("evalExp: Unrecognised SchedulerStatus");
1528 #ifdef CRUDE_PROFILING
1535 static List local addStgVar( List binds, Pair bind )
1537 StgVar nv = mkStgVar(NIL,NIL);
1538 Text t = textOf(fst(bind));
1539 Name n = findName(t);
1541 if (isNull(n)) { /* Lookup global name - the only way*/
1542 n = newName(t,NIL); /* this (should be able to happen) */
1543 } /* is with new global var introduced*/
1544 /* after type check; e.g. remPat1 */
1545 name(n).stgVar = nv;
1546 return cons(nv,binds);
1550 Void compileDefns() { /* compile script definitions */
1551 Target t = length(valDefns) + length(genDefns) + length(selDefns);
1555 /* a nasty hack. But I don't know an easier way to make */
1556 /* these things appear. */
1557 if (lastModule() == modulePrelude) {
1558 implementCfun ( nameCons, NIL );
1559 implementCfun ( nameNil, NIL );
1560 implementCfun ( nameUnit, NIL );
1566 for(vs=genDefns; nonNull(vs); vs=tl(vs)) {
1568 StgVar nv = mkStgVar(NIL,NIL);
1570 name(n).stgVar = nv;
1571 binds = cons(nv,binds);
1573 for(vss=selDefns; nonNull(vss); vss=tl(vss)) {
1574 for(vs=hd(vss); nonNull(vs); vs=tl(vs)) {
1577 StgVar nv = mkStgVar(NIL,NIL);
1579 name(n).stgVar = nv;
1580 binds = cons(nv,binds);
1585 setGoal("Translating",t);
1586 /* do valDefns before everything else so that all stgVar's get added. */
1587 for (; nonNull(valDefns); valDefns=tl(valDefns)) {
1588 hd(valDefns) = transBinds(hd(valDefns));
1589 mapAccum(addStgVar,binds,hd(valDefns));
1590 mapProc(compileGlobalFunction,hd(valDefns));
1593 for (; nonNull(genDefns); genDefns=tl(genDefns)) {
1594 compileGenFunction(hd(genDefns));
1597 for (; nonNull(selDefns); selDefns=tl(selDefns)) {
1598 mapOver(compileSelFunction,hd(selDefns));
1602 binds = addGlobals(binds);
1604 #if USE_HUGS_OPTIMIZER
1607 setGoal("Simplifying",t);
1608 optimiseTopBinds(binds);
1612 setGoal("Generating code",t);
1618 static Void local compileGlobalFunction(bind)
1620 Name n = findName(textOf(fst(bind)));
1621 List defs = snd(bind);
1622 Int arity = length(fst(hd(defs)));
1625 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1628 static Void local compileGenFunction(n) /* Produce code for internally */
1629 Name n; { /* generated function */
1630 List defs = name(n).defn;
1631 Int arity = length(fst(hd(defs)));
1634 mapProc(transAlt,defs);
1635 stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1639 static Name local compileSelFunction(p) /* Produce code for selector func */
1640 Pair p; { /* Should be merged with genDefns, */
1641 Name s = fst(p); /* but the name(_).defn field is */
1642 List defs = snd(p); /* already used for other purposes */
1643 Int arity = length(fst(hd(defs))); /* in selector functions. */
1646 mapProc(transAlt,defs);
1647 stgDefn(s,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1652 /* --------------------------------------------------------------------------
1654 * ------------------------------------------------------------------------*/
1660 case RESET : freeVars = NIL;
1662 freeBegin = mkOffset(0);
1669 case MARK : mark(freeVars);
1676 /*-------------------------------------------------------------------------*/