HsUtils.lhs 14.4 KB
Newer Older
1
%
2
% (c) The University of Glasgow, 1992-2006
3
4
%

5
6
7
8
9
10
11
12
13
Here we collect a variety of helper functions that construct or
analyse HsSyn.  All these functions deal with generic HsSyn; functions
which deal with the intantiated versions are located elsewhere:

   Parameterised by	Module
   ----------------     -------------
   RdrName		parser/RdrHsSyn
   Name			rename/RnHsSyn
   Id			typecheck/TcHsSyn	
14
15
16
17
18
19
20
21
22
23
24

\begin{code}
module HsUtils where

#include "HsVersions.h"

import HsBinds
import HsExpr
import HsPat
import HsTypes	
import HsLit
25
import HsDecls
26

27
28
29
30
31
32
import RdrName
import Var
import Type
import DataCon
import Name
import BasicTypes
33
import SrcLoc
34
import FastString
35
import Outputable
36
import Util
37
38
39
40
41
42
import Bag
\end{code}


%************************************************************************
%*									*
43
	Some useful helpers for constructing syntax
44
45
46
%*									*
%************************************************************************

47
48
49
These functions attempt to construct a not-completely-useless SrcSpan
from their components, compared with the nl* functions below which
just attach noSrcSpan to everything.
50
51
52
53
54

\begin{code}
mkHsPar :: LHsExpr id -> LHsExpr id
mkHsPar e = L (getLoc e) (HsPar e)

55
56
mkSimpleMatch :: [LPat id] -> LHsExpr id -> LMatch id
mkSimpleMatch pats rhs 
57
  = L loc $
58
    Match pats Nothing (unguardedGRHSs rhs)
59
60
61
62
  where
    loc = case pats of
		[]      -> getLoc rhs
		(pat:_) -> combineSrcSpans (getLoc pat) (getLoc rhs)
63

64
65
66
unguardedGRHSs :: LHsExpr id -> GRHSs id
unguardedGRHSs rhs = GRHSs (unguardedRHS rhs) emptyLocalBinds

67
unguardedRHS :: LHsExpr id -> [LGRHS id]
68
unguardedRHS rhs@(L loc _) = [L loc (GRHS [] rhs)]
69
70
71
72
73
74
75

mkHsAppTy :: LHsType name -> LHsType name -> LHsType name
mkHsAppTy t1 t2 = addCLoc t1 t2 (HsAppTy t1 t2)

mkHsApp :: LHsExpr name -> LHsExpr name -> LHsExpr name
mkHsApp e1 e2 = addCLoc e1 e2 (HsApp e1 e2)

76
nlHsTyApp :: name -> [Type] -> LHsExpr name
77
nlHsTyApp fun_id tys = noLoc (HsWrap (mkWpTyApps tys) (HsVar fun_id))
78

79
80
mkLHsWrap :: HsWrapper -> LHsExpr id -> LHsExpr id
mkLHsWrap co_fn (L loc e) = L loc (mkHsWrap co_fn e)
81

82
83
84
mkHsWrap :: HsWrapper -> HsExpr id -> HsExpr id
mkHsWrap co_fn e | isIdHsWrapper co_fn = e
		 | 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
90
91
92
	  matches = mkMatchGroup [mkSimpleMatch pats body]

mkMatchGroup :: [LMatch id] -> MatchGroup id
mkMatchGroup matches = MatchGroup matches placeHolderType
93

94
95
96
97
mkHsDictLet :: LHsBinds Id -> LHsExpr Id -> LHsExpr Id
-- Used for the dictionary bindings gotten from TcSimplify
-- We make them recursive to be on the safe side
mkHsDictLet binds expr 
98
  | isEmptyLHsBinds binds = expr
99
100
  | otherwise             = L (getLoc expr) (HsLet (HsValBinds val_binds) expr)
			  where
101
			    val_binds = ValBindsOut [(Recursive, binds)] []
102
103
104
105

