Add support for overloaded string literals.
[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 mkHsIsString   s       = HsIsString   s  noSyntaxExpr
122 mkHsDo ctxt stmts body = HsDo ctxt stmts body placeHolderType
123
124 mkNPat lit neg     = NPat lit neg noSyntaxExpr placeHolderType
125 mkNPlusKPat id lit = NPlusKPat id lit noSyntaxExpr noSyntaxExpr
126
127 mkExprStmt expr     = ExprStmt expr noSyntaxExpr placeHolderType
128 mkBindStmt pat expr = BindStmt pat expr noSyntaxExpr noSyntaxExpr
129 mkRecStmt stmts     = RecStmt stmts [] [] [] emptyLHsBinds
130
131 -------------------------------
132 --- A useful function for building @OpApps@.  The operator is always a
133 -- variable, and we don't know the fixity yet.
134 mkHsOpApp e1 op e2 = OpApp e1 (noLoc (HsVar op)) (error "mkOpApp:fixity") e2
135
136 mkHsSplice e = HsSplice unqualSplice e
137
138 unqualSplice = mkRdrUnqual (mkVarOccFS FSLIT("splice"))
139                 -- A name (uniquified later) to
140                 -- identify the splice
141
142 mkHsString s = HsString (mkFastString s)
143
144 -------------
145 userHsTyVarBndrs :: [Located name] -> [Located (HsTyVarBndr name)]
146 userHsTyVarBndrs bndrs = [ L loc (UserTyVar v) | L loc v <- bndrs ]
147 \end{code}
148
149
150 %************************************************************************
151 %*                                                                      *
152         Constructing syntax with no location info
153 %*                                                                      *
154 %************************************************************************
155
156 \begin{code}
157 nlHsVar :: id -> LHsExpr id
158 nlHsVar n = noLoc (HsVar n)
159
160 nlHsLit :: HsLit -> LHsExpr id
161 nlHsLit n = noLoc (HsLit n)
162
163 nlVarPat :: id -> LPat id
164 nlVarPat n = noLoc (VarPat n)
165
166 nlLitPat :: HsLit -> LPat id
167 nlLitPat l = noLoc (LitPat l)
168
169 nlHsApp :: LHsExpr id -> LHsExpr id -> LHsExpr id
170 nlHsApp f x = noLoc (HsApp f x)
171
172 nlHsIntLit n = noLoc (HsLit (HsInt n))
173
174 nlHsApps :: id -> [LHsExpr id] -> LHsExpr id
175 nlHsApps f xs = foldl nlHsApp (nlHsVar f) xs
176              
177 nlHsVarApps :: id -> [id] -> LHsExpr id
178 nlHsVarApps f xs = noLoc (foldl mk (HsVar f) (map HsVar xs))
179                  where
180                    mk f a = HsApp (noLoc f) (noLoc a)
181
182 nlConVarPat :: id -> [id] -> LPat id
183 nlConVarPat con vars = nlConPat con (map nlVarPat vars)
184
185 nlInfixConPat :: id -> LPat id -> LPat id -> LPat id
186 nlInfixConPat con l r = noLoc (ConPatIn (noLoc con) (InfixCon l r))
187
188 nlConPat :: id -> [LPat id] -> LPat id
189 nlConPat con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats))
190
191 nlNullaryConPat :: id -> LPat id
192 nlNullaryConPat con = noLoc (ConPatIn (noLoc con) (PrefixCon []))
193
194 nlWildConPat :: DataCon -> LPat RdrName
195 nlWildConPat con = noLoc (ConPatIn (noLoc (getRdrName con))
196                                    (PrefixCon (nOfThem (dataConSourceArity con) nlWildPat)))
197
198 nlTuplePat pats box = noLoc (TuplePat pats box placeHolderType)
199 nlWildPat  = noLoc (WildPat placeHolderType)    -- Pre-typechecking
200
201 nlHsDo :: HsStmtContext Name -> [LStmt id] -> LHsExpr id -> LHsExpr id
202 nlHsDo ctxt stmts body = noLoc (mkHsDo ctxt stmts body)
203
204 nlHsOpApp e1 op e2 = noLoc (mkHsOpApp e1 op e2)
205
206 nlHsLam match           = noLoc (HsLam (mkMatchGroup [match]))
207 nlHsPar e               = noLoc (HsPar e)
208 nlHsIf cond true false  = noLoc (HsIf cond true false)
209 nlHsCase expr matches   = noLoc (HsCase expr (mkMatchGroup matches))
210 nlTuple exprs box       = noLoc (ExplicitTuple exprs box)
211 nlList exprs            = noLoc (ExplicitList placeHolderType exprs)
212
213 nlHsAppTy f t           = noLoc (HsAppTy f t)
214 nlHsTyVar x             = noLoc (HsTyVar x)
215 nlHsFunTy a b           = noLoc (HsFunTy a b)
216
217 nlHsTyConApp tycon tys  = foldl nlHsAppTy (nlHsTyVar tycon) tys
218 \end{code}
219
220
221
222 %************************************************************************
223 %*                                                                      *
224                 Bindings; with a location at the top
225 %*                                                                      *
226 %************************************************************************
227
228 \begin{code}
229 mkFunBind :: Located id -> [LMatch id] -> HsBind id
230 -- Not infix, with place holders for coercion and free vars
231 mkFunBind fn ms = FunBind { fun_id = fn, fun_infix = False, fun_matches = mkMatchGroup ms,
232                             fun_co_fn = idHsWrapper, bind_fvs = placeHolderNames,
233                             fun_tick = Nothing }
234
235
236 mkVarBind :: SrcSpan -> RdrName -> LHsExpr RdrName -> LHsBind RdrName
237 mkVarBind loc var rhs = mk_easy_FunBind loc var [] rhs
238
239 ------------
240 mk_easy_FunBind :: SrcSpan -> RdrName -> [LPat RdrName]
241                 -> LHsExpr RdrName -> LHsBind RdrName
242
243 mk_easy_FunBind loc fun pats expr
244   = L loc $ mkFunBind (L loc fun) [mkMatch pats expr emptyLocalBinds]
245
246 ------------
247 mk_FunBind :: SrcSpan -> RdrName
248            -> [([LPat RdrName], LHsExpr RdrName)]
249            -> LHsBind RdrName
250
251 mk_FunBind loc fun [] = panic "TcGenDeriv:mk_FunBind"
252 mk_FunBind loc fun pats_and_exprs
253   = L loc $ mkFunBind (L loc fun) matches
254   where
255     matches = [mkMatch p e emptyLocalBinds | (p,e) <-pats_and_exprs]
256
257 ------------
258 mkMatch :: [LPat id] -> LHsExpr id -> HsLocalBinds id -> LMatch id
259 mkMatch pats expr binds
260   = noLoc (Match (map paren pats) Nothing 
261                  (GRHSs (unguardedRHS expr) binds))
262   where
263     paren p = case p of
264                 L _ (VarPat _) -> p
265                 L l _          -> L l (ParPat p)
266 \end{code}
267
268
269 %************************************************************************
270 %*                                                                      *
271         Collecting binders from HsBindGroups and HsBinds
272 %*                                                                      *
273 %************************************************************************
274
275 Get all the binders in some HsBindGroups, IN THE ORDER OF APPEARANCE. eg.
276
277 ...
278 where
279   (x, y) = ...
280   f i j  = ...
281   [a, b] = ...
282
283 it should return [x, y, f, a, b] (remember, order important).
284
285 \begin{code}
286 collectLocalBinders :: HsLocalBinds name -> [Located name]
287 collectLocalBinders (HsValBinds val_binds) = collectHsValBinders val_binds
288 collectLocalBinders (HsIPBinds _)   = []
289 collectLocalBinders EmptyLocalBinds = []
290
291 collectHsValBinders :: HsValBinds name -> [Located name]
292 collectHsValBinders (ValBindsIn binds sigs)  = collectHsBindLocatedBinders binds
293 collectHsValBinders (ValBindsOut binds sigs) = foldr collect_one [] binds
294   where
295    collect_one (_,binds) acc = foldrBag (collectAcc . unLoc) acc binds
296
297 collectAcc :: HsBind name -> [Located name] -> [Located name]
298 collectAcc (PatBind { pat_lhs = p }) acc = collectLocatedPatBinders p ++ acc
299 collectAcc (FunBind { fun_id = f })  acc    = f : acc
300 collectAcc (VarBind { var_id = f })  acc    = noLoc f : acc
301 collectAcc (AbsBinds { abs_exports = dbinds, abs_binds = binds }) acc
302   = [noLoc dp | (_,dp,_,_) <- dbinds] ++ acc
303         -- ++ foldr collectAcc acc binds
304         -- I don't think we want the binders from the nested binds
305         -- The only time we collect binders from a typechecked 
306         -- binding (hence see AbsBinds) is in zonking in TcHsSyn
307
308 collectHsBindBinders :: LHsBinds name -> [name]
309 collectHsBindBinders binds = map unLoc (collectHsBindLocatedBinders binds)
310
311 collectHsBindLocatedBinders :: LHsBinds name -> [Located name]
312 collectHsBindLocatedBinders binds = foldrBag (collectAcc . unLoc) [] binds
313 \end{code}
314
315
316 %************************************************************************
317 %*                                                                      *
318         Getting binders from statements
319 %*                                                                      *
320 %************************************************************************
321
322 \begin{code}
323 collectLStmtsBinders :: [LStmt id] -> [Located id]
324 collectLStmtsBinders = concatMap collectLStmtBinders
325
326 collectStmtsBinders :: [Stmt id] -> [Located id]
327 collectStmtsBinders = concatMap collectStmtBinders
328
329 collectLStmtBinders :: LStmt id -> [Located id]
330 collectLStmtBinders = collectStmtBinders . unLoc
331
332 collectStmtBinders :: Stmt id -> [Located id]
333   -- Id Binders for a Stmt... [but what about pattern-sig type vars]?
334 collectStmtBinders (BindStmt pat _ _ _) = collectLocatedPatBinders pat
335 collectStmtBinders (LetStmt binds)      = collectLocalBinders binds
336 collectStmtBinders (ExprStmt _ _ _)     = []
337 collectStmtBinders (RecStmt ss _ _ _ _) = collectLStmtsBinders ss
338 collectStmtBinders other                = panic "collectStmtBinders"
339 \end{code}
340
341
342 %************************************************************************
343 %*                                                                      *
344 %*      Gathering stuff out of patterns
345 %*                                                                      *
346 %************************************************************************
347
348 This function @collectPatBinders@ works with the ``collectBinders''
349 functions for @HsBinds@, etc.  The order in which the binders are
350 collected is important; see @HsBinds.lhs@.
351
352 It collects the bounds *value* variables in renamed patterns; type variables
353 are *not* collected.
354
355 \begin{code}
356 collectPatBinders :: LPat a -> [a]
357 collectPatBinders pat = map unLoc (collectLocatedPatBinders pat)
358
359 collectLocatedPatBinders :: LPat a -> [Located a]
360 collectLocatedPatBinders pat = collectl pat []
361
362 collectPatsBinders :: [LPat a] -> [a]
363 collectPatsBinders pats = map unLoc (collectLocatedPatsBinders pats)
364
365 collectLocatedPatsBinders :: [LPat a] -> [Located a]
366 collectLocatedPatsBinders pats = foldr collectl [] pats
367
368 ---------------------
369 collectl (L l pat) bndrs
370   = go pat
371   where
372     go (VarPat var)               = L l var : bndrs
373     go (VarPatOut var bs)         = L l var : collectHsBindLocatedBinders bs 
374                                     ++ bndrs
375     go (WildPat _)                = bndrs
376     go (LazyPat pat)              = collectl pat bndrs
377     go (BangPat pat)              = collectl pat bndrs
378     go (AsPat a pat)              = a : collectl pat bndrs
379     go (ParPat  pat)              = collectl pat bndrs
380                                   
381     go (ListPat pats _)           = foldr collectl bndrs pats
382     go (PArrPat pats _)           = foldr collectl bndrs pats
383     go (TuplePat pats _ _)        = foldr collectl bndrs pats
384                                   
385     go (ConPatIn c ps)            = foldr collectl bndrs (hsConArgs ps)
386     go (ConPatOut {pat_args=ps})  = foldr collectl bndrs (hsConArgs ps)
387         -- See Note [Dictionary binders in ConPatOut]
388     go (LitPat _)                 = bndrs
389     go (NPat _ _ _ _)             = bndrs
390     go (NPlusKPat n _ _ _)        = n : bndrs
391                                   
392     go (SigPatIn pat _)           = collectl pat bndrs
393     go (SigPatOut pat _)          = collectl pat bndrs
394     go (TypePat ty)               = bndrs
395     go (DictPat ids1 ids2)        = map noLoc ids1 ++ map noLoc ids2
396                                     ++ bndrs
397     go (CoPat _ pat ty)           = collectl (noLoc pat) bndrs
398 \end{code}
399
400 Note [Dictionary binders in ConPatOut]
401 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
402 Do *not* gather (a) dictionary and (b) dictionary bindings as binders
403 of a ConPatOut pattern.  For most calls it doesn't matter, because
404 it's pre-typechecker and there are no ConPatOuts.  But it does matter
405 more in the desugarer; for example, DsUtils.mkSelectorBinds uses
406 collectPatBinders.  In a lazy pattern, for example f ~(C x y) = ...,
407 we want to generate bindings for x,y but not for dictionaries bound by
408 C.  (The type checker ensures they would not be used.)
409
410 \begin{code}
411 collectSigTysFromPats :: [InPat name] -> [LHsType name]
412 collectSigTysFromPats pats = foldr collect_lpat [] pats
413
414 collectSigTysFromPat :: InPat name -> [LHsType name]
415 collectSigTysFromPat pat = collect_lpat pat []
416
417 collect_lpat pat acc = collect_pat (unLoc pat) acc
418
419 collect_pat (SigPatIn pat ty)   acc = collect_lpat pat (ty:acc)
420 collect_pat (TypePat ty)        acc = ty:acc
421
422 collect_pat (LazyPat pat)       acc = collect_lpat pat acc
423 collect_pat (BangPat pat)       acc = collect_lpat pat acc
424 collect_pat (AsPat a pat)       acc = collect_lpat pat acc
425 collect_pat (ParPat  pat)       acc = collect_lpat pat acc
426 collect_pat (ListPat pats _)    acc = foldr collect_lpat acc pats
427 collect_pat (PArrPat pats _)    acc = foldr collect_lpat acc pats
428 collect_pat (TuplePat pats _ _) acc = foldr collect_lpat acc pats
429 collect_pat (ConPatIn c ps)     acc = foldr collect_lpat acc (hsConArgs ps)
430 collect_pat other               acc = acc       -- Literals, vars, wildcard
431 \end{code}