56440968a2dbcbd5711fb13e30d8b6836b6fcfdf
[ghc-hetmet.git] / ghc / compiler / deSugar / DsListComp.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[DsListComp]{Desugaring list comprehensions}
5
6 \begin{code}
7 module DsListComp ( dsListComp ) where
8
9 #include "HsVersions.h"
10
11 import {-# SOURCE #-} DsExpr ( dsExpr )
12 import {-# SOURCE #-} DsBinds ( dsBinds )
13
14 import HsSyn            ( Stmt(..), HsExpr, HsBinds )
15 import TcHsSyn          ( TypecheckedStmt, TypecheckedHsExpr , TypecheckedHsBinds )
16 import DsHsSyn          ( outPatType )
17 import CoreSyn
18
19 import DsMonad          -- the monadery used in the desugarer
20 import DsUtils
21
22 import CmdLineOpts      ( opt_FoldrBuildOn )
23 import CoreUtils        ( coreExprType, mkCoreIfThenElse )
24 import Id               ( Id )
25 import PrelVals         ( mkBuild, foldrId )
26 import Type             ( mkTyVarTy, mkForAllTy, mkFunTys, mkFunTy, Type )
27 import TysPrim          ( alphaTy )
28 import TysWiredIn       ( nilDataCon, consDataCon, listTyCon )
29 import TyVar            ( alphaTyVar )
30 import Match            ( matchSimply )
31 import Util             ( panic )
32 \end{code}
33
34 List comprehensions may be desugared in one of two ways: ``ordinary''
35 (as you would expect if you read SLPJ's book) and ``with foldr/build
36 turned on'' (if you read Gill {\em et al.}'s paper on the subject).
37
38 There will be at least one ``qualifier'' in the input.
39
40 \begin{code}
41 dsListComp :: [TypecheckedStmt] 
42            -> Type              -- Type of list elements
43            -> DsM CoreExpr
44
45 dsListComp quals elt_ty
46   | not opt_FoldrBuildOn                 -- Be boring
47   = deListComp quals nil_expr
48
49   | otherwise                            -- foldr/build lives!
50   = newTyVarsDs [alphaTyVar]    `thenDs` \ [n_tyvar] ->
51     let
52         alpha_to_alpha = alphaTy `mkFunTy` alphaTy
53
54         n_ty = mkTyVarTy n_tyvar
55         c_ty = mkFunTys [elt_ty, n_ty] n_ty
56         g_ty = mkForAllTy alphaTyVar (
57                 (elt_ty `mkFunTy` alpha_to_alpha)
58                 `mkFunTy` 
59                 alpha_to_alpha
60            )
61     in
62     newSysLocalsDs [c_ty,n_ty,g_ty]  `thenDs` \ [c, n, g] ->
63
64     dfListComp  c_ty c
65                 n_ty n
66                 quals       `thenDs` \ result ->
67
68     returnDs (mkBuild elt_ty n_tyvar c n g result)
69   where
70     nil_expr    = mkCon nilDataCon [elt_ty] []
71 \end{code}
72
73 %************************************************************************
74 %*                                                                      *
75 \subsection[DsListComp-ordinary]{Ordinary desugaring of list comprehensions}
76 %*                                                                      *
77 %************************************************************************
78
79 Just as in Phil's chapter~7 in SLPJ, using the rules for
80 optimally-compiled list comprehensions.  This is what Kevin followed
81 as well, and I quite happily do the same.  The TQ translation scheme
82 transforms a list of qualifiers (either boolean expressions or
83 generators) into a single expression which implements the list
84 comprehension.  Because we are generating 2nd-order polymorphic
85 lambda-calculus, calls to NIL and CONS must be applied to a type
86 argument, as well as their usual value arguments.
87 \begin{verbatim}
88 TE << [ e | qs ] >>  =  TQ << [ e | qs ] ++ Nil (typeOf e) >>
89
90 (Rule C)
91 TQ << [ e | ] ++ L >> = Cons (typeOf e) TE <<e>> TE <<L>>
92
93 (Rule B)
94 TQ << [ e | b , qs ] ++ L >> =
95     if TE << b >> then TQ << [ e | qs ] ++ L >> else TE << L >>
96
97 (Rule A')
98 TQ << [ e | p <- L1, qs ]  ++  L2 >> =
99   letrec
100     h = \ u1 ->
101           case u1 of
102             []        ->  TE << L2 >>
103             (u2 : u3) ->
104                   (( \ TE << p >> -> ( TQ << [e | qs]  ++  (h u3) >> )) u2)
105                     [] (h u3)
106   in
107     h ( TE << L1 >> )
108
109 "h", "u1", "u2", and "u3" are new variables.
110 \end{verbatim}
111
112 @deListComp@ is the TQ translation scheme.  Roughly speaking, @dsExpr@
113 is the TE translation scheme.  Note that we carry around the @L@ list
114 already desugared.  @dsListComp@ does the top TE rule mentioned above.
115
116 \begin{code}
117 deListComp :: [TypecheckedStmt] -> CoreExpr -> DsM CoreExpr
118
119 deListComp [ReturnStmt expr] list               -- Figure 7.4, SLPJ, p 135, rule C above
120   = dsExpr expr                 `thenDs` \ core_expr ->
121     mkConDs consDataCon [TyArg (coreExprType core_expr), VarArg core_expr, VarArg list]
122
123 deListComp (GuardStmt guard locn : quals) list  -- rule B above
124   = dsExpr guard                `thenDs` \ core_guard ->
125     deListComp quals list       `thenDs` \ core_rest ->
126     returnDs (mkCoreIfThenElse core_guard core_rest list)
127
128 -- [e | let B, qs] = let B in [e | qs]
129 deListComp (LetStmt binds : quals) list
130   = dsBinds False{-don't auto scc-} binds       `thenDs` \ core_binds ->
131     deListComp quals list                       `thenDs` \ core_rest ->
132     returnDs (mkCoLetsAny core_binds core_rest)
133
134 deListComp (BindStmt pat list1 locn : quals) core_list2 -- rule A' above
135   = dsExpr list1                    `thenDs` \ core_list1 ->
136     let
137         u3_ty@u1_ty = coreExprType core_list1   -- two names, same thing
138
139         -- u1_ty is a [alpha] type, and u2_ty = alpha
140         u2_ty = outPatType pat
141
142         res_ty = coreExprType core_list2
143         h_ty   = u1_ty `mkFunTy` res_ty
144     in
145     newSysLocalsDs [h_ty, u1_ty, u2_ty, u3_ty]  `thenDs` \ [h, u1, u2, u3] ->
146
147     -- the "fail" value ...
148     mkAppDs (Var h) [VarArg (Var u3)]           `thenDs` \ core_fail ->
149     deListComp quals core_fail                  `thenDs` \ rest_expr ->
150     matchSimply (Var u2) ListCompMatch pat res_ty 
151                 rest_expr core_fail             `thenDs` \ core_match ->
152     mkAppDs (Var h) [VarArg core_list1]         `thenDs` \ letrec_body ->
153
154     returnDs (
155       mkCoLetrecAny [
156       ( h,
157         (Lam (ValBinder u1)
158          (Case (Var u1)
159             (AlgAlts
160               [(nilDataCon,  [],        core_list2),
161                (consDataCon, [u2, u3],  core_match)]
162             NoDefault)))
163       )] letrec_body
164     )
165 \end{code}
166
167 %************************************************************************
168 %*                                                                      *
169 \subsection[DsListComp-foldr-build]{Foldr/Build desugaring of list comprehensions}
170 %*                                                                      *
171 %************************************************************************
172
173 @dfListComp@ are the rules used with foldr/build turned on:
174 \begin{verbatim}
175 TE < [ e | ] >>          c n = c e n
176 TE << [ e | b , q ] >>   c n = if b then TE << [ e | q ] >> c n else n
177 TE << [ e | p <- l , q ] c n =  foldr
178                         (\ TE << p >> b -> TE << [ e | q ] >> c b
179                            _          b  -> b)  n l
180 \end{verbatim}
181 \begin{code}
182 dfListComp :: Type -> Id                -- 'c'; its type and id
183            -> Type -> Id                -- 'n'; its type and id
184            -> [TypecheckedStmt]         -- the rest of the qual's
185            -> DsM CoreExpr
186
187 dfListComp c_ty c_id n_ty n_id [ReturnStmt expr]
188   = dsExpr expr                 `thenDs` \ core_expr ->
189     mkAppDs (Var c_id) [VarArg core_expr, VarArg (Var n_id)]
190
191 dfListComp c_ty c_id n_ty n_id (GuardStmt guard locn  : quals)
192   = dsExpr guard                                `thenDs` \ core_guard ->
193     dfListComp c_ty c_id n_ty n_id quals        `thenDs` \ core_rest ->
194     returnDs (mkCoreIfThenElse core_guard core_rest (Var n_id))
195
196 dfListComp c_ty c_id n_ty n_id (LetStmt binds : quals)
197   -- new in 1.3, local bindings
198   = dsBinds False{-don't auto scc-} binds        `thenDs` \ core_binds ->
199     dfListComp c_ty c_id n_ty n_id quals         `thenDs` \ core_rest ->
200     returnDs (mkCoLetsAny core_binds core_rest)
201
202 dfListComp c_ty c_id n_ty n_id (BindStmt pat list1 locn : quals)
203     -- evaluate the two lists
204   = dsExpr list1                                `thenDs` \ core_list1 ->
205
206     -- find the required type
207
208     let p_ty   = outPatType pat
209         b_ty   = n_ty           -- alias b_ty to n_ty
210         fn_ty  = mkFunTys [p_ty, b_ty] b_ty
211         lst_ty = coreExprType core_list1
212     in
213
214     -- create some new local id's
215
216     newSysLocalsDs [b_ty,p_ty,fn_ty,lst_ty]             `thenDs` \ [b,p,fn,lst] ->
217
218     -- build rest of the comprehesion
219
220     dfListComp c_ty c_id b_ty b quals                   `thenDs` \ core_rest ->
221     -- build the pattern match
222
223     matchSimply (Var p) ListCompMatch pat b_ty core_rest (Var b)        `thenDs` \ core_expr ->
224
225     -- now build the outermost foldr, and return
226
227     returnDs (
228       mkCoLetsAny
229         [NonRec fn (mkValLam [p, b] core_expr),
230          NonRec lst core_list1]
231         (mkFoldr p_ty n_ty fn n_id lst)
232     )
233
234 mkFoldr a b f z xs
235   = mkValApp (mkTyApp (Var foldrId) [a,b]) [VarArg f, VarArg z, VarArg xs]
236 \end{code}