mkHsConApp :: DataCon -> [Type] -> [HsExpr Id] -> LHsExpr Id
-- Used for constructing dictinoary terms etc, so no locations 
mkHsConApp data_con tys args 
106
  = foldl mk_app (nlHsTyApp (dataConWrapId data_con) tys) args
107
108
109
110
111
112
  where
    mk_app f a = noLoc (HsApp f (noLoc a))

mkSimpleHsAlt :: LPat id -> LHsExpr id -> LMatch id
-- A simple lambda with a single pattern, no binds, no guards; pre-typechecking
mkSimpleHsAlt pat expr 
113
  = mkSimpleMatch [pat] expr
114

115
-------------------------------
116
117
118
-- These are the bits of syntax that contain rebindable names
-- See RnEnv.lookupSyntaxName

119
120
121
122
123
124
mkHsIntegral   i       = HsIntegral   i  noSyntaxExpr
mkHsFractional f       = HsFractional f  noSyntaxExpr
mkHsDo ctxt stmts body = HsDo ctxt stmts body placeHolderType

mkNPat lit neg     = NPat lit neg noSyntaxExpr placeHolderType
mkNPlusKPat id lit = NPlusKPat id lit noSyntaxExpr noSyntaxExpr
125

126
127
128
129
130
mkExprStmt expr	    = ExprStmt expr noSyntaxExpr placeHolderType
mkBindStmt pat expr = BindStmt pat expr noSyntaxExpr noSyntaxExpr
mkRecStmt stmts	    = RecStmt stmts [] [] [] emptyLHsBinds

-------------------------------
131
132
133
134
135
136
--- A useful function for building @OpApps@.  The operator is always a
-- variable, and we don't know the fixity yet.
mkHsOpApp e1 op e2 = OpApp e1 (noLoc (HsVar op)) (error "mkOpApp:fixity") e2

mkHsSplice e = HsSplice unqualSplice e

137
unqualSplice = mkRdrUnqual (mkVarOccFS FSLIT("splice"))
138
139
140
141
		-- A name (uniquified later) to
		-- identify the splice

mkHsString s = HsString (mkFastString s)
142
143
144
145

-------------
userHsTyVarBndrs :: [Located name] -> [Located (HsTyVarBndr name)]
userHsTyVarBndrs bndrs = [ L loc (UserTyVar v) | L loc v <- bndrs ]
146
147
148
149
150
\end{code}


%************************************************************************
%*									*
151
	Constructing syntax with no location info
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
%*									*
%************************************************************************

\begin{code}
nlHsVar :: id -> LHsExpr id
nlHsVar n = noLoc (HsVar n)

nlHsLit :: HsLit -> LHsExpr id
nlHsLit n = noLoc (HsLit n)

nlVarPat :: id -> LPat id
nlVarPat n = noLoc (VarPat n)

nlLitPat :: HsLit -> LPat id
nlLitPat l = noLoc (LitPat l)

nlHsApp :: LHsExpr id -> LHsExpr id -> LHsExpr id
nlHsApp f x = noLoc (HsApp f x)

nlHsIntLit n = noLoc (HsLit (HsInt n))

nlHsApps :: id -> [LHsExpr id] -> LHsExpr id
nlHsApps f xs = foldl nlHsApp (nlHsVar f) xs
	     
nlHsVarApps :: id -> [id] -> LHsExpr id
nlHsVarApps f xs = noLoc (foldl mk (HsVar f) (map HsVar xs))
		 where
		   mk f a = HsApp (noLoc f) (noLoc a)

nlConVarPat :: id -> [id] -> LPat id
nlConVarPat con vars = nlConPat con (map nlVarPat vars)

nlInfixConPat :: id -> LPat id -> LPat id -> LPat id
nlInfixConPat con l r = noLoc (ConPatIn (noLoc con) (InfixCon l r))

nlConPat :: id -> [LPat id] -> LPat id
nlConPat con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats))

nlNullaryConPat :: id -> LPat id
nlNullaryConPat con = noLoc (ConPatIn (noLoc con) (PrefixCon []))

