[project @ 1997-03-14 07:52:06 by simonpj]
[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            ( Stmt(..), HsExpr, HsBinds )
15 import TcHsSyn          ( SYN_IE(TypecheckedStmt), 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 :: [TypecheckedStmt] 
41            -> Type              -- Type of list elements
42            -> DsM CoreExpr
43
44 dsListComp quals elt_ty
45   | not opt_FoldrBuildOn                 -- Be boring
46   = deListComp quals nil_expr
47
48   | otherwise                            -- foldr/build lives!
49   = newTyVarsDs [alphaTyVar]    `thenDs` \ [n_tyvar] ->
50     let
51         alpha_to_alpha = alphaTy `mkFunTy` alphaTy
52
53         n_ty = mkTyVarTy n_tyvar
54         c_ty = mkFunTys [elt_ty, n_ty] n_ty
55         g_ty = mkForAllTy alphaTyVar (
56                 (elt_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  c_ty c
64                 n_ty n
65                 quals       `thenDs` \ result ->
66
67     returnDs (mkBuild elt_ty n_tyvar c n g result)
68   where
69     nil_expr    = mkCon nilDataCon [] [elt_ty] []
70 \end{code}
71
72 %************************************************************************
73 %*                                                                      *
74 \subsection[DsListComp-ordinary]{Ordinary desugaring of list comprehensions}
75 %*                                                                      *
76 %************************************************************************
77
78 Just as in Phil's chapter~7 in SLPJ, using the rules for
79 optimally-compiled list comprehensions.  This is what Kevin followed
80 as well, and I quite happily do the same.  The TQ translation scheme
81 transforms a list of qualifiers (either boolean expressions or
82 generators) into a single expression which implements the list
83 comprehension.  Because we are generating 2nd-order polymorphic
84 lambda-calculus, calls to NIL and CONS must be applied to a type
85 argument, as well as their usual value arguments.
86 \begin{verbatim}
87 TE << [ e | qs ] >>  =  TQ << [ e | qs ] ++ Nil (typeOf e) >>
88
89 (Rule C)
90 TQ << [ e | ] ++ L >> = Cons (typeOf e) TE <<e>> TE <<L>>
91
92 (Rule B)
93 TQ << [ e | b , qs ] ++ L >> =
94     if TE << b >> then TQ << [ e | qs ] ++ L >> else TE << L >>
95
96 (Rule A')
97 TQ << [ e | p <- L1, qs ]  ++  L2 >> =
98   letrec
99     h = \ u1 ->
100           case u1 of
101             []        ->  TE << L2 >>
102             (u2 : u3) ->
103                   (( \ TE << p >> -> ( TQ << [e | qs]  ++  (h u3) >> )) u2)
104                     [] (h u3)
105   in
106     h ( TE << L1 >> )
107
108 "h", "u1", "u2", and "u3" are new variables.
109 \end{verbatim}
110
111 @deListComp@ is the TQ translation scheme.  Roughly speaking, @dsExpr@
112 is the TE translation scheme.  Note that we carry around the @L@ list
113 already desugared.  @dsListComp@ does the top TE rule mentioned above.
114
115 \begin{code}
116 deListComp :: [TypecheckedStmt] -> CoreExpr -> DsM CoreExpr
117
118 deListComp [ReturnStmt expr] list               -- Figure 7.4, SLPJ, p 135, rule C above
119   = dsExpr expr                 `thenDs` \ core_expr ->
120     mkConDs consDataCon [TyArg (coreExprType core_expr), VarArg core_expr, VarArg list]
121
122 deListComp (GuardStmt guard locn : quals) list  -- rule B above
123   = dsExpr guard                `thenDs` \ core_guard ->
124     deListComp quals list       `thenDs` \ core_rest ->
125     returnDs (mkCoreIfThenElse core_guard core_rest list)
126
127 -- [e | let B, qs] = let B in [e | qs]
128 deListComp (LetStmt binds : quals) list
129   = dsBinds binds               `thenDs` \ core_binds ->
130     deListComp quals list       `thenDs` \ core_rest ->
131     returnDs (mkCoLetsAny core_binds core_rest)
132
133 deListComp (BindStmt pat list1 locn : quals) core_list2 -- rule A' above
134   = dsExpr list1                    `thenDs` \ core_list1 ->
135     let
136         u3_ty@u1_ty = coreExprType core_list1   -- two names, same thing
137
138         -- u1_ty is a [alpha] type, and u2_ty = alpha
139         u2_ty = outPatType pat
140
141         res_ty = coreExprType core_list2
142         h_ty   = u1_ty `mkFunTy` res_ty
143     in
144     newSysLocalsDs [h_ty, u1_ty, u2_ty, u3_ty]  `thenDs` \ [h, u1, u2, u3] ->
145
146     -- the "fail" value ...
147     mkAppDs (Var h) [VarArg (Var u3)]           `thenDs` \ core_fail ->
148     deListComp quals core_fail                  `thenDs` \ rest_expr ->
149     matchSimply (Var u2) pat res_ty 
150                 rest_expr core_fail             `thenDs` \ core_match ->
151     mkAppDs (Var h) [VarArg core_list1]         `thenDs` \ letrec_body ->
152
153     returnDs (
154       mkCoLetrecAny [
155       ( h,
156         (Lam (ValBinder u1)
157          (Case (Var u1)
158             (AlgAlts
159               [(nilDataCon,  [],        core_list2),
160                (consDataCon, [u2, u3],  core_match)]
161             NoDefault)))
162       )] letrec_body
163     )
164 \end{code}
165
166 %************************************************************************
167 %*                                                                      *
168 \subsection[DsListComp-foldr-build]{Foldr/Build desugaring of list comprehensions}
169 %*                                                                      *
170 %************************************************************************
171
172 @dfListComp@ are the rules used with foldr/build turned on:
173 \begin{verbatim}
174 TE < [ e | ] >>          c n = c e n
175 TE << [ e | b , q ] >>   c n = if b then TE << [ e | q ] >> c n else n
176 TE << [ e | p <- l , q ] c n =  foldr
177                         (\ TE << p >> b -> TE << [ e | q ] >> c b
178                            _          b  -> b)  n l
179 \end{verbatim}
180 \begin{code}
181 dfListComp :: Type -> Id                -- 'c'; its type and id
182            -> Type -> Id                -- 'n'; its type and id
183            -> [TypecheckedStmt]         -- the rest of the qual's
184            -> DsM CoreExpr
185
186 dfListComp c_ty c_id n_ty n_id [ReturnStmt expr]
187   = dsExpr expr                 `thenDs` \ core_expr ->
188     mkAppDs (Var c_id) [VarArg core_expr, VarArg (Var n_id)]
189
190 dfListComp c_ty c_id n_ty n_id (GuardStmt guard locn  : quals)
191   = dsExpr guard                                `thenDs` \ core_guard ->
192     dfListComp c_ty c_id n_ty n_id quals        `thenDs` \ core_rest ->
193     returnDs (mkCoreIfThenElse core_guard core_rest (Var n_id))
194
195 dfListComp c_ty c_id n_ty n_id (LetStmt binds : quals)
196   -- new in 1.3, local bindings
197   = dsBinds binds                         `thenDs` \ core_binds ->
198     dfListComp c_ty c_id n_ty n_id quals  `thenDs` \ core_rest ->
199     returnDs (mkCoLetsAny core_binds core_rest)
200
201 dfListComp c_ty c_id n_ty n_id (BindStmt pat list1 locn : quals)
202     -- evaluate the two lists
203   = dsExpr list1                                `thenDs` \ core_list1 ->
204
205     -- find the required type
206
207     let p_ty   = outPatType pat
208         b_ty   = n_ty           -- alias b_ty to n_ty
209         fn_ty  = mkFunTys [p_ty, b_ty] b_ty
210         lst_ty = coreExprType core_list1
211     in
212
213     -- create some new local id's
214
215     newSysLocalsDs [b_ty,p_ty,fn_ty,lst_ty]             `thenDs` \ [b,p,fn,lst] ->
216
217     -- build rest of the comprehesion
218
219     dfListComp c_ty c_id b_ty b quals                   `thenDs` \ core_rest ->
220     -- build the pattern match
221
222     matchSimply (Var p) pat b_ty core_rest (Var b)      `thenDs` \ core_expr ->
223
224     -- now build the outermost foldr, and return
225
226     returnDs (
227       mkCoLetsAny
228         [NonRec fn (mkValLam [p, b] core_expr),
229          NonRec lst core_list1]
230         (mkFoldr p_ty n_ty fn n_id lst)
231     )
232
233 mkFoldr a b f z xs
234   = mkValApp (mkTyApp (Var foldrId) [a,b]) [VarArg f, VarArg z, VarArg xs]
235 \end{code}