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