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