3302820b994fe583262e07d7f31986570e68a8bc
[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 import HsDecls
26
27 import RdrName
28 import Var
29 import Type
30 import DataCon
31 import Name
32 import BasicTypes
33 import SrcLoc
34 import FastString
35 import Outputable
36 import Util
37 import Bag
38 \end{code}
39
40
41 %************************************************************************
42 %*                                                                      *
43         Some useful helpers for constructing syntax
44 %*                                                                      *
45 %************************************************************************
46
47 These functions attempt to construct a not-completely-useless SrcSpan
48 from their components, compared with the nl* functions below which
49 just attach noSrcSpan to everything.
50
51 \begin{code}
52 mkHsPar :: LHsExpr id -> LHsExpr id
53 mkHsPar e = L (getLoc e) (HsPar e)
54
55 mkSimpleMatch :: [LPat id] -> LHsExpr id -> LMatch id
56 mkSimpleMatch pats rhs 
57   = L loc $
58     Match pats Nothing (unguardedGRHSs rhs)
59   where
60     loc = case pats of
61                 []      -> getLoc rhs
62                 (pat:_) -> combineSrcSpans (getLoc pat) (getLoc rhs)
63
64 unguardedGRHSs :: LHsExpr id -> GRHSs id
65 unguardedGRHSs rhs = GRHSs (unguardedRHS rhs) emptyLocalBinds
66
67 unguardedRHS :: LHsExpr id -> [LGRHS id]
68 unguardedRHS rhs@(L loc _) = [L loc (GRHS [] rhs)]
69
70 mkHsAppTy :: LHsType name -> LHsType name -> LHsType name
71 mkHsAppTy t1 t2 = addCLoc t1 t2 (HsAppTy t1 t2)
72
73 mkHsApp :: LHsExpr name -> LHsExpr name -> LHsExpr name
74 mkHsApp e1 e2 = addCLoc e1 e2 (HsApp e1 e2)
75
76 nlHsTyApp :: name -> [Type] -> LHsExpr name
77 nlHsTyApp fun_id tys = noLoc (HsWrap (mkWpTyApps tys) (HsVar fun_id))
78
79 mkLHsWrap :: HsWrapper -> LHsExpr id -> LHsExpr id
80 mkLHsWrap co_fn (L loc e) = L loc (mkHsWrap co_fn e)
81
82 mkHsWrap :: HsWrapper -> HsExpr id -> HsExpr id
83 mkHsWrap co_fn e | isIdHsWrapper co_fn = e
84                  | otherwise          = HsWrap co_fn e
85
86 mkHsLam :: [LPat id] -> LHsExpr id -> LHsExpr id
87 mkHsLam pats body = mkHsPar (L (getLoc body) (HsLam matches))
88         where
89           matches = mkMatchGroup [mkSimpleMatch pats body]
90
91 mkMatchGroup :: [LMatch id] -> MatchGroup id
92 mkMatchGroup matches = MatchGroup matches placeHolderType
93
94 mkHsDictLet :: LHsBinds Id -> LHsExpr Id -> LHsExpr Id
95 -- Used for the dictionary bindings gotten from TcSimplify
96 -- We make them recursive to be on the safe side
97 mkHsDictLet binds expr 
98   | isEmptyLHsBinds binds = expr
99   | otherwise             = L (getLoc expr) (HsLet (HsValBinds val_binds) expr)
100                           where
101                             val_binds = ValBindsOut [(Recursive, binds)] []
102
103 mkHsConApp :: DataCon -> [Type] -> [HsExpr Id] -> LHsExpr Id
104 -- Used for constructing dictinoary terms etc, so no locations 
105 mkHsConApp data_con tys args 
106   = foldl mk_app (nlHsTyApp (dataConWrapId data_con) tys) args
107   where
108     mk_app f a = noLoc (HsApp f (noLoc a))
109
110 mkSimpleHsAlt :: LPat id -> LHsExpr id -> LMatch id
111 -- A simple lambda with a single pattern, no binds, no guards; pre-typechecking
112 mkSimpleHsAlt pat expr 
113   = mkSimpleMatch [pat] expr
114
115 -------------------------------
116 -- These are the bits of syntax that contain rebindable names
117 -- See RnEnv.lookupSyntaxName
118
119 mkHsIntegral   i       = HsIntegral   i  noSyntaxExpr
120 mkHsFractional f       = HsFractional f  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 \end{code}
216
217
218
219 %************************************************************************
220 %*                                                                      *
221                 Bindings; with a location at the top
222 %*                                                                      *
223 %************************************************************************
224
225 \begin{code}
226 mkFunBind :: Located id -> [LMatch id] -> HsBind id
227 -- Not infix, with place holders for coercion and free vars
228 mkFunBind fn ms = FunBind { fun_id = fn, fun_infix = False, fun_matches = mkMatchGroup ms,
229                             fun_co_fn = idHsWrapper, bind_fvs = placeHolderNames,
230                             fun_tick = Nothing }
231
232
233 mkVarBind :: SrcSpan -> RdrName -> LHsExpr RdrName -> LHsBind RdrName
234 mkVarBind loc var rhs = mk_easy_FunBind loc var [] rhs
235
236 ------------
237 mk_easy_FunBind :: SrcSpan -> RdrName -> [LPat RdrName]
238                 -> LHsExpr RdrName -> LHsBind RdrName
239
240 mk_easy_FunBind loc fun pats expr
241   = L loc $ mkFunBind (L loc fun) [mkMatch pats expr emptyLocalBinds]
242
243 ------------
244 mk_FunBind :: SrcSpan -> RdrName
245            -> [([LPat RdrName], LHsExpr RdrName)]
246            -> LHsBind RdrName
247
248 mk_FunBind loc fun [] = panic "TcGenDeriv:mk_FunBind"
249 mk_FunBind loc fun pats_and_exprs
250   = L loc $ mkFunBind (L loc fun) matches
251   where
252     matches = [mkMatch p e emptyLocalBinds | (p,e) <-pats_and_exprs]
253
254 ------------
255 mkMatch :: [LPat id] -> LHsExpr id -> HsLocalBinds id -> LMatch id
256 mkMatch pats expr binds
257   = noLoc (Match (map paren pats) Nothing 
258                  (GRHSs (unguardedRHS expr) binds))
259   where
260     paren p = case p of
261                 L _ (VarPat _) -> p
262                 L l _          -> L l (ParPat p)
263 \end{code}
264
265
266 %************************************************************************
267 %*                                                                      *
268         Collecting binders from HsBindGroups and HsBinds
269 %*                                                                      *
270 %************************************************************************
271
272 Get all the binders in some HsBindGroups, IN THE ORDER OF APPEARANCE. eg.
273
274 ...
275 where
276   (x, y) = ...
277   f i j  = ...
278   [a, b] = ...
279
280 it should return [x, y, f, a, b] (remember, order important).
281
282 \begin{code}
283 collectLocalBinders :: HsLocalBinds name -> [Located name]
284 collectLocalBinders (HsValBinds val_binds) = collectHsValBinders val_binds
285 collectLocalBinders (HsIPBinds _)   = []
286 collectLocalBinders EmptyLocalBinds = []
287
288 collectHsValBinders :: HsValBinds name -> [Located name]
289 collectHsValBinders (ValBindsIn binds sigs)  = collectHsBindLocatedBinders binds
290 collectHsValBinders (ValBindsOut binds sigs) = foldr collect_one [] binds
291   where
292    collect_one (_,binds) acc = foldrBag (collectAcc . unLoc) acc binds
293
294 collectAcc :: HsBind name -> [Located name] -> [Located name]
295 collectAcc (PatBind { pat_lhs = p }) acc = collectLocatedPatBinders p ++ acc
296 collectAcc (FunBind { fun_id = f })  acc    = f : acc
297 collectAcc (VarBind { var_id = f })  acc    = noLoc f : acc
298 collectAcc (AbsBinds { abs_exports = dbinds, abs_binds = binds }) acc
299   = [noLoc dp | (_,dp,_,_) <- dbinds] ++ acc
300         -- ++ foldr collectAcc acc binds
301         -- I don't think we want the binders from the nested binds
302         -- The only time we collect binders from a typechecked 
303         -- binding (hence see AbsBinds) is in zonking in TcHsSyn
304
305 collectHsBindBinders :: LHsBinds name -> [name]
306 collectHsBindBinders binds = map unLoc (collectHsBindLocatedBinders binds)
307
308 collectHsBindLocatedBinders :: LHsBinds name -> [Located name]
309 collectHsBindLocatedBinders binds = foldrBag (collectAcc . unLoc) [] binds
310 \end{code}
311
312
313 %************************************************************************
314 %*                                                                      *
315         Getting binders from statements
316 %*                                                                      *
317 %************************************************************************
318
319 \begin{code}
320 collectLStmtsBinders :: [LStmt id] -> [Located id]
321 collectLStmtsBinders = concatMap collectLStmtBinders
322
323 collectStmtsBinders :: [Stmt id] -> [Located id]
324 collectStmtsBinders = concatMap collectStmtBinders
325
326 collectLStmtBinders :: LStmt id -> [Located id]
327 collectLStmtBinders = collectStmtBinders . unLoc
328
329 collectStmtBinders :: Stmt id -> [Located id]
330   -- Id Binders for a Stmt... [but what about pattern-sig type vars]?
331 collectStmtBinders (BindStmt pat _ _ _) = collectLocatedPatBinders pat
332 collectStmtBinders (LetStmt binds)      = collectLocalBinders binds
333 collectStmtBinders (ExprStmt _ _ _)     = []
334 collectStmtBinders (RecStmt ss _ _ _ _) = collectLStmtsBinders ss
335 collectStmtBinders other                = panic "collectStmtBinders"
336 \end{code}
337
338
339 %************************************************************************
340 %*                                                                      *
341 %*      Gathering stuff out of patterns
342 %*                                                                      *
343 %************************************************************************
344
345 This function @collectPatBinders@ works with the ``collectBinders''
346 functions for @HsBinds@, etc.  The order in which the binders are
347 collected is important; see @HsBinds.lhs@.
348
349 It collects the bounds *value* variables in renamed patterns; type variables
350 are *not* collected.
351
352 \begin{code}
353 collectPatBinders :: LPat a -> [a]
354 collectPatBinders pat = map unLoc (collectLocatedPatBinders pat)
355
356 collectLocatedPatBinders :: LPat a -> [Located a]
357 collectLocatedPatBinders pat = collectl pat []
358
359 collectPatsBinders :: [LPat a] -> [a]
360 collectPatsBinders pats = map unLoc (collectLocatedPatsBinders pats)
361
362 collectLocatedPatsBinders :: [LPat a] -> [Located a]
363 collectLocatedPatsBinders pats = foldr collectl [] pats
364
365 ---------------------
366 collectl (L l pat) bndrs
367   = go pat
368   where
369     go (VarPat var)               = L l var : bndrs
370     go (VarPatOut var bs)         = L l var : collectHsBindLocatedBinders bs 
371                                     ++ bndrs
372     go (WildPat _)                = bndrs
373     go (LazyPat pat)              = collectl pat bndrs
374     go (BangPat pat)              = collectl pat bndrs
375     go (AsPat a pat)              = a : collectl pat bndrs
376     go (ParPat  pat)              = collectl pat bndrs
377                                   
378     go (ListPat pats _)           = foldr collectl bndrs pats
379     go (PArrPat pats _)           = foldr collectl bndrs pats
380     go (TuplePat pats _ _)        = foldr collectl bndrs pats
381                                   
382     go (ConPatIn c ps)            = foldr collectl bndrs (hsConArgs ps)
383     go (ConPatOut {pat_args=ps})  = foldr collectl bndrs (hsConArgs ps)
384         -- See Note [Dictionary binders in ConPatOut]
385     go (LitPat _)                 = bndrs
386     go (NPat _ _ _ _)             = bndrs
387     go (NPlusKPat n _ _ _)        = n : bndrs
388                                   
389     go (SigPatIn pat _)           = collectl pat bndrs
390     go (SigPatOut pat _)          = collectl pat bndrs
391     go (TypePat ty)               = bndrs
392     go (DictPat ids1 ids2)        = map noLoc ids1 ++ map noLoc ids2
393                                     ++ bndrs
394     go (CoPat _ pat ty)           = collectl (noLoc pat) bndrs
395 \end{code}
396
397 Note [Dictionary binders in ConPatOut]
398 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
399 Do *not* gather (a) dictionary and (b) dictionary bindings as binders
400 of a ConPatOut pattern.  For most calls it doesn't matter, because
401 it's pre-typechecker and there are no ConPatOuts.  But it does matter
402 more in the desugarer; for example, DsUtils.mkSelectorBinds uses
403 collectPatBinders.  In a lazy pattern, for example f ~(C x y) = ...,
404 we want to generate bindings for x,y but not for dictionaries bound by
405 C.  (The type checker ensures they would not be used.)
406
407 \begin{code}
408 collectSigTysFromPats :: [InPat name] -> [LHsType name]
409 collectSigTysFromPats pats = foldr collect_lpat [] pats
410
411 collectSigTysFromPat :: InPat name -> [LHsType name]
412 collectSigTysFromPat pat = collect_lpat pat []
413
414 collect_lpat pat acc = collect_pat (unLoc pat) acc
415
416 collect_pat (SigPatIn pat ty)   acc = collect_lpat pat (ty:acc)
417 collect_pat (TypePat ty)        acc = ty:acc
418
419 collect_pat (LazyPat pat)       acc = collect_lpat pat acc
420 collect_pat (BangPat pat)       acc = collect_lpat pat acc
421 collect_pat (AsPat a pat)       acc = collect_lpat pat acc
422 collect_pat (ParPat  pat)       acc = collect_lpat pat acc
423 collect_pat (ListPat pats _)    acc = foldr collect_lpat acc pats
424 collect_pat (PArrPat pats _)    acc = foldr collect_lpat acc pats
425 collect_pat (TuplePat pats _ _) acc = foldr collect_lpat acc pats
426 collect_pat (ConPatIn c ps)     acc = foldr collect_lpat acc (hsConArgs ps)
427 collect_pat other               acc = acc       -- Literals, vars, wildcard
428 \end{code}
429
430 %************************************************************************
431 %*                                                                      *
432 %*      Getting the main binder name of a top declaration
433 %*                                                                      *
434 %************************************************************************
435
436 \begin{code}
437
438 getMainDeclBinder :: HsDecl name -> Maybe name
439 getMainDeclBinder (TyClD d) = Just (tcdName d)
440 getMainDeclBinder (ValD d)
441    = case collectAcc d [] of
442         []       -> Nothing   -- see rn003
443         (name:_) -> Just (unLoc name)
444 getMainDeclBinder (SigD d) = sigNameNoLoc d
445 getMainDeclBinder (ForD (ForeignImport name _ _)) = Just (unLoc name)
446 getMainDeclBinder (ForD (ForeignExport name _ _)) = Just (unLoc name)
447 getMainDeclBinder _ = Nothing
448
449 \end{code}