nlWildConPat :: DataCon -> LPat RdrName
nlWildConPat con = noLoc (ConPatIn (noLoc (getRdrName con))
195
				   (PrefixCon (nOfThem (dataConSourceArity con) nlWildPat)))
196

197
nlTuplePat pats box = noLoc (TuplePat pats box placeHolderType)
198
nlWildPat  = noLoc (WildPat placeHolderType)	-- Pre-typechecking
199

200
201
nlHsDo :: HsStmtContext Name -> [LStmt id] -> LHsExpr id -> LHsExpr id
nlHsDo ctxt stmts body = noLoc (mkHsDo ctxt stmts body)
202
203
204

nlHsOpApp e1 op e2 = noLoc (mkHsOpApp e1 op e2)

205
nlHsLam	match		= noLoc (HsLam (mkMatchGroup [match]))
206
207
nlHsPar e		= noLoc (HsPar e)
nlHsIf cond true false	= noLoc (HsIf cond true false)
208
nlHsCase expr matches	= noLoc (HsCase expr (mkMatchGroup matches))
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
nlTuple exprs box	= noLoc (ExplicitTuple exprs box)
nlList exprs		= noLoc (ExplicitList placeHolderType exprs)

nlHsAppTy f t		= noLoc (HsAppTy f t)
nlHsTyVar x		= noLoc (HsTyVar x)
nlHsFunTy a b		= noLoc (HsFunTy a b)
\end{code}



%************************************************************************
%*									*
		Bindings; with a location at the top
%*									*
%************************************************************************

\begin{code}
226
227
228
mkFunBind :: Located id -> [LMatch id] -> HsBind id
-- Not infix, with place holders for coercion and free vars
mkFunBind fn ms = FunBind { fun_id = fn, fun_infix = False, fun_matches = mkMatchGroup ms,
andy@galois.com's avatar
andy@galois.com committed
229
230
			    fun_co_fn = idHsWrapper, bind_fvs = placeHolderNames,
			    fun_tick = Nothing }
231
232


233
234
mkVarBind :: SrcSpan -> RdrName -> LHsExpr RdrName -> LHsBind RdrName
mkVarBind loc var rhs = mk_easy_FunBind loc var [] rhs
235

236
------------
237
238
mk_easy_FunBind :: SrcSpan -> RdrName -> [LPat RdrName]
		-> LHsExpr RdrName -> LHsBind RdrName
239

240
mk_easy_FunBind loc fun pats expr
241
  = L loc $ mkFunBind (L loc fun) [mkMatch pats expr emptyLocalBinds]
242

243
244
245
246
------------
mk_FunBind :: SrcSpan -> RdrName
	   -> [([LPat RdrName], LHsExpr RdrName)]
	   -> LHsBind RdrName
247
248
249

mk_FunBind loc fun [] = panic "TcGenDeriv:mk_FunBind"
mk_FunBind loc fun pats_and_exprs
250
  = L loc $ mkFunBind (L loc fun) matches
251
  where
252
    matches = [mkMatch p e emptyLocalBinds | (p,e) <-pats_and_exprs]
253
254
255

------------
mkMatch :: [LPat id] -> LHsExpr id -> HsLocalBinds id -> LMatch id
256
257
mkMatch pats expr binds
  = noLoc (Match (map paren pats) Nothing 
258
		 (GRHSs (unguardedRHS expr) binds))
259
260
261
262
263
264
  where
    paren p = case p of
		L _ (VarPat _) -> p
		L l _	       -> L l (ParPat p)
\end{code}

265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282

%************************************************************************
%*									*
	Collecting binders from HsBindGroups and HsBinds
%*									*
%************************************************************************

Get all the binders in some HsBindGroups, IN THE ORDER OF APPEARANCE. eg.

...
where
  (x, y) = ...
  f i j  = ...
  [a, b] = ...

it should return [x, y, f, a, b] (remember, order important).

