07d0fc44fcd11652152533deeb737ad223e4b23a
[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.13 $
15  * $Date: 1999/11/18 12:10:18 $
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     switch (whatIs(e)) {
98         case LETREC     : snd(snd(e)) = translate(snd(snd(e)));
99                           return expandLetrec(e);
100
101         case COND       : transTriple(snd(e));
102                           return e;
103
104         case AP         : fst(e) = translate(fst(e));
105
106                           if (fst(e)==nameId || fst(e)==nameInd)
107                               return translate(snd(e));
108                           if (isName(fst(e)) &&
109                               isMfun(fst(e)) &&
110                               mfunOf(fst(e))==0)
111                               return translate(snd(e));
112
113                           snd(e) = translate(snd(e));
114                           return e;
115
116         case NAME       : if (e==nameOtherwise)
117                               return nameTrue;
118                           if (isCfun(e)) {
119                               if (isName(name(e).defn))
120                                   return name(e).defn;
121                               if (isPair(name(e).defn))
122                                   return snd(name(e).defn);
123                           }
124                           return e;
125
126 #if TREX
127         case RECSEL     : return nameRecSel;
128
129         case EXT        :
130 #endif
131         case TUPLE      :
132         case VAROPCELL  :
133         case VARIDCELL  :
134         case DICTVAR    :
135         case INTCELL    :
136         case FLOATCELL  :
137         case STRCELL    :
138         case BIGCELL    :
139         case CHARCELL   : return e;
140 #if IPARAM
141         case IPVAR      : return nameId;
142 #endif
143         case FINLIST    : mapOver(translate,snd(e));
144                           return mkConsList(snd(e));
145
146         case DOCOMP     : {   Cell m = translate(fst(snd(e)));
147                               Cell r = translate(fst(snd(snd(e))));
148                               return transDo(m,r,snd(snd(snd(e))));
149                           }
150
151         case MONADCOMP  : {   Cell m  = translate(fst(snd(e)));
152                               Cell r  = translate(fst(snd(snd(e))));
153                               Cell qs = snd(snd(snd(e)));
154                               if (m == nameListMonad)
155                                   return transComp(r,qs,nameNil);
156                               else {
157 #if MONAD_COMPS
158                                   r = ap(ap(nameReturn,m),r);
159                                   return transDo(m,r,qs);
160 #else
161                                   internal("translate: monad comps");
162 #endif
163                               }
164                           }
165
166         case CONFLDS    : return transConFlds(fst(snd(e)),snd(snd(e)));
167
168         case UPDFLDS    : return transUpdFlds(fst3(snd(e)),
169                                               snd3(snd(e)),
170                                               thd3(snd(e)));
171
172         case CASE       : {   Cell nv = inventVar();
173                               mapProc(transCase,snd(snd(e)));
174                               return ap(LETREC,
175                                         pair(singleton(pair(nv,snd(snd(e)))),
176                                              ap(nv,translate(fst(snd(e))))));
177                           }
178
179         case LAMBDA     : {   Cell nv = inventVar();
180                               transAlt(snd(e));
181                               return ap(LETREC,
182                                         pair(singleton(pair(
183                                                         nv,
184                                                         singleton(snd(e)))),
185                                              nv));
186                           }
187
188         default         : fprintf(stderr, "stuff=%d\n",whatIs(e));internal("translate");
189     }
190     return e;
191 }
192
193 static Void local transPair(pr)        /* Translate each component in a    */
194 Pair pr; {                             /* pair of expressions.             */
195     fst(pr) = translate(fst(pr));
196     snd(pr) = translate(snd(pr));
197 }
198
199 static Void local transTriple(tr)      /* Translate each component in a    */
200 Triple tr; {                           /* triple of expressions.           */
201     fst3(tr) = translate(fst3(tr));
202     snd3(tr) = translate(snd3(tr));
203     thd3(tr) = translate(thd3(tr));
204 }
205
206 static Void local transAlt(e)          /* Translate alt:                   */
207 Cell e; {                              /* ([Pat], Rhs) ==> ([Pat], Rhs')   */
208     snd(e) = transRhs(snd(e));
209 }
210
211 static Void local transCase(c)         /* Translate case:                  */
212 Cell c; {                              /* (Pat, Rhs) ==> ([Pat], Rhs')     */
213     fst(c) = singleton(fst(c));
214     snd(c) = transRhs(snd(c));
215 }
216
217 static List local transBinds(bs)        /* Translate list of bindings:     */
218 List bs; {                              /* eliminating pattern matching on */
219     List newBinds = NIL;                /* lhs of bindings.                */
220     for (; nonNull(bs); bs=tl(bs)) {
221 #if IPARAM
222         Cell v = fst(hd(bs));
223         while (isAp(v) && fst(v) == nameInd)
224             v = arg(v);
225         fst(hd(bs)) = v;
226         if (isVar(v)) {
227 #else
228         if (isVar(fst(hd(bs)))) {
229 #endif
230             mapProc(transAlt,snd(hd(bs)));
231             newBinds = cons(hd(bs),newBinds);
232         }
233         else
234             newBinds = remPat(fst(snd(hd(bs))),
235                               snd(snd(hd(bs)))=transRhs(snd(snd(hd(bs)))),
236                               newBinds);
237     }
238     return newBinds;
239 }
240
241 static Cell local transRhs(rhs)        /* Translate rhs: removing line nos */
242 Cell rhs; {
243     switch (whatIs(rhs)) {
244         case LETREC  : snd(snd(rhs)) = transRhs(snd(snd(rhs)));
245                        return expandLetrec(rhs);
246
247         case GUARDED : mapOver(snd,snd(rhs));       /* discard line number */
248                        mapProc(transPair,snd(rhs));
249                        return rhs;
250
251         default      : return translate(snd(rhs));  /* discard line number */
252     }
253 }
254
255 static Cell local mkConsList(es)       /* Construct expression for list es */
256 List es; {                             /* using nameNil and nameCons       */
257     if (isNull(es))
258         return nameNil;
259     else
260         return ap(ap(nameCons,hd(es)),mkConsList(tl(es)));
261 }
262
263 static Cell local expandLetrec(root)   /* translate LETREC with list of    */
264 Cell root; {                           /* groups of bindings (from depend. */
265     Cell e   = snd(snd(root));         /* analysis) to use nested LETRECs  */
266     List bss = fst(snd(root));
267     Cell temp;
268
269     if (isNull(bss))                   /* should never happen, but just in */
270         return e;                      /* case:  LETREC [] IN e  ==>  e    */
271
272     mapOver(transBinds,bss);           /* translate each group of bindings */
273
274     for (temp=root; nonNull(tl(bss)); bss=tl(bss)) {
275         fst(snd(temp)) = hd(bss);
276         snd(snd(temp)) = ap(LETREC,pair(NIL,e));
277         temp           = snd(snd(temp));
278     }
279     fst(snd(temp)) = hd(bss);
280
281     return root;
282 }
283
284 /* --------------------------------------------------------------------------
285  * Translation of list comprehensions is based on the description in
286  * `The Implementation of Functional Programming Languages':
287  *
288  * [ e | qs ] ++ l            => transComp e qs l
289  * transComp e []           l => e : l
290  * transComp e ((p<-xs):qs) l => LETREC _h []      = l
291  *                                      _h (p:_xs) = transComp e qs (_h _xs)
292  *                                      _h (_:_xs) = _h _xs --if p !failFree
293  *                               IN _h xs
294  * transComp e (b:qs)       l => if b then transComp e qs l else l
295  * transComp e (decls:qs)   l => LETREC decls IN transComp e qs l
296  * ------------------------------------------------------------------------*/
297
298 static Cell local transComp(e,qs,l)    /* Translate [e | qs] ++ l          */
299 Cell e;
300 List qs;
301 Cell l; {
302     if (nonNull(qs)) {
303         Cell q   = hd(qs);
304         Cell qs1 = tl(qs);
305
306         switch (fst(q)) {
307             case FROMQUAL : {   Cell ld    = NIL;
308                                 Cell hVar  = inventVar();
309                                 Cell xsVar = inventVar();
310
311                                 if (!failFree(fst(snd(q))))
312                                     ld = cons(pair(singleton(
313                                                     ap(ap(nameCons,
314                                                           WILDCARD),
315                                                           xsVar)),
316                                                    ap(hVar,xsVar)),
317                                               ld);
318
319                                 ld = cons(pair(singleton(
320                                                 ap(ap(nameCons,
321                                                       fst(snd(q))),
322                                                       xsVar)),
323                                                transComp(e,
324                                                          qs1,
325                                                          ap(hVar,xsVar))),
326                                           ld);
327                                 ld = cons(pair(singleton(nameNil),
328                                                l),
329                                           ld);
330
331                                 return ap(LETREC,
332                                           pair(singleton(pair(hVar,
333                                                               ld)),
334                                                ap(hVar,
335                                                   translate(snd(snd(q))))));
336                             }
337
338             case QWHERE   : return
339                                 expandLetrec(ap(LETREC,
340                                                 pair(snd(q),
341                                                      transComp(e,qs1,l))));
342
343             case BOOLQUAL : return ap(COND,
344                                       triple(translate(snd(q)),
345                                              transComp(e,qs1,l),
346                                              l));
347         }
348     }
349
350     return ap(ap(nameCons,e),l);
351 }
352
353 /* --------------------------------------------------------------------------
354  * Translation of monad comprehensions written using do-notation:
355  *
356  * do { e }               =>  e
357  * do { p <- exp; qs }    =>  LETREC _h p = do { qs }
358  *                                   _h _ = fail m "match fails"
359  *                            IN bind m exp _h
360  * do { LET decls; qs }   =>  LETREC decls IN do { qs }
361  * do { IF guard; qs }    =>  if guard then do { qs } else fail m  "guard fails"
362  * do { e; qs }           =>  LETREC _h _ = [ e | qs ] in bind m exp _h
363  *
364  * where m :: Monad f
365  * ------------------------------------------------------------------------*/
366
367 static Cell local transDo(m,e,qs)       /* Translate do { qs ; e }         */
368 Cell m;
369 Cell e;
370 List qs; {
371     if (nonNull(qs)) {
372         Cell q   = hd(qs);
373         Cell qs1 = tl(qs);
374
375         switch (fst(q)) {
376             case FROMQUAL : {   Cell ld   = NIL;
377                                 Cell hVar = inventVar();
378
379                                 if (!failFree(fst(snd(q)))) {
380                                     Cell str = mkStr(findText("match fails"));
381                                     ld = cons(pair(singleton(WILDCARD),
382                                                    ap2(nameMFail,m,str)),
383                                               ld);
384                                 }
385
386                                 ld = cons(pair(singleton(fst(snd(q))),
387                                                transDo(m,e,qs1)),
388                                           ld);
389
390                                 return ap(LETREC,
391                                           pair(singleton(pair(hVar,ld)),
392                                                ap(ap(ap(nameBind,
393                                                         m),
394                                                      translate(snd(snd(q)))),
395                                                   hVar)));
396                             }
397
398             case DOQUAL :   {   Cell hVar = inventVar();
399                                 Cell ld   = cons(pair(singleton(WILDCARD),
400                                                       transDo(m,e,qs1)),
401                                                  NIL);
402                                 return ap(LETREC,
403                                           pair(singleton(pair(hVar,ld)),
404                                                ap(ap(ap(nameBind,
405                                                         m),
406                                                      translate(snd(q))),
407                                                   hVar)));
408                             }
409
410             case QWHERE   : return
411                                 expandLetrec(ap(LETREC,
412                                                 pair(snd(q),
413                                                      transDo(m,e,qs1))));
414
415             case BOOLQUAL : return
416                                 ap(COND,
417                                    triple(translate(snd(q)),
418                                           transDo(m,e,qs1),
419                                           ap2(nameMFail,m,
420                                             mkStr(findText("guard fails")))));
421         }
422     }
423     return e;
424 }
425
426 /* --------------------------------------------------------------------------
427  * Translation of named field construction and update:
428  *
429  * Construction is implemented using the following transformation:
430  *
431  *   C{x1=e1, ..., xn=en} =  C v1 ... vm
432  * where:
433  *   vi = e1,        if the ith component of C is labelled with x1
434  *       ...
435  *      = en,        if the ith component of C is labelled with xn
436  *      = undefined, otherwise
437  *
438  * Update is implemented using the following transformation:
439  *
440  *   e{x1=e1, ..., xn=en}
441  *      =  let nv (C a1 ... am) v1 ... vn = C a1' .. am'
442  *             nv (D b1 ... bk) v1 ... vn = D b1' .. bk
443  *             ...
444  *             nv _             v1 ... vn = error "failed update"
445  *         in nv e e1 ... en
446  * where:
447  *   nv, v1, ..., vn, a1, ..., am, b1, ..., bk, ... are new variables,
448  *   C,D,... = { K | K is a constr fun s.t. {x1,...,xn} subset of sels(K)}
449  * and:
450  *   ai' = v1,   if the ith component of C is labelled with x1
451  *       ...
452  *       = vn,   if the ith component of C is labelled with xn
453  *       = ai,   otherwise
454  *  etc...
455  *
456  * The error case may be omitted if C,D,... is an enumeration of all of the
457  * constructors for the datatype concerned.  Strictly speaking, error case
458  * isn't needed at all -- the only benefit of including it is that the user
459  * will get a "failed update" message rather than a cryptic {v354 ...}.
460  * So, for now, we'll go with the second option!
461  *
462  * For the time being, code for each update operation is generated
463  * independently of any other updates.  However, if updates are used
464  * frequently, then we might want to consider changing the implementation
465  * at a later stage to cache definitions of functions like nv above.  This
466  * would create a shared library of update functions, indexed by a set of
467  * constructors {C,D,...}.
468  * ------------------------------------------------------------------------*/
469
470 static Cell local transConFlds(c,flds)  /* Translate C{flds}               */
471 Name c;
472 List flds; {
473     Cell e = c;
474     Int  m = name(c).arity;
475     Int  i;
476     for (i=m; i>0; i--)
477         e = ap(e,nameUndefined);
478     for (; nonNull(flds); flds=tl(flds)) {
479         Cell a = e;
480         for (i=m-sfunPos(fst(hd(flds)),c); i>0; i--)
481             a = fun(a);
482         arg(a) = translate(snd(hd(flds)));
483     }
484     return e;
485 }
486
487 static Cell local transUpdFlds(e,cs,flds)/* Translate e{flds}              */
488 Cell e;                                 /* (cs is corresp list of constrs) */
489 List cs;
490 List flds; {
491     Cell nv   = inventVar();
492     Cell body = ap(nv,translate(e));
493     List fs   = flds;
494     List args = NIL;
495     List alts = NIL;
496
497     for (; nonNull(fs); fs=tl(fs)) {    /* body = nv e1 ... en             */
498         Cell b = hd(fs);                /* args = [v1, ..., vn]            */
499         body   = ap(body,translate(snd(b)));
500         args   = cons(inventVar(),args);
501     }
502
503     for (; nonNull(cs); cs=tl(cs)) {    /* Loop through constructors to    */
504         Cell c   = hd(cs);              /* build up list of alts.          */
505         Cell pat = c;
506         Cell rhs = c;
507         List as  = args;
508         Int  m   = name(c).arity;
509         Int  i;
510
511         for (i=m; i>0; i--) {           /* pat  = C a1 ... am              */
512             Cell a = inventVar();       /* rhs  = C a1 ... am              */
513             pat    = ap(pat,a);
514             rhs    = ap(rhs,a);
515         }
516
517         for (fs=flds; nonNull(fs); fs=tl(fs), as=tl(as)) {
518             Name s = fst(hd(fs));       /* Replace approp ai in rhs with   */
519             Cell r = rhs;               /* vars from [v1,...,vn]           */
520             for (i=m-sfunPos(s,c); i>0; i--)
521                 r = fun(r);
522             arg(r) = hd(as);
523         }
524
525         alts     = cons(pair(cons(pat,args),rhs),alts);
526     }
527     return ap(LETREC,pair(singleton(pair(nv,alts)),body));
528 }
529
530 /* --------------------------------------------------------------------------
531  * Elimination of pattern bindings:
532  *
533  * The following code adopts the definition of failure free patterns as given
534  * in the Haskell 1.3 report; the term "irrefutable" is also used there for
535  * a subset of the failure free patterns described here, but has no useful
536  * role in this implementation.  Basically speaking, the failure free patterns
537  * are:         variable, wildcard, ~apat
538  *              var@apat,               if apat is failure free
539  *              C apat1 ... apatn       if C is a product constructor
540  *                                      (i.e. an only constructor) and
541  *                                      apat1,...,apatn are failure free
542  * Note that the last case automatically covers the case where C comes from
543  * a newtype construction.
544  * ------------------------------------------------------------------------*/
545
546 Bool failFree(pat)                /* is pattern failure free? (do we need  */
547 Cell pat; {                       /* a conformality check?)                */
548     Cell c = getHead(pat);
549
550     switch (whatIs(c)) {
551         case ASPAT     : return failFree(snd(snd(pat)));
552
553         case NAME      : if (!isCfun(c) || cfunOf(c)!=0)
554                              return FALSE;
555                          /*intentional fall-thru*/
556         case TUPLE     : for (; isAp(pat); pat=fun(pat))
557                              if (!failFree(arg(pat)))
558                                 return FALSE;
559                          /*intentional fall-thru*/
560         case LAZYPAT   :
561         case VAROPCELL :
562         case VARIDCELL :
563         case DICTVAR   :
564         case WILDCARD  : return TRUE;
565
566 #if TREX
567         case EXT       : return failFree(extField(pat)) &&
568                                 failFree(extRow(pat));
569 #endif
570
571         case CONFLDS   : if (cfunOf(fst(snd(c)))==0) {
572                              List fs = snd(snd(c));
573                              for (; nonNull(fs); fs=tl(fs))
574                                  if (!failFree(snd(hd(fs))))
575                                      return FALSE;
576                              return TRUE;
577                          }
578                          /*intentional fall-thru*/
579         default        : return FALSE;
580     }
581 }
582
583 static Cell local refutePat(pat)  /* find pattern to refute in conformality*/
584 Cell pat; {                       /* test with pat.                        */
585                                   /* e.g. refPat  (x:y) == (_:_)           */
586                                   /*      refPat ~(x:y) == _      etc..    */
587
588     switch (whatIs(pat)) {
589         case ASPAT     : return refutePat(snd(snd(pat)));
590
591         case FINLIST   : {   Cell ys = snd(pat);
592                              Cell xs = NIL;
593                              for (; nonNull(ys); ys=tl(ys))
594                                  xs = ap(ap(nameCons,refutePat(hd(ys))),xs);
595                              return revOnto(xs,nameNil);
596                          }
597
598         case CONFLDS   : {   Cell ps = NIL;
599                              Cell fs = snd(snd(pat));
600                              for (; nonNull(fs); fs=tl(fs)) {
601                                  Cell p = refutePat(snd(hd(fs)));
602                                  ps     = cons(pair(fst(hd(fs)),p),ps);
603                              }
604                              return pair(CONFLDS,pair(fst(snd(pat)),rev(ps)));
605                          }
606
607         case VAROPCELL :
608         case VARIDCELL :
609         case DICTVAR   :
610         case WILDCARD  :
611         case LAZYPAT   : return WILDCARD;
612
613         case STRCELL   :
614         case CHARCELL  :
615 #if NPLUSK
616         case ADDPAT    :
617 #endif
618         case TUPLE     :
619         case NAME      : return pat;
620
621         case AP        : return refutePatAp(pat);
622
623         default        : internal("refutePat");
624                          return NIL; /*NOTREACHED*/
625     }
626 }
627
628 static Cell local refutePatAp(p)  /* find pattern to refute in conformality*/
629 Cell p; {
630     Cell h = getHead(p);
631     if (h==nameFromInt || h==nameFromInteger || h==nameFromDouble)
632         return p;
633 #if NPLUSK
634     else if (whatIs(h)==ADDPAT)
635         return ap(fun(p),refutePat(arg(p)));
636 #endif
637 #if TREX
638     else if (isExt(h)) {
639         Cell pf = refutePat(extField(p));
640         Cell pr = refutePat(extRow(p));
641         return ap(ap(fun(fun(p)),pf),pr);
642     }
643 #endif
644     else {
645         List as = getArgs(p);
646         mapOver(refutePat,as);
647         return applyToArgs(h,as);
648     }
649 }
650
651 static Cell local matchPat(pat) /* find pattern to match against           */
652 Cell pat; {                     /* replaces parts of pattern that do not   */
653                                 /* include variables with wildcards        */
654     switch (whatIs(pat)) {
655         case ASPAT     : {   Cell p = matchPat(snd(snd(pat)));
656                              return (p==WILDCARD) ? fst(snd(pat))
657                                                   : ap(ASPAT,
658                                                        pair(fst(snd(pat)),p));
659                          }
660
661         case FINLIST   : {   Cell ys = snd(pat);
662                              Cell xs = NIL;
663                              for (; nonNull(ys); ys=tl(ys))
664                                  xs = cons(matchPat(hd(ys)),xs);
665                              while (nonNull(xs) && hd(xs)==WILDCARD)
666                                  xs = tl(xs);
667                              for (ys=nameNil; nonNull(xs); xs=tl(xs))
668                                  ys = ap(ap(nameCons,hd(xs)),ys);
669                              return ys;
670                          }
671
672         case CONFLDS   : {   Cell ps   = NIL;
673                              Name c    = fst(snd(pat));
674                              Cell fs   = snd(snd(pat));
675                              Bool avar = FALSE;
676                              for (; nonNull(fs); fs=tl(fs)) {
677                                  Cell p = matchPat(snd(hd(fs)));
678                                  ps     = cons(pair(fst(hd(fs)),p),ps);
679                                  if (p!=WILDCARD)
680                                      avar = TRUE;
681                              }
682                              return avar ? pair(CONFLDS,pair(c,rev(ps)))
683                                          : WILDCARD;
684                          }
685
686         case VAROPCELL :
687         case VARIDCELL :
688         case DICTVAR   : return pat;
689
690         case LAZYPAT   : {   Cell p = matchPat(snd(pat));
691                              return (p==WILDCARD) ? WILDCARD : ap(LAZYPAT,p);
692                          }
693
694         case WILDCARD  :
695         case STRCELL   :
696         case CHARCELL  : return WILDCARD;
697
698         case TUPLE     :
699         case NAME      :
700         case AP        : {   Cell h = getHead(pat);
701                              if (h==nameFromInt     ||
702                                  h==nameFromInteger || h==nameFromDouble)
703                                  return WILDCARD;
704 #if NPLUSK
705                              else if (whatIs(h)==ADDPAT)
706                                  return pat;
707 #endif
708 #if TREX
709                              else if (isExt(h)) {
710                                  Cell pf = matchPat(extField(pat));
711                                  Cell pr = matchPat(extRow(pat));
712                                  return (pf==WILDCARD && pr==WILDCARD)
713                                           ? WILDCARD
714                                           : ap(ap(fun(fun(pat)),pf),pr);
715                              }
716 #endif
717                              else {
718                                  List args = NIL;
719                                  Bool avar = FALSE;
720                                  for (; isAp(pat); pat=fun(pat)) {
721                                      Cell p = matchPat(arg(pat));
722                                      if (p!=WILDCARD)
723                                          avar = TRUE;
724                                      args = cons(p,args);
725                                  }
726                                  return avar ? applyToArgs(pat,args)
727                                              : WILDCARD;
728                              }
729                          }
730
731         default        : internal("matchPat");
732                          return NIL; /*NOTREACHED*/
733     }
734 }
735
736 #define addEqn(v,val,lds)  cons(pair(v,singleton(pair(NIL,val))),lds)
737
738 static List local remPat(pat,expr,lds)
739 Cell pat;                         /* Produce list of definitions for eqn   */
740 Cell expr;                        /* pat = expr, including a conformality  */
741 List lds; {                       /* check if required.                    */
742
743     /* Conformality test (if required):
744      *   pat = expr  ==>    nv = LETREC confCheck nv@pat = nv
745      *                           IN confCheck expr
746      *                      remPat1(pat,nv,.....);
747      */
748
749     if (!failFree(pat)) {
750         Cell confVar = inventVar();
751         Cell nv      = inventVar();
752         Cell locfun  = pair(confVar,         /* confVar [([nv@refPat],nv)] */
753                             singleton(pair(singleton(ap(ASPAT,
754                                                         pair(nv,
755                                                              refutePat(pat)))),
756                                            nv)));
757
758         if (whatIs(expr)==GUARDED) {         /* A spanner ... special case */
759             lds  = addEqn(nv,expr,lds);      /* for guarded pattern binding*/
760             expr = nv;
761             nv   = inventVar();
762         }
763
764         if (whatIs(pat)==ASPAT) {            /* avoid using new variable if*/
765             nv   = fst(snd(pat));            /* a variable is already given*/
766             pat  = snd(snd(pat));            /* by an as-pattern           */
767         }
768
769         lds = addEqn(nv,                                /* nv =            */
770                      ap(LETREC,pair(singleton(locfun),  /* LETREC [locfun] */
771                                     ap(confVar,expr))), /* IN confVar expr */
772                      lds);
773
774         return remPat1(matchPat(pat),nv,lds);
775     }
776
777     return remPat1(matchPat(pat),expr,lds);
778 }
779
780 static List local remPat1(pat,expr,lds)
781 Cell pat;                         /* Add definitions for: pat = expr to    */
782 Cell expr;                        /* list of local definitions in lds.     */
783 List lds; {
784     Cell c = getHead(pat);
785
786     switch (whatIs(c)) {
787         case WILDCARD  :
788         case STRCELL   :
789         case CHARCELL  : break;
790
791         case ASPAT     : return remPat1(snd(snd(pat)),     /* v@pat = expr */
792                                         fst(snd(pat)),
793                                         addEqn(fst(snd(pat)),expr,lds));
794
795         case LAZYPAT   : {   Cell nv;
796
797                              if (isVar(expr) || isName(expr))
798                                  nv  = expr;
799                              else {
800                                  nv  = inventVar();
801                                  lds = addEqn(nv,expr,lds);
802                              }
803
804                              return remPat(snd(pat),nv,lds);
805                          }
806
807 #if NPLUSK
808         case ADDPAT    : return remPat1(arg(pat),       /* n + k = expr */
809                                         ap(ap(ap(namePmSub,
810                                                  arg(fun(pat))),
811                                                  mkInt(snd(fun(fun(pat))))),
812                                                  expr),
813                                         lds);
814 #endif
815
816         case FINLIST   : return remPat1(mkConsList(snd(pat)),expr,lds);
817
818         case CONFLDS   : {   Name h  = fst(snd(pat));
819                              Int  m  = name(h).arity;
820                              Cell p  = h;
821                              List fs = snd(snd(pat));
822                              Int  i  = m;
823                              while (0<i--)
824                                  p = ap(p,WILDCARD);
825                              for (; nonNull(fs); fs=tl(fs)) {
826                                  Cell r = p;
827                                  for (i=m-sfunPos(fst(hd(fs)),h); i>0; i--)
828                                      r = fun(r);
829                                  arg(r) = snd(hd(fs));
830                              }
831                              return remPat1(p,expr,lds);
832                          }
833
834         case DICTVAR   : /* shouldn't really occur */
835                          assert(0); /* so let's test for it then! ADR */
836         case VARIDCELL :
837         case VAROPCELL : return addEqn(pat,expr,lds);
838
839         case NAME      : if (c==nameFromInt || c==nameFromInteger
840                                             || c==nameFromDouble) {
841                              if (argCount==2)
842                                  arg(fun(pat)) = translate(arg(fun(pat)));
843                              break;
844                          }
845
846                          if (argCount==1 && isCfun(c)       /* for newtype */
847                              && cfunOf(c)==0 && name(c).defn==nameId)
848                              return remPat1(arg(pat),expr,lds);
849
850                          /* intentional fall-thru */
851         case TUPLE     : {   List ps = getArgs(pat);
852
853                              if (nonNull(ps)) {
854                                  Cell nv, sel;
855                                  Int  i;
856
857                                  if (isVar(expr) || isName(expr))
858                                      nv  = expr;
859                                  else {
860                                      nv  = inventVar();
861                                      lds = addEqn(nv,expr,lds);
862                                  }
863
864                                  sel = ap(ap(nameSel,c),nv);
865                                  for (i=1; nonNull(ps); ++i, ps=tl(ps))
866                                       lds = remPat1(hd(ps),
867                                                     ap(sel,mkInt(i)),
868                                                     lds);
869                              }
870                          }
871                          break;
872
873 #if TREX
874         case EXT       : {   Cell nv = inventVar();
875                              arg(fun(fun(pat)))
876                                  = translate(arg(fun(fun(pat))));
877                              lds = addEqn(nv,
878                                           ap(ap(nameRecBrk,
879                                                 arg(fun(fun(pat)))),
880                                              expr),
881                                           lds);
882                              lds = remPat1(extField(pat),ap(nameFst,nv),lds);
883                              lds = remPat1(extRow(pat),ap(nameSnd,nv),lds);
884                          }
885                          break;
886 #endif
887
888         default        : internal("remPat1");
889                          break;
890     }
891     return lds;
892 }
893
894 /* --------------------------------------------------------------------------
895  * Eliminate pattern matching in function definitions -- pattern matching
896  * compiler:
897  *
898  * The original Gofer/Hugs pattern matching compiler was based on Wadler's
899  * algorithms described in `Implementation of functional programming
900  * languages'.  That should still provide a good starting point for anyone
901  * wanting to understand this part of the system.  However, the original
902  * algorithm has been generalized and restructured in order to implement
903  * new features added in Haskell 1.3.
904  *
905  * During the translation, in preparation for later stages of compilation,
906  * all local and bound variables are replaced by suitable offsets, and
907  * locally defined function symbols are given new names (which will
908  * eventually be their names when lifted to make top level definitions).
909  * ------------------------------------------------------------------------*/
910
911 static Offset freeBegin; /* only variables with offset <= freeBegin are of */
912 static List   freeVars;  /* interest as `free' variables                   */
913 static List   freeFuns;  /* List of `free' local functions                 */
914
915 static Cell local pmcTerm(co,sc,e)     /* apply pattern matching compiler  */
916 Int  co;                               /* co = current offset              */
917 List sc;                               /* sc = scope                       */
918 Cell e;  {                             /* e  = expr to transform           */
919     switch (whatIs(e)) {
920         case GUARDED  : map2Over(pmcPair,co,sc,snd(e));
921                         break;
922
923         case LETREC   : pmcLetrec(co,sc,snd(e));
924                         break;
925
926         case VARIDCELL:
927         case VAROPCELL:
928         case DICTVAR  : return pmcVar(sc,textOf(e));
929
930         case COND     : return ap(COND,pmcTriple(co,sc,snd(e)));
931
932         case AP       : return pmcPair(co,sc,e);
933
934 #if NPLUSK
935         case ADDPAT   :
936 #endif
937 #if TREX
938         case EXT      :
939 #endif
940         case TUPLE    :
941         case NAME     :
942         case CHARCELL :
943         case INTCELL  :
944         case BIGCELL  :
945         case FLOATCELL:
946         case STRCELL  : break;
947
948         default       : internal("pmcTerm");
949                         break;
950     }
951     return e;
952 }
953
954 static Cell local pmcPair(co,sc,pr)    /* apply pattern matching compiler  */
955 Int  co;                               /* to a pair of exprs               */
956 List sc;
957 Pair pr; {
958     return pair(pmcTerm(co,sc,fst(pr)),
959                 pmcTerm(co,sc,snd(pr)));
960 }
961
962 static Cell local pmcTriple(co,sc,tr)  /* apply pattern matching compiler  */
963 Int    co;                             /* to a triple of exprs             */
964 List   sc;
965 Triple tr; {
966     return triple(pmcTerm(co,sc,fst3(tr)),
967                   pmcTerm(co,sc,snd3(tr)),
968                   pmcTerm(co,sc,thd3(tr)));
969 }
970
971 static Cell local pmcVar(sc,t)         /* find translation of variable     */
972 List sc;                               /* in current scope                 */
973 Text t; {
974     List xs;
975     Name n;
976
977     for (xs=sc; nonNull(xs); xs=tl(xs)) {
978         Cell x = hd(xs);
979         if (t==textOf(fst(x))) {
980             if (isOffset(snd(x))) {                  /* local variable ... */
981                 if (snd(x)<=freeBegin && !cellIsMember(snd(x),freeVars))
982                     freeVars = cons(snd(x),freeVars);
983                 return snd(x);
984             }
985             else {                                   /* local function ... */
986                 if (!cellIsMember(snd(x),freeFuns))
987                     freeFuns = cons(snd(x),freeFuns);
988                 return fst3(snd(x));
989             }
990         }
991     }
992
993     if (isNull(n=findName(t)))         /* Lookup global name - the only way*/
994         n = newName(t,currentName);    /* this (should be able to happen)  */
995                                        /* is with new global var introduced*/
996                                        /* after type check; e.g. remPat1   */
997     return n;
998 }
999
1000 static Void local pmcLetrec(co,sc,e)   /* apply pattern matching compiler  */
1001 Int  co;                               /* to LETREC, splitting decls into  */
1002 List sc;                               /* two sections                     */
1003 Pair e; {
1004     List fs = NIL;                     /* local function definitions       */
1005     List vs = NIL;                     /* local variable definitions       */
1006     List ds;
1007
1008     for (ds=fst(e); nonNull(ds); ds=tl(ds)) {      /* Split decls into two */
1009         Cell v     = fst(hd(ds));
1010         Int  arity = length(fst(hd(snd(hd(ds)))));
1011
1012         if (arity==0) {                            /* Variable declaration */
1013             vs = cons(snd(hd(ds)),vs);
1014             sc = cons(pair(v,mkOffset(++co)),sc);
1015         }
1016         else {                                     /* Function declaration */
1017             fs = cons(triple(inventVar(),mkInt(arity),snd(hd(ds))),fs);
1018             sc = cons(pair(v,hd(fs)),sc);
1019         }
1020     }
1021     vs       = rev(vs);                /* Put declaration lists back in    */
1022     fs       = rev(fs);                /* original order                   */
1023     fst(e)   = pair(vs,fs);            /* Store declaration lists          */
1024     map2Over(pmcVarDef,co,sc,vs);      /* Translate variable definitions   */
1025     map2Proc(pmcFunDef,co,sc,fs);      /* Translate function definitions   */
1026     snd(e)   = pmcTerm(co,sc,snd(e));  /* Translate LETREC body            */
1027     freeFuns = diffList(freeFuns,fs);  /* Delete any `freeFuns' bound in fs*/
1028 }
1029
1030 static Cell local pmcVarDef(co,sc,vd)  /* apply pattern matching compiler  */
1031 Int  co;                               /* to variable definition           */
1032 List sc;
1033 List vd; {                             /* vd :: [ ([], rhs) ]              */
1034     Cell d = snd(hd(vd));
1035     if (nonNull(tl(vd)) && canFail(d))
1036         return ap(FATBAR,pair(pmcTerm(co,sc,d),
1037                               pmcVarDef(co,sc,tl(vd))));
1038     return pmcTerm(co,sc,d);
1039 }
1040
1041 static Void local pmcFunDef(co,sc,fd)  /* apply pattern matching compiler  */
1042 Int    co;                             /* to function definition           */
1043 List   sc;
1044 Triple fd; {                           /* fd :: (Var, Arity, [Alt])        */
1045     Offset saveFreeBegin = freeBegin;
1046     List   saveFreeVars  = freeVars;
1047     List   saveFreeFuns  = freeFuns;
1048     Int    arity         = intOf(snd3(fd));
1049     Cell   temp          = altsMatch(co+1,arity,sc,thd3(fd));
1050     Cell   xs;
1051
1052     freeBegin = mkOffset(co);
1053     freeVars  = NIL;
1054     freeFuns  = NIL;
1055     temp      = match(co+arity,temp);
1056     thd3(fd)  = triple(freeVars,freeFuns,temp);
1057
1058     for (xs=freeVars; nonNull(xs); xs=tl(xs))
1059         if (hd(xs)<=saveFreeBegin && !cellIsMember(hd(xs),saveFreeVars))
1060             saveFreeVars = cons(hd(xs),saveFreeVars);
1061
1062     for (xs=freeFuns; nonNull(xs); xs=tl(xs))
1063         if (!cellIsMember(hd(xs),saveFreeFuns))
1064             saveFreeFuns = cons(hd(xs),saveFreeFuns);
1065
1066     freeBegin = saveFreeBegin;
1067     freeVars  = saveFreeVars;
1068     freeFuns  = saveFreeFuns;
1069 }
1070
1071 /* ---------------------------------------------------------------------------
1072  * Main part of pattern matching compiler: convert [Alt] to case constructs
1073  *
1074  * This section of Hugs has been almost completely rewritten to be more
1075  * general, in particular, to allow pattern matching in orders other than the
1076  * strictly left-to-right approach of the previous version.  This is needed
1077  * for the implementation of the so-called Haskell 1.3 `record' syntax.
1078  *
1079  * At each stage, the different branches for the cases to be considered
1080  * are represented by a list of values of type:
1081  *   Match ::= { maPats :: [Pat],       patterns to match
1082  *               maOffs :: [Offs],      offsets of corresponding values
1083  *               maSc   :: Scope,       mapping from vars to offsets
1084  *               maRhs  :: Rhs }        right hand side
1085  * [Implementation uses nested pairs, ((pats,offs),(sc,rhs)).]
1086  *
1087  * The Scope component has type:
1088  *   Scope  ::= [(Var,Expr)]
1089  * and provides a mapping from variable names to offsets used in the matching
1090  * process.
1091  *
1092  * Matches can be normalized by reducing them to a form in which the list
1093  * of patterns is empty (in which case the match itself is described as an
1094  * empty match), or in which the list is non-empty and the first pattern is
1095  * one that requires either a CASE or NUMCASE (or EXTCASE) to decompose.
1096  * ------------------------------------------------------------------------*/
1097
1098 #define mkMatch(ps,os,sc,r)     pair(pair(ps,os),pair(sc,r))
1099 #define maPats(ma)              fst(fst(ma))
1100 #define maOffs(ma)              snd(fst(ma))
1101 #define maSc(ma)                fst(snd(ma))
1102 #define maRhs(ma)               snd(snd(ma))
1103 #define extSc(v,o,ma)           maSc(ma) = cons(pair(v,o),maSc(ma))
1104
1105 static List local altsMatch(co,n,sc,as) /* Make a list of matches from list*/
1106 Int  co;                                /* of Alts, with initial offsets   */
1107 Int  n;                                 /* reverse (take n [co..])         */
1108 List sc;
1109 List as; {
1110     List mas = NIL;
1111     List us  = NIL;
1112     for (; n>0; n--)
1113         us = cons(mkOffset(co++),us);
1114     for (; nonNull(as); as=tl(as))      /* Each Alt is ([Pat], Rhs)        */
1115         mas = cons(mkMatch(fst(hd(as)),us,sc,snd(hd(as))),mas);
1116     return rev(mas);
1117 }
1118
1119 static Cell local match(co,mas) /* Generate case statement for Matches mas */
1120 Int  co;                        /* at current offset co                    */
1121 List mas; {                     /* N.B. Assumes nonNull(mas).              */
1122     Cell srhs = NIL;            /* Rhs for selected matches                */
1123     List smas = mas;            /* List of selected matches                */
1124     mas       = tl(mas);
1125     tl(smas)  = NIL;
1126
1127     if (emptyMatch(hd(smas))) {         /* The case for empty matches:     */
1128         while (nonNull(mas) && emptyMatch(hd(mas))) {
1129             List temp = tl(mas);
1130             tl(mas)   = smas;
1131             smas      = mas;
1132             mas       = temp;
1133         }
1134         srhs = joinMas(co,rev(smas));
1135     }
1136     else {                              /* Non-empty match                 */
1137         Int  o = offsetOf(hd(maOffs(hd(smas))));
1138         Cell d = maDiscr(hd(smas));
1139         if (isNumDiscr(d)) {            /* Numeric match                   */
1140             Int  da = discrArity(d);
1141             Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1142             while (nonNull(mas) && !emptyMatch(hd(mas))
1143                                 && o==offsetOf(hd(maOffs(hd(mas))))
1144                                 && isNumDiscr(d=maDiscr(hd(mas)))
1145                                 && eqNumDiscr(d,d1)) {
1146                 List temp = tl(mas);
1147                 tl(mas)   = smas;
1148                 smas      = mas;
1149                 mas       = temp;
1150             }
1151             smas = rev(smas);
1152             map2Proc(advance,co,da,smas);
1153             srhs = ap(NUMCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1154         }
1155 #if TREX
1156         else if (isExtDiscr(d)) {       /* Record match                    */
1157             Int  da = discrArity(d);
1158             Cell d1 = pmcTerm(co,maSc(hd(smas)),d);
1159             while (nonNull(mas) && !emptyMatch(hd(mas))
1160                                 && o==offsetOf(hd(maOffs(hd(mas))))
1161                                 && isExtDiscr(d=maDiscr(hd(mas)))
1162                                 && eqExtDiscr(d,d1)) {
1163                 List temp = tl(mas);
1164                 tl(mas)   = smas;
1165                 smas      = mas;
1166                 mas       = temp;
1167             }
1168             smas = rev(smas);
1169             map2Proc(advance,co,da,smas);
1170             srhs = ap(EXTCASE,triple(mkOffset(o),d1,match(co+da,smas)));
1171         }
1172 #endif
1173         else {                          /* Constructor match               */
1174             List tab = addConTable(d,hd(smas),NIL);
1175             Int  da;
1176             while (nonNull(mas) && !emptyMatch(hd(mas))
1177                                 && o==offsetOf(hd(maOffs(hd(mas))))
1178                                 && !isNumDiscr(d=maDiscr(hd(mas)))) {
1179                 tab = addConTable(d,hd(mas),tab);
1180                 mas = tl(mas);
1181             }
1182             for (tab=rev(tab); nonNull(tab); tab=tl(tab)) {
1183                 d    = fst(hd(tab));
1184                 smas = snd(hd(tab));
1185                 da   = discrArity(d);
1186                 map2Proc(advance,co,da,smas);
1187                 srhs = cons(pair(d,match(co+da,smas)),srhs);
1188             }
1189             srhs = ap(CASE,pair(mkOffset(o),srhs));
1190         }
1191     }
1192     return nonNull(mas) ? ap(FATBAR,pair(srhs,match(co,mas))) : srhs;
1193 }
1194
1195 static Cell local joinMas(co,mas)       /* Combine list of matches into rhs*/
1196 Int  co;                                /* using FATBARs as necessary      */
1197 List mas; {                             /* Non-empty list of empty matches */
1198     Cell ma  = hd(mas);
1199     Cell rhs = pmcTerm(co,maSc(ma),maRhs(ma));
1200     if (nonNull(tl(mas)) && canFail(rhs))
1201         return ap(FATBAR,pair(rhs,joinMas(co,tl(mas))));
1202     else
1203         return rhs;
1204 }
1205
1206 static Bool local canFail(rhs)         /* Determine if expression (as rhs) */
1207 Cell rhs; {                            /* might ever be able to fail       */
1208     switch (whatIs(rhs)) {
1209         case LETREC  : return canFail(snd(snd(rhs)));
1210         case GUARDED : return TRUE;    /* could get more sophisticated ..? */
1211         default      : return FALSE;
1212     }
1213 }
1214
1215 /* type Table a b = [(a, [b])]
1216  *
1217  * addTable                 :: a -> b -> Table a b -> Table a b
1218  * addTable x y []           = [(x,[y])]
1219  * addTable x y (z@(n,sws):zs)
1220  *              | n == x     = (n,sws++[y]):zs
1221  *              | otherwise  = (n,sws):addTable x y zs
1222  */
1223
1224 static List local addConTable(x,y,tab) /* add element (x,y) to table       */
1225 Cell x, y;
1226 List tab; {
1227     if (isNull(tab))
1228         return singleton(pair(x,singleton(y)));
1229     else if (fst(hd(tab))==x)
1230         snd(hd(tab)) = appendOnto(snd(hd(tab)),singleton(y));
1231     else
1232         tl(tab) = addConTable(x,y,tl(tab));
1233
1234     return tab;
1235 }
1236
1237 static Void local advance(co,a,ma)      /* Advance non-empty match by      */
1238 Int  co;                                /* processing head pattern         */
1239 Int  a;                                 /* discriminator arity             */
1240 Cell ma; {
1241     Cell p  = hd(maPats(ma));
1242     List ps = tl(maPats(ma));
1243     List us = tl(maOffs(ma));
1244     if (whatIs(p)==CONFLDS) {           /* Special case for record syntax  */
1245         Name c  = fst(snd(p));
1246         List fs = snd(snd(p));
1247         List qs = NIL;
1248         List vs = NIL;
1249         for (; nonNull(fs); fs=tl(fs)) {
1250             vs = cons(mkOffset(co+a+1-sfunPos(fst(hd(fs)),c)),vs);
1251             qs = cons(snd(hd(fs)),qs);
1252         }
1253         ps = revOnto(qs,ps);
1254         us = revOnto(vs,us);
1255     }
1256     else                                /* Normally just spool off patterns*/
1257         for (; a>0; --a) {              /* and corresponding offsets ...   */
1258             us = cons(mkOffset(++co),us);
1259             ps = cons(arg(p),ps);
1260             p  = fun(p);
1261         }
1262
1263     maPats(ma) = ps;
1264     maOffs(ma) = us;
1265 }
1266
1267 /* --------------------------------------------------------------------------
1268  * Normalize and test for empty match:
1269  * ------------------------------------------------------------------------*/
1270
1271 static Bool local emptyMatch(ma)/* Normalize and test to see if a given    */
1272 Cell ma; {                      /* match, ma, is empty.                    */
1273
1274     while (nonNull(maPats(ma))) {
1275         Cell p;
1276 tidyHd: switch (whatIs(p=hd(maPats(ma)))) {
1277             case LAZYPAT   : {   Cell nv   = inventVar();
1278                                  maRhs(ma) = ap(LETREC,
1279                                                 pair(remPat(snd(p),nv,NIL),
1280                                                      maRhs(ma)));
1281                                  p         = nv;
1282                              }
1283                              /* intentional fall-thru */
1284             case VARIDCELL :
1285             case VAROPCELL :
1286             case DICTVAR   : extSc(p,hd(maOffs(ma)),ma);
1287             case WILDCARD  : maPats(ma) = tl(maPats(ma));
1288                              maOffs(ma) = tl(maOffs(ma));
1289                              continue;
1290
1291             /* So-called "as-patterns"are really just pattern intersections:
1292              *    (p1@p2:ps, o:os, sc, e) ==> (p1:p2:ps, o:o:os, sc, e)
1293              * (But the input grammar probably doesn't let us take
1294              * advantage of this, so we stick with the special case
1295              * when p1 is a variable.)
1296              */
1297             case ASPAT     : extSc(fst(snd(p)),hd(maOffs(ma)),ma);
1298                              hd(maPats(ma)) = snd(snd(p));
1299                              goto tidyHd;
1300
1301             case FINLIST   : hd(maPats(ma)) = mkConsList(snd(p));
1302                              return FALSE;
1303
1304             case STRCELL   : {   String s = textToStr(textOf(p));
1305                                  for (p=NIL; *s!='\0'; ++s) {
1306                                      if (*s!='\\' || *++s=='\\')
1307                                          p = ap(consChar(*s),p);
1308                                      else
1309                                          p = ap(consChar('\0'),p);
1310                                  }
1311                                  hd(maPats(ma)) = revOnto(p,nameNil);
1312                              }
1313                              return FALSE;
1314
1315             case AP        : if (isName(fun(p)) && isCfun(fun(p))
1316                                  && cfunOf(fun(p))==0
1317                                  && name(fun(p)).defn==nameId) {
1318                                   hd(maPats(ma)) = arg(p);
1319                                   goto tidyHd;
1320                              }
1321                              /* intentional fall-thru */
1322             case CHARCELL  :
1323             case NAME      :
1324             case CONFLDS   :
1325                              return FALSE;
1326
1327             default        : internal("emptyMatch");
1328         }
1329     }
1330     return TRUE;
1331 }
1332
1333 /* --------------------------------------------------------------------------
1334  * Discriminators:
1335  * ------------------------------------------------------------------------*/
1336
1337 static Cell local maDiscr(ma)   /* Get the discriminator for a non-empty   */
1338 Cell ma; {                      /* match, ma.                              */
1339     Cell p = hd(maPats(ma));
1340     Cell h = getHead(p);
1341     switch (whatIs(h)) {
1342         case CONFLDS : return fst(snd(p));
1343 #if NPLUSK
1344         case ADDPAT  : arg(fun(p)) = translate(arg(fun(p)));
1345                        return fun(p);
1346 #endif
1347 #if TREX
1348         case EXT     : h      = fun(fun(p));
1349                        arg(h) = translate(arg(h));
1350                        return h;
1351 #endif
1352         case NAME    : if (h==nameFromInt || h==nameFromInteger
1353                                           || h==nameFromDouble) {
1354                            if (argCount==2)
1355                                arg(fun(p)) = translate(arg(fun(p)));
1356                            return p;
1357                        }
1358     }
1359     return h;
1360 }
1361
1362 static Bool local isNumDiscr(d) /* TRUE => numeric discriminator           */
1363 Cell d; {
1364     switch (whatIs(d)) {
1365         case NAME      :
1366         case TUPLE     :
1367         case CHARCELL  : return FALSE;
1368
1369 #if TREX
1370         case AP        : return !isExt(fun(d));
1371 #else
1372         case AP        : return TRUE;   /* must be a literal or (n+k)      */
1373 #endif
1374     }
1375     internal("isNumDiscr");
1376     return 0;/*NOTREACHED*/
1377 }
1378
1379 Int discrArity(d)                      /* Find arity of discriminator      */
1380 Cell d; {
1381     switch (whatIs(d)) {
1382         case NAME      : return name(d).arity;
1383         case TUPLE     : return tupleOf(d);
1384         case CHARCELL  : return 0;
1385 #if TREX
1386         case AP        : switch (whatIs(fun(d))) {
1387 #if NPLUSK
1388                              case ADDPAT : return 1;
1389 #endif
1390                              case EXT    : return 2;
1391                              default     : return 0;
1392                          }
1393 #else
1394 #if NPLUSK
1395         case AP        : return (whatIs(fun(d))==ADDPAT) ? 1 : 0;
1396 #else
1397         case AP        : return 0;      /* must be an Int or Float lit     */
1398 #endif
1399 #endif
1400     }
1401     internal("discrArity");
1402     return 0;/*NOTREACHED*/
1403 }
1404
1405 static Bool local eqNumDiscr(d1,d2)     /* Determine whether two numeric   */
1406 Cell d1, d2; {                          /* descriptors have same value     */
1407 #if NPLUSK
1408     if (whatIs(fun(d1))==ADDPAT)
1409         return whatIs(fun(d2))==ADDPAT && snd(fun(d1))==snd(fun(d2));
1410 #endif
1411     if (isInt(arg(d1)))
1412         return isInt(arg(d2)) && intOf(arg(d1))==intOf(arg(d2));
1413     if (isFloat(arg(d1)))
1414         return isFloat(arg(d2)) && floatOf(arg(d1))==floatOf(arg(d2));
1415     internal("eqNumDiscr");
1416     return FALSE;/*NOTREACHED*/
1417 }
1418
1419 #if TREX
1420 static Bool local isExtDiscr(d)         /* Test of extension discriminator */
1421 Cell d; {
1422     return isAp(d) && isExt(fun(d));
1423 }
1424
1425 static Bool local eqExtDiscr(d1,d2)     /* Determine whether two extension */
1426 Cell d1, d2; {                          /* discriminators have same label  */
1427     return fun(d1)==fun(d2);
1428 }
1429 #endif
1430
1431 /*-------------------------------------------------------------------------*/
1432
1433
1434
1435 /* --------------------------------------------------------------------------
1436  * STG stuff
1437  * ------------------------------------------------------------------------*/
1438
1439 static Void local stgCGBinds( List );
1440
1441 static Void local stgCGBinds(binds)
1442 List binds; {
1443     cgBinds(binds);
1444 }
1445
1446 /* --------------------------------------------------------------------------
1447  * Main entry points to compiler:
1448  * ------------------------------------------------------------------------*/
1449
1450 static List addGlobals( List binds )
1451 {
1452     /* stgGlobals = list of top-level STG binds */
1453     for(;nonNull(stgGlobals);stgGlobals=tl(stgGlobals)) {
1454         StgVar bind = snd(hd(stgGlobals));
1455         if (nonNull(stgVarBody(bind))) {
1456             binds = cons(bind,binds);
1457         }
1458     }
1459     return binds;
1460 }
1461
1462 typedef void (*sighandler_t)(int);
1463 void eval_ctrlbrk ( int dunnowhat )
1464 {
1465    interruptStgRts();
1466    /* reinstall the signal handler so that further interrupts which
1467       happen before the thread can return to the scheduler, lead back
1468       here rather than invoking the previous break handler. */
1469    signal(SIGINT, eval_ctrlbrk);
1470 }
1471
1472 Void evalExp() {                    /* compile and run input expression    */
1473     /* ToDo: this name (and other names generated during pattern match?)
1474      * get inserted in the symbol table but never get removed.
1475      */
1476     Name n = newName(inventText(),NIL);
1477     Cell e;
1478     StgVar v = mkStgVar(NIL,NIL);
1479     name(n).stgVar = v;
1480     compiler(RESET);
1481     e = pmcTerm(0,NIL,translate(inputExpr));
1482     stgDefn(n,0,e);
1483     inputExpr = NIL;
1484     stgCGBinds(addGlobals(singleton(v)));
1485     
1486     /* Run thread (and any other runnable threads) */
1487
1488     /* Re-initialise the scheduler - ToDo: do I need this? */
1489     /* JRS, 991118: on SM's advice, don't call initScheduler every time.
1490        This causes an assertion failure in GC.c(revert_dead_cafs)
1491        unless doRevertCAFs below is permanently TRUE.
1492      */
1493     /* initScheduler(); */
1494 #ifdef CRUDE_PROFILING
1495     cp_init();
1496 #endif
1497
1498     {
1499         HaskellObj      result; /* ignored */
1500         sighandler_t    old_ctrlbrk;
1501         SchedulerStatus status;
1502         Bool            doRevertCAFs = TRUE;  /* do not change -- comment above */
1503         old_ctrlbrk         = signal(SIGINT, eval_ctrlbrk);
1504         ASSERT(old_ctrlbrk != SIG_ERR);
1505         status              = rts_eval_(closureOfVar(v),10000,&result);
1506         signal(SIGINT,old_ctrlbrk);
1507         fflush (stderr); 
1508         fflush (stdout);
1509         switch (status) {
1510         case Deadlock:
1511         case AllBlocked: /* I don't understand the distinction - ADR */
1512                 printf("{Deadlock}");
1513                 if (doRevertCAFs) RevertCAFs();
1514                 break;
1515         case Interrupted:
1516                 printf("{Interrupted}");
1517                 if (doRevertCAFs) RevertCAFs();
1518                 break;
1519         case Killed:
1520                 printf("{Interrupted or Killed}");
1521                 if (doRevertCAFs) RevertCAFs();
1522                 break;
1523         case Success:
1524                 if (doRevertCAFs) RevertCAFs();
1525                 break;
1526         default:
1527                 internal("evalExp: Unrecognised SchedulerStatus");
1528         }
1529         deleteAllThreads();
1530         fflush(stdout);
1531         fflush(stderr);
1532     }
1533 #ifdef CRUDE_PROFILING
1534     cp_show();
1535 #endif
1536
1537 }
1538
1539
1540 static List local addStgVar( List binds, Pair bind )
1541 {
1542     StgVar nv = mkStgVar(NIL,NIL);
1543     Text   t  = textOf(fst(bind));
1544     Name   n  = findName(t);
1545
1546     if (isNull(n)) {                   /* Lookup global name - the only way*/
1547         n = newName(t,NIL);            /* this (should be able to happen)  */
1548     }                                  /* is with new global var introduced*/
1549                                        /* after type check; e.g. remPat1   */
1550     name(n).stgVar = nv;
1551     return cons(nv,binds);
1552 }
1553
1554
1555 Void compileDefns() {                  /* compile script definitions       */
1556     Target t = length(valDefns) + length(genDefns) + length(selDefns);
1557     Target i = 0;
1558     List binds = NIL;
1559
1560     /* a nasty hack.  But I don't know an easier way to make */
1561     /* these things appear.                                  */
1562     if (lastModule() == modulePrelude) {
1563        implementCfun ( nameCons, NIL );
1564        implementCfun ( nameNil, NIL );
1565        implementCfun ( nameUnit, NIL );
1566     }
1567
1568     {
1569         List vss;
1570         List vs;
1571         for(vs=genDefns; nonNull(vs); vs=tl(vs)) {
1572             Name   n  = hd(vs);
1573             StgVar nv = mkStgVar(NIL,NIL);
1574             assert(isName(n));
1575             name(n).stgVar = nv;
1576             binds = cons(nv,binds);
1577         }
1578         for(vss=selDefns; nonNull(vss); vss=tl(vss)) {
1579             for(vs=hd(vss); nonNull(vs); vs=tl(vs)) {
1580                 Pair p = hd(vs);
1581                 Name n = fst(p);
1582                 StgVar nv = mkStgVar(NIL,NIL);
1583                 assert(isName(n));
1584                 name(n).stgVar = nv;
1585                 binds = cons(nv,binds);
1586             }
1587         }
1588     }
1589
1590     setGoal("Translating",t);
1591     /* do valDefns before everything else so that all stgVar's get added. */
1592     for (; nonNull(valDefns); valDefns=tl(valDefns)) {
1593         hd(valDefns) = transBinds(hd(valDefns));
1594         mapAccum(addStgVar,binds,hd(valDefns));
1595         mapProc(compileGlobalFunction,hd(valDefns));
1596         soFar(i++);
1597     }
1598     for (; nonNull(genDefns); genDefns=tl(genDefns)) {
1599         compileGenFunction(hd(genDefns));
1600         soFar(i++);
1601     }
1602     for (; nonNull(selDefns); selDefns=tl(selDefns)) {
1603         mapOver(compileSelFunction,hd(selDefns));
1604         soFar(i++);
1605     }
1606
1607     binds = addGlobals(binds);
1608     done();
1609     setGoal("Generating code",t);
1610     stgCGBinds(binds);
1611
1612     done();
1613 }
1614
1615 static Void local compileGlobalFunction(bind)
1616 Pair bind; {
1617     Name n     = findName(textOf(fst(bind)));
1618     List defs  = snd(bind);
1619     Int  arity = length(fst(hd(defs)));
1620     assert(isName(n));
1621     compiler(RESET);
1622     stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1623 }
1624
1625 static Void local compileGenFunction(n) /* Produce code for internally     */
1626 Name n; {                               /* generated function              */
1627     List defs  = name(n).defn;
1628     Int  arity = length(fst(hd(defs)));
1629     compiler(RESET);
1630     currentName = n;
1631     mapProc(transAlt,defs);
1632     stgDefn(n,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1633     name(n).defn = NIL;
1634 }
1635
1636 static Name local compileSelFunction(p) /* Produce code for selector func  */
1637 Pair p; {                               /* Should be merged with genDefns, */
1638     Name s     = fst(p);                /* but the name(_).defn field is   */
1639     List defs  = snd(p);                /* already used for other purposes */
1640     Int  arity = length(fst(hd(defs))); /* in selector functions.          */
1641
1642     compiler(RESET);
1643     mapProc(transAlt,defs);
1644     stgDefn(s,arity,match(arity,altsMatch(1,arity,NIL,defs)));
1645     return s;
1646 }
1647
1648
1649 /* --------------------------------------------------------------------------
1650  * Compiler control:
1651  * ------------------------------------------------------------------------*/
1652
1653 Void compiler(what)
1654 Int what; {
1655     switch (what) {
1656         case INSTALL :
1657         case RESET   : freeVars      = NIL;
1658                        freeFuns      = NIL;
1659                        freeBegin     = mkOffset(0);
1660                        //extraVars     = NIL;
1661                        //numExtraVars  = 0;
1662                        //localOffset   = 0;
1663                        //localArity    = 0;
1664                        break;
1665
1666         case MARK    : mark(freeVars);
1667                        mark(freeFuns);
1668                        //mark(extraVars);
1669                        break;
1670     }
1671 }
1672
1673 /*-------------------------------------------------------------------------*/