TcUnify.subFunTys must take type families into account
[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 {-# OPTIONS -w #-}
17 -- The above warning supression flag is a temporary kludge.
18 -- While working on this module you are encouraged to remove it and fix
19 -- any warnings in the module. See
20 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
21 -- for details
22
23 module HsUtils where
24
25 #include "HsVersions.h"
26
27 import HsBinds
28 import HsExpr
29 import HsPat
30 import HsTypes  
31 import HsLit
32
33 import RdrName
34 import Var
35 import Coercion
36 import Type
37 import DataCon
38 import Name
39 import BasicTypes
40 import SrcLoc
41 import FastString
42 import Outputable
43 import Util
44 import Bag
45 \end{code}
46
47
48 %************************************************************************
49 %*                                                                      *
50         Some useful helpers for constructing syntax
51 %*                                                                      *
52 %************************************************************************
53
54 These functions attempt to construct a not-completely-useless SrcSpan
55 from their components, compared with the nl* functions below which
56 just attach noSrcSpan to everything.
57
58 \begin{code}
59 mkHsPar :: LHsExpr id -> LHsExpr id
60 mkHsPar e = L (getLoc e) (HsPar e)
61
62 mkSimpleMatch :: [LPat id] -> LHsExpr id -> LMatch id
63 mkSimpleMatch pats rhs 
64   = L loc $
65     Match pats Nothing (unguardedGRHSs rhs)
66   where
67     loc = case pats of
68                 []      -> getLoc rhs
69                 (pat:_) -> combineSrcSpans (getLoc pat) (getLoc rhs)
70
71 unguardedGRHSs :: LHsExpr id -> GRHSs id
72 unguardedGRHSs rhs = GRHSs (unguardedRHS rhs) emptyLocalBinds
73
74 unguardedRHS :: LHsExpr id -> [LGRHS id]
75 unguardedRHS rhs@(L loc _) = [L loc (GRHS [] rhs)]
76
77 mkHsAppTy :: LHsType name -> LHsType name -> LHsType name
78 mkHsAppTy t1 t2 = addCLoc t1 t2 (HsAppTy t1 t2)
79
80 mkHsApp :: LHsExpr name -> LHsExpr name -> LHsExpr name
81 mkHsApp e1 e2 = addCLoc e1 e2 (HsApp e1 e2)
82
83 nlHsTyApp :: name -> [Type] -> LHsExpr name
84 nlHsTyApp fun_id tys = noLoc (HsWrap (mkWpTyApps tys) (HsVar fun_id))
85
86 mkLHsWrap :: HsWrapper -> LHsExpr id -> LHsExpr id
87 mkLHsWrap co_fn (L loc e) = L loc (mkHsWrap co_fn e)
88
89 mkHsWrap :: HsWrapper -> HsExpr id -> HsExpr id
90 mkHsWrap co_fn e | isIdHsWrapper co_fn = e
91                  | otherwise           = HsWrap co_fn e
92
93 mkHsWrapCoI :: CoercionI -> HsExpr id -> HsExpr id
94 mkHsWrapCoI IdCo     e = e
95 mkHsWrapCoI (ACo co) e = mkHsWrap (WpCo co) e
96
97 coiToHsWrapper :: CoercionI -> HsWrapper
98 coiToHsWrapper IdCo     = idHsWrapper
99 coiToHsWrapper (ACo co) = WpCo co
100
101 mkHsLam :: [LPat id] -> LHsExpr id -> LHsExpr id
102 mkHsLam pats body = mkHsPar (L (getLoc body) (HsLam matches))
103         where
104           matches = mkMatchGroup [mkSimpleMatch pats body]
105
106 mkMatchGroup :: [LMatch id] -> MatchGroup id
107 mkMatchGroup matches = MatchGroup matches placeHolderType
108
109 mkHsDictLet :: LHsBinds Id -> LHsExpr Id -> LHsExpr Id
110 -- Used for the dictionary bindings gotten from TcSimplify
111 -- We make them recursive to be on the safe side
112 mkHsDictLet binds expr 
113   | isEmptyLHsBinds binds = expr
114   | otherwise             = L (getLoc expr) (HsLet (HsValBinds val_binds) expr)
115                           where
116                             val_binds = ValBindsOut [(Recursive, binds)] []
117
118 mkHsConApp :: DataCon -> [Type] -> [HsExpr Id] -> LHsExpr Id
119 -- Used for constructing dictionary terms etc, so no locations 
120 mkHsConApp data_con tys args 
121   = foldl mk_app (nlHsTyApp (dataConWrapId data_con) tys) args
122   where
123     mk_app f a = noLoc (HsApp f (noLoc a))
124
125 mkSimpleHsAlt :: LPat id -> LHsExpr id -> LMatch id
126 -- A simple lambda with a single pattern, no binds, no guards; pre-typechecking
127 mkSimpleHsAlt pat expr 
128   = mkSimpleMatch [pat] expr
129
130 -------------------------------
131 -- These are the bits of syntax that contain rebindable names
132 -- See RnEnv.lookupSyntaxName
133
134 mkHsIntegral   i       = HsIntegral   i  noSyntaxExpr
135 mkHsFractional f       = HsFractional f  noSyntaxExpr
136 mkHsIsString   s       = HsIsString   s  noSyntaxExpr
137 mkHsDo ctxt stmts body = HsDo ctxt stmts body placeHolderType
138
139 mkNPat lit neg     = NPat lit neg noSyntaxExpr
140 mkNPlusKPat id lit = NPlusKPat id lit noSyntaxExpr noSyntaxExpr
141
142 mkExprStmt expr     = ExprStmt expr noSyntaxExpr placeHolderType
143 mkBindStmt pat expr = BindStmt pat expr noSyntaxExpr noSyntaxExpr
144 mkRecStmt stmts     = RecStmt stmts [] [] [] emptyLHsBinds
145
146 -------------------------------
147 --- A useful function for building @OpApps@.  The operator is always a
148 -- variable, and we don't know the fixity yet.
149 mkHsOpApp e1 op e2 = OpApp e1 (noLoc (HsVar op)) (error "mkOpApp:fixity") e2
150
151 mkHsSplice e = HsSplice unqualSplice e
152
153 unqualSplice = mkRdrUnqual (mkVarOccFS FSLIT("splice"))
154                 -- A name (uniquified later) to
155                 -- identify the splice
156
157 mkHsString s = HsString (mkFastString s)
158
159 -------------
160 userHsTyVarBndrs :: [Located name] -> [Located (HsTyVarBndr name)]
161 userHsTyVarBndrs bndrs = [ L loc (UserTyVar v) | L loc v <- bndrs ]
162 \end{code}
163
164
165 %************************************************************************
166 %*                                                                      *
167         Constructing syntax with no location info
168 %*                                                                      *
169 %************************************************************************
170
171 \begin{code}
172 nlHsVar :: id -> LHsExpr id
173 nlHsVar n = noLoc (HsVar n)
174
175 nlHsLit :: HsLit -> LHsExpr id
176 nlHsLit n = noLoc (HsLit n)
177
178 nlVarPat :: id -> LPat id
179 nlVarPat n = noLoc (VarPat n)
180
181 nlLitPat :: HsLit -> LPat id
182 nlLitPat l = noLoc (LitPat l)
183
184 nlHsApp :: LHsExpr id -> LHsExpr id -> LHsExpr id
185 nlHsApp f x = noLoc (HsApp f x)
186
187 nlHsIntLit n = noLoc (HsLit (HsInt n))
188
189 nlHsApps :: id -> [LHsExpr id] -> LHsExpr id
190 nlHsApps f xs = foldl nlHsApp (nlHsVar f) xs
191              
192 nlHsVarApps :: id -> [id] -> LHsExpr id
193 nlHsVarApps f xs = noLoc (foldl mk (HsVar f) (map HsVar xs))
194                  where
195                    mk f a = HsApp (noLoc f) (noLoc a)
196
197 nlConVarPat :: id -> [id] -> LPat id
198 nlConVarPat con vars = nlConPat con (map nlVarPat vars)
199
200 nlInfixConPat :: id -> LPat id -> LPat id -> LPat id
201 nlInfixConPat con l r = noLoc (ConPatIn (noLoc con) (InfixCon l r))
202
203 nlConPat :: id -> [LPat id] -> LPat id
204 nlConPat con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats))
205
206 nlNullaryConPat :: id -> LPat id
207 nlNullaryConPat con = noLoc (ConPatIn (noLoc con) (PrefixCon []))
208
209 nlWildConPat :: DataCon -> LPat RdrName
210 nlWildConPat con = noLoc (ConPatIn (noLoc (getRdrName con))
211                                    (PrefixCon (nOfThem (dataConSourceArity con) nlWildPat)))
212
213 nlTuplePat pats box = noLoc (TuplePat pats box placeHolderType)
214 nlWildPat  = noLoc (WildPat placeHolderType)    -- Pre-typechecking
215
216 nlHsDo :: HsStmtContext Name -> [LStmt id] -> LHsExpr id -> LHsExpr id
217 nlHsDo ctxt stmts body = noLoc (mkHsDo ctxt stmts body)
218
219 nlHsOpApp e1 op e2 = noLoc (mkHsOpApp e1 op e2)
220
221 nlHsLam match           = noLoc (HsLam (mkMatchGroup [match]))
222 nlHsPar e               = noLoc (HsPar e)
223 nlHsIf cond true false  = noLoc (HsIf cond true false)
224 nlHsCase expr matches   = noLoc (HsCase expr (mkMatchGroup matches))
225 nlTuple exprs box       = noLoc (ExplicitTuple exprs box)
226 nlList exprs            = noLoc (ExplicitList placeHolderType exprs)
227
228 nlHsAppTy f t           = noLoc (HsAppTy f t)
229 nlHsTyVar x             = noLoc (HsTyVar x)
230 nlHsFunTy a b           = noLoc (HsFunTy a b)
231
232 nlHsTyConApp tycon tys  = foldl nlHsAppTy (nlHsTyVar tycon) tys
233 \end{code}
234
235
236
237 %************************************************************************
238 %*                                                                      *
239                 Bindings; with a location at the top
240 %*                                                                      *
241 %************************************************************************
242
243 \begin{code}
244 mkFunBind :: Located id -> [LMatch id] -> HsBind id
245 -- Not infix, with place holders for coercion and free vars
246 mkFunBind fn ms = FunBind { fun_id = fn, fun_infix = False, fun_matches = mkMatchGroup ms,
247                             fun_co_fn = idHsWrapper, bind_fvs = placeHolderNames,
248                             fun_tick = Nothing }
249
250
251 mkVarBind :: SrcSpan -> RdrName -> LHsExpr RdrName -> LHsBind RdrName
252 mkVarBind loc var rhs = mk_easy_FunBind loc var [] rhs
253
254 ------------
255 mk_easy_FunBind :: SrcSpan -> RdrName -> [LPat RdrName]
256                 -> LHsExpr RdrName -> LHsBind RdrName
257
258 mk_easy_FunBind loc fun pats expr
259   = L loc $ mkFunBind (L loc fun) [mkMatch pats expr emptyLocalBinds]
260
261 ------------
262 mk_FunBind :: SrcSpan -> RdrName
263            -> [([LPat RdrName], LHsExpr RdrName)]
264            -> LHsBind RdrName
265
266 mk_FunBind loc fun [] = panic "TcGenDeriv:mk_FunBind"
267 mk_FunBind loc fun pats_and_exprs
268   = L loc $ mkFunBind (L loc fun) matches
269   where
270     matches = [mkMatch p e emptyLocalBinds | (p,e) <-pats_and_exprs]
271
272 ------------
273 mkMatch :: [LPat id] -> LHsExpr id -> HsLocalBinds id -> LMatch id
274 mkMatch pats expr binds
275   = noLoc (Match (map paren pats) Nothing 
276                  (GRHSs (unguardedRHS expr) binds))
277   where
278     paren p = case p of
279                 L _ (VarPat _) -> p
280                 L l _          -> L l (ParPat p)
281 \end{code}
282
283
284 %************************************************************************
285 %*                                                                      *
286         Collecting binders from HsBindGroups and HsBinds
287 %*                                                                      *
288 %************************************************************************
289
290 Get all the binders in some HsBindGroups, IN THE ORDER OF APPEARANCE. eg.
291
292 ...
293 where
294   (x, y) = ...
295   f i j  = ...
296   [a, b] = ...
297
298 it should return [x, y, f, a, b] (remember, order important).
299
300 \begin{code}
301 collectLocalBinders :: HsLocalBindsLR idL idR -> [Located idL]
302 collectLocalBinders (HsValBinds val_binds) = collectHsValBinders val_binds
303 collectLocalBinders (HsIPBinds _)   = []
304 collectLocalBinders EmptyLocalBinds = []
305
306 collectHsValBinders :: HsValBindsLR idL idR -> [Located idL]
307 collectHsValBinders (ValBindsIn binds sigs)  = collectHsBindLocatedBinders binds
308 collectHsValBinders (ValBindsOut binds sigs) = foldr collect_one [] binds
309   where
310    collect_one (_,binds) acc = foldrBag (collectAcc . unLoc) acc binds
311
312 collectAcc :: HsBindLR idL idR -> [Located idL] -> [Located idL]
313 collectAcc (PatBind { pat_lhs = p }) acc = collectLocatedPatBinders p ++ acc
314 collectAcc (FunBind { fun_id = f })  acc    = f : acc
315 collectAcc (VarBind { var_id = f })  acc    = noLoc f : acc
316 collectAcc (AbsBinds { abs_exports = dbinds, abs_binds = binds }) acc
317   = [noLoc dp | (_,dp,_,_) <- dbinds] ++ acc
318         -- ++ foldr collectAcc acc binds
319         -- I don't think we want the binders from the nested binds
320         -- The only time we collect binders from a typechecked 
321         -- binding (hence see AbsBinds) is in zonking in TcHsSyn
322
323 collectHsBindBinders :: LHsBindsLR idL idR -> [idL]
324 collectHsBindBinders binds = map unLoc (collectHsBindLocatedBinders binds)
325
326 collectHsBindLocatedBinders :: LHsBindsLR idL idR -> [Located idL]
327 collectHsBindLocatedBinders binds = foldrBag (collectAcc . unLoc) [] binds
328 \end{code}
329
330
331 %************************************************************************
332 %*                                                                      *
333         Getting binders from statements
334 %*                                                                      *
335 %************************************************************************
336
337 \begin{code}
338 collectLStmtsBinders :: [LStmtLR idL idR] -> [Located idL]
339 collectLStmtsBinders = concatMap collectLStmtBinders
340
341 collectStmtsBinders :: [StmtLR idL idR] -> [Located idL]
342 collectStmtsBinders = concatMap collectStmtBinders
343
344 collectLStmtBinders :: LStmtLR idL idR -> [Located idL]
345 collectLStmtBinders = collectStmtBinders . unLoc
346
347 collectStmtBinders :: StmtLR idL idR -> [Located idL]
348   -- Id Binders for a Stmt... [but what about pattern-sig type vars]?
349 collectStmtBinders (BindStmt pat _ _ _) = collectLocatedPatBinders pat
350 collectStmtBinders (LetStmt binds)      = collectLocalBinders binds
351 collectStmtBinders (ExprStmt _ _ _)     = []
352 collectStmtBinders (ParStmt xs)         = collectLStmtsBinders
353                                         $ concatMap fst xs
354 collectStmtBinders (RecStmt ss _ _ _ _) = collectLStmtsBinders ss
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 (BangPat pat)              = collectl pat bndrs
394     go (AsPat a pat)              = a : collectl pat bndrs
395     go (ViewPat exp pat _)     = collectl pat bndrs
396     go (ParPat  pat)              = collectl pat bndrs
397                                   
398     go (ListPat pats _)           = foldr collectl bndrs pats
399     go (PArrPat pats _)           = foldr collectl bndrs pats
400     go (TuplePat pats _ _)        = foldr collectl bndrs pats
401                                   
402     go (ConPatIn c ps)            = foldr collectl bndrs (hsConPatArgs ps)
403     go (ConPatOut {pat_args=ps})  = foldr collectl bndrs (hsConPatArgs ps)
404         -- See Note [Dictionary binders in ConPatOut]
405     go (LitPat _)                 = bndrs
406     go (NPat _ _ _)               = bndrs
407     go (NPlusKPat n _ _ _)        = n : bndrs
408                                   
409     go (SigPatIn pat _)           = collectl pat bndrs
410     go (SigPatOut pat _)          = collectl pat bndrs
411     go (TypePat ty)               = bndrs
412     go (CoPat _ pat ty)           = collectl (noLoc pat) bndrs
413 \end{code}
414
415 Note [Dictionary binders in ConPatOut]
416 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
417 Do *not* gather (a) dictionary and (b) dictionary bindings as binders
418 of a ConPatOut pattern.  For most calls it doesn't matter, because
419 it's pre-typechecker and there are no ConPatOuts.  But it does matter
420 more in the desugarer; for example, DsUtils.mkSelectorBinds uses
421 collectPatBinders.  In a lazy pattern, for example f ~(C x y) = ...,
422 we want to generate bindings for x,y but not for dictionaries bound by
423 C.  (The type checker ensures they would not be used.)
424
425 Desugaring of arrow case expressions needs these bindings (see DsArrows
426 and arrowcase1), but SPJ (Jan 2007) says it's safer for it to use its
427 own pat-binder-collector:
428
429 Here's the problem.  Consider
430
431 data T a where
432    C :: Num a => a -> Int -> T a
433
434 f ~(C (n+1) m) = (n,m)
435
436 Here, the pattern (C (n+1)) binds a hidden dictionary (d::Num a),
437 and *also* uses that dictionary to match the (n+1) pattern.  Yet, the
438 variables bound by the lazy pattern are n,m, *not* the dictionary d.
439 So in mkSelectorBinds in DsUtils, we want just m,n as the variables bound.
440
441 \begin{code}
442 collectSigTysFromPats :: [InPat name] -> [LHsType name]
443 collectSigTysFromPats pats = foldr collect_lpat [] pats
444
445 collectSigTysFromPat :: InPat name -> [LHsType name]
446 collectSigTysFromPat pat = collect_lpat pat []
447
448 collect_lpat pat acc = collect_pat (unLoc pat) acc
449
450 collect_pat (SigPatIn pat ty)   acc = collect_lpat pat (ty:acc)
451 collect_pat (TypePat ty)        acc = ty:acc
452
453 collect_pat (LazyPat pat)       acc = collect_lpat pat acc
454 collect_pat (BangPat pat)       acc = collect_lpat pat acc
455 collect_pat (AsPat a pat)       acc = collect_lpat pat acc
456 collect_pat (ParPat  pat)       acc = collect_lpat pat acc
457 collect_pat (ListPat pats _)    acc = foldr collect_lpat acc pats
458 collect_pat (PArrPat pats _)    acc = foldr collect_lpat acc pats
459 collect_pat (TuplePat pats _ _) acc = foldr collect_lpat acc pats
460 collect_pat (ConPatIn c ps)     acc = foldr collect_lpat acc (hsConPatArgs ps)
461 collect_pat other               acc = acc       -- Literals, vars, wildcard
462 \end{code}