[project @ 2005-04-04 11:55:11 by simonpj]
[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 BasicTypes       ( RecFlag(..) )
31 import OccName          ( mkVarOcc )
32 import Name             ( Name )
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) [])
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 mkHsLet :: LHsBinds name -> LHsExpr name -> LHsExpr name
97 mkHsLet binds expr 
98   | isEmptyLHsBinds binds = expr
99   | otherwise             = L (getLoc expr) (HsLet [HsBindGroup binds [] Recursive] expr)
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 (noLoc (HsVar (dataConWrapId data_con)) `mkHsTyApp` 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 glueBindsOnGRHSs :: HsBindGroup id -> GRHSs id -> GRHSs id
114 glueBindsOnGRHSs binds1 (GRHSs grhss binds2)
115   = GRHSs grhss (binds1 : binds2)
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 (mkVarOcc FSLIT("splice"))
140                 -- A name (uniquified later) to
141                 -- identify the splice
142
143 mkHsString s = HsString (mkFastString s)
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)
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 mkVarBind :: SrcSpan -> RdrName -> LHsExpr RdrName -> LHsBind RdrName
225 mkVarBind loc var rhs = mk_easy_FunBind loc var [] emptyLHsBinds rhs
226
227 mk_easy_FunBind :: SrcSpan -> RdrName -> [LPat RdrName]
228                     -> LHsBinds RdrName -> LHsExpr RdrName
229                     -> LHsBind RdrName
230
231 mk_easy_FunBind loc fun pats binds expr
232   = L loc (FunBind (L loc fun) False{-not infix-} 
233                    (mkMatchGroup [mk_easy_Match pats binds expr]))
234
235 mk_easy_Match pats binds expr
236   = mkMatch pats expr [HsBindGroup binds [] Recursive]
237         -- The renamer expects everything in its input to be a
238         -- "recursive" MonoBinds, and it is its job to sort things out
239         -- from there.
240
241 mk_FunBind      :: SrcSpan 
242                 -> RdrName
243                 -> [([LPat RdrName], LHsExpr RdrName)]
244                 -> LHsBind RdrName
245
246 mk_FunBind loc fun [] = panic "TcGenDeriv:mk_FunBind"
247 mk_FunBind loc fun pats_and_exprs
248   = L loc (FunBind (L loc fun) False{-not infix-} 
249                    (mkMatchGroup [mkMatch p e [] | (p,e) <-pats_and_exprs]))
250
251 mkMatch :: [LPat id] -> LHsExpr id -> [HsBindGroup id] -> LMatch id
252 mkMatch pats expr binds
253   = noLoc (Match (map paren pats) Nothing 
254 -- gaw 2004
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 collectGroupBinders :: [HsBindGroup name] -> [Located name]
281 collectGroupBinders groups = foldr collect_group [] groups
282         where
283           collect_group (HsBindGroup bag sigs is_rec) acc
284                 = foldrBag (collectAcc . unLoc) acc bag
285           collect_group (HsIPBinds _) acc = acc
286
287
288 collectAcc :: HsBind name -> [Located name] -> [Located name]
289 collectAcc (PatBind pat _ _) acc = collectLocatedPatBinders pat ++ acc
290 collectAcc (FunBind f _ _) acc   = f : acc
291 collectAcc (VarBind f _) acc  = noLoc f : acc
292 collectAcc (AbsBinds _ _ dbinds _ binds) acc
293   = [noLoc dp | (_,dp,_) <- dbinds] ++ acc
294         -- ++ foldr collectAcc acc binds
295         -- I don't think we want the binders from the nested binds
296         -- The only time we collect binders from a typechecked 
297         -- binding (hence see AbsBinds) is in zonking in TcHsSyn
298
299 collectHsBindBinders :: Bag (LHsBind name) -> [name]
300 collectHsBindBinders binds = map unLoc (collectHsBindLocatedBinders binds)
301
302 collectHsBindLocatedBinders :: Bag (LHsBind name) -> [Located name]
303 collectHsBindLocatedBinders binds = foldrBag (collectAcc . unLoc) [] binds
304 \end{code}
305
306
307 %************************************************************************
308 %*                                                                      *
309         Getting pattern signatures out of bindings
310 %*                                                                      *
311 %************************************************************************
312
313 Get all the pattern type signatures out of a bunch of bindings
314
315 \begin{code}
316 collectSigTysFromHsBinds :: [LHsBind name] -> [LHsType name]
317 collectSigTysFromHsBinds binds = concat (map collectSigTysFromHsBind binds)
318
319 collectSigTysFromHsBind :: LHsBind name -> [LHsType name]
320 collectSigTysFromHsBind bind
321   = go (unLoc bind)
322   where
323     go (PatBind pat _ _) 
324         = collectSigTysFromPat pat
325     go (FunBind f _ (MatchGroup ms _))
326         = [sig | L _ (Match [] (Just sig) _) <- ms]
327         -- A binding like    x :: a = f y
328         -- is parsed as FunMonoBind, but for this purpose we    
329         -- want to treat it as a pattern binding
330 \end{code}
331
332 %************************************************************************
333 %*                                                                      *
334         Getting binders from statements
335 %*                                                                      *
336 %************************************************************************
337
338 \begin{code}
339 collectLStmtsBinders :: [LStmt id] -> [Located id]
340 collectLStmtsBinders = concatMap collectLStmtBinders
341
342 collectStmtsBinders :: [Stmt id] -> [Located id]
343 collectStmtsBinders = concatMap collectStmtBinders
344
345 collectLStmtBinders :: LStmt id -> [Located id]
346 collectLStmtBinders = collectStmtBinders . unLoc
347
348 collectStmtBinders :: Stmt id -> [Located id]
349   -- Id Binders for a Stmt... [but what about pattern-sig type vars]?
350 collectStmtBinders (BindStmt pat _ _ _) = collectLocatedPatBinders pat
351 collectStmtBinders (LetStmt binds)      = collectGroupBinders binds
352 collectStmtBinders (ExprStmt _ _ _)     = []
353 collectStmtBinders (RecStmt ss _ _ _ _) = collectLStmtsBinders ss
354 collectStmtBinders other                = panic "collectStmtBinders"
355 \end{code}
356
357
358 %************************************************************************
359 %*                                                                      *
360 %*      Gathering stuff out of patterns
361 %*                                                                      *
362 %************************************************************************
363
364 This function @collectPatBinders@ works with the ``collectBinders''
365 functions for @HsBinds@, etc.  The order in which the binders are
366 collected is important; see @HsBinds.lhs@.
367
368 It collects the bounds *value* variables in renamed patterns; type variables
369 are *not* collected.
370
371 \begin{code}
372 collectPatBinders :: LPat a -> [a]
373 collectPatBinders pat = map unLoc (collectLocatedPatBinders pat)
374
375 collectLocatedPatBinders :: LPat a -> [Located a]
376 collectLocatedPatBinders pat = collectl pat []
377
378 collectPatsBinders :: [LPat a] -> [a]
379 collectPatsBinders pats = map unLoc (collectLocatedPatsBinders pats)
380
381 collectLocatedPatsBinders :: [LPat a] -> [Located a]
382 collectLocatedPatsBinders pats = foldr collectl [] pats
383
384 ---------------------
385 collectl (L l pat) bndrs
386   = go pat
387   where
388     go (VarPat var)               = L l var : bndrs
389     go (VarPatOut var bs)         = L l var : collectHsBindLocatedBinders bs 
390                                     ++ bndrs
391     go (WildPat _)                = bndrs
392     go (LazyPat pat)              = collectl pat bndrs
393     go (AsPat a pat)              = a : collectl pat bndrs
394     go (ParPat  pat)              = collectl pat bndrs
395                                   
396     go (ListPat pats _)           = foldr collectl bndrs pats
397     go (PArrPat pats _)           = foldr collectl bndrs pats
398     go (TuplePat pats _)          = foldr collectl bndrs pats
399                                   
400     go (ConPatIn c ps)            = foldr collectl bndrs (hsConArgs ps)
401     go (ConPatOut c _ ds bs ps _) = map noLoc ds
402                                     ++ collectHsBindLocatedBinders bs
403                                     ++ foldr collectl bndrs (hsConArgs ps)
404     go (LitPat _)                 = bndrs
405     go (NPat _ _ _ _)             = bndrs
406     go (NPlusKPat n _ _ _)        = n : bndrs
407
408     go (SigPatIn pat _)           = collectl pat bndrs
409     go (SigPatOut pat _)          = collectl pat bndrs
410     go (TypePat ty)               = bndrs
411     go (DictPat ids1 ids2)        = map noLoc ids1 ++ map noLoc ids2
412                                     ++ bndrs
413 \end{code}
414
415 \begin{code}
416 collectSigTysFromPats :: [InPat name] -> [LHsType name]
417 collectSigTysFromPats pats = foldr collect_lpat [] pats
418
419 collectSigTysFromPat :: InPat name -> [LHsType name]
420 collectSigTysFromPat pat = collect_lpat pat []
421
422 collect_lpat pat acc = collect_pat (unLoc pat) acc
423
424 collect_pat (SigPatIn pat ty)  acc = collect_lpat pat (ty:acc)
425 collect_pat (TypePat ty)       acc = ty:acc
426
427 collect_pat (LazyPat pat)      acc = collect_lpat pat acc
428 collect_pat (AsPat a pat)      acc = collect_lpat pat acc
429 collect_pat (ParPat  pat)      acc = collect_lpat pat acc
430 collect_pat (ListPat pats _)   acc = foldr collect_lpat acc pats
431 collect_pat (PArrPat pats _)   acc = foldr collect_lpat acc pats
432 collect_pat (TuplePat pats _)  acc = foldr collect_lpat acc pats
433 collect_pat (ConPatIn c ps)    acc = foldr collect_lpat acc (hsConArgs ps)
434 collect_pat other              acc = acc        -- Literals, vars, wildcard
435 \end{code}