\begin{code}
283
284
285
286
collectLocalBinders :: HsLocalBinds name -> [Located name]
collectLocalBinders (HsValBinds val_binds) = collectHsValBinders val_binds
collectLocalBinders (HsIPBinds _)   = []
collectLocalBinders EmptyLocalBinds = []
287

288
collectHsValBinders :: HsValBinds name -> [Located name]
289
290
collectHsValBinders (ValBindsIn binds sigs)  = collectHsBindLocatedBinders binds
collectHsValBinders (ValBindsOut binds sigs) = foldr collect_one [] binds
291
292
  where
   collect_one (_,binds) acc = foldrBag (collectAcc . unLoc) acc binds
293
294

collectAcc :: HsBind name -> [Located name] -> [Located name]
295
296
297
298
collectAcc (PatBind { pat_lhs = p }) acc = collectLocatedPatBinders p ++ acc
collectAcc (FunBind { fun_id = f })  acc    = f : acc
collectAcc (VarBind { var_id = f })  acc    = noLoc f : acc
collectAcc (AbsBinds { abs_exports = dbinds, abs_binds = binds }) acc
299
  = [noLoc dp | (_,dp,_,_) <- dbinds] ++ acc
300
301
302
303
304
	-- ++ foldr collectAcc acc binds
	-- I don't think we want the binders from the nested binds
	-- The only time we collect binders from a typechecked 
	-- binding (hence see AbsBinds) is in zonking in TcHsSyn

305
collectHsBindBinders :: LHsBinds name -> [name]
306
307
collectHsBindBinders binds = map unLoc (collectHsBindLocatedBinders binds)

308
collectHsBindLocatedBinders :: LHsBinds name -> [Located name]
309
310
311
312
313
314
315
316
317
318
319
collectHsBindLocatedBinders binds = foldrBag (collectAcc . unLoc) [] binds
\end{code}


%************************************************************************
%*									*
	Getting binders from statements
%*									*
%************************************************************************

\begin{code}
320
321
collectLStmtsBinders :: [LStmt id] -> [Located id]
collectLStmtsBinders = concatMap collectLStmtBinders
322

323
324
325
326
collectStmtsBinders :: [Stmt id] -> [Located id]
collectStmtsBinders = concatMap collectStmtBinders

collectLStmtBinders :: LStmt id -> [Located id]
327
328
329
330
collectLStmtBinders = collectStmtBinders . unLoc

collectStmtBinders :: Stmt id -> [Located id]
  -- Id Binders for a Stmt... [but what about pattern-sig type vars]?
331
collectStmtBinders (BindStmt pat _ _ _) = collectLocatedPatBinders pat
332
collectStmtBinders (LetStmt binds)      = collectLocalBinders binds
333
334
335
collectStmtBinders (ExprStmt _ _ _)   	= []
collectStmtBinders (RecStmt ss _ _ _ _)	= collectLStmtsBinders ss
collectStmtBinders other              	= panic "collectStmtBinders"
336
\end{code}
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365


%************************************************************************
%*									*
%* 	Gathering stuff out of patterns
%*									*
%************************************************************************

This function @collectPatBinders@ works with the ``collectBinders''
functions for @HsBinds@, etc.  The order in which the binders are
collected is important; see @HsBinds.lhs@.

It collects the bounds *value* variables in renamed patterns; type variables
are *not* collected.

\begin{code}
collectPatBinders :: LPat a -> [a]
collectPatBinders pat = map unLoc (collectLocatedPatBinders pat)

collectLocatedPatBinders :: LPat a -> [Located a]
collectLocatedPatBinders pat = collectl pat []

collectPatsBinders :: [LPat a] -> [a]
collectPatsBinders pats = map unLoc (collectLocatedPatsBinders pats)

collectLocatedPatsBinders :: [LPat a] -> [Located a]
collectLocatedPatsBinders pats = foldr collectl [] pats

