RnExpr.lhs 44.2 KB
Newer Older
1
%
2
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3
4
5
6
7
%
\section[RnExpr]{Renaming of expressions}

Basically dependency analysis.

8
Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes.  In
9
10
11
12
13
general, all of these functions return a renamed thing, and a set of
free variables.

\begin{code}
module RnExpr (
14
	rnLExpr, rnExpr, rnStmts
15
16
   ) where

17
18
#include "HsVersions.h"

19
20
21
22
#ifdef GHCI
import {-# SOURCE #-} TcSplice( runQuasiQuoteExpr )
#endif 	/* GHCI */

23
import RnSource  ( rnSrcDecls, findSplice )
24
import RnBinds   ( rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS,
25
                   rnMatchGroup, makeMiniFixityEnv) 
26
import HsSyn
27
import TcRnMonad
28
import TcEnv		( thRnBrack )
29
import RnEnv
30
import RnTypes		( rnHsTypeFVs, rnSplice, checkTH,
31
			  mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec)
Ian Lynagh's avatar
Ian Lynagh committed
32
import RnPat
33
import DynFlags
34
import BasicTypes	( FixityDirection(..) )
35
import PrelNames
mnislaih's avatar
mnislaih committed
36

Ian Lynagh's avatar
Ian Lynagh committed
37
import Name
38
import NameSet
Ian Lynagh's avatar
Ian Lynagh committed
39
import RdrName
Simon Marlow's avatar
Simon Marlow committed
40
import LoadIface	( loadInterfaceForName )
Ian Lynagh's avatar
Ian Lynagh committed
41
import UniqSet
Ian Lynagh's avatar
Ian Lynagh committed
42
import Data.List
43
import Util		( isSingleton )
44
import ListSetOps	( removeDups )
sof's avatar
sof committed
45
import Outputable
Ian Lynagh's avatar
Ian Lynagh committed
46
import SrcLoc
47
import FastString
48
import Control.Monad
49
50
51
\end{code}


Ian Lynagh's avatar
Ian Lynagh committed
52
53
54
55
56
57
58
59
60
\begin{code}
-- XXX
thenM :: Monad a => a b -> (b -> a c) -> a c
thenM = (>>=)

thenM_ :: Monad a => a b -> a c -> a c
thenM_ = (>>)
\end{code}

61
62
63
64
65
66
67
%************************************************************************
%*									*
\subsubsection{Expressions}
%*									*
%************************************************************************

\begin{code}
68
rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
sof's avatar
sof committed
69
70
rnExprs ls = rnExprs' ls emptyUniqSet
 where
71
  rnExprs' [] acc = return ([], acc)
sof's avatar
sof committed
72
  rnExprs' (expr:exprs) acc
73
   = rnLExpr expr 	        `thenM` \ (expr', fvExpr) ->
sof's avatar
sof committed
74
75
76
77

	-- Now we do a "seq" on the free vars because typically it's small
	-- or empty, especially in very long lists of constants
    let
78
	acc' = acc `plusFV` fvExpr
sof's avatar
sof committed
79
    in
80
    acc' `seq` rnExprs' exprs acc' `thenM` \ (exprs', fvExprs) ->
81
    return (expr':exprs', fvExprs)
82
83
\end{code}

84
Variables. We look up the variable and return the resulting name. 
85
86

\begin{code}
87
88
89
90
rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
rnLExpr = wrapLocFstM rnExpr

rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
91

92
93
94
95
96
97
98
99
100
101
102
finishHsVar :: Name -> RnM (HsExpr Name, FreeVars)
-- Separated from rnExpr because it's also used
-- when renaming infix expressions
-- See Note [Adding the implicit parameter to 'assert']
finishHsVar name 
 = do { ignore_asserts <- doptM Opt_IgnoreAsserts
      ; if ignore_asserts || not (name `hasKey` assertIdKey)
	then return (HsVar name, unitFV name)
	else do { e <- mkAssertErrorExpr
		; return (e, unitFV name) } }

103
rnExpr (HsVar v)
104
105
  = do name <- lookupOccRn v
       finishHsVar name
106

107
rnExpr (HsIPVar v)
108
  = newIPNameRn v		`thenM` \ name ->
109
    return (HsIPVar name, emptyFVs)
110

111
112
rnExpr (HsLit lit@(HsString s))
  = do {
113
         opt_OverloadedStrings <- xoptM Opt_OverloadedStrings
114
       ; if opt_OverloadedStrings then
115
            rnExpr (HsOverLit (mkHsIsString s placeHolderType))
116
117
	 else -- Same as below
	    rnLit lit		`thenM_`
118
            return (HsLit lit, emptyFVs)
119
120
       }

121
rnExpr (HsLit lit) 
122
  = rnLit lit		`thenM_`
123
    return (HsLit lit, emptyFVs)
124

125
rnExpr (HsOverLit lit) 
126
  = rnOverLit lit		`thenM` \ (lit', fvs) ->
127
    return (HsOverLit lit', fvs)
128

129
rnExpr (HsApp fun arg)
130
131
  = rnLExpr fun		`thenM` \ (fun',fvFun) ->
    rnLExpr arg		`thenM` \ (arg',fvArg) ->
132
    return (HsApp fun' arg', fvFun `plusFV` fvArg)
133

134
135
rnExpr (OpApp e1 (L op_loc (HsVar op_rdr)) _ e2)
  = do  { (e1', fv_e1) <- rnLExpr e1
136
137
138
139
140
	; (e2', fv_e2) <- rnLExpr e2
	; op_name <- setSrcSpan op_loc (lookupOccRn op_rdr)
  	; (op', fv_op) <- finishHsVar op_name
		-- NB: op' is usually just a variable, but might be
		--     an applicatoin (assert "Foo.hs:47")
sof's avatar
sof committed
141
142
	-- Deal with fixity
	-- When renaming code synthesised from "deriving" declarations
143
144
145
	-- we used to avoid fixity stuff, but we can't easily tell any
	-- more, so I've removed the test.  Adding HsPars in TcGenDeriv
	-- should prevent bad things happening.
146
147
148
	; fixity <- lookupFixityRn op_name
	; final_e <- mkOpAppRn e1' (L op_loc op') fixity e2'
	; return (final_e, fv_e1 `plusFV` fv_op `plusFV` fv_e2) }
149
150
151
152
rnExpr (OpApp _ other_op _ _)
  = failWith (vcat [ hang (ptext (sLit "Operator application with a non-variable operator:"))
                        2 (ppr other_op)
                   , ptext (sLit "(Probably resulting from a Template Haskell splice)") ])
153

154
rnExpr (NegApp e _)
155
  = rnLExpr e			`thenM` \ (e', fv_e) ->
156
157
    lookupSyntaxName negateName	`thenM` \ (neg_name, fv_neg) ->
    mkNegAppRn e' neg_name	`thenM` \ final_e ->
158
    return (final_e, fv_e `plusFV` fv_neg)
159

160
------------------------------------------
161
-- Template Haskell extensions
162
163
-- Don't ifdef-GHCI them because we want to fail gracefully
-- (not with an rnExpr crash) in a stage-1 compiler.
164
165
rnExpr e@(HsBracket br_body)
  = checkTH e "bracket"		`thenM_`
166
    rnBracket br_body		`thenM` \ (body', fvs_e) ->
167
    return (HsBracket body', fvs_e)
168

Ian Lynagh's avatar
Ian Lynagh committed
169
rnExpr (HsSpliceE splice)
170
  = rnSplice splice 		`thenM` \ (splice', fvs) ->
171
    return (HsSpliceE splice', fvs)
172

173
174
175
#ifndef GHCI
rnExpr e@(HsQuasiQuoteE _) = pprPanic "Cant do quasiquotation without GHCi" (ppr e)
#else
Ian Lynagh's avatar
Ian Lynagh committed
176
rnExpr (HsQuasiQuoteE qq)
177
178
  = runQuasiQuoteExpr qq	`thenM` \ (L _ expr') ->
    rnExpr expr'
179
180
#endif 	/* GHCI */

181
182
183
184
185
186
187
188
189
190
---------------------------------------------
--	Sections
-- See Note [Parsing sections] in Parser.y.pp
rnExpr (HsPar (L loc (section@(SectionL {}))))
  = do	{ (section', fvs) <- rnSection section
	; return (HsPar (L loc section'), fvs) }

rnExpr (HsPar (L loc (section@(SectionR {}))))
  = do	{ (section', fvs) <- rnSection section
	; return (HsPar (L loc section'), fvs) }
191

192
193
194
rnExpr (HsPar e)
  = do	{ (e', fvs_e) <- rnLExpr e
	; return (HsPar e', fvs_e) }
195

196
197
198
199
200
201
rnExpr expr@(SectionL {})
  = do	{ addErr (sectionErr expr); rnSection expr }
rnExpr expr@(SectionR {})
  = do	{ addErr (sectionErr expr); rnSection expr }

---------------------------------------------
202
rnExpr (HsCoreAnn ann expr)
203
  = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
204
    return (HsCoreAnn ann expr', fvs_expr)
205

206
rnExpr (HsSCC lbl expr)
207
  = rnLExpr expr	 	`thenM` \ (expr', fvs_expr) ->
208
    return (HsSCC lbl expr', fvs_expr)
andy@galois.com's avatar
andy@galois.com committed
209
210
rnExpr (HsTickPragma info expr)
  = rnLExpr expr	 	`thenM` \ (expr', fvs_expr) ->
211
    return (HsTickPragma info expr', fvs_expr)
212

213
214
rnExpr (HsLam matches)
  = rnMatchGroup LambdaExpr matches	`thenM` \ (matches', fvMatch) ->
215
    return (HsLam matches', fvMatch)
216
217

rnExpr (HsCase expr matches)
218
  = rnLExpr expr		 	`thenM` \ (new_expr, e_fvs) ->
219
    rnMatchGroup CaseAlt matches	`thenM` \ (new_matches, ms_fvs) ->
220
    return (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
221
222

rnExpr (HsLet binds expr)
223
  = rnLocalBindsAndThen binds		$ \ binds' ->
224
    rnLExpr expr			 `thenM` \ (expr',fvExpr) ->
225
    return (HsLet binds' expr', fvExpr)
226

Ian Lynagh's avatar
Ian Lynagh committed
227
rnExpr (HsDo do_or_lc stmts body _)
228
  = do  { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $ \ _ ->
229
230
				    rnLExpr body
	; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
231

232
rnExpr (ExplicitList _ exps)
233
  = rnExprs exps		 	`thenM` \ (exps', fvs) ->
234
    return  (ExplicitList placeHolderType exps', fvs)
235

chak's avatar
chak committed
236
rnExpr (ExplicitPArr _ exps)
237
  = rnExprs exps		 	`thenM` \ (exps', fvs) ->
238
    return  (ExplicitPArr placeHolderType exps', fvs)
chak's avatar
chak committed
239

240
241
242
243
244
245
246
247
rnExpr (ExplicitTuple tup_args boxity)
  = do { checkTupleSection tup_args
       ; checkTupSize (length tup_args)
       ; (tup_args', fvs) <- mapAndUnzipM rnTupArg tup_args
       ; return (ExplicitTuple tup_args' boxity, plusFVs fvs) }
  where
    rnTupArg (Present e) = do { (e',fvs) <- rnLExpr e; return (Present e', fvs) }
    rnTupArg (Missing _) = return (Missing placeHolderType, emptyFVs)
248

249
250
rnExpr (RecordCon con_id _ rbinds)
  = do	{ conname <- lookupLocatedOccRn con_id
251
	; (rbinds', fvRbinds) <- rnHsRecBinds (HsRecFieldCon (unLoc conname)) rbinds
252
253
	; return (RecordCon conname noPostTcExpr rbinds', 
		  fvRbinds `addOneFV` unLoc conname) }
254

255
256
rnExpr (RecordUpd expr rbinds _ _ _)
  = do	{ (expr', fvExpr) <- rnLExpr expr
257
	; (rbinds', fvRbinds) <- rnHsRecBinds HsRecFieldUpd rbinds
258
259
	; return (RecordUpd expr' rbinds' [] [] [], 
		  fvExpr `plusFV` fvRbinds) }
260
261

rnExpr (ExprWithTySig expr pty)
262
263
264
265
  = do	{ (pty', fvTy) <- rnHsTypeFVs doc pty
	; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
		  	     rnLExpr expr
	; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
266
267
  where 
    doc = text "In an expression type signature"
268

269
270
rnExpr (HsIf _ p b1 b2)
  = do { (p', fvP) <- rnLExpr p
271
272
273
274
       ; (b1', fvB1) <- rnLExpr b1
       ; (b2', fvB2) <- rnLExpr b2
       ; (mb_ite, fvITE) <- lookupIfThenElse
       ; return (HsIf mb_ite p' b1' b2', plusFVs [fvITE, fvP, fvB1, fvB2]) }
275

276
rnExpr (HsType a)
277
  = rnHsTypeFVs doc a	`thenM` \ (t, fvT) -> 
278
    return (HsType t, fvT)
279
  where 
280
    doc = text "In a type argument"
281

282
rnExpr (ArithSeq _ seq)
283
  = rnArithSeq seq	 `thenM` \ (new_seq, fvs) ->
284
    return (ArithSeq noPostTcExpr new_seq, fvs)
chak's avatar
chak committed
285

286
rnExpr (PArrSeq _ seq)
287
  = rnArithSeq seq	 `thenM` \ (new_seq, fvs) ->
288
    return (PArrSeq noPostTcExpr new_seq, fvs)
289
\end{code}
290

291
292
293
294
295
These three are pattern syntax appearing in expressions.
Since all the symbols are reservedops we can simply reject them.
We return a (bogus) EWildPat in each case.

\begin{code}
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
296
297
rnExpr e@EWildPat      = patSynErr e
rnExpr e@(EAsPat {})   = patSynErr e
298
rnExpr e@(EViewPat {}) = patSynErr e
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
299
rnExpr e@(ELazyPat {}) = patSynErr e
300
301
\end{code}

302
303
304
305
306
307
308
%************************************************************************
%*									*
	Arrow notation
%*									*
%************************************************************************

\begin{code}
309
rnExpr (HsProc pat body)
ross's avatar
ross committed
310
  = newArrowScope $
311
    rnPat ProcExpr pat $ \ pat' ->
312
    rnCmdTop body	         `thenM` \ (body',fvBody) ->
313
    return (HsProc pat' body', fvBody)
314

315
rnExpr (HsArrApp arrow arg _ ho rtl)
ross's avatar
ross committed
316
317
  = select_arrow_scope (rnLExpr arrow)	`thenM` \ (arrow',fvArrow) ->
    rnLExpr arg				`thenM` \ (arg',fvArg) ->
318
    return (HsArrApp arrow' arg' placeHolderType ho rtl,
319
	     fvArrow `plusFV` fvArg)
ross's avatar
ross committed
320
321
322
323
  where
    select_arrow_scope tc = case ho of
        HsHigherOrderApp -> tc
        HsFirstOrderApp  -> escapeArrowScope tc
324
325

-- infix form
326
rnExpr (HsArrForm op (Just _) [arg1, arg2])
ross's avatar
ross committed
327
  = escapeArrowScope (rnLExpr op)
328
329
			`thenM` \ (op',fv_op) ->
    let L _ (HsVar op_name) = op' in
330
331
332
333
334
335
336
337
    rnCmdTop arg1	`thenM` \ (arg1',fv_arg1) ->
    rnCmdTop arg2	`thenM` \ (arg2',fv_arg2) ->

	-- Deal with fixity

    lookupFixityRn op_name		`thenM` \ fixity ->
    mkOpFormRn arg1' op' fixity arg2'	`thenM` \ final_e -> 

338
    return (final_e,
339
340
	      fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)

341
rnExpr (HsArrForm op fixity cmds)
ross's avatar
ross committed
342
343
  = escapeArrowScope (rnLExpr op)	`thenM` \ (op',fvOp) ->
    rnCmdArgs cmds			`thenM` \ (cmds',fvCmds) ->
344
    return (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
345

346
rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
347
	-- HsWrap
348

349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
----------------------
-- See Note [Parsing sections] in Parser.y.pp
rnSection :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
rnSection section@(SectionR op expr)
  = do	{ (op', fvs_op)     <- rnLExpr op
	; (expr', fvs_expr) <- rnLExpr expr
	; checkSectionPrec InfixR section op' expr'
	; return (SectionR op' expr', fvs_op `plusFV` fvs_expr) }

rnSection section@(SectionL expr op)
  = do	{ (expr', fvs_expr) <- rnLExpr expr
	; (op', fvs_op)     <- rnLExpr op
	; checkSectionPrec InfixL section op' expr'
	; return (SectionL expr' op', fvs_op `plusFV` fvs_expr) }

rnSection other = pprPanic "rnSection" (ppr other)
\end{code}
366

367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
%************************************************************************
%*									*
	Records
%*									*
%************************************************************************

\begin{code}
rnHsRecBinds :: HsRecFieldContext -> HsRecordBinds RdrName
             -> RnM (HsRecordBinds Name, FreeVars)
rnHsRecBinds ctxt rec_binds@(HsRecFields { rec_dotdot = dd })
  = do { (flds, fvs) <- rnHsRecFields1 ctxt HsVar rec_binds
       ; (flds', fvss) <- mapAndUnzipM rn_field flds
       ; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }, 
                 fvs `plusFV` plusFVs fvss) }
  where 
    rn_field fld = do { (arg', fvs) <- rnLExpr (hsRecFieldArg fld)
                      ; return (fld { hsRecFieldArg = arg' }, fvs) }
\end{code}


387
388
389
390
391
392
393
%************************************************************************
%*									*
	Arrow commands
%*									*
%************************************************************************

\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
394
rnCmdArgs :: [LHsCmdTop RdrName] -> RnM ([LHsCmdTop Name], FreeVars)
395
rnCmdArgs [] = return ([], emptyFVs)
396
397
398
rnCmdArgs (arg:args)
  = rnCmdTop arg	`thenM` \ (arg',fvArg) ->
    rnCmdArgs args	`thenM` \ (args',fvArgs) ->
399
    return (arg':args', fvArg `plusFV` fvArgs)
400

Ian Lynagh's avatar
Ian Lynagh committed
401
rnCmdTop :: LHsCmdTop RdrName -> RnM (LHsCmdTop Name, FreeVars)
402
403
404
405
406
rnCmdTop = wrapLocFstM rnCmdTop'
 where
  rnCmdTop' (HsCmdTop cmd _ _ _) 
   = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
     let 
407
	cmd_names = [arrAName, composeAName, firstAName] ++
408
409
		    nameSetToList (methodNamesCmd (unLoc cmd'))
     in
410
	-- Generate the rebindable syntax for the monad
411
     lookupSyntaxTable cmd_names	`thenM` \ (cmd_names', cmd_fvs) ->
412

413
     return (HsCmdTop cmd' [] placeHolderType cmd_names', 
414
415
416
417
418
	     fvCmd `plusFV` cmd_fvs)

---------------------------------------------------
-- convert OpApp's in a command context to HsArrForm's

419
420
421
convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
convertOpFormsLCmd = fmap convertOpFormsCmd

422
423
convertOpFormsCmd :: HsCmd id -> HsCmd id

424
convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
425
426
427
convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
convertOpFormsCmd (OpApp c1 op fixity c2)
  = let
428
429
	arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
	arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
430
    in
431
    HsArrForm op (Just fixity) [arg1, arg2]
432

433
convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
434

435
convertOpFormsCmd (HsCase exp matches)
436
  = HsCase exp (convertOpFormsMatch matches)
437

438
439
convertOpFormsCmd (HsIf f exp c1 c2)
  = HsIf f exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
440
441

convertOpFormsCmd (HsLet binds cmd)
442
  = HsLet binds (convertOpFormsLCmd cmd)
443

444
445
446
convertOpFormsCmd (HsDo ctxt stmts body ty)
  = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
	      (convertOpFormsLCmd body) ty
447
448
449
450
451
452

-- Anything else is unchanged.  This includes HsArrForm (already done),
-- things with no sub-commands, and illegal commands (which will be
-- caught by the type checker)
convertOpFormsCmd c = c

Ian Lynagh's avatar
Ian Lynagh committed
453
convertOpFormsStmt :: StmtLR id id -> StmtLR id id
454
455
456
457
convertOpFormsStmt (BindStmt pat cmd _ _)
  = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
convertOpFormsStmt (ExprStmt cmd _ _)
  = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
458
459
convertOpFormsStmt stmt@(RecStmt { recS_stmts = stmts })
  = stmt { recS_stmts = map (fmap convertOpFormsStmt) stmts }
460
461
convertOpFormsStmt stmt = stmt

Ian Lynagh's avatar
Ian Lynagh committed
462
convertOpFormsMatch :: MatchGroup id -> MatchGroup id
463
464
convertOpFormsMatch (MatchGroup ms ty)
  = MatchGroup (map (fmap convert) ms) ty
465
466
 where convert (Match pat mty grhss)
	  = Match pat mty (convertOpFormsGRHSs grhss)
467

Ian Lynagh's avatar
Ian Lynagh committed
468
convertOpFormsGRHSs :: GRHSs id -> GRHSs id
469
470
convertOpFormsGRHSs (GRHSs grhss binds)
  = GRHSs (map convertOpFormsGRHS grhss) binds
471

Ian Lynagh's avatar
Ian Lynagh committed
472
convertOpFormsGRHS :: Located (GRHS id) -> Located (GRHS id)
473
convertOpFormsGRHS = fmap convert
474
475
 where 
   convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
476
477
478
479
480
481

---------------------------------------------------
type CmdNeeds = FreeVars	-- Only inhabitants are 
				-- 	appAName, choiceAName, loopAName

-- find what methods the Cmd needs (loop, choice, apply)
482
483
484
methodNamesLCmd :: LHsCmd Name -> CmdNeeds
methodNamesLCmd = methodNamesCmd . unLoc

485
486
methodNamesCmd :: HsCmd Name -> CmdNeeds

Ian Lynagh's avatar
Ian Lynagh committed
487
methodNamesCmd (HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
488
  = emptyFVs
Ian Lynagh's avatar
Ian Lynagh committed
489
methodNamesCmd (HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
490
  = unitFV appAName
Ian Lynagh's avatar
Ian Lynagh committed
491
methodNamesCmd (HsArrForm {}) = emptyFVs
492

493
methodNamesCmd (HsPar c) = methodNamesLCmd c
494

495
methodNamesCmd (HsIf _ _ c1 c2)
496
  = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
497

Ian Lynagh's avatar
Ian Lynagh committed
498
methodNamesCmd (HsLet _ c) = methodNamesLCmd c
499

Ian Lynagh's avatar
Ian Lynagh committed
500
methodNamesCmd (HsDo _ stmts body _) 
501
  = methodNamesStmts stmts `plusFV` methodNamesLCmd body
502

Ian Lynagh's avatar
Ian Lynagh committed
503
methodNamesCmd (HsApp c _) = methodNamesLCmd c
ross's avatar
ross committed
504

505
506
methodNamesCmd (HsLam match) = methodNamesMatch match

Ian Lynagh's avatar
Ian Lynagh committed
507
methodNamesCmd (HsCase _ matches)
508
  = methodNamesMatch matches `addOneFV` choiceAName
509

Ian Lynagh's avatar
Ian Lynagh committed
510
methodNamesCmd _ = emptyFVs
511
512
513
514
515
   -- Other forms can't occur in commands, but it's not convenient 
   -- to error here so we just do what's convenient.
   -- The type checker will complain later

---------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
516
methodNamesMatch :: MatchGroup Name -> FreeVars
517
methodNamesMatch (MatchGroup ms _)
518
519
  = plusFVs (map do_one ms)
 where 
Ian Lynagh's avatar
Ian Lynagh committed
520
    do_one (L _ (Match _ _ grhss)) = methodNamesGRHSs grhss
521
522

-------------------------------------------------
523
-- gaw 2004
Ian Lynagh's avatar
Ian Lynagh committed
524
525
methodNamesGRHSs :: GRHSs Name -> FreeVars
methodNamesGRHSs (GRHSs grhss _) = plusFVs (map methodNamesGRHS grhss)
526
527

-------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
528
529
530

methodNamesGRHS :: Located (GRHS Name) -> CmdNeeds
methodNamesGRHS (L _ (GRHS _ rhs)) = methodNamesLCmd rhs
531
532

---------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
533
methodNamesStmts :: [Located (StmtLR Name Name)] -> FreeVars
534
methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
535
536

---------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
537
methodNamesLStmt :: Located (StmtLR Name Name) -> FreeVars
538
539
methodNamesLStmt = methodNamesStmt . unLoc

Ian Lynagh's avatar
Ian Lynagh committed
540
methodNamesStmt :: StmtLR Name Name -> FreeVars
541
542
543
544
545
methodNamesStmt (ExprStmt cmd _ _)               = methodNamesLCmd cmd
methodNamesStmt (BindStmt _ cmd _ _)             = methodNamesLCmd cmd
methodNamesStmt (RecStmt { recS_stmts = stmts }) = methodNamesStmts stmts `addOneFV` loopAName
methodNamesStmt (LetStmt _)                      = emptyFVs
methodNamesStmt (ParStmt _)                      = emptyFVs
546
547
methodNamesStmt (TransformStmt {})               = emptyFVs
methodNamesStmt (GroupStmt {})                   = emptyFVs
548
   -- ParStmt, TransformStmt and GroupStmt can't occur in commands, but it's not convenient to error 
549
550
551
552
   -- here so we just do what's convenient
\end{code}


553
554
555
556
557
558
559
%************************************************************************
%*									*
	Arithmetic sequences
%*									*
%************************************************************************

\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
560
rnArithSeq :: ArithSeqInfo RdrName -> RnM (ArithSeqInfo Name, FreeVars)
561
rnArithSeq (From expr)
562
 = rnLExpr expr 	`thenM` \ (expr', fvExpr) ->
563
   return (From expr', fvExpr)
564
565

rnArithSeq (FromThen expr1 expr2)
566
567
 = rnLExpr expr1 	`thenM` \ (expr1', fvExpr1) ->
   rnLExpr expr2	`thenM` \ (expr2', fvExpr2) ->
568
   return (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
569
570

rnArithSeq (FromTo expr1 expr2)
571
572
 = rnLExpr expr1	`thenM` \ (expr1', fvExpr1) ->
   rnLExpr expr2	`thenM` \ (expr2', fvExpr2) ->
573
   return (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
574
575

rnArithSeq (FromThenTo expr1 expr2 expr3)
576
577
578
 = rnLExpr expr1	`thenM` \ (expr1', fvExpr1) ->
   rnLExpr expr2	`thenM` \ (expr2', fvExpr2) ->
   rnLExpr expr3	`thenM` \ (expr3', fvExpr3) ->
579
   return (FromThenTo expr1' expr2' expr3',
580
581
	    plusFVs [fvExpr1, fvExpr2, fvExpr3])
\end{code}
582

583
584
585
586
587
%************************************************************************
%*									*
	Template Haskell brackets
%*									*
%************************************************************************
588

589
\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
590
rnBracket :: HsBracket RdrName -> RnM (HsBracket Name, FreeVars)
591
rnBracket (VarBr n) = do { name <- lookupOccRn n
592
			 ; this_mod <- getModule
593
			 ; unless (nameIsLocalOrFrom this_mod name) $	-- Reason: deprecation checking asumes the
594
			   do { _ <- loadInterfaceForName msg name	-- home interface is loaded, and this is the
595
			      ; return () }				-- only way that is going to happen
596
			 ; return (VarBr name, unitFV name) }
597
		    where
Ian Lynagh's avatar
Ian Lynagh committed
598
		      msg = ptext (sLit "Need interface for Template Haskell quoted Name")
599
600
601

rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
			 ; return (ExpBr e', fvs) }
602

603
604
rnBracket (PatBr p) = rnPat ThPatQuote p $ \ p' -> return (PatBr p', emptyFVs)

605
606
rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
			 ; return (TypBr t', fvs) }
607
		    where
Ian Lynagh's avatar
Ian Lynagh committed
608
		      doc = ptext (sLit "In a Template-Haskell quoted type")
609

610
611
612
613
rnBracket (DecBrL decls) 
  = do { (group, mb_splice) <- findSplice decls
       ; case mb_splice of
           Nothing -> return ()
614
           Just (SpliceDecl (L loc _) _, _)  
615
616
617
618
619
620
              -> setSrcSpan loc $
                 addErr (ptext (sLit "Declaration splices are not permitted inside declaration brackets"))
		-- Why not?  See Section 7.3 of the TH paper.  

       ; gbl_env  <- getGblEnv
       ; let new_gbl_env = gbl_env { tcg_dus = emptyDUs }
621
622
623
624
625
	      		  -- The emptyDUs is so that we just collect uses for this
                          -- group alone in the call to rnSrcDecls below
       ; (tcg_env, group') <- setGblEnv new_gbl_env $ 
       	 	   	      setStage thRnBrack $
			      rnSrcDecls group      
626

627
628
629
	      -- Discard the tcg_env; it contains only extra info about fixity
        ; traceRn (text "rnBracket dec" <+> (ppr (tcg_dus tcg_env) $$ ppr (duUses (tcg_dus tcg_env))))
	; return (DecBrG group', duUses (tcg_dus tcg_env)) }
630
631

rnBracket (DecBrG _) = panic "rnBracket: unexpected DecBrG"
632
633
\end{code}

634
635
%************************************************************************
%*									*
636
\subsubsection{@Stmt@s: in @do@ expressions}
637
638
639
640
%*									*
%************************************************************************

\begin{code}
641
rnStmts :: HsStmtContext Name -> [LStmt RdrName]
642
	      -> ([Name] -> RnM (thing, FreeVars))
643
	      -> RnM (([LStmt Name], thing), FreeVars)	
644
645
646
647
648
-- Variables bound by the Stmts, and mentioned in thing_inside,
-- do not appear in the result FreeVars
--
-- Renaming a single RecStmt can give a sequence of smaller Stmts

649
rnStmts _ [] thing_inside
650
651
  = do { (res, fvs) <- thing_inside []
       ; return (([], res), fvs) }
652

653
rnStmts ctxt (stmt@(L loc _) : stmts) thing_inside
654
  = do { ((stmts1, (stmts2, thing)), fvs) 
655
656
            <- setSrcSpan loc           $
               rnStmt ctxt stmt         $ \ bndrs1 ->
657
               rnStmts ctxt stmts $ \ bndrs2 ->
658
               thing_inside (bndrs1 ++ bndrs2)
659
	; return (((stmts1 ++ stmts2), thing), fvs) }
660
661


662
rnStmt :: HsStmtContext Name -> LStmt RdrName
663
       -> ([Name] -> RnM (thing, FreeVars))
664
       -> RnM (([LStmt Name], thing), FreeVars)
665
666
-- Variables bound by the Stmt, and mentioned in thing_inside,
-- do not appear in the result FreeVars
667

668
rnStmt _ (L loc (ExprStmt expr _ _)) thing_inside
669
670
  = do	{ (expr', fv_expr) <- rnLExpr expr
	; (then_op, fvs1)  <- lookupSyntaxName thenMName
671
	; (thing, fvs2)    <- thing_inside []
672
	; return (([L loc (ExprStmt expr' then_op placeHolderType)], thing),
673
674
		  fv_expr `plusFV` fvs1 `plusFV` fvs2) }

675
rnStmt ctxt (L loc (BindStmt pat expr _ _)) thing_inside
676
677
678
679
  = do	{ (expr', fv_expr) <- rnLExpr expr
		-- The binders do not scope over the expression
	; (bind_op, fvs1) <- lookupSyntaxName bindMName
	; (fail_op, fvs2) <- lookupSyntaxName failMName
680
	; rnPat (StmtCtxt ctxt) pat $ \ pat' -> do
681
	{ (thing, fvs3) <- thing_inside (collectPatBinders pat')
682
	; return (([L loc (BindStmt pat' expr' bind_op fail_op)], thing),
683
		  fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
684
       -- fv_expr shouldn't really be filtered by the rnPatsAndThen
685
	-- but it does not matter because the names are unique
686

687
rnStmt ctxt (L loc (LetStmt binds)) thing_inside 
688
689
  = do	{ checkLetStmt ctxt binds
	; rnLocalBindsAndThen binds $ \binds' -> do
690
	{ (thing, fvs) <- thing_inside (collectLocalBinders binds')
691
        ; return (([L loc (LetStmt binds')], thing), fvs) }  }
692

693
rnStmt ctxt (L _ (RecStmt { recS_stmts = rec_stmts })) thing_inside
694
  = do	{ checkRecStmt ctxt
695
696
697
698
699
700
701
702
703
704

	-- Step1: Bring all the binders of the mdo into scope
	-- (Remember that this also removes the binders from the
	-- finally-returned free-vars.)
   	-- And rename each individual stmt, making a
	-- singleton segment.  At this stage the FwdRefs field
	-- isn't finished: it's empty for all except a BindStmt
	-- for which it's the fwd refs within the bind itself
	-- (This set may not be empty, because we're in a recursive 
	-- context.)
705
        ; rnRecStmtsAndThen rec_stmts   $ \ segs -> do
706

707
708
709
	{ let bndrs = nameSetToList $ foldr (unionNameSets . (\(ds,_,_,_) -> ds)) 
                                            emptyNameSet segs
        ; (thing, fvs_later) <- thing_inside bndrs
710
711
712
	; (return_op, fvs1)  <- lookupSyntaxName returnMName
	; (mfix_op,   fvs2)  <- lookupSyntaxName mfixName
	; (bind_op,   fvs3)  <- lookupSyntaxName bindMName
713
	; let
714
715
716
717
		-- Step 2: Fill in the fwd refs.
		-- 	   The segments are all singletons, but their fwd-ref
		--	   field mentions all the things used by the segment
		--	   that are bound after their use
718
	    segs_w_fwd_refs          = addFwdRefs segs
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737

		-- Step 3: Group together the segments to make bigger segments
		--	   Invariant: in the result, no segment uses a variable
		--	   	      bound in a later segment
	    grouped_segs = glomSegments segs_w_fwd_refs

		-- Step 4: Turn the segments into Stmts
		--	   Use RecStmt when and only when there are fwd refs
		--	   Also gather up the uses from the end towards the
		--	   start, so we can tell the RecStmt which things are
		--	   used 'after' the RecStmt
	    empty_rec_stmt = emptyRecStmt { recS_ret_fn  = return_op
                                          , recS_mfix_fn = mfix_op
                                          , recS_bind_fn = bind_op }
	    (rec_stmts', fvs) = segsToStmts empty_rec_stmt grouped_segs fvs_later

	; return ((rec_stmts', thing), fvs `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) } }

rnStmt ctxt (L loc (ParStmt segs)) thing_inside
738
739
  = do	{ checkParStmt ctxt
	; ((segs', thing), fvs) <- rnParallelStmts (ParStmtCtxt ctxt) segs thing_inside
740
	; return (([L loc (ParStmt segs')], thing), fvs) }
741

742
743
rnStmt ctxt (L loc (TransformStmt stmts _ using by)) thing_inside
  = do { checkTransformStmt ctxt
744
    
745
746
747
       ; (using', fvs1) <- rnLExpr using

       ; ((stmts', (by', used_bndrs, thing)), fvs2)
748
             <- rnStmts (TransformStmtCtxt ctxt) stmts $ \ bndrs ->
749
750
751
752
753
                do { (by', fvs_by) <- case by of
                                        Nothing -> return (Nothing, emptyFVs)
                                        Just e  -> do { (e', fvs) <- rnLExpr e; return (Just e', fvs) }
                   ; (thing, fvs_thing) <- thing_inside bndrs
                   ; let fvs        = fvs_by `plusFV` fvs_thing
754
755
756
                         used_bndrs = filter (`elemNameSet` fvs) bndrs
                         -- The paper (Fig 5) has a bug here; we must treat any free varaible of
                         -- the "thing inside", **or of the by-expression**, as used
757
758
759
760
                   ; return ((by', used_bndrs, thing), fvs) }

       ; return (([L loc (TransformStmt stmts' used_bndrs using' by')], thing), 
                 fvs1 `plusFV` fvs2) }
761
        
762
763
rnStmt ctxt (L loc (GroupStmt stmts _ by using)) thing_inside
  = do { checkTransformStmt ctxt
764
    
765
766
767
768
769
770
771
772
773
         -- Rename the 'using' expression in the context before the transform is begun
       ; (using', fvs1) <- case using of
                             Left e  -> do { (e', fvs) <- rnLExpr e; return (Left e', fvs) }
			     Right _ -> do { (e', fvs) <- lookupSyntaxName groupWithName
                                           ; return (Right e', fvs) }

         -- Rename the stmts and the 'by' expression
	 -- Keep track of the variables mentioned in the 'by' expression
       ; ((stmts', (by', used_bndrs, thing)), fvs2) 
774
             <- rnStmts (TransformStmtCtxt ctxt) stmts $ \ bndrs ->
775
776
777
778
779
780
781
782
                do { (by',   fvs_by) <- mapMaybeFvRn rnLExpr by
                   ; (thing, fvs_thing) <- thing_inside bndrs
                   ; let fvs = fvs_by `plusFV` fvs_thing
                         used_bndrs = filter (`elemNameSet` fvs) bndrs
                   ; return ((by', used_bndrs, thing), fvs) }

       ; let all_fvs  = fvs1 `plusFV` fvs2 
             bndr_map = used_bndrs `zip` used_bndrs
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
783
	     -- See Note [GroupStmt binder map] in HsExpr
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810

       ; traceRn (text "rnStmt: implicitly rebound these used binders:" <+> ppr bndr_map)
       ; return (([L loc (GroupStmt stmts' bndr_map by' using')], thing), all_fvs) }


type ParSeg id = ([LStmt id], [id])	   -- The Names are bound by the Stmts

rnParallelStmts :: forall thing. HsStmtContext Name 
                -> [ParSeg RdrName]
                -> ([Name] -> RnM (thing, FreeVars))
                -> RnM (([ParSeg Name], thing), FreeVars)
-- Note [Renaming parallel Stmts]
rnParallelStmts ctxt segs thing_inside
  = do { orig_lcl_env <- getLocalRdrEnv
       ; rn_segs orig_lcl_env [] segs }
  where
    rn_segs :: LocalRdrEnv
            -> [Name] -> [ParSeg RdrName]
            -> RnM (([ParSeg Name], thing), FreeVars)
    rn_segs _ bndrs_so_far [] 
      = do { let (bndrs', dups) = removeDups cmpByOcc bndrs_so_far
           ; mapM_ dupErr dups
           ; (thing, fvs) <- bindLocalNames bndrs' (thing_inside bndrs')
           ; return (([], thing), fvs) }

    rn_segs env bndrs_so_far ((stmts,_) : segs) 
      = do { ((stmts', (used_bndrs, segs', thing)), fvs)
811
                    <- rnStmts ctxt stmts $ \ bndrs ->
812
813
814
815
816
817
818
819
820
821
                       setLocalRdrEnv env       $ do
                       { ((segs', thing), fvs) <- rn_segs env (bndrs ++ bndrs_so_far) segs
		       ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
                       ; return ((used_bndrs, segs', thing), fvs) }
		       
           ; let seg' = (stmts', used_bndrs)
           ; return ((seg':segs', thing), fvs) }

    cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
    dupErr vs = addErr (ptext (sLit "Duplicate binding in parallel list comprehension for:")
822
                    <+> quotes (ppr (head vs)))
823
824
\end{code}

825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
Note [Renaming parallel Stmts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Renaming parallel statements is painful.  Given, say  
     [ a+c | a <- as, bs <- bss
           | c <- bs, a <- ds ]
Note that
  (a) In order to report "Defined by not used" about 'bs', we must rename
      each group of Stmts with a thing_inside whose FreeVars include at least {a,c}
   
  (b) We want to report that 'a' is illegally bound in both branches

  (c) The 'bs' in the second group must obviously not be captured by 
      the binding in the first group

To satisfy (a) we nest the segements. 
To satisfy (b) we check for duplicates just before thing_inside.
To satisfy (c) we reset the LocalRdrEnv each time.
842
843
844

%************************************************************************
%*									*
845
\subsubsection{mdo expressions}
846
847
%*									*
%************************************************************************
848

849
\begin{code}
850
type FwdRefs = NameSet
851
852
853
type Segment stmts = (Defs,
		      Uses, 	-- May include defs
		      FwdRefs,	-- A subset of uses that are 
854
855
				--   (a) used before they are bound in this segment, or 
				--   (b) used here, and bound in subsequent segments
856
857
		      stmts)	-- Either Stmt or [Stmt]

858

859
-- wrapper that does both the left- and right-hand sides
860
rnRecStmtsAndThen :: [LStmt RdrName]
861
862
863
864
                         -- assumes that the FreeVars returned includes
                         -- the FreeVars of the Segments
                      -> ([Segment (LStmt Name)] -> RnM (a, FreeVars))
                      -> RnM (a, FreeVars)
865
rnRecStmtsAndThen s cont
866
867
868
869
870
871
872
  = do	{ -- (A) Make the mini fixity env for all of the stmts
	  fix_env <- makeMiniFixityEnv (collectRecStmtsFixities s)

	  -- (B) Do the LHSes
	; new_lhs_and_fv <- rn_rec_stmts_lhs fix_env s

	  --    ...bring them and their fixities into scope
873
	; let bound_names = collectLStmtsBinders (map fst new_lhs_and_fv)
874
875
	      -- Fake uses of variables introduced implicitly (warning suppression, see #4404)
	      implicit_uses = lStmtsImplicits (map fst new_lhs_and_fv)
876
877
	; bindLocalNamesFV bound_names $
          addLocalFixities fix_env bound_names $ do
878
879
880
881

	  -- (C) do the right-hand-sides and thing-inside
	{ segs <- rn_rec_stmts bound_names new_lhs_and_fv
	; (res, fvs) <- cont segs 
882
	; warnUnusedLocalBinds bound_names (fvs `unionNameSets` implicit_uses)
883
	; return (res, fvs) }}
884
885

-- get all the fixity decls in any Let stmt
Ian Lynagh's avatar
Ian Lynagh committed
886
collectRecStmtsFixities :: [LStmtLR RdrName RdrName] -> [LFixitySig RdrName]
887
888
collectRecStmtsFixities l = 
    foldr (\ s -> \acc -> case s of 
Ian Lynagh's avatar
Ian Lynagh committed
889
                            (L _ (LetStmt (HsValBinds (ValBindsIn _ sigs)))) -> 
890
891
892
893
894
895
896
                                foldr (\ sig -> \ acc -> case sig of 
                                                           (L loc (FixSig s)) -> (L loc s) : acc
                                                           _ -> acc) acc sigs
                            _ -> acc) [] l
                             
-- left-hand sides

897
rn_rec_stmt_lhs :: MiniFixityEnv
898
899
900
901
902
903
                -> LStmt RdrName
                   -- rename LHS, and return its FVs
                   -- Warning: we will only need the FreeVars below in the case of a BindStmt,
                   -- so we don't bother to compute it accurately in the other cases
                -> RnM [(LStmtLR Name RdrName, FreeVars)]

Ian Lynagh's avatar
Ian Lynagh committed
904
rn_rec_stmt_lhs _ (L loc (ExprStmt expr a b)) = return [(L loc (ExprStmt expr a b), 
905
906
907
908
909
910
                                                       -- this is actually correct
                                                       emptyFVs)]

rn_rec_stmt_lhs fix_env (L loc (BindStmt pat expr a b)) 
  = do 
      -- should the ctxt be MDo instead?
911
      (pat', fv_pat) <- rnBindPat (localRecNameMaker fix_env) pat 
912
913
914
      return [(L loc (BindStmt pat' expr a b),
               fv_pat)]

Ian Lynagh's avatar
Ian Lynagh committed
915
rn_rec_stmt_lhs _ (L _ (LetStmt binds@(HsIPBinds _)))
916
  = failWith (badIpBinds (ptext (sLit "an mdo expression")) binds)
917
918

rn_rec_stmt_lhs fix_env (L loc (LetStmt (HsValBinds binds))) 
919
    = do (_bound_names, binds') <- rnLocalValBindsLHS fix_env binds
920
921
922
923
924
         return [(L loc (LetStmt (HsValBinds binds')),
                 -- Warning: this is bogus; see function invariant
                 emptyFVs
                 )]

925
926
-- XXX Do we need to do something with the return and mfix names?
rn_rec_stmt_lhs fix_env (L _ (RecStmt { recS_stmts = stmts }))	-- Flatten Rec inside Rec
927
928
929
930
    = rn_rec_stmts_lhs fix_env stmts

rn_rec_stmt_lhs _ stmt@(L _ (ParStmt _))	-- Syntactically illegal in mdo
  = pprPanic "rn_rec_stmt" (ppr stmt)
931
  
932
rn_rec_stmt_lhs _ stmt@(L _ (TransformStmt {}))	-- Syntactically illegal in mdo
933
934
  = pprPanic "rn_rec_stmt" (ppr stmt)
  
935
rn_rec_stmt_lhs _ stmt@(L _ (GroupStmt {}))	-- Syntactically illegal in mdo
936
  = pprPanic "rn_rec_stmt" (ppr stmt)
Ian Lynagh's avatar
Ian Lynagh committed
937
938
939
940

rn_rec_stmt_lhs _ (L _ (LetStmt EmptyLocalBinds))
  = panic "rn_rec_stmt LetStmt EmptyLocalBinds"

941
rn_rec_stmts_lhs :: MiniFixityEnv
942
943
                 -> [LStmt RdrName] 
                 -> RnM [(LStmtLR Name RdrName, FreeVars)]
944
rn_rec_stmts_lhs fix_env stmts
945
946
  = do { ls <- concatMapM (rn_rec_stmt_lhs fix_env) stmts
       ; let boundNames = collectLStmtsBinders (map fst ls)
947
948
949
            -- First do error checking: we need to check for dups here because we
            -- don't bind all of the variables from the Stmt at once
            -- with bindLocatedLocals.
950
951
       ; checkDupNames boundNames
       ; return ls }
952
953
954
955
956


-- right-hand-sides

rn_rec_stmt :: [Name] -> LStmtLR Name RdrName -> FreeVars -> RnM [Segment (LStmt Name)]
957
	-- Rename a Stmt that is inside a RecStmt (or mdo)
958
959
	-- Assumes all binders are already in scope
	-- Turns each stmt into a singleton Stmt
Ian Lynagh's avatar
Ian Lynagh committed
960
rn_rec_stmt _ (L loc (ExprStmt expr _ _)) _
961
  = rnLExpr expr `thenM` \ (expr', fvs) ->
962
    lookupSyntaxName thenMName	`thenM` \ (then_op, fvs1) ->
963
    return [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
964
	      L loc (ExprStmt expr' then_op placeHolderType))]
965

Ian Lynagh's avatar
Ian Lynagh committed
966
rn_rec_stmt _ (L loc (BindStmt pat' expr _ _)) fv_pat
967
  = rnLExpr expr		`thenM` \ (expr', fv_expr) ->
968
969
    lookupSyntaxName bindMName	`thenM` \ (bind_op, fvs1) ->
    lookupSyntaxName failMName	`thenM` \ (fail_op, fvs2) ->
970
971
    let
	bndrs = mkNameSet (collectPatBinders pat')
972
	fvs   = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
973
    in
974
    return [(bndrs, fvs, bndrs `intersectNameSet` fvs,
975
	      L loc (BindStmt pat' expr' bind_op fail_op))]
976

Ian Lynagh's avatar
Ian Lynagh committed
977
rn_rec_stmt _ (L _ (LetStmt binds@(HsIPBinds _))) _
978
  = failWith (badIpBinds (ptext (sLit "an mdo expression")) binds)
979

980
981
rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds'))) _ = do 
  (binds', du_binds) <- 
982
      -- fixities and unused are handled above in rnRecStmtsAndThen
983
      rnLocalValBindsRHS (mkNameSet all_bndrs) binds'
984
985
  return [(duDefs du_binds, allUses du_binds, 
	   emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
986

987
-- no RecStmt case becuase they get flattened above when doing the LHSes
988
rn_rec_stmt _ stmt@(L _ (RecStmt {})) _
989
  = pprPanic "rn_rec_stmt: RecStmt" (ppr stmt)
990

991
rn_rec_stmt _ stmt@(L _ (ParStmt {})) _	-- Syntactically illegal in mdo
992
993
  = pprPanic "rn_rec_stmt: ParStmt" (ppr stmt)

994
rn_rec_stmt _ stmt@(L _ (TransformStmt {})) _	-- Syntactically illegal in mdo
995
996
  = pprPanic "rn_rec_stmt: TransformStmt" (ppr stmt)

997
rn_rec_stmt _ stmt@(L _ (GroupStmt {})) _	-- Syntactically illegal in mdo
998
999
  = pprPanic "rn_rec_stmt: GroupStmt" (ppr stmt)

Ian Lynagh's avatar
Ian Lynagh committed
1000
1001
1002
rn_rec_stmt _ (L _ (LetStmt EmptyLocalBinds)) _
  = panic "rn_rec_stmt: LetStmt EmptyLocalBinds"

1003
rn_rec_stmts :: [Name] -> [(LStmtLR Name RdrName, FreeVars)] -> RnM [Segment (LStmt Name)]