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