---------------------
366
367
368
369
370
371
372
373
collectl (L l pat) bndrs
  = go pat
  where
    go (VarPat var) 	   	  = L l var : bndrs
    go (VarPatOut var bs) 	  = L l var : collectHsBindLocatedBinders bs 
				    ++ bndrs
    go (WildPat _)	      	  = bndrs
    go (LazyPat pat)     	  = collectl pat bndrs
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
374
    go (BangPat pat)     	  = collectl pat bndrs
375
376
377
378
379
    go (AsPat a pat)     	  = a : collectl pat bndrs
    go (ParPat  pat)     	  = collectl pat bndrs
				  
    go (ListPat pats _)    	  = foldr collectl bndrs pats
    go (PArrPat pats _)    	  = foldr collectl bndrs pats
380
    go (TuplePat pats _ _)  	  = foldr collectl bndrs pats
381
382
				  
    go (ConPatIn c ps)   	  = foldr collectl bndrs (hsConArgs ps)
383
384
385
    go (ConPatOut { pat_dicts = ds, 
		    pat_binds = bs, pat_args = ps })
				  = map noLoc ds
386
387
388
389
390
391
392
393
394
395
396
				    ++ collectHsBindLocatedBinders bs
				    ++ foldr collectl bndrs (hsConArgs ps)
    go (LitPat _)	      	  = bndrs
    go (NPat _ _ _ _)		  = bndrs
    go (NPlusKPat n _ _ _)        = n : bndrs

    go (SigPatIn pat _)	 	  = collectl pat bndrs
    go (SigPatOut pat _)	  = collectl pat bndrs
    go (TypePat ty)               = bndrs
    go (DictPat ids1 ids2)        = map noLoc ids1 ++ map noLoc ids2
				    ++ bndrs
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
397
    go (CoPat _ pat ty)           = collectl (noLoc pat) bndrs
398
399
400
401
402
403
404
405
406
407
408
\end{code}

\begin{code}
collectSigTysFromPats :: [InPat name] -> [LHsType name]
collectSigTysFromPats pats = foldr collect_lpat [] pats

collectSigTysFromPat :: InPat name -> [LHsType name]
collectSigTysFromPat pat = collect_lpat pat []

collect_lpat pat acc = collect_pat (unLoc pat) acc

409
410
411
412
collect_pat (SigPatIn pat ty)  	acc = collect_lpat pat (ty:acc)
collect_pat (TypePat ty)       	acc = ty:acc

collect_pat (LazyPat pat)      	acc = collect_lpat pat acc
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
413
collect_pat (BangPat pat)      	acc = collect_lpat pat acc
414
415
416
417
418
collect_pat (AsPat a pat)      	acc = collect_lpat pat acc
collect_pat (ParPat  pat)      	acc = collect_lpat pat acc
collect_pat (ListPat pats _)   	acc = foldr collect_lpat acc pats
collect_pat (PArrPat pats _)   	acc = foldr collect_lpat acc pats
collect_pat (TuplePat pats _ _) acc = foldr collect_lpat acc pats
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
419
420
collect_pat (ConPatIn c ps)     acc = foldr collect_lpat acc (hsConArgs ps)
collect_pat other	        acc = acc 	-- Literals, vars, wildcard
421
\end{code}
422
423
424
425
426
427
428
429
430
431
432

%************************************************************************
%*									*
%* 	Getting the main binder name of a top declaration
%*									*
%************************************************************************

\begin{code}

getMainDeclBinder :: HsDecl name -> Maybe name
getMainDeclBinder (TyClD d) = Just (tcdName d)
433
434
435
436
getMainDeclBinder (ValD d)
   = case collectAcc d [] of
        []       -> Nothing   -- see rn003
        (name:_) -> Just (unLoc name)
437
438
439
440
441
442
getMainDeclBinder (SigD d) = sigNameNoLoc d
getMainDeclBinder (ForD (ForeignImport name _ _)) = Just (unLoc name)
getMainDeclBinder (ForD (ForeignExport name _ _)) = Just (unLoc name)
getMainDeclBinder _ = Nothing

\end{code}