f8efa6cfb94f206e7047953e32c87d6b486eacac
[ghc-hetmet.git] / ghc / 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 mkHsTyApp :: LHsExpr name -> [Type] -> LHsExpr name
75 mkHsTyApp expr []  = expr
76 mkHsTyApp expr tys = L (getLoc expr) (TyApp expr tys)
77
78 mkHsDictApp :: LHsExpr name -> [name] -> LHsExpr name
79 mkHsDictApp expr []      = expr
80 mkHsDictApp expr dict_vars = L (getLoc expr) (DictApp expr dict_vars)
81
82 mkHsLam :: [LPat id] -> LHsExpr id -> LHsExpr id
83 mkHsLam pats body = mkHsPar (L (getLoc body) (HsLam matches))
84         where
85           matches = mkMatchGroup [mkSimpleMatch pats body]
86
87 mkMatchGroup :: [LMatch id] -> MatchGroup id
88 mkMatchGroup matches = MatchGroup matches placeHolderType
89
90 mkHsTyLam []     expr = expr
91 mkHsTyLam tyvars expr = L (getLoc expr) (TyLam tyvars expr)
92
93 mkHsDictLam []    expr = expr
94 mkHsDictLam dicts expr = L (getLoc expr) (DictLam dicts expr)
95
96 mkHsDictLet :: LHsBinds Id -> LHsExpr Id -> LHsExpr Id
97 -- Used for the dictionary bindings gotten from TcSimplify
98 -- We make them recursive to be on the safe side
99 mkHsDictLet binds expr 
100   | isEmptyLHsBinds binds = expr
101   | otherwise             = L (getLoc expr) (HsLet (HsValBinds val_binds) expr)
102                           where
103                             val_binds = ValBindsOut [(Recursive, binds)] []
104
105 mkHsConApp :: DataCon -> [Type] -> [HsExpr Id] -> LHsExpr Id
106 -- Used for constructing dictinoary terms etc, so no locations 
107 mkHsConApp data_con tys args 
108   = foldl mk_app (noLoc (HsVar (dataConWrapId data_con)) `mkHsTyApp` tys) args
109   where
110     mk_app f a = noLoc (HsApp f (noLoc a))
111
112 mkSimpleHsAlt :: LPat id -> LHsExpr id -> LMatch id
113 -- A simple lambda with a single pattern, no binds, no guards; pre-typechecking
114 mkSimpleHsAlt pat expr 
115   = mkSimpleMatch [pat] expr
116
117 -------------------------------
118 -- These are the bits of syntax that contain rebindable names
119 -- See RnEnv.lookupSyntaxName
120
121 mkHsIntegral   i       = HsIntegral   i  noSyntaxExpr
122 mkHsFractional f       = HsFractional f  noSyntaxExpr
123 mkHsDo ctxt stmts body = HsDo ctxt stmts body placeHolderType
124
125 mkNPat lit neg     = NPat lit neg noSyntaxExpr placeHolderType
126 mkNPlusKPat id lit = NPlusKPat id lit noSyntaxExpr noSyntaxExpr
127
128 mkExprStmt expr     = ExprStmt expr noSyntaxExpr placeHolderType
129 mkBindStmt pat expr = BindStmt pat expr noSyntaxExpr noSyntaxExpr
130 mkRecStmt stmts     = RecStmt stmts [] [] [] emptyLHsBinds
131
132 -------------------------------
133 --- A useful function for building @OpApps@.  The operator is always a
134 -- variable, and we don't know the fixity yet.
135 mkHsOpApp e1 op e2 = OpApp e1 (noLoc (HsVar op)) (error "mkOpApp:fixity") e2
136
137 mkHsSplice e = HsSplice unqualSplice e
138
139 unqualSplice = mkRdrUnqual (mkVarOccFS FSLIT("splice"))
140                 -- A name (uniquified later) to
141                 -- identify the splice
142
143 mkHsString s = HsString (mkFastString s)
144
145 -------------
146 userHsTyVarBndrs :: [Located name] -> [Located (HsTyVarBndr name)]
147 userHsTyVarBndrs bndrs = [ L loc (UserTyVar v) | L loc v <- bndrs ]
148 \end{code}
149
150
151 %************************************************************************
152 %*                                                                      *
153         Constructing syntax with no location info
154 %*                                                                      *
155 %************************************************************************
156
157 \begin{code}
158 nlHsVar :: id -> LHsExpr id
159 nlHsVar n = noLoc (HsVar n)
160
161 nlHsLit :: HsLit -> LHsExpr id
162 nlHsLit n = noLoc (HsLit n)
163
164 nlVarPat :: id -> LPat id
165 nlVarPat n = noLoc (VarPat n)
166
167 nlLitPat :: HsLit -> LPat id
168 nlLitPat l = noLoc (LitPat l)
169
170 nlHsApp :: LHsExpr id -> LHsExpr id -> LHsExpr id
171 nlHsApp f x = noLoc (HsApp f x)
172
173 nlHsIntLit n = noLoc (HsLit (HsInt n))
174
175 nlHsApps :: id -> [LHsExpr id] -> LHsExpr id
176 nlHsApps f xs = foldl nlHsApp (nlHsVar f) xs
177              
178 nlHsVarApps :: id -> [id] -> LHsExpr id
179 nlHsVarApps f xs = noLoc (foldl mk (HsVar f) (map HsVar xs))
180                  where
181                    mk f a = HsApp (noLoc f) (noLoc a)
182
183 nlConVarPat :: id -> [id] -> LPat id
184 nlConVarPat con vars = nlConPat con (map nlVarPat vars)
185
186 nlInfixConPat :: id -> LPat id -> LPat id -> LPat id
187 nlInfixConPat con l r = noLoc (ConPatIn (noLoc con) (InfixCon l r))
188
189 nlConPat :: id -> [LPat id] -> LPat id
190 nlConPat con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats))
191
192 nlNullaryConPat :: id -> LPat id
193 nlNullaryConPat con = noLoc (ConPatIn (noLoc con) (PrefixCon []))
194
195 nlWildConPat :: DataCon -> LPat RdrName
196 nlWildConPat con = noLoc (ConPatIn (noLoc (getRdrName con))
197                                    (PrefixCon (nOfThem (dataConSourceArity con) nlWildPat)))
198
199 nlTuplePat pats box = noLoc (TuplePat pats box)
200 nlWildPat  = noLoc (WildPat placeHolderType)    -- Pre-typechecking
201
202 nlHsDo :: HsStmtContext Name -> [LStmt id] -> LHsExpr id -> LHsExpr id
203 nlHsDo ctxt stmts body = noLoc (mkHsDo ctxt stmts body)
204
205 nlHsOpApp e1 op e2 = noLoc (mkHsOpApp e1 op e2)
206
207 nlHsLam match           = noLoc (HsLam (mkMatchGroup [match]))
208 nlHsPar e               = noLoc (HsPar e)
209 nlHsIf cond true false  = noLoc (HsIf cond true false)
210 nlHsCase expr matches   = noLoc (HsCase expr (mkMatchGroup matches))
211 nlTuple exprs box       = noLoc (ExplicitTuple exprs box)
212 nlList exprs            = noLoc (ExplicitList placeHolderType exprs)
213
214 nlHsAppTy f t           = noLoc (HsAppTy f t)
215 nlHsTyVar x             = noLoc (HsTyVar x)
216 nlHsFunTy a b           = noLoc (HsFunTy a b)
217 \end{code}
218
219
220
221 %************************************************************************
222 %*                                                                      *
223                 Bindings; with a location at the top
224 %*                                                                      *
225 %************************************************************************
226
227 \begin{code}
228 mkVarBind :: SrcSpan -> RdrName -> LHsExpr RdrName -> LHsBind RdrName
229 mkVarBind loc var rhs = mk_easy_FunBind loc var [] rhs
230
231 ------------
232 mk_easy_FunBind :: SrcSpan -> RdrName -> [LPat RdrName]
233                 -> LHsExpr RdrName -> LHsBind RdrName
234
235 mk_easy_FunBind loc fun pats expr
236   = L loc (FunBind (L loc fun) False{-not infix-} matches placeHolderNames)
237   where
238     matches = mkMatchGroup [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 (FunBind (L loc fun) False{-not infix-} matches placeHolderNames)
248   where
249     matches = mkMatchGroup [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 _ _ _) acc = collectLocatedPatBinders pat ++ acc
293 collectAcc (FunBind f _ _ _) acc   = f : acc
294 collectAcc (VarBind f _) acc       = noLoc f : acc
295 collectAcc (AbsBinds _ _ dbinds 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 pattern signatures out of bindings
313 %*                                                                      *
314 %************************************************************************
315
316 Get all the pattern type signatures out of a bunch of bindings
317
318 \begin{code}
319 collectSigTysFromHsBinds :: LHsBinds name -> [LHsType name]
320 collectSigTysFromHsBinds binds = concatMap collectSigTysFromHsBind (bagToList binds)
321
322 collectSigTysFromHsBind :: LHsBind name -> [LHsType name]
323 collectSigTysFromHsBind bind
324   = go (unLoc bind)
325   where
326     go (PatBind pat _ _ _) 
327         = collectSigTysFromPat pat
328     go (FunBind f _ (MatchGroup ms _) _)
329         = [sig | L _ (Match [] (Just sig) _) <- ms]
330         -- A binding like    x :: a = f y
331         -- is parsed as FunMonoBind, but for this purpose we    
332         -- want to treat it as a pattern binding
333     go out_bind = panic "collectSigTysFromHsBind"
334 \end{code}
335
336 %************************************************************************
337 %*                                                                      *
338         Getting binders from statements
339 %*                                                                      *
340 %************************************************************************
341
342 \begin{code}
343 collectLStmtsBinders :: [LStmt id] -> [Located id]
344 collectLStmtsBinders = concatMap collectLStmtBinders
345
346 collectStmtsBinders :: [Stmt id] -> [Located id]
347 collectStmtsBinders = concatMap collectStmtBinders
348
349 collectLStmtBinders :: LStmt id -> [Located id]
350 collectLStmtBinders = collectStmtBinders . unLoc
351
352 collectStmtBinders :: Stmt id -> [Located id]
353   -- Id Binders for a Stmt... [but what about pattern-sig type vars]?
354 collectStmtBinders (BindStmt pat _ _ _) = collectLocatedPatBinders pat
355 collectStmtBinders (LetStmt binds)      = collectLocalBinders binds
356 collectStmtBinders (ExprStmt _ _ _)     = []
357 collectStmtBinders (RecStmt ss _ _ _ _) = collectLStmtsBinders ss
358 collectStmtBinders other                = panic "collectStmtBinders"
359 \end{code}
360
361
362 %************************************************************************
363 %*                                                                      *
364 %*      Gathering stuff out of patterns
365 %*                                                                      *
366 %************************************************************************
367
368 This function @collectPatBinders@ works with the ``collectBinders''
369 functions for @HsBinds@, etc.  The order in which the binders are
370 collected is important; see @HsBinds.lhs@.
371
372 It collects the bounds *value* variables in renamed patterns; type variables
373 are *not* collected.
374
375 \begin{code}
376 collectPatBinders :: LPat a -> [a]
377 collectPatBinders pat = map unLoc (collectLocatedPatBinders pat)
378
379 collectLocatedPatBinders :: LPat a -> [Located a]
380 collectLocatedPatBinders pat = collectl pat []
381
382 collectPatsBinders :: [LPat a] -> [a]
383 collectPatsBinders pats = map unLoc (collectLocatedPatsBinders pats)
384
385 collectLocatedPatsBinders :: [LPat a] -> [Located a]
386 collectLocatedPatsBinders pats = foldr collectl [] pats
387
388 ---------------------
389 collectl (L l pat) bndrs
390   = go pat
391   where
392     go (VarPat var)               = L l var : bndrs
393     go (VarPatOut var bs)         = L l var : collectHsBindLocatedBinders bs 
394                                     ++ bndrs
395     go (WildPat _)                = bndrs
396     go (LazyPat pat)              = collectl pat bndrs
397     go (AsPat a pat)              = a : collectl pat bndrs
398     go (ParPat  pat)              = collectl pat bndrs
399                                   
400     go (ListPat pats _)           = foldr collectl bndrs pats
401     go (PArrPat pats _)           = foldr collectl bndrs pats
402     go (TuplePat pats _)          = foldr collectl bndrs pats
403                                   
404     go (ConPatIn c ps)            = foldr collectl bndrs (hsConArgs ps)
405     go (ConPatOut c _ ds bs ps _) = map noLoc ds
406                                     ++ collectHsBindLocatedBinders bs
407                                     ++ foldr collectl bndrs (hsConArgs ps)
408     go (LitPat _)                 = bndrs
409     go (NPat _ _ _ _)             = bndrs
410     go (NPlusKPat n _ _ _)        = n : bndrs
411
412     go (SigPatIn pat _)           = collectl pat bndrs
413     go (SigPatOut pat _)          = collectl pat bndrs
414     go (TypePat ty)               = bndrs
415     go (DictPat ids1 ids2)        = map noLoc ids1 ++ map noLoc ids2
416                                     ++ bndrs
417 \end{code}
418
419 \begin{code}
420 collectSigTysFromPats :: [InPat name] -> [LHsType name]
421 collectSigTysFromPats pats = foldr collect_lpat [] pats
422
423 collectSigTysFromPat :: InPat name -> [LHsType name]
424 collectSigTysFromPat pat = collect_lpat pat []
425
426 collect_lpat pat acc = collect_pat (unLoc pat) acc
427
428 collect_pat (SigPatIn pat ty)  acc = collect_lpat pat (ty:acc)
429 collect_pat (TypePat ty)       acc = ty:acc
430
431 collect_pat (LazyPat pat)      acc = collect_lpat pat acc
432 collect_pat (AsPat a pat)      acc = collect_lpat pat acc
433 collect_pat (ParPat  pat)      acc = collect_lpat pat acc
434 collect_pat (ListPat pats _)   acc = foldr collect_lpat acc pats
435 collect_pat (PArrPat pats _)   acc = foldr collect_lpat acc pats
436 collect_pat (TuplePat pats _)  acc = foldr collect_lpat acc pats
437 collect_pat (ConPatIn c ps)    acc = foldr collect_lpat acc (hsConArgs ps)
438 collect_pat other              acc = acc        -- Literals, vars, wildcard
439 \end{code}