Handle ParStmt in collectStmtBinders; fixes tcrun013(ghci) failure
[ghc-hetmet.git] / compiler / hsSyn / HsUtils.lhs
1 %
2 % (c) The University of Glasgow, 1992-2006
3 %
4
5 Here we collect a variety of helper functions that construct or
6 analyse HsSyn.  All these functions deal with generic HsSyn; functions
7 which deal with the intantiated versions are located elsewhere:
8
9    Parameterised by     Module
10    ----------------     -------------
11    RdrName              parser/RdrHsSyn
12    Name                 rename/RnHsSyn
13    Id                   typecheck/TcHsSyn       
14
15 \begin{code}
16 module HsUtils where
17
18 #include "HsVersions.h"
19
20 import HsBinds
21 import HsExpr
22 import HsPat
23 import HsTypes  
24 import HsLit
25
26 import RdrName
27 import Var
28 import Type
29 import DataCon
30 import Name
31 import BasicTypes
32 import SrcLoc
33 import FastString
34 import Outputable
35 import Util
36 import Bag
37 \end{code}
38
39
40 %************************************************************************
41 %*                                                                      *
42         Some useful helpers for constructing syntax
43 %*                                                                      *
44 %************************************************************************
45
46 These functions attempt to construct a not-completely-useless SrcSpan
47 from their components, compared with the nl* functions below which
48 just attach noSrcSpan to everything.
49
50 \begin{code}
51 mkHsPar :: LHsExpr id -> LHsExpr id
52 mkHsPar e = L (getLoc e) (HsPar e)
53
54 mkSimpleMatch :: [LPat id] -> LHsExpr id -> LMatch id
55 mkSimpleMatch pats rhs 
56   = L loc $
57     Match pats Nothing (unguardedGRHSs rhs)
58   where
59     loc = case pats of
60                 []      -> getLoc rhs
61                 (pat:_) -> combineSrcSpans (getLoc pat) (getLoc rhs)
62
63 unguardedGRHSs :: LHsExpr id -> GRHSs id
64 unguardedGRHSs rhs = GRHSs (unguardedRHS rhs) emptyLocalBinds
65
66 unguardedRHS :: LHsExpr id -> [LGRHS id]
67 unguardedRHS rhs@(L loc _) = [L loc (GRHS [] rhs)]
68
69 mkHsAppTy :: LHsType name -> LHsType name -> LHsType name
70 mkHsAppTy t1 t2 = addCLoc t1 t2 (HsAppTy t1 t2)
71
72 mkHsApp :: LHsExpr name -> LHsExpr name -> LHsExpr name
73 mkHsApp e1 e2 = addCLoc e1 e2 (HsApp e1 e2)
74
75 nlHsTyApp :: name -> [Type] -> LHsExpr name
76 nlHsTyApp fun_id tys = noLoc (HsWrap (mkWpTyApps tys) (HsVar fun_id))
77
78 mkLHsWrap :: HsWrapper -> LHsExpr id -> LHsExpr id
79 mkLHsWrap co_fn (L loc e) = L loc (mkHsWrap co_fn e)
80
81 mkHsWrap :: HsWrapper -> HsExpr id -> HsExpr id
82 mkHsWrap co_fn e | isIdHsWrapper co_fn = e
83                  | otherwise          = HsWrap co_fn e
84
85 mkHsLam :: [LPat id] -> LHsExpr id -> LHsExpr id
86 mkHsLam pats body = mkHsPar (L (getLoc body) (HsLam matches))
87         where
88           matches = mkMatchGroup [mkSimpleMatch pats body]
89
90 mkMatchGroup :: [LMatch id] -> MatchGroup id
91 mkMatchGroup matches = MatchGroup matches placeHolderType
92
93 mkHsDictLet :: LHsBinds Id -> LHsExpr Id -> LHsExpr Id
94 -- Used for the dictionary bindings gotten from TcSimplify
95 -- We make them recursive to be on the safe side
96 mkHsDictLet binds expr 
97   | isEmptyLHsBinds binds = expr
98   | otherwise             = L (getLoc expr) (HsLet (HsValBinds val_binds) expr)
99                           where
100                             val_binds = ValBindsOut [(Recursive, binds)] []
101
102 mkHsConApp :: DataCon -> [Type] -> [HsExpr Id] -> LHsExpr Id
103 -- Used for constructing dictinoary terms etc, so no locations 
104 mkHsConApp data_con tys args 
105   = foldl mk_app (nlHsTyApp (dataConWrapId data_con) tys) args
106   where
107     mk_app f a = noLoc (HsApp f (noLoc a))
108
109 mkSimpleHsAlt :: LPat id -> LHsExpr id -> LMatch id
110 -- A simple lambda with a single pattern, no binds, no guards; pre-typechecking
111 mkSimpleHsAlt pat expr 
112   = mkSimpleMatch [pat] expr
113
114 -------------------------------
115 -- These are the bits of syntax that contain rebindable names
116 -- See RnEnv.lookupSyntaxName
117
118 mkHsIntegral   i       = HsIntegral   i  noSyntaxExpr
119 mkHsFractional f       = HsFractional f  noSyntaxExpr
120 mkHsIsString   s       = HsIsString   s  noSyntaxExpr
121 mkHsDo ctxt stmts body = HsDo ctxt stmts body placeHolderType
122
123 mkNPat lit neg     = NPat lit neg noSyntaxExpr placeHolderType
124 mkNPlusKPat id lit = NPlusKPat id lit noSyntaxExpr noSyntaxExpr
125
126 mkExprStmt expr     = ExprStmt expr noSyntaxExpr placeHolderType
127 mkBindStmt pat expr = BindStmt pat expr noSyntaxExpr noSyntaxExpr
128 mkRecStmt stmts     = RecStmt stmts [] [] [] emptyLHsBinds
129
130 -------------------------------
131 --- A useful function for building @OpApps@.  The operator is always a
132 -- variable, and we don't know the fixity yet.
133 mkHsOpApp e1 op e2 = OpApp e1 (noLoc (HsVar op)) (error "mkOpApp:fixity") e2
134
135 mkHsSplice e = HsSplice unqualSplice e
136
137 unqualSplice = mkRdrUnqual (mkVarOccFS FSLIT("splice"))
138                 -- A name (uniquified later) to
139                 -- identify the splice
140
141 mkHsString s = HsString (mkFastString s)
142
143 -------------
144 userHsTyVarBndrs :: [Located name] -> [Located (HsTyVarBndr name)]
145 userHsTyVarBndrs bndrs = [ L loc (UserTyVar v) | L loc v <- bndrs ]
146 \end{code}
147
148
149 %************************************************************************
150 %*                                                                      *
151         Constructing syntax with no location info
152 %*                                                                      *
153 %************************************************************************
154
155 \begin{code}
156 nlHsVar :: id -> LHsExpr id
157 nlHsVar n = noLoc (HsVar n)
158
159 nlHsLit :: HsLit -> LHsExpr id
160 nlHsLit n = noLoc (HsLit n)
161
162 nlVarPat :: id -> LPat id
163 nlVarPat n = noLoc (VarPat n)
164
165 nlLitPat :: HsLit -> LPat id
166 nlLitPat l = noLoc (LitPat l)
167
168 nlHsApp :: LHsExpr id -> LHsExpr id -> LHsExpr id
169 nlHsApp f x = noLoc (HsApp f x)
170
171 nlHsIntLit n = noLoc (HsLit (HsInt n))
172
173 nlHsApps :: id -> [LHsExpr id] -> LHsExpr id
174 nlHsApps f xs = foldl nlHsApp (nlHsVar f) xs
175              
176 nlHsVarApps :: id -> [id] -> LHsExpr id
177 nlHsVarApps f xs = noLoc (foldl mk (HsVar f) (map HsVar xs))
178                  where
179                    mk f a = HsApp (noLoc f) (noLoc a)
180
181 nlConVarPat :: id -> [id] -> LPat id
182 nlConVarPat con vars = nlConPat con (map nlVarPat vars)
183
184 nlInfixConPat :: id -> LPat id -> LPat id -> LPat id
185 nlInfixConPat con l r = noLoc (ConPatIn (noLoc con) (InfixCon l r))
186
187 nlConPat :: id -> [LPat id] -> LPat id
188 nlConPat con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats))
189
190 nlNullaryConPat :: id -> LPat id
191 nlNullaryConPat con = noLoc (ConPatIn (noLoc con) (PrefixCon []))
192
193 nlWildConPat :: DataCon -> LPat RdrName
194 nlWildConPat con = noLoc (ConPatIn (noLoc (getRdrName con))
195                                    (PrefixCon (nOfThem (dataConSourceArity con) nlWildPat)))
196
197 nlTuplePat pats box = noLoc (TuplePat pats box placeHolderType)
198 nlWildPat  = noLoc (WildPat placeHolderType)    -- Pre-typechecking
199
200 nlHsDo :: HsStmtContext Name -> [LStmt id] -> LHsExpr id -> LHsExpr id
201 nlHsDo ctxt stmts body = noLoc (mkHsDo ctxt stmts body)
202
203 nlHsOpApp e1 op e2 = noLoc (mkHsOpApp e1 op e2)
204
205 nlHsLam match           = noLoc (HsLam (mkMatchGroup [match]))
206 nlHsPar e               = noLoc (HsPar e)
207 nlHsIf cond true false  = noLoc (HsIf cond true false)
208 nlHsCase expr matches   = noLoc (HsCase expr (mkMatchGroup matches))
209 nlTuple exprs box       = noLoc (ExplicitTuple exprs box)
210 nlList exprs            = noLoc (ExplicitList placeHolderType exprs)
211
212 nlHsAppTy f t           = noLoc (HsAppTy f t)
213 nlHsTyVar x             = noLoc (HsTyVar x)
214 nlHsFunTy a b           = noLoc (HsFunTy a b)
215
216 nlHsTyConApp tycon tys  = foldl nlHsAppTy (nlHsTyVar tycon) tys
217 \end{code}
218
219
220
221 %************************************************************************
222 %*                                                                      *
223                 Bindings; with a location at the top
224 %*                                                                      *
225 %************************************************************************
226
227 \begin{code}
228 mkFunBind :: Located id -> [LMatch id] -> HsBind id
229 -- Not infix, with place holders for coercion and free vars
230 mkFunBind fn ms = FunBind { fun_id = fn, fun_infix = False, fun_matches = mkMatchGroup ms,
231                             fun_co_fn = idHsWrapper, bind_fvs = placeHolderNames,
232                             fun_tick = Nothing }
233
234
235 mkVarBind :: SrcSpan -> RdrName -> LHsExpr RdrName -> LHsBind RdrName
236 mkVarBind loc var rhs = mk_easy_FunBind loc var [] rhs
237
238 ------------
239 mk_easy_FunBind :: SrcSpan -> RdrName -> [LPat RdrName]
240                 -> LHsExpr RdrName -> LHsBind RdrName
241
242 mk_easy_FunBind loc fun pats expr
243   = L loc $ mkFunBind (L loc fun) [mkMatch pats expr emptyLocalBinds]
244
245 ------------
246 mk_FunBind :: SrcSpan -> RdrName
247            -> [([LPat RdrName], LHsExpr RdrName)]
248            -> LHsBind RdrName
249
250 mk_FunBind loc fun [] = panic "TcGenDeriv:mk_FunBind"
251 mk_FunBind loc fun pats_and_exprs
252   = L loc $ mkFunBind (L loc fun) matches
253   where
254     matches = [mkMatch p e emptyLocalBinds | (p,e) <-pats_and_exprs]
255
256 ------------
257 mkMatch :: [LPat id] -> LHsExpr id -> HsLocalBinds id -> LMatch id
258 mkMatch pats expr binds
259   = noLoc (Match (map paren pats) Nothing 
260                  (GRHSs (unguardedRHS expr) binds))
261   where
262     paren p = case p of
263                 L _ (VarPat _) -> p
264                 L l _          -> L l (ParPat p)
265 \end{code}
266
267
268 %************************************************************************
269 %*                                                                      *
270         Collecting binders from HsBindGroups and HsBinds
271 %*                                                                      *
272 %************************************************************************
273
274 Get all the binders in some HsBindGroups, IN THE ORDER OF APPEARANCE. eg.
275
276 ...
277 where
278   (x, y) = ...
279   f i j  = ...
280   [a, b] = ...
281
282 it should return [x, y, f, a, b] (remember, order important).
283
284 \begin{code}
285 collectLocalBinders :: HsLocalBinds name -> [Located name]
286 collectLocalBinders (HsValBinds val_binds) = collectHsValBinders val_binds
287 collectLocalBinders (HsIPBinds _)   = []
288 collectLocalBinders EmptyLocalBinds = []
289
290 collectHsValBinders :: HsValBinds name -> [Located name]
291 collectHsValBinders (ValBindsIn binds sigs)  = collectHsBindLocatedBinders binds
292 collectHsValBinders (ValBindsOut binds sigs) = foldr collect_one [] binds
293   where
294    collect_one (_,binds) acc = foldrBag (collectAcc . unLoc) acc binds
295
296 collectAcc :: HsBind name -> [Located name] -> [Located name]
297 collectAcc (PatBind { pat_lhs = p }) acc = collectLocatedPatBinders p ++ acc
298 collectAcc (FunBind { fun_id = f })  acc    = f : acc
299 collectAcc (VarBind { var_id = f })  acc    = noLoc f : acc
300 collectAcc (AbsBinds { abs_exports = dbinds, abs_binds = binds }) acc
301   = [noLoc dp | (_,dp,_,_) <- dbinds] ++ acc
302         -- ++ foldr collectAcc acc binds
303         -- I don't think we want the binders from the nested binds
304         -- The only time we collect binders from a typechecked 
305         -- binding (hence see AbsBinds) is in zonking in TcHsSyn
306
307 collectHsBindBinders :: LHsBinds name -> [name]
308 collectHsBindBinders binds = map unLoc (collectHsBindLocatedBinders binds)
309
310 collectHsBindLocatedBinders :: LHsBinds name -> [Located name]
311 collectHsBindLocatedBinders binds = foldrBag (collectAcc . unLoc) [] binds
312 \end{code}
313
314
315 %************************************************************************
316 %*                                                                      *
317         Getting binders from statements
318 %*                                                                      *
319 %************************************************************************
320
321 \begin{code}
322 collectLStmtsBinders :: OutputableBndr id => [LStmt id] -> [Located id]
323 collectLStmtsBinders = concatMap collectLStmtBinders
324
325 collectStmtsBinders :: OutputableBndr id => [Stmt id] -> [Located id]
326 collectStmtsBinders = concatMap collectStmtBinders
327
328 collectLStmtBinders :: OutputableBndr id => LStmt id -> [Located id]
329 collectLStmtBinders = collectStmtBinders . unLoc
330
331 collectStmtBinders :: OutputableBndr id => Stmt id -> [Located id]
332   -- Id Binders for a Stmt... [but what about pattern-sig type vars]?
333 collectStmtBinders (BindStmt pat _ _ _) = collectLocatedPatBinders pat
334 collectStmtBinders (LetStmt binds)      = collectLocalBinders binds
335 collectStmtBinders (ExprStmt _ _ _)     = []
336 collectStmtBinders (ParStmt xs)         = collectLStmtsBinders
337                                         $ concatMap fst xs
338 collectStmtBinders (RecStmt ss _ _ _ _) = collectLStmtsBinders ss
339 collectStmtBinders s                    = pprPanic "collectStmtBinders" (ppr s)
340 \end{code}
341
342
343 %************************************************************************
344 %*                                                                      *
345 %*      Gathering stuff out of patterns
346 %*                                                                      *
347 %************************************************************************
348
349 This function @collectPatBinders@ works with the ``collectBinders''
350 functions for @HsBinds@, etc.  The order in which the binders are
351 collected is important; see @HsBinds.lhs@.
352
353 It collects the bounds *value* variables in renamed patterns; type variables
354 are *not* collected.
355
356 \begin{code}
357 collectPatBinders :: LPat a -> [a]
358 collectPatBinders pat = map unLoc (collectLocatedPatBinders pat)
359
360 collectLocatedPatBinders :: LPat a -> [Located a]
361 collectLocatedPatBinders pat = collectl pat []
362
363 collectPatsBinders :: [LPat a] -> [a]
364 collectPatsBinders pats = map unLoc (collectLocatedPatsBinders pats)
365
366 collectLocatedPatsBinders :: [LPat a] -> [Located a]
367 collectLocatedPatsBinders pats = foldr collectl [] pats
368
369 ---------------------
370 collectl (L l pat) bndrs
371   = go pat
372   where
373     go (VarPat var)               = L l var : bndrs
374     go (VarPatOut var bs)         = L l var : collectHsBindLocatedBinders bs 
375                                     ++ bndrs
376     go (WildPat _)                = bndrs
377     go (LazyPat pat)              = collectl pat bndrs
378     go (BangPat pat)              = collectl pat bndrs
379     go (AsPat a pat)              = a : collectl pat bndrs
380     go (ParPat  pat)              = collectl pat bndrs
381                                   
382     go (ListPat pats _)           = foldr collectl bndrs pats
383     go (PArrPat pats _)           = foldr collectl bndrs pats
384     go (TuplePat pats _ _)        = foldr collectl bndrs pats
385                                   
386     go (ConPatIn c ps)            = foldr collectl bndrs (hsConArgs ps)
387     go (ConPatOut {pat_args=ps})  = foldr collectl bndrs (hsConArgs ps)
388         -- See Note [Dictionary binders in ConPatOut]
389     go (LitPat _)                 = bndrs
390     go (NPat _ _ _ _)             = bndrs
391     go (NPlusKPat n _ _ _)        = n : bndrs
392                                   
393     go (SigPatIn pat _)           = collectl pat bndrs
394     go (SigPatOut pat _)          = collectl pat bndrs
395     go (TypePat ty)               = bndrs
396     go (DictPat ids1 ids2)        = map noLoc ids1 ++ map noLoc ids2
397                                     ++ bndrs
398     go (CoPat _ pat ty)           = collectl (noLoc pat) bndrs
399 \end{code}
400
401 Note [Dictionary binders in ConPatOut]
402 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
403 Do *not* gather (a) dictionary and (b) dictionary bindings as binders
404 of a ConPatOut pattern.  For most calls it doesn't matter, because
405 it's pre-typechecker and there are no ConPatOuts.  But it does matter
406 more in the desugarer; for example, DsUtils.mkSelectorBinds uses
407 collectPatBinders.  In a lazy pattern, for example f ~(C x y) = ...,
408 we want to generate bindings for x,y but not for dictionaries bound by
409 C.  (The type checker ensures they would not be used.)
410
411 \begin{code}
412 collectSigTysFromPats :: [InPat name] -> [LHsType name]
413 collectSigTysFromPats pats = foldr collect_lpat [] pats
414
415 collectSigTysFromPat :: InPat name -> [LHsType name]
416 collectSigTysFromPat pat = collect_lpat pat []
417
418 collect_lpat pat acc = collect_pat (unLoc pat) acc
419
420 collect_pat (SigPatIn pat ty)   acc = collect_lpat pat (ty:acc)
421 collect_pat (TypePat ty)        acc = ty:acc
422
423 collect_pat (LazyPat pat)       acc = collect_lpat pat acc
424 collect_pat (BangPat pat)       acc = collect_lpat pat acc
425 collect_pat (AsPat a pat)       acc = collect_lpat pat acc
426 collect_pat (ParPat  pat)       acc = collect_lpat pat acc
427 collect_pat (ListPat pats _)    acc = foldr collect_lpat acc pats
428 collect_pat (PArrPat pats _)    acc = foldr collect_lpat acc pats
429 collect_pat (TuplePat pats _ _) acc = foldr collect_lpat acc pats
430 collect_pat (ConPatIn c ps)     acc = foldr collect_lpat acc (hsConArgs ps)
431 collect_pat other               acc = acc       -- Literals, vars, wildcard
432 \end{code}