[project @ 2000-01-25 11:25:54 by rrt]
[ghc-hetmet.git] / ghc / interpreter / compiler.c
1
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).
6  *
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.
12  *
13  * $RCSfile: compiler.c,v $
14  * $Revision: 1.17 $
15  * $Date: 2000/01/13 10:47:05 $
16  * ------------------------------------------------------------------------*/
17
18 #include "prelude.h"
19 #include "storage.h"
20 #include "backend.h"
21 #include "connect.h"
22 #include "errors.h"
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                   */
26 #include "Schedule.h"
27 #include "link.h"
28
29 Addr inputCode;                        /* Addr of compiled code for expr   */
30 static Name currentName;               /* Top level name being processed   */
31 #if DEBUG_CODE
32 Bool   debugCode     = FALSE;          /* TRUE => print G-code to screen   */
33 #endif
34
35
36
37 /* --------------------------------------------------------------------------
38  * Local function prototypes:
39  * ------------------------------------------------------------------------*/
40
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));
54
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));
60
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));
78 #if TREX
79 static Bool local isExtDiscr            Args((Cell));
80 static Bool local eqExtDiscr            Args((Cell,Cell));
81 #endif
82
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));
87
88
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  * ------------------------------------------------------------------------*/
94
95 static Cell local translate(e)         /* Translate expression:            */
96 Cell e; {
97 #if 0
98     printf ( "translate: " );print(e,100);printf("\n");
99 #endif
100     switch (whatIs(e)) {
101         case LETREC     : snd(snd(e)) = translate(snd(snd(e)));
102                           return expandLetrec(e);
103
104         case COND       : transTriple(snd(e));
105                           return e;
106
107         case AP         : fst(e) = translate(fst(e));
108
109                           if (fst(e)==nameId || fst(e)==nameInd)
110                               return translate(snd(e));
111                           if (isName(fst(e)) &&
112                               isMfun(fst(e)) &&
113                               mfunOf(fst(e))==0)
114                               return translate(snd(e));
115
116                           snd(e) = translate(snd(e));
117                           return e;
118
119         case NAME       : if (e==nameOtherwise)
120                               return nameTrue;
121                           if (isCfun(e)) {
122                               if (isName(name(e).defn))
123                                   return name(e).defn;
124                               if (isPair(name(e).defn))
125                                   return snd(name(e).defn);
126                           }
127                           return e;
128
129 #if TREX
130         case RECSEL     : return nameRecSel;
131
132         case EXT        :
133 #endif
134         case TUPLE      :
135         case VAROPCELL  :
136         case VARIDCELL  :
137         case DICTVAR    :
138         case INTCELL    :
139         case FLOATCELL  :
140         case STRCELL    :
141         case BIGCELL    :
142         case CHARCELL   : return e;
143 #if IPARAM
144         case IPVAR      : return nameId;
145 #endif
146         case FINLIST    : mapOver(translate,snd(e));
147                           return mkConsList(snd(e));
148
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))));
152                           }
153
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);
159                               else {
160 #if MONAD_COMPS
161                                   r = ap(ap(nameReturn,m),r);
162                                   return transDo(m,r,qs);
163 #else
164                                   internal("translate: monad comps");
165 #endif
166                               }
167                           }
168
169         case CONFLDS    : return transConFlds(fst(snd(e)),snd(snd(e)));
170
171         case UPDFLDS    : return transUpdFlds(fst3(snd(e)),
172                                               snd3(snd(e)),
173                                               thd3(snd(e)));
174
175         case CASE       : {   Cell nv = inventVar();
176                               mapProc(transCase,snd(snd(e)));
177                               return ap(LETREC,
178                                         pair(singleton(pair(nv,snd(snd(e)))),
179                                              ap(nv,translate(fst(snd(e))))));
180                           }
181
182         case LAMBDA     : {   Cell nv = inventVar();
183                               transAlt(snd(e));
184                               return ap(LETREC,
185                                         pair(singleton(pair(
186                                                         nv,
187                                                         singleton(snd(e)))),
188                                              nv));
189                           }
190
191         default         : fprintf(stderr, "stuff=%d\n",whatIs(e));internal("translate");
192     }
193     return e;
194 }
195
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));
200 }
201
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));
207 }
208
209 static Void local transAlt(e)          /* Translate alt:                   */
210 Cell e; {                              /* ([Pat], Rhs) ==> ([Pat], Rhs')   */
211     snd(e) = transRhs(snd(e));
212 }
213
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));
218 }
219
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)) {
224 #if IPARAM
225         Cell v = fst(hd(bs));
226         while (isAp(v) && fst(v) == nameInd)
227             v = arg(v);
228         fst(hd(bs)) = v;
229         if (isVar(v)) {
230 #else
231         if (isVar(fst(hd(bs)))) {
232 #endif
233             mapProc(transAlt,snd(hd(bs)));
234             newBinds = cons(hd(bs),newBinds);
235         }
236         else
237             newBinds = remPat(fst(snd(hd(bs))),
238                               snd(snd(hd(bs)))=transRhs(snd(snd(hd(bs)))),
239                               newBinds);
240     }
241     return newBinds;
242 }
243
244 static Cell local transRhs(rhs)        /* Translate rhs: removing line nos */
245 Cell rhs; {
246     switch (whatIs(rhs)) {
247         case LETREC  : snd(snd(rhs)) = transRhs(snd(snd(rhs)));
248                        return expandLetrec(rhs);
249
250         case GUARDED : mapOver(snd,snd(rhs));       /* discard line number */
251                        mapProc(transPair,snd(rhs));
252                        return rhs;
253
254         default      : return translate(snd(rhs));  /* discard line number */
255     }
256 }
257
258 static Cell local mkConsList(es)       /* Construct expression for list es */
259 List es; {                             /* using nameNil and nameCons       */
260     if (isNull(es))
261         return nameNil;
262     else
263         return ap(ap(nameCons,hd(es)),mkConsList(tl(es)));
264 }
265
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));
270     Cell temp;
271
272     if (isNull(bss))                   /* should never happen, but just in */
273         return e;                      /* case:  LETREC [] IN e  ==>  e    */
274
275     mapOver(transBinds,bss);           /* translate each group of bindings */
276
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));
281     }
282     fst(snd(temp)) = hd(bss);
283
284     return root;
285 }
286
287 /* --------------------------------------------------------------------------
288  * Translation of list comprehensions is based on the description in
289  * `The Implementation of Functional Programming Languages':
290  *
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
296  *                               IN _h xs
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  * ------------------------------------------------------------------------*/
300
301 static Cell local transComp(e,qs,l)    /* Translate [e | qs] ++ l          */
302 Cell e;
303 List qs;
304 Cell l; {
305     if (nonNull(qs)) {
306         Cell q   = hd(qs);
307         Cell qs1 = tl(qs);
308
309         switch (fst(q)) {
310             case FROMQUAL : {   Cell ld    = NIL;
311                                 Cell hVar  = inventVar();
312                                 Cell xsVar = inventVar();
313
314                                 if (!failFree(fst(snd(q))))
315                                     ld = cons(pair(singleton(
316                                                     ap(ap(nameCons,
317                                                           WILDCARD),
318                                                           xsVar)),
319                                                    ap(hVar,xsVar)),
320                                               ld);
321
322                                 ld = cons(pair(singleton(
323                                                 ap(ap(nameCons,
324                                                       fst(snd(q))),
325                                                       xsVar)),
326                                                transComp(e,
327                                                          qs1,
328                                                          ap(hVar,xsVar))),
329                                           ld);
330                                 ld = cons(pair(singleton(nameNil),
331                                                l),
332                                           ld);
333
334                                 return ap(LETREC,
335                                           pair(singleton(pair(hVar,
336                                                               ld)),
337                                                ap(hVar,
338                                                   translate(snd(snd(q))))));
339                             }
340
341             case QWHERE   : return
342                                 expandLetrec(ap(LETREC,
343                                                 pair(snd(q),
344                                                      transComp(e,qs1,l))));
345
346             case BOOLQUAL : return ap(COND,
347                                       triple(translate(snd(q)),
348                                              transComp(e,qs1,l),
349                                              l));
350         }
351     }
352
353     return ap(ap(nameCons,e),l);
354 }
355
356 /* --------------------------------------------------------------------------
357  * Translation of monad comprehensions written using do-notation:
358  *
359  * do { e }               =>  e
360  * do { p <- exp; qs }    =>  LETREC _h p = do { qs }
361  *                                   _h _ = fail m "match fails"
362  *                            IN bind m exp _h
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
366  *
367  * where m :: Monad f
368  * ------------------------------------------------------------------------*/
369
370 static Cell local transDo(m,e,qs)       /* Translate do { qs ; e }         */
371 Cell m;
372 Cell e;
373 List qs; {
374     if (nonNull(qs)) {
375         Cell q   = hd(qs);
376         Cell qs1 = tl(qs);
377
378         switch (fst(q)) {
379             case FROMQUAL : {   Cell ld   = NIL;
380                                 Cell hVar = inventVar();
381
382                                 if (!failFree(fst(snd(q)))) {
383                                     Cell str = mkStr(findText("match fails"));
384                                     ld = cons(pair(singleton(WILDCARD),
385                                                    ap2(nameMFail,m,str)),
386                                               ld);
387                                 }
388
389                                 ld = cons(pair(singleton(fst(snd(q))),
390                                                transDo(m,e,qs1)),
391                                           ld);
392
393                                 return ap(LETREC,
394                                           pair(singleton(pair(hVar,ld)),
395                                                ap(ap(ap(nameBind,
396                                                         m),
397                                                      translate(snd(snd(q)))),
398                                                   hVar)));
399                             }
400
401             case DOQUAL :   {   Cell hVar = inventVar();
402                                 Cell ld   = cons(pair(singleton(WILDCARD),
403                                                       transDo(m,e,qs1)),
404                                                  NIL);
405                                 return ap(LETREC,
406                                           pair(singleton(pair(hVar,ld)),
407                                                ap(ap(ap(nameBind,
408                                                         m),
409                                                      translate(snd(q))),
410                                                   hVar)));
411                             }
412
413             case QWHERE   : return
414                                 expandLetrec(ap(LETREC,
415                                                 pair(snd(q),
416                                                      transDo(m,e,qs1))));
417
418             case BOOLQUAL : return
419                                 ap(COND,
420                                    triple(translate(snd(q)),
421                                           transDo(m,e,qs1),
422                                           ap2(nameMFail,m,
423                                             mkStr(findText("guard fails")))));
424         }
425     }
426     return e;
427 }
428
429 /* --------------------------------------------------------------------------
430  * Translation of named field construction and update:
431  *
432  * Construction is implemented using the following transformation:
433  *
434  *   C{x1=e1, ..., xn=en} =  C v1 ... vm
435  * where:
436  *   vi = e1,        if the ith component of C is labelled with x1
437  *       ...
438  *      = en,        if the ith component of C is labelled with xn
439  *      = undefined, otherwise
440  *
441  * Update is implemented using the following transformation:
442  *
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
446  *             ...
447  *             nv _             v1 ... vn = error "failed update"
448  *         in nv e e1 ... en
449  * where:
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)}
452  * and:
453  *   ai' = v1,   if the ith component of C is labelled with x1
454  *       ...
455  *       = vn,   if the ith component of C is labelled with xn
456  *       = ai,   otherwise
457  *  etc...
458  *
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!
464  *
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  * ------------------------------------------------------------------------*/
472
473 static Cell local transConFlds(c,flds)  /* Translate C{flds}               */
474 Name c;
475 List flds; {
476     Cell e = c;
477     Int  m = name(c).arity;
478     Int  i;
479     for (i=m; i>0; i--)
480         e = ap(e,nameUndefined);
481     for (; nonNull(flds); flds=tl(flds)) {
482         Cell a = e;
483         for (i=m-sfunPos(fst(hd(flds)),c); i>0; i--)
484             a = fun(a);
485         arg(a) = translate(snd(hd(flds)));
486     }
487     return e;
488 }
489
490 static Cell local transUpdFlds(e,cs,flds)/* Translate e{flds}              */
491 Cell e;                                 /* (cs is corresp list of constrs) */
492 List cs;
493 List flds; {
494     Cell nv   = inventVar();
495     Cell body = ap(nv,translate(e));
496     List fs   = flds;
497     List args = NIL;
498     List alts = NIL;
499
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);
504     }
505
506     for (; nonNull(cs); cs=tl(cs)) {    /* Loop through constructors to    */
507         Cell c   = hd(cs);              /* build up list of alts.          */
508         Cell pat = c;
509         Cell rhs = c;
510         List as  = args;
511         Int  m   = name(c).arity;
512         Int  i;
513
514         for (i=m; i>0; i--) {           /* pat  = C a1 ... am              */
515             Cell a = inventVar();       /* rhs  = C a1 ... am              */
516             pat    = ap(pat,a);
517             rhs    = ap(rhs,a);
518         }
519
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--)
524                 r = fun(r);
525             arg(r) = hd(as);
526         }
527
528         alts     = cons(pair(cons(pat,args),rhs),alts);
529     }
530     return ap(LETREC,pair(singleton(pair(nv,alts)),body));
531 }
532
533 /* --------------------------------------------------------------------------
534  * Elimination of pattern bindings:
535  *
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  * ------------------------------------------------------------------------*/
548
549 Bool failFree(pat)                /* is pattern failure free? (do we need  */
550 Cell pat; {                       /* a conformality check?)                */
551     Cell c = getHead(pat);
552
553     switch (whatIs(c)) {
554         case ASPAT     : return failFree(snd(snd(pat)));
555
556         case NAME      : if (!isCfun(c) || cfunOf(c)!=0)
557                              return FALSE;
558                          /*intentional fall-thru*/
559         case TUPLE     : for (; isAp(pat); pat=fun(pat))
560                              if (!failFree(arg(pat)))
561                                 return FALSE;
562                          /*intentional fall-thru*/
563         case LAZYPAT   :
564         case VAROPCELL :
565         case VARIDCELL :
566         case DICTVAR   :
567         case WILDCARD  : return TRUE;
568
569 #if TREX
570         case EXT       : return failFree(extField(pat)) &&
571                                 failFree(extRow(pat));
572 #endif
573
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))))
578                                      return FALSE;
579                              return TRUE;
580                          }
581                          /*intentional fall-thru*/
582         default        : return FALSE;
583     }
584 }
585
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..    */
590
591     switch (whatIs(pat)) {
592         case ASPAT     : return refutePat(snd(snd(pat)));
593
594         case FINLIST   : {   Cell ys = snd(pat);
595                              Cell xs = NIL;
596                              for (; nonNull(ys); ys=tl(ys))
597                                  xs = ap(ap(nameCons,refutePat(hd(ys))),xs);
598                              return revOnto(xs,nameNil);
599                          }
600
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);
606                              }
607                              return pair(CONFLDS,pair(fst(snd(pat)),rev(ps)));
608                          }
609
610         case VAROPCELL :
611         case VARIDCELL :
612         case DICTVAR   :
613         case WILDCARD  :
614         case LAZYPAT   : return WILDCARD;
615
616         case STRCELL   :
617         case CHARCELL  :
618 #if NPLUSK
619         case ADDPAT    :
620 #endif
621         case TUPLE     :
622         case NAME      : return pat;
623
624         case AP        : return refutePatAp(pat);
625
626         default        : internal("refutePat");
627                          return NIL; /*NOTREACHED*/
628     }
629 }
630
631 static Cell local refutePatAp(p)  /* find pattern to refute in conformality*/
632 Cell p; {
633     Cell h = getHead(p);
634     if (h==nameFromInt || h==nameFromInteger || h==nameFromDouble)
635         return p;
636 #if NPLUSK
637     else if (whatIs(h)==ADDPAT)
638         return ap(fun(p),refutePat(arg(p)));
639 #endif
640 #if TREX
641     else if (isExt(h)) {
642         Cell pf = refutePat(extField(p));
643         Cell pr = refutePat(extRow(p));
644         return ap(ap(fun(fun(p)),pf),pr);
645     }
646 #endif
647     else {
648         List as = getArgs(p);
649         mapOver(refutePat,as);
650         return applyToArgs(h,as);
651     }
652 }
653
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))
660                                                   : ap(ASPAT,
661                                                        pair(fst(snd(pat)),p));
662                          }
663
664         case FINLIST   : {   Cell ys = snd(pat);
665                              Cell xs = NIL;
666                              for (; nonNull(ys); ys=tl(ys))
667                                  xs = cons(matchPat(hd(ys)),xs);
668                              while (nonNull(xs) && hd(xs)==WILDCARD)
669                                  xs = tl(xs);
670                              for (ys=nameNil; nonNull(xs); xs=tl(xs))
671                                  ys = ap(ap(nameCons,hd(xs)),ys);
672                              return ys;
673                          }
674
675         case CONFLDS   : {   Cell ps   = NIL;
676                              Name c    = fst(snd(pat));
677                              Cell fs   = snd(snd(pat));
678                              Bool avar = FALSE;
679                              for (; nonNull(fs); fs=tl(fs)) {
680                                  Cell p = matchPat(snd(hd(fs)));
681                                  ps     = cons(pair(fst(hd(fs)),p),ps);
682                                  if (p!=WILDCARD)
683                                      avar = TRUE;
684                              }
685                              return avar ? pair(CONFLDS,pair(c,rev(ps)))
686                                          : WILDCARD;
687                          }
688
689         case VAROPCELL :
690         case VARIDCELL :
691         case DICTVAR   : return pat;
692
693         case LAZYPAT   : {   Cell p = matchPat(snd(pat));
694                              return (p==WILDCARD) ? WILDCARD : ap(LAZYPAT,p);
695                          }
696
697         case WILDCARD  :
698         case STRCELL   :
699         case CHARCELL  : return WILDCARD;
700
701         case TUPLE     :
702         case NAME      :
703         case AP        : {   Cell h = getHead(pat);
704                              if (h==nameFromInt     ||
705                                  h==nameFromInteger || h==nameFromDouble)
706                                  return WILDCARD;
707 #if NPLUSK
708                              else if (whatIs(h)==ADDPAT)
709                                  return pat;
710 #endif
711 #if TREX
712                              else if (isExt(h)) {
713                                  Cell pf = matchPat(extField(pat));
714                                  Cell pr = matchPat(extRow(pat));
715                                  return (pf==WILDCARD && pr==WILDCARD)
716                                           ? WILDCARD
717                                           : ap(ap(fun(fun(pat)),pf),pr);
718                              }
719 #endif
720                              else {
721                                  List args = NIL;
722                                  Bool avar = FALSE;
723                                  for (; isAp(pat); pat=fun(pat)) {
724                                      Cell p = matchPat(arg(pat));
725                                      if (p!=WILDCARD)
726                                          avar = TRUE;
727                                      args = cons(p,args);
728                                  }
729                                  return avar ? applyToArgs(pat,args)
730                                              : WILDCARD;
731                              }
732                          }
733
734         default        : internal("matchPat");
735                          return NIL; /*NOTREACHED*/
736     }
737 }
738
739 #define addEqn(v,val,lds)  cons(pair(v,singleton(pair(NIL,val))),lds)
740
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.                    */
745
746     /* Conformality test (if required):
747      *   pat = expr  ==>    nv = LETREC confCheck nv@pat = nv
748      *                           IN confCheck expr
749      *                      remPat1(pat,nv,.....);
750      */
751
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,
757                                                         pair(nv,
758                                                              refutePat(pat)))),
759                                            nv)));
760
761         if (whatIs(expr)==GUARDED) {         /* A spanner ... special case */
762             lds  = addEqn(nv,expr,lds);      /* for guarded pattern binding*/
763             expr = nv;
764             nv   = inventVar();
765         }
766
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           */
770         }
771
772         lds = addEqn(nv,                                /* nv =            */
773                      ap(LETREC,pair(singleton(locfun),  /* LETREC [locfun] */
774                                     ap(confVar,expr))), /* IN confVar expr */
775                      lds);
776
777         return remPat1(matchPat(pat),nv,lds);
778     }
779
780     return remPat1(matchPat(pat),expr,lds);
781 }
782
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.     */
786 List lds; {
787     Cell c = getHead(pat);
788
789     switch (whatIs(c)) {
790         case WILDCARD  :
791         case STRCELL   :
792         case CHARCELL  : break;
793
794         case ASPAT     : return remPat1(snd(snd(pat)),     /* v@pat = expr */
795                                         fst(snd(pat)),
796                                         addEqn(fst(snd(pat)),expr,lds));
797
798         case LAZYPAT   : {   Cell nv;
799
800                              if (isVar(expr) || isName(expr))
801                                  nv  = expr;
802                              else {
803                                  nv  = inventVar();
804                                  lds = addEqn(nv,expr,lds);
805                              }
806
807                              return remPat(snd(pat),nv,lds);
808                          }
809
810 #if NPLUSK
811         case ADDPAT    : return remPat1(arg(pat),       /* n + k = expr */
812                                         ap(ap(ap(namePmSub,
813                                                  arg(fun(pat))),
814                                                  mkInt(snd(fun(fun(pat))))),
815                                                  expr),
816                                         lds);
817 #endif
818
819         case FINLIST   : return remPat1(mkConsList(snd(pat)),expr,lds);
820
821         case CONFLDS   : {   Name h  = fst(snd(pat));
822                              Int  m  = name(h).arity;
823                              Cell p  = h;
824                              List fs = snd(snd(pat));
825                              Int  i  = m;
826                              while (0<i--)
827                                  p = ap(p,WILDCARD);
828                              for (; nonNull(fs); fs=tl(fs)) {
829                                  Cell r = p;
830                                  for (i=m-sfunPos(fst(hd(fs)),h); i>0; i--)
831                                      r = fun(r);
832                                  arg(r) = snd(hd(fs));
833                              }
834                              return remPat1(p,expr,lds);
835                          }
836
837         case DICTVAR   : /* shouldn't really occur */
838                          assert(0); /* so let's test for it then! ADR */
839         case VARIDCELL :
840         case VAROPCELL : return addEqn(pat,expr,lds);
841
842         case NAME      : if (c==nameFromInt || c==nameFromInteger
843                                             || c==nameFromDouble) {
844                              if (argCount==2)
845                                  arg(fun(pat)) = translate(arg(fun(pat)));
846                              break;
847                          }
848
849                          if (argCount==1 && isCfun(c)       /* for newtype */
850                              && cfunOf(c)==0 && name(c).defn==nameId)
851                              return remPat1(arg(pat),expr,lds);
852
853                          /* intentional fall-thru */
854         case TUPLE     : {   List ps = getArgs(pat);
855
856                              if (nonNull(ps)) {
857                                  Cell nv, sel;
858                                  Int  i;
859
860                                  if (isVar(expr) || isName(expr))
861                                      nv  = expr;
862                                  else {
863                                      nv  = inventVar();
864                                      lds = addEqn(nv,expr,lds);
865                                  }
866
867                                  sel = ap(ap(nameSel,c),nv);
868                                  for (i=1; nonNull(ps); ++i, ps=tl(ps))
869                                       lds = remPat1(hd(ps),
870                                                     ap(sel,mkInt(i)),
871                                                     lds);
872                              }
873                          }
874                          break;
875
876 #if TREX
877         case EXT       : {   Cell nv = inventVar();
878                              arg(fun(fun(pat)))
879                                  = translate(arg(fun(fun(pat))));
880                              lds = addEqn(nv,
881                                           ap(ap(nameRecBrk,
882                                                 arg(fun(fun(pat)))),
883                                              expr),
884                                           lds);
885                              lds = remPat1(extField(pat),ap(nameFst,nv),lds);
886                              lds = remPat1(extRow(pat),ap(nameSnd,nv),lds);
887                          }
888                          break;
889 #endif
890
891         default        : internal("remPat1");
892                          break;
893     }
894     return lds;
895 }
896
897 /* --------------------------------------------------------------------------
898  * Eliminate pattern matching in function definitions -- pattern matching
899  * compiler:
900  *
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.
907  *
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  * ------------------------------------------------------------------------*/
913
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                 */
917
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           */
922     switch (whatIs(e)) {
923         case GUARDED  : map2Over(pmcPair,co,sc,snd(e));
924                         break;
925
926         case LETREC   : pmcLetrec(co,sc,snd(e));
927                         break;
928
929         case VARIDCELL:
930         case VAROPCELL:
931         case DICTVAR  : return pmcVar(sc,textOf(e));
932
933         case COND     : return ap(COND,pmcTriple(co,sc,snd(e)));
934
935         case AP       : return pmcPair(co,sc,e);
936
937 #if NPLUSK
938         case ADDPAT   :
939 #endif
940 #if TREX
941         case EXT      :
942 #endif
943         case TUPLE    :
944         case NAME     :
945         case CHARCELL :
946         case INTCELL  :
947         case BIGCELL  :
948         case FLOATCELL:
949         case STRCELL  : break;
950
951         default       : internal("pmcTerm");
952                         break;
953     }
954     return e;
955 }
956
957 static Cell local pmcPair(co,sc,pr)    /* apply pattern matching compiler  */
958 Int  co;                               /* to a pair of exprs               */
959 List sc;
960 Pair pr; {
961     return pair(pmcTerm(co,sc,fst(pr)),
962                 pmcTerm(co,sc,snd(pr)));
963 }
964
965 static Cell local pmcTriple(co,sc,tr)  /* apply pattern matching compiler  */
966 Int    co;                             /* to a triple of exprs             */
967 List   sc;
968 Triple tr; {
969     return triple(pmcTerm(co,sc,fst3(tr)),
970                   pmcTerm(co,sc,snd3(tr)),
971                   pmcTerm(co,sc,thd3(tr)));
972 }
973
974 static Cell local pmcVar(sc,t)         /* find translation of variable     */
975 List sc;                               /* in current scope                 */
976 Text t; {
977     List xs;
978     Name n;
979
980     for (xs=sc; nonNull(xs); xs=tl(xs)) {
981         Cell x = hd(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);
986                 return snd(x);
987             }
988             else {                                   /* local function ... */
989                 if (!cellIsMember(snd(x),freeFuns))
990                     freeFuns = cons(snd(x),freeFuns);
991                 return fst3(snd(x));
992             }
993         }
994     }
995
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   */
1000     return n;
1001 }
1002
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                     */
1006 Pair e; {
1007     List fs = NIL;                     /* local function definitions       */
1008     List vs = NIL;                     /* local variable definitions       */
1009     List ds;
1010
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)))));
1014
1015         if (arity==0) {                            /* Variable declaration */
1016             vs = cons(snd(hd(ds)),vs);
1017             sc = cons(pair(v,mkOffset(++co)),sc);
1018         }
1019         else {                                     /* Function declaration */
1020             fs = cons(triple(inventVar(),mkInt(arity),snd(hd(ds))),fs);
1021             sc = cons(pair(v,hd(fs)),sc);
1022         }
1023     }
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*/
1031 }
1032
1033 static Cell local pmcVarDef(co,sc,vd)  /* apply pattern matching compiler  */
1034 Int  co;                               /* to variable definition           */
1035 List sc;
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);
1042 }
1043
1044 static Void local pmcFunDef(co,sc,fd)  /* apply pattern matching compiler  */
1045 Int    co;                             /* to function definition           */
1046 List   sc;
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));
1053     Cell   xs;
1054
1055     freeBegin = mkOffset(co);
1056     freeVars  = NIL;
1057     freeFuns  = NIL;
1058     temp      = match(co+arity,temp);
1059     thd3(fd)  = triple(freeVars,freeFuns,temp);
1060
1061     for (xs=freeVars; nonNull(xs); xs=tl(xs))
1062         if (hd(xs)<=saveFreeBegin && !cellIsMember(hd(xs),saveFreeVars))
1063             saveFreeVars = cons(hd(xs),saveFreeVars);
1064
1065     for (xs=freeFuns; nonNull(xs); xs=tl(xs))
1066         if (!cellIsMember(hd(xs),saveFreeFuns))
1067             saveFreeFuns = cons(hd(xs),saveFreeFuns);
1068
1069     freeBegin = saveFreeBegin;
1070     freeVars  = saveFreeVars;
1071     freeFuns  = saveFreeFuns;
1072 }
1073
1074 /* ---------------------------------------------------------------------------
1075  * Main part of pattern matching compiler: convert [Alt] to case constructs
1076  *
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.
1081  *
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)).]
1089  *
1090  * The Scope component has type:
1091  *   Scope  ::= [(Var,Expr)]
1092  * and provides a mapping from variable names to offsets used in the matching
1093  * process.
1094  *
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  * ------------------------------------------------------------------------*/
1100
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))
1107
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..])         */
1111 List sc;
1112 List as; {
1113     List mas = NIL;
1114     List us  = NIL;
1115     for (; n>0; n--)
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);
1119     return rev(mas);
1120 }
1121
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                */
1127     mas       = tl(mas);
1128     tl(smas)  = NIL;
1129
1130     if (emptyMatch(hd(smas))) {         /* The case for empty matches:     */
1131         while (nonNull(mas) && emptyMatch(hd(mas))) {
1132             List temp = tl(mas);
1133             tl(mas)   = smas;
1134             smas      = mas;
1135             mas       = temp;
1136         }
1137         srhs = joinMas(co,rev(smas));
1138     }
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);
1150                 tl(mas)   = smas;
1151                 smas      = mas;
1152                 mas       = temp;
1153             }
1154             smas = rev(smas);
1155             map2Proc(advance,co,da,smas);
1156             srhs = ap(NUMCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1157         }
1158 #if TREX
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);
1167                 tl(mas)   = smas;
1168                 smas      = mas;
1169                 mas       = temp;
1170             }
1171             smas = rev(smas);
1172             map2Proc(advance,co,da,smas);
1173             srhs = ap(EXTCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1174         }
1175 #endif
1176         else {                          /* Constructor match               */
1177             List tab = addConTable(d,hd(smas),NIL);
1178             Int  da;
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);
1183                 mas = tl(mas);
1184             }
1185             for (tab=rev(tab); nonNull(tab); tab=tl(tab)) {
1186                 d    = fst(hd(tab));
1187                 smas = snd(hd(tab));
1188                 da   = discrArity(d);
1189                 map2Proc(advance,co,da,smas);
1190                 srhs = cons(pair(d,match(co+da,smas)),srhs);
1191             }
1192             srhs = ap(CASE,pair(mkOffset(o),srhs));
1193         }
1194     }
1195     return nonNull(mas) ? ap(FATBAR,pair(srhs,match(co,mas))) : srhs;
1196 }
1197
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 */
1201     Cell ma  = hd(mas);
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))));
1205     else
1206         return rhs;
1207 }
1208
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;
1215     }
1216 }
1217
1218 /* type Table a b = [(a, [b])]
1219  *
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
1225  */
1226
1227 static List local addConTable(x,y,tab) /* add element (x,y) to table       */
1228 Cell x, y;
1229 List tab; {
1230     if (isNull(tab))
1231         return singleton(pair(x,singleton(y)));
1232     else if (fst(hd(tab))==x)
1233         snd(hd(tab)) = appendOnto(snd(hd(tab)),singleton(y));
1234     else
1235         tl(tab) = addConTable(x,y,tl(tab));
1236
1237     return tab;
1238 }
1239
1240 static Void local advance(co,a,ma)      /* Advance non-empty match by      */
1241 Int  co;                                /* processing head pattern         */
1242 Int  a;                                 /* discriminator arity             */
1243 Cell ma; {
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));
1250         List qs = NIL;
1251         List vs = NIL;
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);
1255         }
1256         ps = revOnto(qs,ps);
1257         us = revOnto(vs,us);
1258     }
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);
1263             p  = fun(p);
1264         }
1265
1266     maPats(ma) = ps;
1267     maOffs(ma) = us;
1268 }
1269
1270 /* --------------------------------------------------------------------------
1271  * Normalize and test for empty match:
1272  * ------------------------------------------------------------------------*/
1273
1274 static Bool local emptyMatch(ma)/* Normalize and test to see if a given    */
1275 Cell ma; {                      /* match, ma, is empty.                    */
1276
1277     while (nonNull(maPats(ma))) {
1278         Cell p;
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),
1283                                                      maRhs(ma)));
1284                                  p         = nv;
1285                              }
1286                              /* intentional fall-thru */
1287             case VARIDCELL :
1288             case VAROPCELL :
1289             case DICTVAR   : extSc(p,hd(maOffs(ma)),ma);
1290             case WILDCARD  : maPats(ma) = tl(maPats(ma));
1291                              maOffs(ma) = tl(maOffs(ma));
1292                              continue;
1293
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.)
1299              */
1300             case ASPAT     : extSc(fst(snd(p)),hd(maOffs(ma)),ma);
1301                              hd(maPats(ma)) = snd(snd(p));
1302                              goto tidyHd;
1303
1304             case FINLIST   : hd(maPats(ma)) = mkConsList(snd(p));
1305                              return FALSE;
1306
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);
1311                                      else
1312                                          p = ap(consChar('\0'),p);
1313                                  }
1314                                  hd(maPats(ma)) = revOnto(p,nameNil);
1315                              }
1316                              return FALSE;
1317
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);
1322                                   goto tidyHd;
1323                              }
1324                              /* intentional fall-thru */
1325             case CHARCELL  :
1326             case NAME      :
1327             case CONFLDS   :
1328                              return FALSE;
1329
1330             default        : internal("emptyMatch");
1331         }
1332     }
1333     return TRUE;
1334 }
1335
1336 /* --------------------------------------------------------------------------
1337  * Discriminators:
1338  * ------------------------------------------------------------------------*/
1339
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));
1346 #if NPLUSK
1347         case ADDPAT  : arg(fun(p)) = translate(arg(fun(p)));
1348                        return fun(p);
1349 #endif
1350 #if TREX
1351         case EXT     : h      = fun(fun(p));
1352                        arg(h) = translate(arg(h));
1353                        return h;
1354 #endif
1355         case NAME    : if (h==nameFromInt || h==nameFromInteger
1356                                           || h==nameFromDouble) {
1357                            if (argCount==2)
1358                                arg(fun(p)) = translate(arg(fun(p)));
1359                            return p;
1360                        }
1361     }
1362     return h;
1363 }
1364
1365 static Bool local isNumDiscr(d) /* TRUE => numeric discriminator           */
1366 Cell d; {
1367     switch (whatIs(d)) {
1368         case NAME      :
1369         case TUPLE     :
1370         case CHARCELL  : return FALSE;
1371
1372 #if TREX
1373         case AP        : return !isExt(fun(d));
1374 #else
1375         case AP        : return TRUE;   /* must be a literal or (n+k)      */
1376 #endif
1377     }
1378     internal("isNumDiscr");
1379     return 0;/*NOTREACHED*/
1380 }
1381
1382 Int discrArity(d)                      /* Find arity of discriminator      */
1383 Cell d; {
1384     switch (whatIs(d)) {
1385         case NAME      : return name(d).arity;
1386         case TUPLE     : return tupleOf(d);
1387         case CHARCELL  : return 0;
1388 #if TREX
1389         case AP        : switch (whatIs(fun(d))) {
1390 #if NPLUSK
1391                              case ADDPAT : return 1;
1392 #endif
1393                              case EXT    : return 2;
1394                              default     : return 0;
1395                          }
1396 #else
1397 #if NPLUSK
1398         case AP        : return (whatIs(fun(d))==ADDPAT) ? 1 : 0;
1399 #else
1400         case AP        : return 0;      /* must be an Int or Float lit     */
1401 #endif
1402 #endif
1403     }
1404     internal("discrArity");
1405     return 0;/*NOTREACHED*/
1406 }
1407
1408 static Bool local eqNumDiscr(d1,d2)     /* Determine whether two numeric   */
1409 Cell d1, d2; {                          /* descriptors have same value     */
1410 #if NPLUSK
1411     if (whatIs(fun(d1))==ADDPAT)
1412         return whatIs(fun(d2))==ADDPAT && snd(fun(d1))==snd(fun(d2));
1413 #endif
1414     if (isInt(arg(d1)))
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*/
1420 }
1421
1422 #if TREX
1423 static Bool local isExtDiscr(d)         /* Test of extension discriminator */
1424 Cell d; {
1425     return isAp(d) && isExt(fun(d));
1426 }
1427
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);
1431 }
1432 #endif
1433
1434 /*-------------------------------------------------------------------------*/
1435
1436
1437
1438 /* --------------------------------------------------------------------------
1439  * STG stuff
1440  * ------------------------------------------------------------------------*/
1441
1442 static Void local stgCGBinds( List );
1443
1444 static Void local stgCGBinds(binds)
1445 List binds; {
1446     cgBinds(binds);
1447 }
1448
1449 /* --------------------------------------------------------------------------
1450  * Main entry points to compiler:
1451  * ------------------------------------------------------------------------*/
1452
1453 static List addGlobals( List binds )
1454 {
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);
1460         }
1461     }
1462     return binds;
1463 }
1464
1465 typedef void (*sighandler_t)(int);
1466 void eval_ctrlbrk ( int dunnowhat )
1467 {
1468    interruptStgRts();
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);
1473 }
1474
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.
1478      */
1479     Name n = newName(inventText(),NIL);
1480     Cell e;
1481     StgVar v = mkStgVar(NIL,NIL);
1482     name(n).stgVar = v;
1483     compiler(RESET);
1484     e = pmcTerm(0,NIL,translate(inputExpr));
1485     stgDefn(n,0,e);
1486     inputExpr = NIL;
1487     stgCGBinds(addGlobals(singleton(v)));
1488     
1489     /* Run thread (and any other runnable threads) */
1490
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.
1495      */
1496     /* initScheduler(); */
1497 #ifdef CRUDE_PROFILING
1498     cp_init();
1499 #endif
1500
1501     {
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);
1510         fflush (stderr); 
1511         fflush (stdout);
1512         switch (status) {
1513         case Deadlock:
1514                 printf("{Deadlock or Blackhole}");
1515                 if (doRevertCAFs) RevertCAFs();
1516                 break;
1517         case Interrupted:
1518                 printf("{Interrupted}");
1519                 if (doRevertCAFs) RevertCAFs();
1520                 break;
1521         case Killed:
1522                 printf("{Interrupted or Killed}");
1523                 if (doRevertCAFs) RevertCAFs();
1524                 break;
1525         case Success:
1526                 if (doRevertCAFs) RevertCAFs();
1527                 break;
1528         default:
1529                 internal("evalExp: Unrecognised SchedulerStatus");
1530         }
1531         deleteAllThreads();
1532         fflush(stdout);
1533         fflush(stderr);
1534     }
1535 #ifdef CRUDE_PROFILING
1536     cp_show();
1537 #endif
1538
1539 }
1540
1541
1542 static List local addStgVar( List binds, Pair bind )
1543 {
1544     StgVar nv = mkStgVar(NIL,NIL);
1545     Text   t  = textOf(fst(bind));
1546     Name   n  = findName(t);
1547
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);
1554 }
1555
1556
1557 Void compileDefns() {                  /* compile script definitions       */
1558     Target t = length(valDefns) + length(genDefns) + length(selDefns);
1559     Target i = 0;
1560     List binds = NIL;
1561
1562     {
1563         List vss;
1564         List vs;
1565         for(vs=genDefns; nonNull(vs); vs=tl(vs)) {
1566             Name   n  = hd(vs);
1567             StgVar nv = mkStgVar(NIL,NIL);
1568             assert(isName(n));
1569             name(n).stgVar = nv;
1570             binds = cons(nv,binds);
1571         }
1572         for(vss=selDefns; nonNull(vss); vss=tl(vss)) {
1573             for(vs=hd(vss); nonNull(vs); vs=tl(vs)) {
1574                 Pair p = hd(vs);
1575                 Name n = fst(p);
1576                 StgVar nv = mkStgVar(NIL,NIL);
1577                 assert(isName(n));
1578                 name(n).stgVar = nv;
1579                 binds = cons(nv,binds);
1580             }
1581         }
1582     }
1583
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));
1590         soFar(i++);
1591     }
1592     for (; nonNull(genDefns); genDefns=tl(genDefns)) {
1593         compileGenFunction(hd(genDefns));
1594         soFar(i++);
1595     }
1596     for (; nonNull(selDefns); selDefns=tl(selDefns)) {
1597         mapOver(compileSelFunction,hd(selDefns));
1598         soFar(i++);
1599     }
1600
1601     binds = addGlobals(binds);
1602     done();
1603     setGoal("Generating code",t);
1604     stgCGBinds(binds);
1605
1606     done();
1607 }
1608
1609 static Void local compileGlobalFunction(bind)
1610 Pair bind; {
1611     Name n     = findName(textOf(fst(bind)));
1612     List defs  = snd(bind);
1613     Int  arity = length(fst(hd(defs)));
1614     assert(isName(n));
1615     compiler(RESET);
1616     stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1617 }
1618
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)));
1623     compiler(RESET);
1624     currentName = n;
1625     mapProc(transAlt,defs);
1626     stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1627     name(n).defn = NIL;
1628 }
1629
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.          */
1635
1636     compiler(RESET);
1637     mapProc(transAlt,defs);
1638     stgDefn(s,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1639     return s;
1640 }
1641
1642
1643 /* --------------------------------------------------------------------------
1644  * Compiler control:
1645  * ------------------------------------------------------------------------*/
1646
1647 Void compiler(what)
1648 Int what; {
1649     switch (what) {
1650         case PREPREL :
1651         case RESET   : freeVars      = NIL;
1652                        freeFuns      = NIL;
1653                        freeBegin     = mkOffset(0);
1654                        break;
1655
1656         case MARK    : mark(freeVars);
1657                        mark(freeFuns);
1658                        break;
1659
1660         case POSTPREL: break;
1661     }
1662 }
1663
1664 /*-------------------------------------------------------------------------*/